Angular 7 ng build, registry.registerUriHandler is not a function in bitbucket pipelines

Question: I just updated my app to Angular 7, it compiles fine in local but when i try to deploy to bitbucket i get this error with ng build

registry.registerUriHandler is not a function TypeError:
  registry.registerUriHandler is not a function
      at Object.runCommand (/opt/atlassian/pipelines/agent/build/node_modules/@angular/cli/models/command-runner.js:47:14)
      at default_1 (/opt/atlassian/pipelines/agent/build/node_modules/@angular/cli/lib/cli/index.js:32:54)
      at Object. (/usr/local/lib/node_modules/@angular/cli/lib/init.js:125:1)
      at Module._compile (module.js:643:30)
      at Object.Module._extensions..js (module.js:654:10)
      at Module.load (module.js:556:32)
      at tryModuleLoad (module.js:499:12)
      at Function.Module._load (module.js:491:3)
      at Module.require (module.js:587:17)
      at require (internal/module.js:11:18)

I don't understand what has pipelines to do with this but i think it could be an error with angular, any idea of how to solve this?
Comment: Are you sure you're only running `ng build` for your deploy? You (should) be running something like `ng build --prod --aot` If you try to run a prod build with aot, can you reproduce it locally?
Comment: I'm using ng build --configuration=test to build with a custom enviroment, but i have been using that for a while and i can make the build locally with no problems
Comment: What is in your test configuration?
Comment: Only this... "test": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.test.ts" } ] }
Comment: Do you have a repo you can share?
Answer: Well i found the problem after lots of headaches, pipelines was trying to build the angular 7 app with the angular 6 cli, even thought i was explicitly installing @angular/cli 7.0.2. I discovered that pipelines makes a cache of node_modules so it was using the old cli, cleaning the cache made the error go away.


Where, how Caesar III?

Question: I used to play Caesar III on my power mac g3 (mac os 9) I have now a pc laptop and I was thinking where I could find it and how I could install it, what operating system I should use, ( I have Ubuntu 10.04 and mac os x 10.6 and win 7.)
simply my question is
Where can i find it?
How can I install it?
this might not be met, but I would love to find a mac version ( I have 5 macs).
Comment: What kind of title is that?
Comment: Sierra games! They also made "Pharaoh"
Answer: You can find it at Good Old Games and it will play on any version of Windows from Windows XP or later.
Comment: +1 for a great link. My childhood right there on one website! Ohh the memories :o)

Where, how Caesar III?


Minecraft java EXCEPTION_ACCESS_VIOLATION in Windows 7?

Question: I was trying to port forward my Minecraft server, using port 25566, and for some reason it wasn't working. So, I opened Minecraft to enter localhost, and after clicking login, the window closed and placed an error log report on my desktop. The same thing happens with all subsequent tries. Here is the error report:
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x690ba2a1, pid=3152, tid=3372
#
# JRE version: 6.0_26-b03
# Java VM: Java HotSpot(TM) Client VM (20.1-b02 mixed mode windows-x86 )
# Problematic frame:
# C  [atioglxx.dll+0x8a2a1]
#
# If you would like to submit a bug report, please visit:
#   http://java.sun.com/webapps/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

---------------  T H R E A D  ---------------

Current thread (0x0200cc00):  JavaThread "Minecraft main thread" daemon [_thread_in_native, id=3372, stack(0x4ef10000,0x4ef60000)]

siginfo: ExceptionCode=0xc0000005, reading address 0x00000b54

Registers:
EAX=0x00000000, EBX=0x4f31c778, ECX=0x00000000, EDX=0x00000000
ESP=0x4ef548a0, EBP=0x4ef561cc, ESI=0x00000000, EDI=0x00000001
EIP=0x690ba2a1, EFLAGS=0x00010212

Top of Stack: (sp=0x4ef548a0)
0x4ef548a0:   00000000 00000000 00000000 4f31c778
0x4ef548b0:   00000000 00000000 00000000 00000000
0x4ef548c0:   00000000 00000000 00000000 00000000
0x4ef548d0:   00000000 00000000 000000f5 00000000
0x4ef548e0:   00000000 00000000 00000000 00000000
0x4ef548f0:   00000000 00000000 00000000 00000000
0x4ef54900:   00000000 00000001 00000000 00000000
0x4ef54910:   00000000 00000000 4f1e9be8 0000000e

Instructions: (pc=0x690ba2a1)
0x690ba281:   14 8d 43 10 50 8d 4c 24 1c 51 56 57 8d 7c 24 50
0x690ba291:   e8 0a 21 04 00 8b 53 10 bf 01 00 00 00 89 43 08
0x690ba2a1:   39 ba 54 0b 00 00 0f 85 85 00 00 00 68 f8 bc f0
0x690ba2b1:   69 e8 07 0b d6 00 83 c4 04 85 c0 74 74 be bc 56

Register to memory mapping:

EAX=0x00000000 is an unknown value
EBX=0x4f31c778 is an unknown value
ECX=0x00000000 is an unknown value
EDX=0x00000000 is an unknown value
ESP=0x4ef548a0 is pointing into the stack for thread: 0x0200cc00
EBP=0x4ef561cc is pointing into the stack for thread: 0x0200cc00
ESI=0x00000000 is an unknown value
EDI=0x00000001 is an unknown value

Stack: [0x4ef10000,0x4ef60000],  sp=0x4ef548a0,  free space=274k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C  [atioglxx.dll+0x8a2a1]  DrvPresentBuffers+0x3e821

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j  org.lwjgl.opengl.WindowsPeerInfo.nChoosePixelFormat(JIILorg/lwjgl/opengl/PixelFormat;Ljava/nio/IntBuffer;ZZZZ)I+0
j  org.lwjgl.opengl.WindowsPeerInfo.choosePixelFormat(JIILorg/lwjgl/opengl/PixelFormat;Ljava/nio/IntBuffer;ZZZZ)I+15
j  org.lwjgl.opengl.WindowsDisplay.createWindow(Lorg/lwjgl/opengl/DisplayMode;Ljava/awt/Canvas;II)V+176
j  org.lwjgl.opengl.Display.createWindow()V+68
j  org.lwjgl.opengl.Display.create(Lorg/lwjgl/opengl/PixelFormat;Lorg/lwjgl/opengl/Drawable;Lorg/lwjgl/opengl/ContextAttribs;)V+63
j  org.lwjgl.opengl.Display.create(Lorg/lwjgl/opengl/PixelFormat;)V+9
j  org.lwjgl.opengl.Display.create()V+13
j  net.minecraft.client.Minecraft.a()V+135
j  net.minecraft.client.Minecraft.run()V+6
j  java.lang.Thread.run()V+11
v  ~StubRoutines::call_stub

---------------  P R O C E S S  ---------------

Java Threads: ( => current thread )
=>0x0200cc00 JavaThread "Minecraft main thread" daemon [_thread_in_native, id=3372, stack(0x4ef10000,0x4ef60000)]
  0x0200d400 JavaThread "Timer hack thread" daemon [_thread_blocked, id=3368, stack(0x4ee80000,0x4eed0000)]
  0x0200a800 JavaThread "Keep-Alive-Timer" daemon [_thread_blocked, id=3356, stack(0x4d490000,0x4d4e0000)]
  0x0200c800 JavaThread "D3D Screen Updater" daemon [_thread_blocked, id=3256, stack(0x4e920000,0x4e970000)]
  0x0200c000 JavaThread "DestroyJavaVM" [_thread_blocked, id=3160, stack(0x00360000,0x003b0000)]
  0x0200b400 JavaThread "TimerQueue" daemon [_thread_blocked, id=3252, stack(0x4d650000,0x4d6a0000)]
  0x0200b000 JavaThread "AWT-EventQueue-0" [_thread_blocked, id=3236, stack(0x4d520000,0x4d570000)]
  0x0200a000 JavaThread "AWT-Windows" daemon [_thread_in_native, id=3204, stack(0x4ab70000,0x4abc0000)]
  0x02009c00 JavaThread "AWT-Shutdown" [_thread_blocked, id=3200, stack(0x4aa00000,0x4aa50000)]
  0x02009400 JavaThread "Java2D Disposer" daemon [_thread_blocked, id=3196, stack(0x4a940000,0x4a990000)]
  0x02009000 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=3188, stack(0x4a620000,0x4a670000)]
  0x02015800 JavaThread "C1 CompilerThread0" daemon [_thread_blocked, id=3184, stack(0x4a590000,0x4a5e0000)]
  0x02008800 JavaThread "Attach Listener" daemon [_thread_blocked, id=3180, stack(0x4a500000,0x4a550000)]
  0x02008400 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=3176, stack(0x4a470000,0x4a4c0000)]
  0x01fdf000 JavaThread "Finalizer" daemon [_thread_blocked, id=3172, stack(0x4a3e0000,0x4a430000)]
  0x01fda400 JavaThread "Reference Handler" daemon [_thread_blocked, id=3168, stack(0x4a350000,0x4a3a0000)]

Other Threads:
  0x01fd5c00 VMThread [stack: 0x4a2c0000,0x4a310000] [id=3164]
  0x0203c000 WatcherThread [stack: 0x4a6b0000,0x4a700000] [id=3192]

VM state:not at safepoint (normal execution)

This error has happened to other people before, but I haven't been able to find an actual answer to the problem. Minecraft + java have been reinstalled in all possible ways, video card drivers(radeon x600) have been changed, updated, everything. I have 4 gigabytes of ddr2 RAM and a pentium d 820, and windows 7 ultimate 64-bit. The answers in the other question like this on this site don't help at all. I say I was fiddling with minecraft server because that's the only thing I did that could have done anything to break minecraft. I was able to play minecraft beforehand. Minecraft for free and in-browser minecraft on minecraft.net don't work either. Minecraft server works perfectly though.
Answer: The issue is caused by openGL mode in minecraft. Turn off openGL mode it it should work fine. If you can not get to the config screen you can edit it by hand by clicking options in the launcher, then game location on disk. open options.txt and change the line advancedOpengl:true to advancedOpengl:false
Comment: well, there is no options.txt, because I have not been able to run minecraft since I last re-installed it. I don't remember, but supposing you are right and the default advanced opengl setting is
Comment: on, then where do i put a copy of the options.txt from my other pc to make it work?
Comment: Actually, that would make sense, because I did change my graphics card to an older one that probably does not support advanced opengl. I didn't put that in the question because I forgot.
Comment: And, I tried that... it didn't work. No change.
Comment: Sry, That was my best guess from what the error said.
Answer: There's a link on the Mojang bug tracker about this, with a solution:
https://bugs.mojang.com/browse/MC-90269
The basic gist of it is that your intel graphics drivers are outdated, or are otherwise conflicting with Java/Minecraft.
You could try updating them, but the hardware may be outdated (or there may not be a new version?)
Comment: It's just that `ig8icd64.dll` is a file that Intel uses for its graphics drivers.  I know for sure that DecoCraft will use different rendering and probably the minimap.  It could be some sort of unsupported operation that one of these uses? It might be worth isolating the problem by only keeping one installed and testing that one.
Comment: My computer hardware is new so I'm not sure that would be causing the problem. The drivers are at newest versions. I reckon it is them conflicting,   I used to have this problem and out of the blue, it went, and now, out of the blue, it has come back. The bug tracker issue solution is not the solution that applies to me. There are so many solutions to this problem it is mad, Mojang should change the error codes as they are not exactly helpful being merged.
Comment: Thanks (I am probably not allowed to say that but oh well), it was DecoCraft. Is there any way I can fix this without uninstalling it? Or should I just contact the mod author?
Comment: OOps soz about feedback
Answer: Can you try running the game after its been reinstalled and thats it. You can keep on trying to run the program under different circumstances.
Comment: Well, I tried doing this when it happened to me last and it just fixed itself
Comment: Alright that's cool man.


How does corruption spread?

Question: I've tried to make an artificial Corruption biome in Terraria for two purposes:

Farming mobs;
Getting a lot of Vile Mushrooms;

But I want to do it accurately and limit the size of the corrupted area. So I'm stuck with the following problems:

Will Ebonstone make blocks of dirt in contact with it corrupted, if I place them in such way?
Does Corruption spread through Corrupted grass and Thorns?
How big or long may corrupted Thorns be?
Answer: As of the time of writing (18.104.22.168), the following applies, for the Corruption. The Crimson has similar mechanics, although the specific blocks are different (and due to the question's focus, I will not deal with the Crimson in this answer):

In Normal Mode:

Corrupt grass can spread in a manner similar to normal grass, converting adjacent Dirt tiles with at least one side open to air (only in the Surface Layer).

This is because grass only spreads on the surface.

Corrupt grass can also displace normal and hallow grass, unless the grass has a Sunflower planted on it.

Note that Hallow grass doesn't appear naturally on a newly-generated world. You can create it using Hallowed Seeds, Holy Water or the Blue Solution (for use with the Clentaminator), imported from a Hardmode world.

Corrupt grass may sprout Thorny Bushes, which can spread corrupt grass according to the same rules.

Thorny Bushes grow in all directions (not just upwards, although they have to start by growing up), and may spread. The maximum range for the Bushes seems to be around 6 blocks from the Corrupt grass block that initially spawned the bush.

In Hardmode:

In addition to corrupt grass, thorns and plants, Ebonstone, Ebonsand and Purple Ice also generate corruption (Red Stucco no longer spreads corruption as of 1.2.3).
Grass can still be converted to corrupt grass, and corrupt grass can cover new dirt as in regular mode.
Mud can now be converted into dirt. Jungle grass can also be converted into corrupt grass (changing the underlying block type to dirt).

Thus Jungle biomes will eventually be partially converted to Corruption.

Stone can be converted to Ebonstone.
Sand can be converted to Ebonsand.
Ice can be converted to Purple Ice.
Sunflowers block corruption in hardmode (as of 1.2)(Before 1.2, Sunflowers will be uprooted if the grass they are planted on becomes corrupted).
Corrupt grass is still limited to the Surface Layer, but Ebonstone and Ebonsand can spread through any depth.
Corruptible blocks that are up to three squares away from an existing corrupt block can be converted (even if incorruptible blocks are in the way).

This means that a single Sunflower (2 blocks wide) will not stop the corruption from spreading to its side.

Silt can be converted (to Ebonsand) as part of the initial burst when you first defeat the Wall of Flesh, but not at other times.

Background walls aren't affected by the Corruption, except when as part of the initial burst when you defeat the Wall of Flesh.
Upon defeating Plantera, Hardmode Crimson, Corruption, and Hallow spread will be slowed down to 1/3 (33%) of their previous speed (As of 18.104.22.168)2.

Prevention:

Preventing The Corruption from spreading can be done by planting at least two sunflowers consecutively or, in alternative, by building small barriers (or forts) of non-corruptible material on both sides of The Corruption at least 3 blocks wide. This can only be easily done in Normal Mode.
Before 1.2, preventing the spread in Hardmode is near impossible, due to the amount of corrupted blocks before and after the defeat of the Wall of Flesh, the lack of efficient biome creators (for reference, at the time there were only seeds and Holy Water, which have small radii of influence) and the increased speed of spreading. The recommended approaches are to create a contained Normal zone (where your base is) before or immediately after the world enters in Hardmode.1
As of 1.2, after defeating any Mechanical Boss, the Steampunker will appear and offer the Clentaminator. It projects a Solution to a range of about 60 tiles, which will convert any block in its path to the corresponding Solution biome block. It is possible to change an entire world by digging hellevators around 120 blocks apart, which makes biome spread more manageable.

Answering the questions placed:

Ebonstone will create an artificial Corruption biome, assuming that on the screen are at least 200 blocks. It will not spread on Normal Mode. It will spread as soon as you pass into Hardmode. Not only that, but Hardmode Corruption spawns the Corruptor that has a projectile attack that spread Corruption, until version 1.2, where that effect was removed.

In this scenario, Ebonstone will not turn blocks of dirt in contact with it corrupted (since dirt is incorruptible) - however it will turn any patch of Normal or Hallowed grass into Corrupted grass. This also means that before Hardmode, the only way to create a mushroom farm is with Corrupt Grass seeds and letting them spread.

Corruption spreads through Thorny Bushes (although the rules behind it aren't well documented). As far as I can tell, at Normal, it needs to contact the dirt blocks (same as grass). At Hardmode it stands to reason that it still spreads as before, but it's unclear whether it can now spread to rock, due to the 3-tile rule. In practice it doesn't matter, as the spread (of Corruption through Stone and other blocks) is faster than the growth of the bushes.
Thorny Bushes grow in the following fashion: They spawn from a block of corrupted grass. This block needs to have air above it. From that block, they can spread to a distance of at most 6 blocks from that point in all directions. They spread it the same way a real bush does (i.e. by spawning a bush block in one of the 8 directions a current bush piece has). If no wall is behind them, they will try to spread orthogonally, otherwise, they can spread to the corner directions.

Note that a Thorny Bush can spread Corrupted grass, and that enables more bushes to spawn.

Disclaimer: Most (if not all) of the information here can be obtained in the official wiki and also at some extent at the unofficial wiki. The information is there, except split across several pages. Also, there seems to be some inconsistencies between some pages; when possible, I use the changelog information as the deciding factor (when possible). The only information not available in the wikis is the information about the Thorny Bush, that I've verified visually with old saves.

1 - It is possible to completely contain everything, by building 3-tile wide walls across the entire map in a grid pattern. It is, however, a complete waste of resources and patience and time. I know because I've tried to do it.
2 - Apparently, it seems the Mechanical Bosses, at one time between their introduction in 1.1 and 220.127.116.11, reduced the spread speed - however I can't find or remember any reference to this. I assume it might have been a typo or the developer's previous intent that seeped into the changelog.
Comment: It appears to be some sort of bug, as seen on [here](http://terraria.gamepedia.com/Hallow#Notes). Although, in [here](http://terraria.gamepedia.com/Corruption#Spread) it is stated it can spread through hallow grass, at least in Normal. The correct behavior is for them not to affect each other, in Hardmode, so I must have been remembering this particularity when writing.
Comment: I didn't know corrupted grass could replace hallowed grass. Do you have a source for this? Does the same happen with other types of blocks?
Answer: You can use Corrupt Seeds on dirt to artificially create corrupted areas yourself. If you want to control how much the corruption spreads, plant Sunflowers on the left and right boundaries of your corrupt areas, as they stop the spread of Corruption.
According to this user, only Corrupt Grass spreads the Corruption (to other dirt blocks) – Ebonstone won't. However, another user states Ebonstone will in fact spread it, so I'm not sure who is correct. Thorny Bushes will spread the Corruption. I don't know if there's any data on the maximum size of Thorny Bushes.
Comment: Ebonstone cannot spread corruption (at least, in my experience), but enough ebonstone in one area can create a 'corruption' biome and induce enemy spawning, etc.
Comment: OK. Thanks for comprehensive answer. I will try to make experiments to confirm (or refute) some ideas. Behavior of ebonstone is very interesting to me.
Comment: Given the age of this answer, a few updates are pertinent: Corruption doubles spread distance and drastically increases speed in Hardmode.  Crimson (an occasional corruption replacement) will not be blocked by sunflowers.  A thick wall of non-corruptable material will block the corruption, usually white stone or regular wood.  In hardmode, the corruption will spread underground and is very difficult to block with a barrier.  A better option at this point would be creating a preserve for a non-corrupted/hallowed area.
Answer: Corruption only spreads on dirt. It cannot spread on any other tile (like Hellstone, ash mud, stone, clay and so on and so forth). You can stop corruption from spreading, by blocking the corruption, with any other tile that is not dirt.
Comment: It's worth a note that mining out the dirt, so there is a chasm between corruption and dirt, is ineffective, and corruption will still spread.
Answer: what i do is box the corruption off by putting  stone bricks around it 1 layer will do and there is a contained biome, corrupted seeds can make a corruption biome. You can also make other artificial biomes like snow by putting snow 7 blocks deep and 10 blocks wide, you can tell because the music changes, meteorite biomes can be made the same way just not jungle or normal biomes.

How does corruption spread?


Unable to install Ubuntu. Cursor blinking on black screen

Question: I have burnt Ubuntu ISO to a USB. When I boot from it, my laptop shows a black screen with a cursor blinking on top-left. This cursor keeps blinking endlessly. I left it overnight once to confirm that it doesn't change. I tried installing Ubuntu in another laptop after this incident with same USB and I was successful in doing so. This blinking cursor appears as soon as I choose the pen drive from Boot Menu or if it is at the top in Boot Order in BIOS. I have tried both 32 and 64 bit versions. If I remove the pen drive and boot from hard drive, Windows boots up perfectly. I was able to burn Windows ISO to this USB and install it successfully.
What is the solution to this? The entire thing happens just after booting from USB (even before anything related to Ubuntu would show up).
Wubi is an option which I am trying currently but it is only a temporary fix as it supports only upto 30 GB hard drive. I want to completely remove Windows.
The Ubuntu version I have tried is 14.04 LTS (32 and 64 bits). I have tried booting from all USB Ports.
Laptop is HP Pavilion i5.
Comment: Did you use the same Live USB on the computer that didn't work as on the computer that did?
Comment: @NBCKLY Yes. Added this info in the question itself. Forgot earlier.
Comment: If newer HP with i5, it is UEFI. Wubi does not work on UEFI systems with gpt partitioning. But if you reinstalled Windows in BIOS mode, it converted to BIOS with MBR(msdos) partitioning and did it incorrectly. Post this from terminal in live installer if you can boot. `sudo parted -l` If you only get black screen http://askubuntu.com/questions/162075/my-computer-boots-to-a-black-screen-what-options-do-i-have-to-fix-it Shows BIOS screens first, if UEFI you need grub menu and edit grub's linux line.
Answer: Sounds like your BIOS is hawing trouble booting from USB.
Check if a new version of BIOS is available and upgrade it.
Or get somewhere a USB-SATA/ATA adapter and then:
a) connect to the laptop a DVD drive and try booting from it.
b) pull the hard drive from the laptop, connect it to some other PC and install Ubuntu there.


how i can get numbers related with my account sid - PHP

Question: i was wondering if possible to get numbers related with my account with using php
<code>require_once 'library/Twilio/autoload.php'
use Twilio\Rest\Client

account_sid ='AC5xxx'
auth_token ='896xxx'
</code>
what else ?
any help please ?
Answer: Twilio evangelist here.
Check out the docs for Reading multiple IncomingPhoneNumber resources.
It includes this sample code:
<code>// Find your Account Sid and Auth Token at twilio.com/console
$sid    = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token  = "your_auth_token";
$twilio = new Client($sid, $token);

$incomingPhoneNumbers = $twilio->incomingPhoneNumbers
                           ->read();

foreach ($incomingPhoneNumbers as $record) {
    print($record->sid);
}
</code>
Hope that helps.
Comment: that's really helpful thank you , i have another probleme https://stackoverflow.com/questions/53299011/twilio-why-i-get-in-call-status-is-in-progress-also-completed-and-my-phone-not check it please


Conceptually what happens to a php array if all its elements are unset?

Question: Conceptually what happens to an array that has all of its elements unset? Please see the below  code for and example:
$ourArray = array(
    "1",
    "2",
    "3",
    "4"
);

foreach($ourArray as $key => $value){
    unset($ourArray[$key])
}

In this case is the entire array considered unset? Or is the array considered empty?
Would $ourArray == array() or null?
Comment: Havde you tried `var_dump()`ing it?
Comment: Try var_dump() when ever you have to debug PHP script. In case of your question the element simply gets deleted.
Comment: The var_dump() returns an empty array. That would indicate that the element exists and is not itself unset.
Answer: The unset() method destroys the variable passed.
So passing all the array keys unset() destroys them (not the array) and leaves the actual array empty.
1. Unsetting all the elements
So doing this will result in an empty $array
foreach ($array as $k => $value)
    unset($array[$k];

var_dump($array) //array {}

2. Unsetting the whole array
However passing the whole array to the unset() method will destroy the whole array and will will result in $array to be NULL
unset($array)

var_dump($array) // NULL

Answer: The keys are not shuffled or renumbered. The unset() key is simply removed and the others remain. So the array still exists, only the element gets deleted. Yes, and the array will remain.
Answer: It should be an array without any values in it. So technically it's the same as array()
Answer: <?php
  $ourArray = array(
    "1",
    "2",
    "3",
    "4"
);

foreach($ourArray as $key => $value){
    unset($ourArray[$key]);
}
var_dump($ourArray);

?>

output
array(0) { }

Answer:
In this case is the entire array considered unset?

No

Or is the array considered empty?

Yes
By the way you can try out your own example with these testcases
<?php

echo isset($ourArray)?1:0; // "prints" 0 since array doesn't contain anything
echo empty($ourArray)?1:0; // "prints" 1 since elements are not there !

$ourArray = array(
    "1",
    "2",
    "3",
    "4"
);
echo empty($ourArray)?1:0; // "prints" 0 since elements are there !

foreach($ourArray as $key => $value){
    unset($ourArray[$key]);
}

echo isset($ourArray)?1:0; // "prints" 1 since the array is set , only the elements are emptied
echo empty($ourArray)?1:0; // "prints" 1 since the array elements are empty

Comment: This is helpful, thank you. I will logic test based on the array being  considered empty. This will give the results I need.


How do I properly place a mine?

Question: I've expanded my city to the other side of the river, where there's a mountain. I assumed I would be able to build a mine on this mountain, but I cannot find a location around the mountain in which each square of my mine is green (there's always at least one red square). How do I properly place a mine (i.e. what are the placement requirements)? Is there a way I can force the terrain to accept a mine at a given location?
Answer: Here's the footprint of the mine's placement, per Banished-Wiki:

Legend:

Tile - Green Arrow: The front of the mine.  You can place a path here.
Tile - Green Space: This land must be relatively flat.
Tile - Brown Space: This land must be part of the mountainside.

As of this posting there is no terrain editor and the game is pretty good about telling you where you can and place structures (as you've indicated), so it may just be the case that you won't be able to use that location.  Is this a lone, done-shaped mountain you've found?
In my experience, I've had trouble with these (unless they're sufficiently large) as well as mountain ridges with a very convex outline.  Try finding a relatively linear mountainside instead?

How do I properly place a mine?


Realtek RTL8723BU on Ubuntu 18.04.3

Question: I've bought a laptop with Realtek rtl8723bu wifi adapter. Wifi works slowly and with weak signal compared to windows. I've search on the net and there are some solutions that download a driver from github, but none of them worked for me (I get an error since the fist step). What could I do? Thanks a lot.
I've followed these steps:
1st Step:
sudo apt install build-essential dkms
sudo apt install git
git clone https://github.com/lwfinger/rtl8723bu.git
sudo apt install libelf-dev

2nd Step:
sudo -i
echo blacklist rtl8xxxu >> /etc/modprobe.d/blacklist.conf
exit

This ensured that the old driver was not be used for my device. In my case the problematic driver was rtl8xxxu. So I black listed it.
3rd Step: Now I disabled a line in the makefile of the new driver, because without this hack, two instances of the wireless chipset was shown in Network Manager
cd rtl8723bu
nano Makefile

Go down to line 21 and change this line:
EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE

To comment it out, like this:
#EXTRA_CFLAGS += -DCONFIG_CONCURRENT_MODE

Save (Ctrl+o followed by Enter) and exit (Ctrl+x) the text editor.
4th Step: Now build and install the driver:
source dkms.conf
sudo mkdir /usr/src/$PACKAGE_NAME-$PACKAGE_VERSION
sudo cp -r core hal include os_dep platform dkms.conf Makefile rtl8723b_fw.bin /usr/src/$PACKAGE_NAME-$PACKAGE_VERSION
sudo dkms add $PACKAGE_NAME/$PACKAGE_VERSION
sudo dkms autoinstall $PACKAGE_NAME/$PACKAGE_VERSION

5th Step: Finally, install the compiled module with this command:
make
sudo make install

But I can't dkms fail on fist step. Also I wonder if that's a secure thing to do.
Comment: You need to post the steps you are trying and errors that you get.
Comment: You can't do `make install` and `dkms` at the same time. And what do you mean by "dkms fail on fist step"?
Answer: Works fine for me. No build errors.
Tested it in VM with Ubuntu 18.04LTS.
I did all steps except make and make install, which are not needed and must not be done with DKMS.
make + make install are for manual installation only if you do not use DKMS. Then you have to do make + make install every time you install new kernel or you have no driver with your new kernel. That is why DKMS was inveted - so you do not have to. Everything is automatic with DKMS.
My build log, no errors:
$ sudo dkms autoinstall $PACKAGE_NAME/$PACKAGE_VERSION

Kernel preparation unnecessary for this kernel.  Skipping...

Building module:
cleaning build area...
make -j2 KERNELRELEASE=4.15.0-70-generic -C /lib/modules/4.15.0-70-generic/build M=/var/lib/dkms/rtl8723bu/22.214.171.124_12942.20141204_BTCOEX20140507-4E40/build............
cleaning build area...

DKMS: build completed.

rtl8723bu.ko:
Running module version sanity check.
 - Original module
   - No original module exists within this kernel
 - Installation
   - Installing to /lib/modules/4.15.0-70-generic/updates/dkms/

depmod...

DKMS: install completed.

If you did make install, then you have to clean it up before trying again.
Try that (replace /path/to with real path):
cd /path/to/rtl8723bu
sudo make uninstall

And then try again without make and make install
If you have not done anything else then you probably only need those two lines from 4th step:
source dkms.conf
sudo dkms autoinstall $PACKAGE_NAME/$PACKAGE_VERSION

Realtek RTL8723BU on Ubuntu 18.04.3


Box disappear, when clicking elsewhere on the document? (jQuery)

Question: I'm showing a hidden box with jQuery on link-click. Now the box disappears when clicking the link again, but how to make it so it kinda "loses focus" and hides. SO, when user click somewhere on document (but not the box itself), it disappears.
Suggestions?
Martti Laine
Answer: A click on the box will bubble to the document, so catching a click there will always close it.  To prevent this, a click inside the box will be caught/stopped, a click outside won't, causing it to bubble up and close.  All the code you need to do this is:
<code>$(document).click(function() {
  $("#myBox").hide();
});

$("#myBox").click(function(e) {
  e.stopPropogation();
});
</code>
...


Xcode plugin load resources

Question: I am writing a screensaver for OSX using Xcode 7.3. This screensaver will show an image of a ball bouncing around the screen. However, I am currently unable to load the image from the bundle.
This is how I load the image in the ScreenSaverView: NSImage *img = [NSImage imageNamed:"ball.png"]; and img turns out to be nil.
The image is definitely added to the bundle: it is added to "Copy Bundle Resources" for the screensaver target; it is in Ball.saver/Contents/Resources.
I tried to print out the resource path with [[NSBundle mainBundle] resourcePath] and it prints out the path of the System Preferences /Applications/System Preferences.app/Contents/Resources, which is understandable since the screensaver is only a system plugin. My question is, how do I load the resources from the screensaver's bundle?
Answer: Turns out, for plugins, you have to find the particular bundle of the plug in and not just use the default bundle, which seems to be the main app's bundle. This is the final solution:
NSBundle *bundle = [NSBundle bundleWithIdentifier:bundleId]
NSString *filePath = [bundle pathForResource:imageName ofType:imageType];
NSImage *image = [[NSImage alloc] initWithContentsOfFile:filePath];

Xcode plugin load resources


Radio Button form to change variables on PHP file

Question: Basically what I'm trying to achieve is a simple PHP on/off where I have PHP code which is set to 0 but have the ability to change it to a 1 or 0 from a form.
 PHP file| $settingon = 1 //1 for active, 0 for inactive
HTML file| <form action="php/settingfile.php">
       <input type="radio" name="settingon" value="1"> Active

       <input type="radio" name="settingon" value="0"> Inactive

       <button type="submit">Save Settings</button>
       </form>

Comment: So what's the problem?
Comment: @s3nzoM when i submit it i want it to change the $settingon to a 1 or 0 depending on the radio selected
Answer: If you want to disable the input:
<form action="php/settingfile.php">
    <input type="radio" name="settingon" <?php $settingon? "":"disabled" ?>> Active

    <button type="submit">Save Settings</button>
</form>

or create a class that displays the input as you want:
<form action="php/settingfile.php">
    <input type="radio" name="settingon" class="<?php $settingon? "active":"inactive" ?>"> Active

    <button type="submit">Save Settings</button>
</form>


How to add/remove classes to a button element (on click) based on the number of sets of other elements visible on a page?

Question: I've gotten lots of help looking at other people's questions and answers on here over the years but I have finally run into a scenario that's pretty unique from other sites I've built (mostly Wordpress) and could use some help with the Jquery part. I've got everything working the way it should on the front-end BUT the Jquery is ugly and not scalable (as will be obvious when you look at it).
Here's a fiddle showing the working prototype:
https://jsfiddle.net/shellygraham/fnhv53me/
Background: On the front-end the goal is to have a typical loop with four posts visible on page load and the rest hidden, there's a button "Load More Work" below the posts that when clicked shows four more posts and so on and so forth for as many sets of four posts within the loop. Once there aren't anymore posts left to load (final one, two, three or four are displayed) the "Load More Work" button is removed/hidden. It's just like a lot of AJAX "load more" style portfolios, etc. except I can't go that route because my client wants all content loaded immediately for SEO purposes. Therefore I have to hide and show posts instead of loading more posts when the button is clicked.
As previously mentioned, it works fine on the front end but the scalable/lean Jquery part for showing and hiding the button outputted for each set of four is a little over my head.
On a possibly relevant side note: This is a custom Wordpress build and because I'm using Foundation 6 framework grid (specifically, the XY Grid) I can't wrap each set of four posts in a container div without breaking up my layout (each post is six columns) and therefore this is my loop:

            <?php $counter = 0;
                  $button  = 1;

                while ( have_posts() ) : the_post(); ?>

                    <?php post_thumbnail(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php the_excerpt(); ?>

                <?php $counter++; ?>

                <?php if( $counter % 4 == 0) { ?>

                    <div class="grid-container button-container not-shown set-<?php echo $button; ?>">

                            Load More Work

                    <?php $button++; ?>

                <?php } ?>

            <?php endwhile; ?>

*I don't have a problem with the loop itself but I posted it for reference. The problem is with my crappy Jquery code.
Anyway, the PHP loop outputs a markup that looks like this (inner content bits abridged for brevity):

            stuff

            stuff

            stuff

            stuff

                Load More Work

            stuff

            stuff

            stuff

            stuff

                Load More Work

            stuff

            stuff

I want to stress that there's no way around this markup due to the way the grid works. Solutions have to work around it. Sad but true.
Here's the pertinent css (adapted from scss):
.work-container.not-shown { display: none; }
.work-container.show { display: block; }
.button-container.not-shown { display: none; }
.button-container.active { display: inline; }

To achieve the "Load More" button behavior of showing on page load after the first four posts (only if there are more than four posts), to display the next set of posts on click and also hide the previous set's button and display the current set's button, until there aren't any more posts to display here is my jquery:
// Load More functionality for tax archive page
size_li = $('.work-container').size();
x=4;
if (size_li > 4 ) {
        $('.button-container.set-1').addClass('active');
        $('.button-container.set-1').removeClass('not-shown');
    }
$('.work-container:lt('+x+')').addClass('show');
$('.work-container:lt('+x+')').removeClass('not-shown');

$('.button-container.set-1 .show-more-work').click(function (e) {
    e.preventDefault();

        $('.button-container.set-1').removeClass('active');
        $('.button-container.set-1').addClass('not-shown');

        $('.button-container.set-2').addClass('active');
        $('.button-container.set-2').removeClass('not-shown');

    x= (x+4 <= size_li) ? x+4 : size_li;
    $('.work-container:lt('+x+')').addClass('show');
    $('.work-container:lt('+x+')').removeClass('not-shown');
});

$('.button-container.set-2 .show-more-work').click(function (e) {
    e.preventDefault();

        $('.button-container.set-2').removeClass('active');
        $('.button-container.set-2').addClass('not-shown');

        $('.button-container.set-3').addClass('active');
        $('.button-container.set-3').removeClass('not-shown');

    x= (x+4 <= size_li) ? x+4 : size_li;
    $('.work-container:lt('+x+')').addClass('show');
    $('.work-container:lt('+x+')').removeClass('not-shown');
});

$('.button-container.set-3 .show-more-work').click(function (e) {
    e.preventDefault();

        $('.button-container.set-3').removeClass('active');
        $('.button-container.set-3').addClass('not-shown');

        $('.button-container.set-4').addClass('active');
        $('.button-container.set-4').removeClass('not-shown');

    x= (x+4 <= size_li) ? x+4 : size_li;
    $('.work-container:lt('+x+')').addClass('show');
    $('.work-container:lt('+x+')').removeClass('not-shown');
});

$('.button-container.set-4 .show-more-work').click(function (e) {
    e.preventDefault();

        $('.button-container.set-4').removeClass('active');
        $('.button-container.set-4').addClass('not-shown');

        $('.button-container.set-5').addClass('active');
        $('.button-container.set-5').removeClass('not-shown');

    x= (x+4 <= size_li) ? x+4 : size_li;
    $('.work-container:lt('+x+')').addClass('show');
    $('.work-container:lt('+x+')').removeClass('not-shown');
});

$('.button-container.set-5 .show-more-work').click(function (e) {
    e.preventDefault();

        $('.button-container.set-5').removeClass('active');
        $('.button-container.set-5').addClass('not-shown');

        $('.button-container.set-6').addClass('active');
        $('.button-container.set-6').removeClass('not-shown');

    x= (x+4 <= size_li) ? x+4 : size_li;
    $('.work-container:lt('+x+')').addClass('show');
    $('.work-container:lt('+x+')').removeClass('not-shown');
});

$('.button-container.set-6 .show-more-work').click(function (e) {
    e.preventDefault();

        $('.button-container.set-6').removeClass('active');
        $('.button-container.set-6').addClass('not-shown');

        $('.button-container.set-7').addClass('active');
        $('.button-container.set-7').removeClass('not-shown');

    x= (x+4 <= size_li) ? x+4 : size_li;
    $('.work-container:lt('+x+')').addClass('show');
    $('.work-container:lt('+x+')').removeClass('not-shown');
});

$('.button-container.set-7 .show-more-work').click(function (e) {
    e.preventDefault();

        $('.button-container.set-7').removeClass('active');
        $('.button-container.set-7').addClass('not-shown');

        $('.button-container.set-8').addClass('active');
        $('.button-container.set-8').removeClass('not-shown');

    x= (x+4 <= size_li) ? x+4 : size_li;
    $('.work-container:lt('+x+')').addClass('show');
    $('.work-container:lt('+x+')').removeClass('not-shown');
});

I'm sure it's pretty obvious where my shortcomings with Jquery are - I can't figure out how to make the button click for each set add and remove classes without reiterating the same code for each ".button-container.set-[number]". I have a hunch there's some way to do it more elegantly using the modulus operator but I'm a total novice with that. I know there's a better way to do this but I've had no luck finding it on here or via Google.
Any help would be greatly appreciated!! Please let me know if you need more information or something I said doesn't make sense. Just looking at the fiddle probably makes more sense than how I've explained the situation.
Comment: A couple things. 1) Most people aren't going to help you with this. It's a mountain of text to read. I suggest paring it down as much as possible while still articulating your issue. 2) Your fiddle doesn't work. 3) If I've understood your mountain of text correctly :-), I think you need to take a look at jQuery's like selector `$("[class^=main]")` http://api.jquery.com/category/selectors/
Comment: @JamesHill Thanks for the feedback. I know it's a lot but I see answers that misinterpret the question all the time on here so I was trying to be thorough. Can you re-try the fiddle? I just re-ran it and it works the way it should.
Answer: First, add a data attribute to your .button-container that will instruct the javascript on what it's activating.
replace:

with:

new javascript:
size_li = $('.work-container').size();
x=4;
if (size_li > 4 ) {
        $('.button-container.set-1').addClass('active');
        $('.button-container.set-1').removeClass('not-shown');
    }
$('.work-container:lt('+x+')').addClass('show');
$('.work-container:lt('+x+')').removeClass('not-shown');

$('.show-more-work').each(function(i, $tag) {
  $tag.click(function(e) {
    e.preventDefault();

    // deactivate, hide everything
      $('.button-container').removeClass('active').addClass('not-shown');

    // activate current class
      $($tag.data('activate')).addClass('active').removeClass('not-shown');

    x= (x+4 <= size_li) ? x+4 : size_li;
    $('.work-container:lt('+x+')').addClass('show');
    $('.work-container:lt('+x+')').removeClass('not-shown');
  })
})

$tag.click(... might need to be $($tag).click(...
I'd suggest trying to consolidate .active and .not-shown into a single class so you don't have to juggle so much around.


The import com.google.api.client cannot be resolved in Eclipse

Question: I am getting this error:
The import com.google.api.client cannot be resolved
My configuration is below:
Project Properties - Android:

Java Build Path:

I still get the error below even after restarting Eclipse.

Can anyone help? Thx :D
Comment: Eclipse sometimes is... Did you restart it?
Comment: @m0skit0 Yes, I've restarted for several times... Still not working
Answer: You haven't added the client libraries in your project.
http://code.google.com/p/google-api-java-client/wiki/Setup.
You will get the google-api-java-client-1.14.1-beta.zip file at the above link.
Save those jar files in your libs folder of Android project.
Answer: Add this:

<dependency>
    <groupId>com.google.api-client</groupId>
    <artifactId>google-api-client</artifactId>
    <version>1.23.0</version>
</dependency>

<dependency>
    <groupId>com.google.oauth-client</groupId>
    <artifactId>google-oauth-client-jetty</artifactId>
    <version>1.23.0</version>
</dependency>

Answer: If you are trying to add a Google API to an Android app as I was, and if you are using Eclipse, the following is very easy.
Right-click on a project, select "Google > Add Google APIs...", select
the Google API you need from the list of available Google APIs,
click Finish, and it will automatically download the API client library
From https://code.google.com/p/google-api-java-client/wiki/Setup


Angular Service Undefined

Question: In the code snippet below, I'm getting "ReferenceError: 'ShoppingListService' is undefined".  I can't see what the error might be, been banging my head against it and searched for a while now, anyone have clues?
var ShoppingListApp = angular.module('ShoppingListApp', [])
ShoppingListApp.factory('ShoppingListService', ['$http', function ($http) {
    var ShoppingListService = {};
    ShoppingListService.getListItems = function () {
        return $http.get('/ShoppingList/GetListItems');
    };
    return ShoppingListService;
}]);

ShoppingListApp.controller('ShoppingListController', function ($scope) {
getItems();
function getItems() {
    ShoppingListService.getListItems() //Error occurs here
    .success(function (shoppingItems) {
        $scope.items = shoppingItems;
        console.log($scope.items);
    })
.[removed for brevity].

The error occurs in the area indicated above.  Angular.js version 1.4.9.
Answer: In your controller definition ShoppingListController you just have one injectable called $scope you need to add a second one called  ShoppingListService.
ShoppingListApp
  .controller('ShoppingListController', ShoppingListController);

ShoppingListController.$inject = ['$scope', 'ShoppingListService'];
function ShoppingListController($scope, ShoppingListService) {

    getItems();

    function getItems() {
        ShoppingListService
          .getListItems() //Error occurs here
          .success(onSuccess);
    }

    function onSuccess(shoppingItems) {
        $scope.items = shoppingItems;
        console.log($scope.items);
    }
    //other code
}

Comment: Thank you, worked perfectly!  Though it works without the ShoppingListController.$inject = ['$scope', 'ShoppingListService']; line.  If you don't mind, what's the purpose of that?
Comment: It makes your code minification safe.  It does the same thing as `ShoppingListApp.factory('ShoppingListService', ['$http', function ($http){}]`.  Its just easier to read.   @user1205100

Angular Service Undefined


Vapor barrier under shed floor

Question: I'm purchasing a shed that I intend to use as a home gym.  On delivery, the shed will be uninsulated, aside from the roof which is metal with a bubble underlayment.  The floor is a single layer of plywood, so I will likely beef that up with an additional course of plywood/OSB to accommodate the weight of equipment.
I'm going to doing some site prep this week, and plan on putting down a bed of clear gravel.  The shed will sit on part of an asphalt drive, and part lawn, so I play on making a level bed of gravel.  We're in Ontario, so climate sees a lot of snow and has relatively warm summer.  I will probably end up insulating the rest of the shed in the future.  It will not be continually heated or AC'ed, but probably will have a bit of heating/cooling it's in use and we're exercising in it during certain seasons.
My question is about vapor barrier/house wrap for the floor.  The layers of the shed from added floor to ground will be:

A.  added floor (plywood or OSB).
B.  "factory" floor (SPF plywood, assuming pressure treated).
C.  sleepers the shed sits on, this will be a 4-6" air gap.
D.  gravel
E.  bare ground/pavement

If I was going to add vapour barrier (if advisable), between which layers would I situate it?  Getting under the shed before deliver to put a vapour barrier been B&C is unlikely.
Is a moisture transmitting house wrap thing (like Tyvek) more appropriate for this use case?
Comment: Update a few months later:

- Used T&G (waxed on one side) OSB above the factory floor, and the 3/4" rubber stall mats over that, with one exception of the lifting platform which 3/4" plywood.  The floor is not warm by any stretch of the imagination but seems to be fine.

I suspect the majority of the humidity in the structure at the moment is coming from the pine board walls, but I plan on installing insulation and vapor barrier there soon.
Answer: This is a subjective question since it's outside the realm of standard building envelope scenarios. I've built two such sheds with similar structure spanning over 20 years. Both had house wrap between the floor framing and the untreated plywood with the intention of minimizing moisture coming up from underneath. They did fine, with the only degradation being where wind-driven rain slipped past the roll-up door.
Your situation is a bit different, however. My advice is to not bother. House wrap is intended as a breathable liquid water barrier. It doesn't do much at all sandwiched between sheets of subfloor, and your treated plywood layer does at least as much to stifle moisture transfer anyway.
I suggest a couple coats of polyurethane on your floor, assuming you don't have plans to install finish flooring. This will obviously prevent stains, but will also provide stability to the strands in the OSB if you go that route.
Answer: I'm in the exact same situation. I put some Kimberly Clark Block It wrap between the factory floor and the 3/4 inch tongue and groove subfloor. I set the printed side facing down toward the elements.  However the original floor was sagging between the sleepers so that had to be addressed before the wrap went down. I think installing it might be overkill but can do no harm.
Comment: It _can_ do harm--to your wallet and to the planet. You haven't provided any justification for installing it.

Vapor barrier under shed floor


Use map with struct key cause crash

Question: I create a simple map use struct as key but crash when running.
Could you point out the issue? Big thanks.
The code is crash when putting item 3rd.
...
typedef struct pmjob
{
    std::string jobId;
    std::string jobGroup;
    int reportingPeriod;
    int compressionType;
    bool operator == (const struct pmjob &other) const
    {
        return ((jobGroup.compare(other.jobGroup) == 0) && (reportingPeriod == other.reportingPeriod));
    }

    bool operator < (const struct pmjob &other) const
    {
        if (reportingPeriod < other.reportingPeriod)
        {
            if(jobGroup.compare(other.jobGroup) == 0)
                return false;
        }
        return true;
        //return ((reportingPeriod < other.reportingPeriod) || (jobGroup.compare(other.jobGroup)));
    }
}PMJob;

typedef std::map<PMJob, int> PMJobMap;
PMJobMap List;
typedef std::pair<PMJob, int> PMJobPair;

Answer: Your comparator is invalid.
bool operator < (const struct pmjob &other) const
It doesn't provide strict weak ordering.
Example of valid comparator:
bool operator < (const struct pmjob &other) const
{
    // first compare most important member
    if (reportingPeriod < other.reportingPeriod) {
        return false;
    }
    if (other.reportingPeriod < reportingPeriod) {
        return true;
    }

    // less important member
    if (compressionType < other.compressionType) {
        return false;
    }
    if (other.compressionType < compressionType) {
        return true;
    }

    if (jobId < other.jobId) {
        return false;
    }
    if (other.jobId < jobId) {
        return true;
    }

    if (jobGroup < other.jobGroup) {
        return false;
    }
    if (other.jobGroup < jobGroup) {
        return true;
    }

    return false;
}

or using std::tie:
bool operator < (const struct pmjob &other) const
{
    return std::tie(jobId, jobGroup, reportingPeriod, compressionType) <
        std::tie(other.jobId, other.jobGroup, other.reportingPeriod, other.compressionType);
}

Comment: Could you suggest one way?
Comment: Thanks @ikleschenkov. You mean we must use compare all string in struct ? I will check it. But how about if I just only use reportingPeriod and jobGroup as key. I mean I don't care jobId and compressionType.
Comment: @doccocobai then compare only `jobId` and `compressionType` (use only them in expression).

Use map with struct key cause crash


Why is `slot.assignedNodes({flatten: true})` not detecting the default `` in the slot?

Question: I just spent many minutes trying to debug this issue. I found no source documenting this behavior ― maybe I missed them if they do exist ― and I decided to write this here in case someone else faces the same issue.
A Web Component I built has a <slot> element with a default
 inside of it:
<slot name="timer">

</slot>

When I tried to update the
 using innerHTML nothing happened. It is as if the
 doesn't exist. Here's how I tried to access the
:
this.timerSlot = this.shadowRoot.querySelector('slot[name=timer]');
let div = this.timerSlot.assignedNodes({flatten: true})[0];
div.innerHTML = "SOME TEXTE";

But nothing is happening. What's wrong with this code?
Answer: DOM nodes are not the same as DOM elements

HelloWeb ComponentsWorld

Elements p and a are a sub-set of all Nodes

So assignedNodes gives you all 5 Nodes (href in the image is an attribute)
and assignedElements gives you the 2 Elements you are after
MDN Documentation:
For documentation always use MDN (although MDN isn't 100% correct either)

https://developer.mozilla.org/en-US/docs/Web/API/HTMLSlotElement/assignedNodes
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSlotElement/assignedElements
Comment: Thanks for sharing this! I never knew about the difference between a node and an element. That explains it perfectly!
Answer: So here's what's wrong with the code above.
For some reason, the
 I created was not assigned the index 0 in the array returned by assignNodes(). It was in fact in case number one. When console.log()ed the return value of this.timerSlot.assignedNodes({flatten: true}) it came as something like this Array(3) [ #text, div.rp__timer, #text ] in both Chrome and Firefox.
It turns out the new lines I added for better readability around the
 in the HTML file were not ignored as I believed they would.
After updating my code into a one-line configuration, i.e. <slot name="timer">

</slot>, the problem disappeared and the code did what it was expected to do.
Now, I don't know it this is a feature or a bug. But since it was present in both Chrome and Firefox I assume it maybe the former. Either way, I was unable to find in the available documentation any mention of it.
I hope you'd find this useful.


How to find the value of gain K at which the root locus intersects with the imaginary axis

Question: Take a look at this closed loop system
$$
T(s) = \frac{-K(s+1)^2}{(1-K)s^2 + 2(1-K)s + (2-K)}
$$
The Routh Table is
$$
\begin{bmatrix}
s^2 & (1-K) & (2-K) \\
s^1 & 2(1-K) & 0 \\
s^0 &(2-K) & 0
\end{bmatrix}
$$
Now we search for a complete row of zeros that yields the possibility for imaginary axis roots. From the table, there are two values of $K$ namely 1,2 and both are positive. The only thing I can conclude from this table is the system is unstable $1<K<2$ but I can't determine the value of K at which the root locus intersects with the imaginary axis. Any suggestion how one can use Routh table in this case? Is this a case where Rough table fails?
Answer: No need for Routh table because from
$$
(1-K)s^2+2(1-K)s+K-2=0
$$
we have
$$
s = \frac{-(K-1)\pm\sqrt{K-1}}{K-1}
$$
or calling $\zeta = K-1$ and assuming that $K > 0$
$$
s = \frac{-\zeta\pm\sqrt{\zeta}}{\zeta}
$$
and for $-1 < \zeta < 0$  both complex roots are inside the negative complex semiplane being stable. For $0\lt \zeta \lt 1$ the denominator has one root is inside the positive complex semiplane and the closed loop is unstable. Finally, for $1 < \zeta < \infty$ the system is stable.
Comment: Thank you for the answer. I'm asking if Routh table fails in this example. I can draw the conclusion about the stability using different methods.


Wait for process with name to spawn in Bash

Question: I want to write a Bash script that runs in a background, waiting for a command to spawn.
Suppose I ran script.sh which waits for ls. After I run ls, it should trigger actions?
Answer: You can use pgrep to create a while loop like this:
#!/bin/bash

# Wait for particular process to run
while ! pgrep "process-name " > /dev/null; do

    # Set optional delay
    sleep .1

done

# Do something when the process has started
your-commands-here

You need to adjust the delay, so that it "catches" the process you run. This of course works best if it should detect a service that doesn't stop again, but this will work for any command that takes longer time to finish than the delay you have set (ls is a bad example, since it only takes milliseconds to finish the process).
Also see this post on Unix and Linux.


Incredibuild not working

Question: I am having Incredibuild for building Visual Studio Project but its not working stating warning message ,

Warning: FORCE_NO_INCREDIBUILD is set. Build process will be time consuming unless you remove it.

I googled FORCE_NO_INCREDIBUILD but not getting a single result.
Please get me rid of that.
Thanks,
Amit.
Comment: You probably want to accept a few answers to other questions before this.
Answer: FORCE_NO_INCREDIBUILD is a custom variable which is not being related to Visual Studio and Incredibuild at all.
I commented out with it form batch script. Now incredibuild is working....:)
Thanks Amit

Incredibuild not working


How can I use "Propose Tag wiki" without taking the risk of a rejected edit?

Question: A few things happened to me the past few days, while submitting suggested edits of wiki tags and/or wiki excerpts, for existing tags (for which I do not have the privilege to create them; at best I can only "suggest" such tags to be created):

Rejected tag wiki edit for aliases, a tag that got deleted AFTER I submitted my suggestion.
Rejected tag wiki excerpt edit for aliases, a tag that got deleted AFTER I submitted my suggestion.
Rejected tag wiki edit for charts.module, a tag that got deleted AFTER I submitted my suggestion, and after 1 approve followed by 1 reject of that suggested edit was performed. So the actual review process for that specific suggested edit seems like interrupted, since a final reviewer probably never got a chance to look at that suggested edit.
Rejected tag wiki edit for remote and Rejected tag wiki excerpt edit for remote, a tag that got deleted AFTER I submitted my suggestion, and after 1 approve was given. So the actual review process for that specific suggested edit seems like either interrupted or still waiting additional reviews.

For the sake of understanding: I do not question in any way the specific reviewers, or their reasons for rejection (I do consider all of them as reviewers that I respect). So let that not be the reason for any potential (anoymous?) downvotes of this question please, or my own answer I added to it (if you've other reasons to downvote: no problem).
However, something seems broken in the review process of suggested edits for wiki tags and / or excerpts. Why do "I" get a "rejected edit" for each of these events described above?
To phrase it another way:

"I" invest time in researching wiki tags that seem to be in use (at least 1 question had these tags, some had multiple questions tagged with it).
"I" invest time to submit the suggested edit.
That suggestion seems to trigger something at 1 or more reviewers like "oeps, that tag should not be there".
And instead of "me" being rewarded for what I suggested, I get punished by a rejected edit.

To further proof my point, please consider existing tagpassword-reset, which:

has 1 question (only!) that is using the tag.
the actual question was asked by ... one of the reviewers involved in one of the reviews mentioned above.
for which NO tag wiki or wiki excerpt exists.

My question: what are "my" options to contribute to this specific tag wiki / excerpt, without taking the risk of another rejected edit?
Comment: Tag wiki edits are dangerous. They  often get rejected, and sometimes for non-obvious reasons.  I've simply stopped doing tag wiki edits. They are simply too often and too easily rejected.
Answer: Suggested edits for wikis relative to tags that are removed from all questions using them, or to tags that get merged, are automatically removed from the review queue simply for the fact it doesn't make sense to review a suggested edit for a tag wiki that is then removed. I assume they are automatically rejected on the assumption that suggesting an edit for a tag that should not be used would not be an action users should take (i.e., it was a not necessary/correct action).
As for the rejected edits you are taking as examples:

aliases was never used for Drush aliases only; I found questions using it for different purposes, including domain aliases.
There is no consensus about using charts.module when there is already charts.
password-reset was used only by a question asked from a user who also self-answered his question, well knowing he was going to suggest a specific module, for which the tag was created. A tag is used for the question, not because an answer mentions a specific module.

As general guideline:

Don't suggest a tag wiki edit for tags that aren't used from at least 10 questions. A single question using the tag doesn't preserve the tag from the automatic deletion, nor it is enough to be sure there is a consensus about using the tag or how the tag should be used.
Before suggesting a tag wiki edit, be sure you understand the meaning given to the tag from the users who use it. In the case the tag has too many meanings, it is probable the tag needs to be removed or replace by two or more tags.
Answer: I think the solution (answer) is like so:
1) At a minimum:

do NOT allow tags to be deleted while a review process of a suggested edit for the tag wiki or wiki tag excerpt is ongoing.
if a tag gets deleted after the review process completed, then do NOT consider that as a rejected edit for the user who suggested an edit to it.

2) Ideally also:

find a way to compensate the user who triggered a review process of a tag that turned out to be obsolete (or something like that).
add an extra option to "flag a tag as potentially candidate for deletion" (similar to flagging a comment for moderation).

3) If perfect is not good enough:
Do not allow tags to be deleted, for as long as there is at least 1 other tag wiki or excerpt that still references it. That would have avoided that I needed to submit these 2 extra edits for the drush, edit I've suggested after the above mentioned tags got deleted:

Suggest removal of reference to remote in tag drush (with suggested edit comment = Remove reference to tag 'remote' which got deleted recently).
Suggest removal of reference to aliases in tag drush (with suggested edit comment = Remove reference to tag 'aliases' which got deleted recently).

I was lucky, these 2 extra edits got accepted. That were 2+2 easy points I gained, but maybe that's because I hinted the reviewers about that orphaned tag reference I suggested to be resolved? But before submitting these 2 extra edits, I actually doubted if they were not going to be clasified as "too minor, this user is trying to just gain some points by cutting an obviously related set of edits in multiple wiki edit iterations" (... and hence 2 more rejected edits!). Note: the real reason, for myself at least, why I did so in 2 iterations is because when I submitted the first wiki edit suggestion, I had not yet noticed that the 2nd tag had been deleted also ...


Divisibility: 2 3 5 7 13 on $n^{13}-n$

Question: I am doing these kinds of revision on my own. And I have read some of the similar posts here and learned some techniques in doing it. However, when I was doing this question, I have trouble figuring out the divisibility of $5$.
For 13, it is obvious that $n^{13} \equiv n( \text{mod} 13)$.
For 7, factorize as $n(n^6 + 1)(n^6-1)$. The second parenthesis is divisible by $7$ by the same theorem.
For 3, further factorization becomes $n(n^6+1)(n^2-1)(n^4+n^2+1)=(n^6+1)(n^3-n)(n^4+n^2+1)$. The middle part is divisible by $3$.
For 2, when n is odd, the outcome is even; when n is even, the outcome is even.
However, for 5, I am trying to find something like $n^5-n$ or $n^4-1$ in the factorization process. But I can't find it. My careless mistake?? Or this has a special method to duel with. Thank you.
Comment: We have [Euler's Theorem](https://en.wikipedia.org/wiki/Euler%27s_theorem) stating that $a^{\varphi(n)}\equiv 1\pmod{n}$. For $n=5$ we have $\varphi(5)=4$ and so $$n^{13}\equiv n^4\cdot n^4\cdot n^4\cdot n\equiv 1\cdot 1\cdot 1\cdot n\pmod5$$ whenever $n,5$ are coprime. For the cases where they are not, the result should be obvious already.
Comment: https://math.stackexchange.com/questions/596074/how-to-show-that-2730-mid-n13-n-forall-n-in-mathbbn
Answer: What you essentially need to note is Euler's theorem : if $a$  is coprime to $l$ then $a^{\phi(l)} \equiv 1 \mod l$. Taking to the power $k$, $k \in \mathbb N$ on both sides gives $a^{k\phi(l)} \equiv 1 \mod l$. .Multiplying by $a$, we get $a^{k\phi(l) + 1} \equiv a \mod l$.
Now, the question is : how do I show that $l = 2,3,5,7,13$ works? Somehow show that $13 = k\phi(x) + 1$ for some $k$ when $x = 2,3,5,7,13$. But, this is the same as showing that $13-1 = 12$ is a multiple of $\phi(x)$ when $x = 2,3,5,7,13$, which is true since $\phi(p) = p-1$ for $p$ prime, so $\phi(x)$ is respectively $1,2,4,6,12$ which is a set of factors of $12$. Therefore, by our extended Euler theorem , the result follows for all the primes i.e.$ a^{13} \equiv a \mod x$ for all these $x$.
puzzle 125 here contains another staggering example of the technique I used here. Note that $a^{13} - a$ is also a multiple of the product of all these primes we have mentioned, so it is a multiple of $2730$.

Divisibility: 2 3 5 7 13 on $n^{13}-n$


How can I glide longer?

Question: I want to glide longer but I don't know if I need the grappel accelerator and where I can get it? Any hints?
Answer: You should have the Accelerator from the very beginning, although you won't be able to use it until you leave Blackgate Prison.
The Grapple Accelerator works in exactly the same way as in Arkham City. Grapple to a ledge and double-tap X (PS3)/ A (Xbox 360)/ Space (PC) while your grapple is still pulling. It only works if you're pulling from a certain distance.
Comment: if no grapple anchor is near then diving for a bit using the shoulder buttons, RT on Xbox, then holding down on the left stick will make batman glide further.
Comment: How you go about unlocking it in `Arkham Origins` vs `Arkham City` is indeed different.  In `Arkham Origins` its simply unlocked and through the normal course of the guide your introduced to it.  In `Arkham City` it was actually an `unlocked` gadget enchancement.  Basically you unlocked the ability within 20 minutes of playing the game considering the intial time within `Blackgate Prison` is basically a tutorial on the `Free Flow Fighting System`
Answer: Too glide longer, just simply dive bomb and glide upwards over and over again. To grapnel accelerate just simply grapple onto a ledge and double tap A(X-Box), X(PlayStation), or space for computers.
Answer: Best way to glide longer is to alternate diving and gliding gently upwards. You can usually get almost back to the height before the dive on each cycle which allows you to go pretty far. Of course the accelerator is also helpful and as already noted is available from the start but is not necessary for long glides (such as those required by the achievement type things).

How can I glide longer?


Sproutcore + handlebars + jquery-ui - how to make a datepicker from an input generated by handlebars

Question: The problem is that the doc.ready fires before handlebar finish generating the inputs jquery ui needs to set the date picker on.
Is there a better event?
Answer: Here's some code that I used for jQuery Data Picker with my SC2 demo app (Chililog)
App.MyField = App.TextBoxView.extend(App.CriteriaFieldDataMixin, {
    valueBinding: 'App.pageController.fromDate',
    name: 'fromDate',
    placeholder: 'yyyy-mm-dd',
    disabledBinding: SC.Binding.from('App.pageController.isSearching').oneWay().bool(),

    /**
     * Attach date picker to text box
     */
    didInsertElement: function() {
      this._super();
      this.$().datepicker({ dateFormat: 'yy-mm-dd' });
    }
})

Use the didInsertElement event to attach the datepicker.  This event fires after the DOM element has been inserted.


TypeScript typing issue (marginally related to (P)React)

Question: [Edit: I've simplified my original question]
Let's assume I want to define UI components in exactly the following
way (the following lines shall not be changed in any way - any
solution that will change the following lines is frankly not a solution
I am looking for ... for example just writing render({ name: 'World' })
is not an option ... neither is the non-null assertion operator ...neither using currying or a builder pattern or something like a withDefaultProps helper function ... etc. ... these are just workarounds (yet easily working) for the actual problem below):
// please do not change anything in this code snippet

type HelloWorldProps = {
  name?: string
}

export default component<HelloWorldProps>({
  displayName: 'HelloWorld',
  defaultProps: { name: 'World' },

  render(props) {
    // the next line shall NOT throw a compile error
    // that props.name might be undefined
    return `HELLO ${props.name.toUpperCase()}`

    // [Edit] Please ignore that the function returns a string
    // and not a virtual element or whatever - this is not important here.
    // My question is about a TypeScript-only problem,
    // not about a React problem.

    // [Edit] As it has been caused some misunderstanding:
    // The type of argument `props` in the render function shall
    // basically be the original component props type plus (&) all
    // properties that are given in `defaultProps` shall be required now.
    // Those optional props that have no default value shall still
    // be optional. If ComponentType is the original type of the component
    // properties and the type of the `defaultProps` is D then
    // the type of the first argument in the render function shall
    // be: ComponentProps & D

     // [Edit] As it seems not to be 100% clear what I am looking for:
     // The problem is mainly because the function "component" depends basically
     // on two types: One is the type of the component props the other is
     // is the type of the default props. AFAIK it's currently only possible in
     // TypeScript to infer either both of them or none of them (or use
     // default types for the type variables - which is not very useful here
     // as the defaults are {}). But I only want to declare ONE type
     // (HelloWorldProps).
     // All workarounds that I know of are either to explictly declare both
     // types or split the single function "component" into two or more
     // functions - then you do not have that problem any more,
     // but then you have to change the syntax and that is exactly
     // what I do NOT want to do (a fact that is the most important
     // part of the  whole question):

     // [this is not the solution I am looking for]
     // export default component<HelloWorldProps>('HelloWorld')({
     //   defaultProps: {...},
     //   render(props) {...}
     // })

     // [this is not the solution I am looking for]
     // export default component<HelloWorldProps>('HelloWorld')
     //   .defaultProps({...})
     //   .render(props => ...) // `render` is the function component
     //                         // creator is this builder pattern

     // [this is not the solution I am looking for]
     // export default component<HelloWorldProps>({
     //   displayName: 'HelloWorld',
     //   render: withDefaultProps(defaultProps, props => { ... })
     // })

     // [this is not the solution I am looking for]
     // type HelloWorldProps = {...}
     // const defaultProps: Partial<HelloWorldProps> = {...}
     // export default component<HelloWorldProps, typeof defaultProps>({...})

     // [this is not the solution I am looking for]
     // return `HELLO ${props.name!.toUpperCase()}`

     // [this is not the solution I am looking for]
     // render(props: HelloWorldProps & typeof defaultProps) {...}

     // [this is not the solution I am looking for]
     // render({ name = 'HelloWorld' }) {...}
  }
})

How exactly do I have to type the function component and the type ComponentConfig to make
the above code work properly?
function component<...>(config: ComponentConfig<...>): any {
  ...
}

Please find a non-working (!) demo here:
» DEMO
[Edit] Maybe this just not possible at the moment. I think it should be possible if this feature would be implemented for the TS compiler.
https://github.com/Microsoft/TypeScript/issues/16597
Comment: @Natasha, as far as I know Typescript (I spent last day thinking in your problem), I think it's not possible to achieve what you want with these conditions.
Comment: Just checking to be sure - `defaultProps` might *not* contain all props, and then `props` should not have that as a required element, correct?
Comment: Yes exactly, `defaultProps` do *not* have to contain all props.
Comment: @Natasha I've created a diagram to better understand your question https://i.imgur.com/n1SNJTv.png. 1 - required P; 2 - required P and D; 3 - not required P and D; 4 - not required P; and 5 - D without an interception with P (does this image make sense?) Which ones do/don't you want as required/not required to render props?
Comment: @Pedro Please move the red square completely to the right - than your diagram is fine.
Comment: @Natasha "move the red square completely to the right" means that 2 is always void. So do you want 1, 3 and 5 as required and 4 as not required?
Comment: Sorry my bad: Move that red square completely to the top-right corner and scratch off that "5" completely.
If the component itself has four properties `1, 2, 3 and 4` where `1 and 2` are required and `3 and 4` are not
required then D shall be a subset of `3 and 4`.
Comment: @Pedro Thanks for your feedback. Maybe you could read the following github issue and tell use your opinion whether this is not possible due to the missing feature that has been requested there:
https://github.com/Microsoft/TypeScript/issues/16597
If you agree that this is the reason that my problem as described above is currently not solvable then please open a new answer that says that what I want is currently NOT POSSIBLE in TS the way I exactly want it and link to the above mentioned github issue as explanation.  TYVM
Answer: The reason there's a compile error on your code is because, indeed, props.name could be undefined.
To fix it you can simply change the type declaration from
type GreeterProps = {
  name?: string // the ? after name means name must be undefined OR string
}

to
type GreeterProps = {
  name: string // name must be a string
}

What if you really want props.name to be able to be left undefined?
You could just change the logic inside render, an example would be:
render(props) {
  if (this.props.name === undefined) return 'You don\'t have a name =/';
  return 'HELLO ' + props.name.toUpperCase();
}

Why you would need to do that?

The answer is very simple, if props.name can be undefined you'd just call .toUpperCase on undefined. Test on your console what happens if you do (PS.: On a real app the result would be even messier).
Further notes
By the way, on a typical TypeScript + React App you'd declare default props using
  public static defaultProps = {
    ...
  };

instead of the approach you've used.
Comment: The real problem is that my type definition of "ComponentConfig" is just wrong, the type of argument "props" of function "render" MUST NOT BE "P" but more like "P with those formerly optional properties made madotary that are configured in defaultProps".
Comment: Interesting problem then, I can't see how to type it correctly without changing the signature (unfortunately with `component(config: Config)` TS can't automatically infer the type of `D` for `defaultProps`). Let's see if someone can come to a nice solution here!
Comment: Thanks Lukas for your answer. Maybe my question was a bit misleading: The type definition of "GreeterProps" is perfectly fine as is (that "Greeter" component shall have an optional (!) "name" property). Also that "component" function itself will make sure that if you define a default property for "name"  in the "defaultProps" configuration, that "props.name" inside of the "render" function will NEVER be undefined. But of course the TypeScript compiler does not know this and thinks that "props.name" inside of the "render" function may be undefined.
Comment: BTW: defaultProps will soon be deprecated for function components in React (not for class-based components, of course, because you really need them there). See https://github.com/reactjs/rfcs/pull/107
Comment: Do you have a repository or gist containing the code where the issue happens on a real application? Or must the problem be focused on the demo you've provided?
Comment: Of course my "real application" is not a "Hello world" program ;-) ... But providing a full repository would not make things easier, as the problem is exactly the same as in that more or less simple Hello World demo. I've linked a second demo in the question above - maybe that helps to understand my problem a bit better.
Comment: @Natasha You wrote _"...that "props.name" inside of the "render" function will NEVER be undefined..."_. False, you can set `name={undefined}` (or more easily `name={props.somethingWhichMightBeUndefined}`) when using that component. Ergo TS is right here complaining that it might be. If you're sure (you shouldn't) then use `!`. For these cases soon you'll be able to write `props.value?.toUpperCase()` (or `props.value?.toUpperCase() ?? "No name"`, for example).
Comment: @Adriano Thanks for your comment. But I was right when saying "will NEVER be undfined" as the library will take care of that. Of course undefined can be passed in but the library/component function will make sure that it will be replaced automatically by the default prop value before that `render` function is called. That's why it is called `defaultProps`, isn't it?
Comment: @Natasha from React point of view, yes. However TS knows nothing about React implementation and it rightly complains. From TS point of view React MAY even implement it as `props = { ...defaultProps, ...props }`
Comment: @Adriano Like written somewhere above, this is not a React problem, this is a Typescript-only problem ... that's why in my code snippet above there's no JSX and no React imports. If you change the syntax to `export default component('HelloWorld')({ defaultProps,  render })` typing in TS is working exactly as I want it to work (but I do not like that syntax) .... and the question is whether this is also somehow possible with exactly the syntax as in the above code snippet above (I spend 75% of my credits just because I hoped someone maybe knows some cool TS tricks to fix this).
Comment: Again: it's NOT a TS problem, it entirely depends on how `component()` overloads are typed. Are you free to change how `component` is typed?
Comment: As long as the above code snippet stays really 100% as-is, every solution is very welcome - but this is actually the problem, that this snippet directly shall not be changed at all. I've added a list of workarounds to the code snippet above - none of those workarounds is a solution that I am looking for.
Answer: After some days discusses and researches, it's not possible to solve your problem given your restrictions.
As you point in your question:

[Edit] Maybe this just not possible at the moment. I think it should be possible if this feature would be implemented for the TS compiler. https://github.com/Microsoft/TypeScript/issues/16597

TS won't infer generics at the moment of the function/class declaration. The idea of your issue is the same as for issue 16597:
// issue example
class Greeter<T, S> {
    greeting: T;
    constructor(message: T, message2: S) {
        this.greeting = message;
    }

}

// your issue
function component
(config: ComponentConfig
): any {
  return null
}

// generalizing
const function<SOME_GIVEN_TYPE, TYPE_TO_BE_INFERED?>() {
  // TYPE_TO_BE_INFERED is defined inside de function/class.
}

Answer: I think that what you're looking for is something like this:
type HelloWorldProps = {
  name?: string
}

export default function HelloWorld({ name = "World"}: HelloWorldProps) {
    return <>HELLO {name.toUpperCase()}</>
}

The main issue you were likely having is that string isn't a valid ReactElement. Components need to return a ReactElement. We wrap the string in a fragment, which is a ReactElement, and return it. Typescript will infer the correct type for the function.
Comment: Thanks Arion for your answer. After I'ver read your answer I have add an additional hint to my question above that the problem is only a TypeScript problem and not a React problem.
Comment: In your example there will not be a "name could be undefined" compile error because of that "{ name = "World" }" default value thing. But in my question above I have explicitly mentioned that this is not the solution I am looking for.
Answer: Yes, this seems doable! Take a look at this playground.
The interesting types:
// Optional meaning 'could be undefined': both { x?: string } and { x: undefined }
type PickOptionalProps<T> = Pick<T, {
    [K in keyof T]-?:
      T extends Record<K, T[K]>
        ? undefined extends T[K] ? K : never
        : K
}[keyof T]>;

type DefaultsFor
 = Partial<PickOptionalProps
>;

type WithoutPropsFrom<T, X> = Omit<T, keyof X>;

// Remove ? or undefined props
type WithoutOptional<T> = {
  [K in keyof T]-?: Exclude<T[K], undefined>
}

type MergePropsAndDefaults = {
    // Props not that aren't both optional & in the defaults stay as they are
    [K in keyof WithoutPropsFrom]: P[K]
} & {
    // Optional props overridden by defaults:
    [K in keyof (PickOptionalProps
 | D)]-?: WithoutOptional
[K] | D[K]
};

type ComponentConfig = D extends {}
  ? {
    displayName: string,
    defaultProps: D,
    render(props: MergePropsAndDefaults
): any
  }
  : {
    displayName: string,
    render(props: P): any
  };

function component(config: ComponentConfig
): any {
  return null
}

This requires that component calls take an explicit type for the default props. It does enforce that the type is correct though, and by pulling the default props into a separate object you could pass this as simply typeof myDefaultProps.
The merging here covers a few other cases you haven't mentioned. As a minimal example:
type Props = { name?: string, age: number, optional?: number, undef: string | undefined };
type DefaultProps = { name: 'default', undef: 'other-default' };
type ResultingProps = MergePropsAndDefaults<Props, DefaultProps>;

// Gives:
type ResultingProps = {
    age: number; // Required, because it's required in the main props
    optional?: number | undefined; // Not required but no default: stays optional
} & {
    name: string; // Optional prop overridden correctly
    undef: string; // Non-optional but could-be-undefined, overridden correctly
}

Comment: Thank you, Tim, for your answer. It seems that in your example just all (!) optional properties are converted to be required in the first argument of the render function and not only those that are configured under `defaultProps`. Please open you demo and comment the `defaultProps: ...` line and you'll see what I mean: `props.name.toUpperCase()` should now throw an compile error again but unfortunately it doesn't...
Comment: Oooh, interesting. It seems that MergePropsAndDefaults works, but the inference of D in the ComponentConfig doesn't. I'll play with it, just a minute.
Comment: Ok, updated @Natasha. I don't think it's possible to ever have TS infer a type for the default props whilst providing an explicit props type, but you can do it by specifying both just once and have everything else inferred from there, and you can enforce that the specified types are correct. In real use you could infer explicitly with `typeof` to avoid duplication. I've updated the demo.
Comment: To test without default props now: remove the default props line, and it'll force you to also remove the generic arg to match, and then work as expected.
Comment: Thank you very much Tim for your kind help. But like written in the question above I want to use exactly (means 100% exactly) the syntax in the above written code snippet and the question is how can this be done with exact this syntax - or maybe is it even possible to do that in the current TS version. To be more clear I've added a list of all of the known workarounds for my problem in the code snippet above - none of those workarounds is an answer to my question. Like written above the following feature would for example solve my problem - but this feature is currently not available in TS:
Answer: Does this solution solve your problem?
DEMO
Basically I've created ComponentConfig this way:
// Keep the original implementation
type PickOptionalProps<T> = Pick<T, {
    [K in keyof T]-?: T extends Record<K, T[K]> ? never : K
}[keyof T]>

// Transform all properties as required
type TransformKeysAsRequired<T> = {
  [P in keyof T]-?: T[P];
}

interface ComponentConfig
 {
  displayName: string,
  // I pick the optional props and transform them as required
  defaultProps?: TransformKeysAsRequired<PickOptionalProps
>,
  // Just transform the props as required
  render(props: TransformKeysAsRequired
): any
}

Please, tell me if I misunderstood your issue.
Comment: Thank you, Pedro, for your answer. The link to your demo does not seem to be correct (I cannot see your demo). Nevertheless, it seems that you suggest to make ALL (!) properties of the first argument of the render function to be required. This will make `props.name.toUpperCase()` possible but will allow allow the same for all still optional props .... for example `props.someStringPropWithoutDefaultValue.toUpperCase()` is now fine for the TS compiler, while this will cause some runtime errors later (as this optional prop can still be undefined).
Comment: I've added an additional comment in my code snippet above to make this more clear.
Answer: A working solution (yet not exactly what I have asked for) would be to use the following syntax
const HelloWorld: Component<HelloWorldProps> = component({ ... })

instead of
const HelloWorld = component<HelloWorldProps>({ ... })

Here's a little demo:
DEMO


Is this an error in the MCTS Self-Paced Training Kit (Exam 70-536)?

Question: I am reading the MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework—Application Development Foundation, Second Edition eBook.
Now I am finishing off the threading chapter (nr. 7). In the questions at the end of lesson 2, the is one question (nr. 2) that asks: "You are writing a method that can be run by multiple threads. Make sure that no thread writes to the file while any thread is reading from the file. But you have to do it as efficiently as possible with regard to multiple threads reading at the same time."
Then there are two answers which are candidates for answers:
A.
lock(file)
{
   // Read
}

and
D.
ReaderWriterLock rwl = new ReaderWriterLock();
rwl.AcquireReaderLock(10000);
   // Read
rwl.ReleaseReaderLock();

The subtle hint in the question that "it has to be efficient for multiple reads" of course means they want you to use the ReaderWriterLock, but then I thought: "Creating a new instance of the ReaderWriterLock inside the method you are locking shouldn't work, every call to the method will lock a different instance of ReaderWriterLock."
However in the answers it says: D.
So IMHO this is an error in the book. They probably meant in the code sample that the new instance would be created somewhere else. If I would get this question on the exam, I would have gotten it wrong (I would choose A).
Comment: I guess they mean that the RWL is created outside the scope of the threaded method...
Comment: Is the code above the entire listing for answer D?
Comment: @Tony: That's also what I think, but they didn't show that in their answer.
Comment: @Lazarus, all except for the VB part and the `// C#` comment.
Comment: Then I agree with you and Tony, the premise is there in the RWL is the most efficient method for having single writer and multiple threaded readers but there should only be a single instance of the RWL as I understand it.
Answer: Your observation is correct, granted that the ReaderWriterLock is indeed created within the method body. For the locking to work as expected, all threads need to use the same ReaderWriterLock instance.
If the code sample in your question is the full code listing for the answer I would say that it is presented in a rather bad way, and it may very well lead people to select the wrong answer because they did a fairly thorough analysis of the given code samples.
Answer: That kit is historically famously full of errors, with errata here. If it helps, the first edition had not 1, not 2, not 3 but 4 erratas. You did well to spot it, but you should be very cautious here, and indeed try to verify anything you are not 100% sure of.


How to prevent the screen lock while watching video (Netflix, Youtube, Amazon Prime) in Ubuntu 17.10

Question: In earlier Ubuntu versions like 16.04 and 17.04 while watching YouTube videos in full-screen mode, the screen would not get locked automatically.
In Ubuntu 17.10 while watching videos in browser, system is getting locked. So Ubuntu 17.10 is considering this scenario as user is not doing anything.
Kindly suggest a solution for that.
Comment: @Rinzwind The correct package name is `gnome-tweak-tool` I believe.
Comment: @Manish Kumar Bisht , I would think having to manually disable the screensaver any time one wanted to watch a video would, at best, be a VERY short-term patch if the problem is as described.
Comment: Did you install `gnome-tweak`? In that program there are some settings that are not in the normal setttings. And yes it has a few I would consider needed (without it I could not set my system to NOT kill my wifi cuz gnome-tweak has an extra setting for "suspend" that was always ON despite normal settings it was set OFF).
Comment: Do you use VLC? If yes, then go to preferences and `disable screensaver`. It will prevent your screen from going dark.
Comment: Did you try other media players that are known to support screensaver inhibition, e. g. Totem or VLC or the native video player of your web browser (typically Firefox or Chrome/Chromium)? MPV isn't that well maintained and Flash player never supported screensaver inhibition. Many web sites don't require Flash to play back videos these days, if you disable it.
Comment: Chrome and Firefox normally support it, so I guess this is not a problem of the media player, but probably caused by the new Wayland display architecture in Ubuntu 17.10.
Comment: Firefox on Ubuntu is now installed with Snap, and one of the reasons they used to push it is full sandboxing. That means that apps have limited to no access to the underlying environment / WM / DE / OS. This specific video blanking problem have been plaguing users since day one, and as of today, no solution is in sight.
Answer: The reason that this does not work any more is because 17.10 is the first ubuntu release that uses wayland as its display server. It looks like preventing screen lock is an entirely missing feature in Xwayland.
It has been filed as a bug in Ubuntu and hopefully will be fixed soon. If you're affected by this bug, please click the launchpad link below and click "Does this bug affect you?" to increase the bug priority.
https://bugs.launchpad.net/ubuntu/+source/chromium-browser/+bug/1697373
As a workaround, you could also select "GNOME on X.org" as your session type when logging on.
There is also a bug in chromium, but it seems to apply only for google hangouts sessions:
https://bugs.chromium.org/p/chromium/issues/detail?id=783737
Comment: This answer is incorrect. I'm using XOrg (specifically Latest Ubuntu with i3 over gnome / lightDM) and I have been experiencing the problem too, ever since Snap became mandatory for installing Firefox ; This problem is most probably due to the very "sandboxed" nature of snap applications. And AFAIK Wayland *does* have this obvious feature.
Answer: You may have to use the great Caffeine, available from here. You have to allow installing extension from Firefox or install the Ubuntu package gnome-shell-extension-caffeine thanks to the command apt. This extension detect any full screen application and prevent from running screensaver. It also adds a small cup beside your volume icon, letting you to disable the screen saver with one click.
Apt method
Open your Terminal, and type
sudo apt install gnome-shell-extension-caffeine

Then go to Gnome Tweak, click on Extensions tab, and enable Caffeine
Gnome Shell extension
Open https://extensions.gnome.org/extension/517/caffeine/ from Firefox, click on Allow from the top bar asking for Gnome Shell Integration. Enable then Caffeine extension.
Comment: Or Keep Awake https://extensions.gnome.org/extension/1097/keep-awake/
Comment: Thanks, I searched before asking and could not find answer, it was not so strait forward, I had to go back and forth a few time ...  I'll go with what I remember.
I had to reboot cause the extension was not showing (I probably just had to log out). Installing Tweak and the extension from command line did not work, I wonder why ?
Comment: Also one  can install Caffeine app (*not* the extension) by running `sudo apt install caffeine`.
Answer: You may try a GNOME shell extension as a workaround called Keep awake!
Product description:

Keep your computer awake! Forbid your computer to activate sceensaver, turn off the screen or suspend when it is idle for a while. Toogle [sic] this option on or off with one click.

Once you install this extension you'll see an "eye" icon in your top bar.

 (screenshot source: extension's homepage at extensions.gnome.org)
Clicking on the eye will switch between "normal" and "no screen-lock or suspend" mode.

Another advanced extension which does the same but provides more customisability  is Caffeine.
Warning: There is (or was, not sure whether it's fixed already) a bug in Caffeine which may freeze your computer for ~30 seconds after clicking on the power-off button in the status menu.
Comment: I posted a duplicate question, sorry. As pomsky said, there should be a bug in Caffeine (there a comment from a couple of days about it), but I should be able to fix it, if I step on it, but I could not see it so far.
Comment: @kbenoit Lucky you if you haven't hit the bug! Then no worries at all, happy "Caffeinating"! :)


Triple Integral in Spherical Coordinates

Question: I'm trying to solve the triple integral of $3x^2 + 3y^2 + 3z^2$ in spherical coordinates, with rho from 1 to 2, theta from 0 to 2$\pi$, and $\phi$ from 0 to $\pi /4$.
Here's how I'm solving it: First I convert the expression to spherical coordinates: $3p^2\sin^2\phi\, cos^2\theta + 3p^2sin^2\phi\, sin^2\theta + 3p^2cos^2\phi$. This is then multiplied by the Jacobean $sin(\phi)*p^2$
I integrate over p. This gives me $3/5  p^5$ over the interval 1 to 2, which leaves me with 18.6 I integrate over $\theta$, which amounts to throwing a 2pi in, giving me $37.2\cdot \int_{0}^{\pi/4}(\pi cos^2(\phi)*sin(\phi) + 1)$.
This is where I know I've gone wrong. I integrate this and get $\pi/4 + cos^3(\phi)/3$. Everyone else online seems to simply get $-cos(\phi)$. This is the only spot our answers differ. Something about my integral is wrong but I don't know what.
Comment: Your integrand should only have $\rho$, no $\theta$.
Comment: [Here](http://meta.math.stackexchange.com/questions/5020/)'s a reference and tutorial for typesetting math on this site.
Answer: It appears to me1 that you simplified
$$ \sin^2 \phi \cos^2 \theta + \sin^2\phi \sin^2 \theta \mapsto 1 $$
when you should have
$$ \sin^2 \phi \cos^2 \theta + \sin^2\phi \sin^2 \theta = \sin^2\phi $$

Alternatively, you may have also recognized from the get-go that
$$ x^2 + y^2 + z^2 = \rho^2 $$
from the definition of $\rho$.

1 I am just making an educated guess based on your description of what you did; short of you showing every line of your work I cannot be sure.
Answer: The integrand becomes
$3x^2 + 3y^2 + 3z^2 \mapsto 3 \rho^2$ times the Jacobian. This means you integrate
$$\int_{\rho=1}^{\rho=2} \int_{\phi=0}^{\phi= \frac{\pi}{4} } \int_{\theta=0}^{\theta=2 \pi} 3 \rho^4 \sin \phi \> d\theta d\phi d\rho$$