Gradle Java compilation error using pattern matching instanceof & switch expressions

Question: I am getting the following error when compiling my Gradle Java project:
<code>> Task :compileJava FAILED
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\CommandsManager.java:52: error: ')' expected
                    if (sender instanceof Player player) {
                                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\CommandsManager.java:52: error: not a statement
                    if (sender instanceof Player player) {
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\CommandsManager.java:52: error: ';' expected
                    if (sender instanceof Player player) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\CommandsManager.java:56: error: 'else' without 'if'
                    } else
                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:38: error: ')' expected
                    if (sender instanceof Player player) {
                                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:38: error: not a statement
                    if (sender instanceof Player player) {
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:38: error: ';' expected
                    if (sender instanceof Player player) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:54: error: 'else' without 'if'
                    } else
                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:66: error: ')' expected
                    if (sender instanceof Player player) {
                                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:66: error: not a statement
                    if (sender instanceof Player player) {
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:66: error: ';' expected
                    if (sender instanceof Player player) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:72: error: 'else' without 'if'
                    } else
                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:81: error: ')' expected
                    if (sender instanceof Player player) {
                                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:81: error: not a statement
                    if (sender instanceof Player player) {
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:81: error: ';' expected
                    if (sender instanceof Player player) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:84: error: 'else' without 'if'
                    } else
                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:93: error: ')' expected
                    if (sender instanceof Player player) {
                                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:93: error: not a statement
                    if (sender instanceof Player player) {
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:93: error: ';' expected
                    if (sender instanceof Player player) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:96: error: 'else' without 'if'
                    } else
                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:107: error: ')' expected
                    if (sender instanceof Player player) {
                                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:107: error: not a statement
                    if (sender instanceof Player player) {
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:107: error: ';' expected
                    if (sender instanceof Player player) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:110: error: ')' expected
                        if (recipe instanceof FurnaceBuilder furnace) {
                                                            ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:110: error: not a statement
                        if (recipe instanceof FurnaceBuilder furnace) {
                                                             ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:110: error: ';' expected
                        if (recipe instanceof FurnaceBuilder furnace) {
                                                                    ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:115: error: 'else' without 'if'
                    } else
                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:125: error: ')' expected
                    if (sender instanceof Player player) {
                                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:125: error: not a statement
                    if (sender instanceof Player player) {
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:125: error: ';' expected
                    if (sender instanceof Player player) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RecipesCommand.java:133: error: 'else' without 'if'
                    } else
                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: : expected
                        case "ITEMS" -> reloadItems(sender);
                                    ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: illegal start of expression
                        case "ITEMS" -> reloadItems(sender);
                                     ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: ';' expected
                        case "ITEMS" -> reloadItems(sender);
                                                   ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: not a statement
                        case "ITEMS" -> reloadItems(sender);
                                                    ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:23: error: ';' expected
                        case "ITEMS" -> reloadItems(sender);
                                                          ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: : expected
                        case "PACK" -> reloadPack(OraxenPlugin.get(), sender);
                                   ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: illegal start of expression
                        case "PACK" -> reloadPack(OraxenPlugin.get(), sender);
                                    ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: ';' expected
                        case "PACK" -> reloadPack(OraxenPlugin.get(), sender);
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: ';' expected
                        case "PACK" -> reloadPack(OraxenPlugin.get(), sender);
                                                                    ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: not a statement
                        case "PACK" -> reloadPack(OraxenPlugin.get(), sender);
                                                                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:24: error: ';' expected
                        case "PACK" -> reloadPack(OraxenPlugin.get(), sender);
                                                                            ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:25: error: : expected
                        case "RECIPES" -> RecipesManager.reload(OraxenPlugin.get());
                                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:25: error: illegal start of expression
                        case "RECIPES" -> RecipesManager.reload(OraxenPlugin.get());
                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:25: error: ';' expected
                        case "RECIPES" -> RecipesManager.reload(OraxenPlugin.get());
                                                        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:26: error: : expected
                        case "CONFIGS" -> OraxenPlugin.get().reloadConfigs();
                                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:26: error: illegal start of expression
                        case "CONFIGS" -> OraxenPlugin.get().reloadConfigs();
                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:26: error: ';' expected
                        case "CONFIGS" -> OraxenPlugin.get().reloadConfigs();
                                                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:27: error: : expected
                        default -> {
                               ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:27: error: illegal start of expression
                        default -> {
                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:27: error: ';' expected
                        default -> {
                                  ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:34: error: ')' expected
                    }
                     ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\ReloadCommand.java:35: error: illegal start of expression
                });
                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:27: error: ')' expected
                    if (sender instanceof Player player) {
                                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:27: error: not a statement
                    if (sender instanceof Player player) {
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:27: error: ';' expected
                    if (sender instanceof Player player) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:55: error: 'else' without 'if'
                    } else {
                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:65: error: ')' expected
        if (!(itemMeta instanceof Damageable damageable))
                                            ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:65: error: illegal start of expression
        if (!(itemMeta instanceof Damageable damageable))
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\RepairCommand.java:65: error: ';' expected
        if (!(itemMeta instanceof Damageable damageable))
                                                        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:8: error: class, interface, or enum expected
public record Glyph(String name, char character, String texture, int ascent,
       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:11: error: class, interface, or enum expected
    public JsonObject toJson() {
           ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:13: error: class, interface, or enum expected
        JsonArray chars = new JsonArray();
        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:14: error: class, interface, or enum expected
        chars.add(String.valueOf(character));
        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:15: error: class, interface, or enum expected
        output.add("chars", chars);
        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:16: error: class, interface, or enum expected
        output.addProperty("file", texture);
        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:17: error: class, interface, or enum expected
        output.addProperty("ascent", 8);
        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:18: error: class, interface, or enum expected
        output.addProperty("height", height);
        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:19: error: class, interface, or enum expected
        output.addProperty("type", "bitmap");
        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:20: error: class, interface, or enum expected
        return output;
        ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:21: error: class, interface, or enum expected
    }
    ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:23: error: class, interface, or enum expected
    public boolean hasPermission(Player player) {
           ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\font\Glyph.java:25: error: class, interface, or enum expected
    }
    ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:71: error: ')' expected
        if (itemMeta instanceof PotionMeta potionMeta) {
                                          ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:71: error: not a statement
        if (itemMeta instanceof PotionMeta potionMeta) {
                                           ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:71: error: ';' expected
        if (itemMeta instanceof PotionMeta potionMeta) {
                                                     ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:80: error: ')' expected
        if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) {
                                                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:80: error: not a statement
        if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:80: error: ';' expected
        if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) {
                                                                             ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:280: error: ')' expected
        if (itemMeta instanceof Damageable damageable) {
                                          ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:280: error: not a statement
        if (itemMeta instanceof Damageable damageable) {
                                           ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:280: error: ';' expected
        if (itemMeta instanceof Damageable damageable) {
                                                     ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:287: error: ')' expected
        if (itemMeta instanceof LeatherArmorMeta leatherArmorMeta) {
                                                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:287: error: not a statement
        if (itemMeta instanceof LeatherArmorMeta leatherArmorMeta) {
                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:287: error: ';' expected
        if (itemMeta instanceof LeatherArmorMeta leatherArmorMeta) {
                                                                 ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:294: error: ')' expected
        if (itemMeta instanceof PotionMeta potionMeta) {
                                          ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:294: error: not a statement
        if (itemMeta instanceof PotionMeta potionMeta) {
                                           ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:294: error: ';' expected
        if (itemMeta instanceof PotionMeta potionMeta) {
                                                     ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:309: error: ')' expected
        if (itemMeta instanceof SkullMeta skullMeta) {
                                         ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:309: error: not a statement
        if (itemMeta instanceof SkullMeta skullMeta) {
                                          ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:309: error: ';' expected
        if (itemMeta instanceof SkullMeta skullMeta) {
                                                   ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:317: error: ')' expected
        if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) {
                                                      ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:317: error: not a statement
        if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) {
                                                       ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\items\ItemBuilder.java:317: error: ';' expected
        if (itemMeta instanceof TropicalFishBucketMeta tropicalFishBucketMeta) {
                                                                             ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:17: error: illegal start of expression
            CustomAction action = switch (params[0]) {
                                  ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:17: error: not a statement
            CustomAction action = switch (params[0]) {
                                         ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:17: error: ';' expected
            CustomAction action = switch (params[0]) {
                                                    ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:18: error: orphaned case
                case "command" -> new CommandAction(params);
                ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:18: error: : expected
                case "command" -> new CommandAction(params);
                              ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:18: error: illegal start of expression
                case "command" -> new CommandAction(params);
                               ^
100 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
2 actionable tasks: 2 executed
</code>
Comment: Looks like this is using features from a java version that is higher than the one you're using.
Comment: Also please don't post text as images but post the text itself (nicely formatted of course to make it readable). And don't post links to code or text as those can break and other users might be wary of following them (or can't due to firewall rules). Do yourself a favor and put some effort into the question.
Comment: I strongly suspect that @FedericoklezCulloca is absolutely correct.  The compilation failure is due to a [pattern matching `instanceof` operator](https://docs.oracle.com/en/java/javase/16/language/pattern-matching-instanceof-operator.html) not being recognized by the compiler.  This feature was not added to the Java language until Java 16.  I'm guessing the project's `build.gradle` isn't enforcing that version of Java, so it uses whatever version you're running the build as.  What version of Java are you using?  What do you get when you run `java --version`?
Comment: Please provide a [mre], including a build.gradle script, and specify the Java version you're using.
Comment: Part of those 100 errors would probably be more useful in understanding what's wrong. Start with a couple from the top, for example.
Comment: https://pastebin.com/Nrjje3Dn complete error
Comment: @Universefilatov: please don't use external links or images instead of updating your question to contain the relevant error messages. Edit your question to contain them instead. And if there are too many error messages for that, then just post the first few (like 10). It's unlikely that anyone's going to read all of them anyway. [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551)
Answer: This appears to be due to an older version of Java being used to compile the code, when at least Java 16 must be used.  Using a new enough version of Java should fix this particular issue.
The compiler output is failing on some newer Java features: the pattern matching <code>instanceof</code> operator added in Java 16, and switch expressions added in Java 14.
<code>D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\commands\CommandsManager.java:52: error: ')' expected
                    if (sender instanceof Player player) {
                                                ^
</code>
<code>D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:17: error: ';' expected
            CustomAction action = switch (params[0]) {
                                                    ^
D:\compilar\Oraxen-master\src\main\java\io\th0rgal\oraxen\mechanics\provided\custom\CustomMechanicAction.java:18: error: orphaned case
                case "command" -> new CommandAction(params);
                ^
</code>
Given that the failures are due to newer language features, this tells me that the issue is likely due to an older version of Java being used (Java 13 or earlier).
There are two ways to address this.  The first (and less portable) way is to ensure the build is running under a new enough version of Java.  For instance, when run under the command line, the <code>java --version</code> should indicate Java version of at least 16 before running the build.  If the version is too old, a newer version must be installed first.
The second approach is to specify the version of Java to be used within the Gradle build.  This will ensure that the build is always used with the correct version of Java.  With newer versions of Gradle, the Java Toolchain can be configured to use the proper version:
<code>java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(16)
    }
}
</code>


Microsoft Botframework encode image bytes into message cards

Question: I am using the Bot framework to create a chat bot. And I want to create message card (Hero or Thumbnail).
If you look at the skype bot api doc, there is a way to encode image bytes directly as the content url. https://docs.botframework.com/en-us/skype/chat/
<code>"type": "message/image",
"attachments": [
    {
        "contentUrl": "<base64 encoded image>",
        "thumbnailUrl": "<base64 encoded thumbnail>",          // optional
        "filename": "bear.jpg"                                 // optional
    }
]
</code>
This works fine for showing an image only. But I want the image to be part of a card.
The card is
<code>{
"type":"message/card.carousel",
"attachments":[
    {
    "contentType":"application/vnd.microsoft.card.hero",
    "content":{
        "images":[
        {
            "image":"https://foo.com/path/image.jpg",
        }
</code>
I have tried to set the image url property to the encoded bytes, but the client can't show it. What's the best way to achieve this?
Answer: You've got the basic idea.  Use this instead:
<code>  "attachments": [
    {
      "contentType": "application/vnd.microsoft.card.hero",
      "content": {
        "title": "Title",
        "subtitle": "SubTitle",
        "text": "Text",
        "images": [
          {
            "url": "image/jpeg;base64,{YOUR IMAGE}",
            "alt": "Alt Image Description"
          }
        ]
      }
    }
  ],
</code>
Comment: Thanks @Lars for helping. I tried to do this, but using the Bot Emulator 184.108.40.206, I don't see any image showing up.

"attachmentLayout": "carousel",
"attachments": [ {
"contentType": "application/vnd.microsoft.card.hero",
"content": {
"title": "Title",
"subtitle": "SubTitle",
"text": "Text",
"images": [ {
**"url": "image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYA.....**


How to implement Floyd's algorithm finding a shortest path on a 11x11 grid that has rectangle obstacles?

Question: I've been trying to figure out how to implement Floyd's algorithm for several days now to find the shortest path in a grid structure as described below. Can anyone point me in the right direction as to how I would implement something like this? Thanks.
Input:

Start/End coordinates
User input must be between 0 to 10 inclusive
Number of obstacles
Obstacle coordinates at top-left and bottom-right

Output:

Path showing all the coordinates that are passed through
Distance as an int

Restrictions:

Obstacles cannot overlap
Start and End cannot be set inside a rectangle obstacle
Path can include traveling along the edges of the rectangle but never through them
The path may only go horizontal and vertical, not diagonal
The distance between two adjacent vertices is 1

I need help generating the conditions for the 121x121 array.
This is what I have so far.
<code>for(i=1;i<=n;i++) {
   for(j=1;j<=n;j++) {
         if( edge exists from i to j ) W[i][j] = 1;
               // distance=1 if nodes are adjacent
         else if ( edge does not exist from i to j ) W[i][j] = inf;
              // distance=inf. if nodes do not meet
         else if ( i = j ) W[i][j] = 0; // distance=0 if i=j
   }
}
</code>
Comment: I need help generating the conditions for the 121x121 array. this is what i got so far.

    `for(i=1;i<=n;i++)
    {
       for(j=1;j<=n;j++)
       {
          if( edge exists from i to j )
             W[i][j] = 1; // distance=1 if nodes are adjacent
          else if ( edge does not exist from i to j )
             W[i][j] = inf; // distance=inf. if nodes do not meet
          else if ( i = j )
             W[i][j] = 0; // distance=0 if i=j
       }
    }`
Comment: @user1351995 FYI: You can go back and edit your original question on this site. I went ahead and copied your clarification into your question.
Answer: http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm
Just use this pseudo code to implement the algorithm (it shouldn't diferentiate that much from the actual C++ code (it's a fairly simple algorithm). The Wiki link also provides an algorithm for the shortest path reconstruction.
Would you consider implementing a simple Breath First Search because you're dealing with a grid.
Haha this is my first post on this forum :)
Comment: Actually Floyd-Warshall is too slow for this (O(n ^ 3) and n = 121 ^ 2). BFS or A* might be better choice.
Comment: haha you're suggesting A* to a person who's having trouble implementing a simple Floyd Warshall algorithm.
Comment: BFS is easy enough to implement and sufficient to solve the problem. A* is if OP wants to speed up the search between a known src and dest. My solution is just in case the OP wants to find shortest path between some pairs of coordinates. If the same board is used, and there are many queries, then Floyd-Warshall may be a better choice, but it will take a lot of time to finish generating the whole 121x121 array.
Comment: Heyy, I've just answered his question about Floyd Warshall. I know that it's slow. That's why I've suggested BFS in the first place. Also, since he's struggling (or even considering) implementing FW algorithm tells me that he won't be using A star any time soon.


Does ls try to access subdirectories?

Question: I am trying to learn about file permissions in UNIX. I am using a terminal with Ubuntu 18.10. Let's say my home directory contains test/test1/test2.
I cd test and then type chmod a=r *. Then when I type cd test1 I get bash: cd: test1: Permission denied. Good, that's what's supposed to happen.
However when I type ls test1 I get ls: cannot access 'test1/test2': Permission denied and in the next line test2.
Can someone explain to a newbie like me why this is happening? Thanks!
Comment: I'm voting to close this question as off-topic because this question is better suited to [Unix & Linux Stack Exchange](http://unix.stackexchange.com/tour). This site is for programming related questions.
Comment: I'm sorry I thought it was more a bash question than a linux one and as such presumed it was ok for here.
Comment: It's actually more of an `ls` question, I would say. You are using GNU coreutils `ls`, I am using BSD `ls`, and you are using an OS that sets `$LS_COLORS` and has a default `alias ls='ls --color=auto'` (or something like that), whereas mine doesn't.
Answer: You have read permission to test1, therefore you are allowed to read its contents. (A directory is simply a file that lists its contents, just like a directory in the real world.) So, it is perfectly normal that you get test2 listed.
However, you don't have enter (x) permissions for test1, so you cannot enter the directory to look at its contents. Therefore, you only know that a file named test2 exists, but you don't know what it is.
On many operating systems, the default for ls when used interactively, is to use different colors to distinguish between different kinds of files, therefore ls will try to access test1/test2 so that it can print it with the correct color, but since you don't have enter permissions for test1, this will fail.
On my operating system, ls is set by default to not print any colors or other indicators, therefore, I simply get test2 without any errors. Conversely, if I add any options that require entering test1, my ls will actually not print anything at all!

Does ls try to access subdirectories?


Map Two Polar Disks To Four Dimensional Spherical Coordinates ($\left(\mathbb{R}^2\right)^2\to\mathbb{R}^4$)

Question: We have two points $(x_1, y_1), (x_2, y_2) \in \mathbb{R}^2$ with polar parameterizations $(r_1, \theta_1), (r_2, \theta_2)$ (i.e., $x_1=r_1 cos(\theta)$ and so on.) How would the point $(x_1, y_1, x_2, y_2) \in \mathbb{R}^4$ be represented with four-dimensional spherical coordinates $(r, \phi_1, \phi_2, \phi_3)$?
Please correct my proposed answer if I have made a mistake or upvote it if you concur.
Finally, how would one inductively generalize equivalency to $\mathbb{R}^{2^n}$ or $\mathbb{R}^{2n}$?
Answer: We begin by equating the components of the two numbers in polar coordinates and the single number in spherical coordinates. Here, $r_3 = \sqrt{r_1^2 + r_2^2}$.
$$r_1 \cos \left( \theta_1 \right) = r_3 \cos \left( \phi_1 \right)$$
$$r_1 \sin \left( \theta_1 \right) = r_3 \sin \left( \phi_1 \right) \cos \left( \phi_2 \right)$$
$$r_2 \cos \left( \theta_2 \right) = r_3 \sin \left( \phi_1 \right) \sin \left( \phi_2 \right) \cos \left( \phi_3 \right)$$
$$r_2 \sin \left( \theta_2 \right) = r_3 \sin \left( \phi_1 \right) \sin \left( \phi_2 \right) \sin \left( \phi_3 \right)$$
Next, the standard definition of $arccos$ does not include the full input plane, so we form a continuous extension to $\mathbb{R}^2 \setminus \mathbb{R}^+$. (We exclude the point intersecting $\mathbb{R}^+$ with $\theta = 0$ or $\theta = 2 \pi$). With an abuse of notation, we will still refer to this continuous extension as $arccos$. An interesting application of this definition of $arccos$ is that $\mathbb{R}^3 \setminus 0$ is not homologically trivial, which is an exercise in Munkre's Analysis on Manifolds.
$$\phi_1 = \arccos \left( r_1 r_3^{-1} \cos \left( \theta_1 \right) \right)$$
$$\phi_2 = \arccos \left( r_1 r_3^{-1}  \frac{ sin (\theta_1) }{sin (\phi_1)} \right)$$
$$\phi_3 = \arccos \left( r_2 r_3^{-1} \frac{ \cos \left( \theta \right) }{ \sin \left( \phi_1 \right) \sin \left( \phi_2 \right)   }  \right)$$
Fortunately, the other direction is simpler to compute.
$$\theta_{1} = \arccos(r_3 r_1^{-1} \cos \left( \phi_1 \right))=\arcsin \left( r_3 r_1^{-1} \sin \left( \phi_1 \right) \cos \left( \phi_2 \right) \right)$$
$$\theta_2 = \arccos \left( r_3 r_2^{-1} \sin \left( \phi_1 \right) \sin \left( \phi_2 \right) \cos \left( \phi_3 \right) \right)=...$$
$$\frac{ r_1 \cos \left( \theta_1 \right) }{ \cos \left( \phi_1 \right) } = \frac{ r_1 \sin \left( \theta_1 \right) }{ \sin \left( \phi_1 \right) \cos \left( \phi_2 \right)   }$$
$r_1 = \left|\frac{ \cos \left( \theta_1 \right) }{ \cos \left( \phi_1 \right) } - \frac{ \sin \left( \theta_1 \right) }{ \sin \left( \phi_1 \right) \cos \left( \phi_2 \right)   }\right|^{-1}$ provided that $cos(\phi_1)\neq0$, $cos(\phi_2)\neq 0$, and $sin(\phi_1)\neq 0$.
$r_2 = \left|\frac{1}{sin(\phi_1) sin(\phi_2)} \left( \frac{cos (\theta_2) }{cos(\phi_3)} - \frac{sin(\theta_2)}{sin(\phi_3)} \right)\right| ^{-1}$ provided that $sin(\phi_1)\neq 0$, $sin (\phi_2) \neq 0$, $cos(\phi_3)\neq 0$, and $sin(\phi_3) \neq 0$.
I wonder if there would be an easier formula for $r_1$ and $r_2$ by taking the components of $r_3$ along two axes. (In this case, $r_1$, $r_2$, and $r_3$ would all be tangent vectors on the same plane, though finding a parameterization or normal vector for the plane is not trivial; one cannot simply compute $\vec{r_1} \times \vec{r_2}$.)
By stipulating $r_3>0$ and $\theta_1, \theta_2, \theta_3 \in [0, 2 \pi)$, proof of injection (being a one-to-one map) should follow immediately. Likewise, every pair of $(x_1, y_1)=(r_1, \theta_1)$ and $(x_2, y_2) = (r_2, \theta_2)$ should produce a value for $(r, \phi_1, \phi_2, \phi_3)$, allowing surjection to follow as well. $f(r_1, \theta_1, r_2, \theta_2)= (r, \phi_1, \phi_2, \phi_3)$ should then satisfy the criteria of an isomorphic map. If feel that I have missed something. Please correct me in the comments or my answer directly if you have sufficient reputation.
Answer: While the other answer would take you to the standard spherical coordinates, the formula gets very unwieldy especially for higher dimensions. An alternative will get you the same radial coordinate but different angles
$$\phi_1=\theta_1$$
$$\phi_2=\theta_2$$
$$r_3\cos\phi = r_1$$
$$r_3\sin\phi = r_2$$
The interesting thing about these coordinates is instead of having the angles be maps $[0,2\pi]\times[0,\pi]^{2n-2}\to S^{2n-1}$, these are maps $[0,2\pi]^{n}\times\left[0,\frac{\pi}{2}\right]^{n-1}\to S^{2n-1}$ (embedded in $\Bbb{R}^{2n}$). The generalization to $\Bbb{R}^{2n}$ is simply setting all of the radial coordinates to the standard spherical coordinates in $\Bbb{R}^n$ but restricted to the first quadrant/octant/etc..
Comment: Thank you for the excellent answer. Do you agree with my belief that the mapping may be made isomorphic? How are the angles necessarily different? I'm sorry, I don't see an immediate consequence of the proposed mapping save for restricting the domains, specifically for $\phi$.
Comment: @JPwin I don't understand. What is not isomorphic about it that has to be "made" isomorphic?
Comment: My apologies. I had already thought the mapping was isomorphic but hadn't made a rigorous proof for it. You do agree that it is one-to-one and onto, right?
Comment: @JPwin sure. You don't need go prove the total mapping is both of those things from scratch. You have that it is a chain of two mappings, both of which you already have are bijections or can prove more easily. Chaining bijections is still a bijection.
Comment: Thank you. I'll remember that the composition of bijections is sufficient for a formal proof. I haven't had much experience with maths outside of the classroom. If one was to, say, take the output of a biholomorphic map $f_1:\mathbb{R}^4 \to \mathbb{R}^4$, your mapping $f_2: \mathbb{R}^{+} \times \mathbb{R}^{+} \times [0,2\pi] \times [0,\frac{\pi}{2}]^{2n-2}\to \mathbb{R}^4_{\geq}$ where $\mathbb{R}^4_{\geq}$ is $\mathbb{R}^4$ with one of the planes restricted to the upper (first) quadrant would have an inverse as it is isomorphic. I could work in the simplified space, and apply the inverse...
Comment: to return to a subset of the output of the biholomorphic map? Actually, I am looking for a simple representation of the argument of a bicomplex number. Current literature represents this very argument as a complex number $\theta$; however, I worry that such a notion forces proofs to work with the encumbered notion of two complex planes as opposed to a single spherical coordinate system built on $\mathbb{R}^4$. My main appeal to the multicomplex numbers was their commutativity at the expense of not being a division algebra.
Comment: Thankfully, the image of the multicomplex natural exponent will produce values that are _always_ invertible, so I had ideally hoped to represent the argument of a product of these natural exponents with three angles instead of two angles and a radius.
Answer: $$r_1 \sin \left( \theta_1 \right) = r_3 \sin \left( \phi_1 \right) \cos \left( \phi_3 \right)$$
$$r_1 \cos \left( \theta_1 \right) = r_3 \cos \left( \phi_{1} \right)$$
We divide the two equations by each other to develop $\theta_1=\arctan \left( \frac{ \sin \left( \phi_1 \right) \cos \left( \phi_3 \right) }{ \cos \left( \phi_1 \right)}  \right) + \vartheta \left( \phi_1, \phi_2, \phi_3 \right)$. Intuitively, $\phi_1 \to \pm \frac{ \pi }{ 2  }$ yields $\theta_1 \to \pm \frac{ \pi }{ 2  }$. $\vartheta$ is a correction term to account for the quadrant of $\theta$.
$$r_2 \sin \left( \theta_2 \right) = r_3 \sin \left( \phi_1 \right) \sin \left( \phi_3 \right) \sin \left( \phi_2 \right)$$
$$r_2 \cos \left( \theta_2 \right) = r_3 \sin \left( \phi_1 \right) \sin \left( \phi_3 \right) \cos \left( \phi_2 \right)$$
Likewise, $\tan \left( \theta_2 \right) = \frac{ r_3 \sin \left( \phi_1 \right) \sin \left( \phi_3 \right) \cos \left( \phi_2 \right) }{ r_3 \sin \left( \phi_1 \right) \sin \left( \phi_3 \right) \sin \left( \phi_2 \right)}$ can be continuously extended to $\theta_2 = \phi_2$
If we restrict ourselves to $\mathbb{R}^2$, $\phi_3 = 0$, so $\theta_1 = \phi_1$. I am still somewhat unsure of a formula for the radii $r_1$ and $r_2$. $$r_1 = \begin{cases}
    \frac{ r_3 \cos \left( \phi_1 \right) }{ \cos \left( \theta_1 \right)   } & \text{ if }\cos \left( \theta_1 \right) \neq 0 \\
    \frac{ r_3 \sin \left( \phi_1 \right) \cos \left( \phi_2 \right)}{ \sin \left( \theta_1 \right)} & \text{ if } \cos \left( \theta_1 \right) = 0
\end{cases}$$
$$r_2 = \sqrt{r_3^2 - r_1^2}$$
Unfortunately, I don't believe that my formula for $r_1$ is properly defined as continuity around $\theta_1=0$ may fail. Once more, $\mathbb{R}^2$ could present a simplification $r_1=r_3$.


Average number of terms required for a sum of exponential variables to reach a specific limit

Question: I have a sum $\sum_{i=1}^\infty Y_i$ where $Y_i=AX_i+a$ if $X_i>X_{lower}$ and $Y_i=BX_i+a$ if $X_i<X_{lower}$. Here $X_{lower}, A, a, B$ are positive constants and all $X_i$'s are i.i.d exponential random variables with parameter $\lambda$. I want to know how to find the average number of terms in the sum so that the sum is equal to or greater than some constant $C$.
I already know how to compute the average number of terms if $Y_i=KX_i+a$ where $K>0$. Hence, I have one solution in my mind which has following two steps.
1- Find the average number of terms for $Y_i=AX_i+a$ and $Y_i=BX_i+a$ cases separately.
2- If the number of terms for $Y_i=AX_i+a$ are $j_1$ and number of terms for $Y_i=BX_i+a$ are $j_2$ then the number of terms for my problem will be $$\text{number of terms}=j_1Pr(X_i>X_{lower})+j_2Pr(X_i<X_{lower}).$$
Is it the right answer? I will be very grateful for your suggestions. Thank you.
Comment: In your heuristic, it looks like you are mixing random variables and expectations. I think you want to find the average number of terms required for your sum to _exceed_ a given limit.  Wald's equation is usually used to get bounds.  https://en.wikipedia.org/wiki/Wald%27s_equation
Comment: It gives bounds because usually the overshoot is hard to calculate. It is easy to calculate if you have an exponential distribution, but you have a mixture of exponentials.  If I were you, I would consider the worst-case overshoot over  either exp distribution 1 or exp distribution 2.
Comment: You haven't responded to Michael's comment that it seems you want the sum to *exceed* a given limit. It makes no sense to ask for the number of terms until the sum is equal to some constant, since the probability for that is zero.
Comment: The approach you suggest is incorrect, since it assume just a single decision on the type of the terms, whereas in fact the decision is taken separately for each term, and the sum contains a mixture of the two types of terms.
Comment: @Michael I think Wald equation may not be useful here. Actually this problem is a slight variation of the problem discussed in http://math.stackexchange.com/questions/1809136/average-number-of-terms-required-in-a-sum-of-exponential-variables-to-reach-a-sp?rq=1
Comment: @joriki I have done it right by changing it to "equal to or greater than"
Comment: @MIchael I think we can get an upper bound on the number of terms using the method of http://math.stackexchange.com/questions/1809136/average-number-of-terms-required-in-a-sum-of-exponential-variables-to-reach-a-sp?rq=1 if $A<B$. In this case the average number of terms will be upper bounded by $\frac{\lambda}{A+\lambda a}e^{\frac{\lambda}{A+\lambda a}}C+1$
Comment: @FrankMoses : How do you get that?  I will write up a quick Wald bound below.
Comment: By applying the methodology of http://math.stackexchange.com/questions/1809136/average-number-of-terms-required-in-a-sum-of-exponential-variables-to-reach-a-sp?rq=1
Comment: Yes, but, how do you get $\lambda/(A + \lambda a)$ from that methodology?  That bound gives $\lambda e^{\lambda t}L+1$ and seems to be for a variation on the problem.
Comment: that is the parameter of the random variable $AX_i+a$. I just put this value in the equation you mentioned in your above comment and got that bound
Comment: @Michael I would love to see the bound from the wald's equation
Answer: The Joriki method in that other link is interesting, I would have approached it differently (via Wald) and (hopefully?) that would also give an exact expression for the exponential case.  For the problem at hand, a Wald-based approach is as follows:
Suppose that $\{Y_i\}_{i=1}^{\infty}$ are iid, nonnegative, and have finite expectation $E[Y]>0$. Define $N$ as the smallest time at which the sum of the $Y_i$ values meets or exceeds a positive threshold $C$, so that $\sum_{i=1}^N Y_i \geq C$.  Define
$$Overshoot = \sum_{i=1}^N Y_i - C$$
Then $Overshoot \geq 0$ and
$$ E\left[\sum_{i=1}^N Y_i \right] = C + E[Overshoot] $$
On the other hand, we can write $\sum_{i=1}^N Y_i = \sum_{i=1}^{\infty} Y_iI_i$ for indicator functions $I_i=1\{i \leq N\}$, so the $I_i$ indicators filter out only those terms that are used. Then, by a Wald-type technique:
\begin{align}
 E\left[\sum_{i=1}^N Y_i\right] &=E\left[\sum_{i=1}^{\infty}Y_iI_i\right]\\
&\overset{(a)}{=}\sum_{i=1}^{\infty}E\left[Y_iI_i \right]\\
&\overset{(b)}{=}\sum_{i=1}^{\infty}E[Y_i]E[I_i] \\
&=E[Y]\sum_{i=1}^{\infty}E[I_i]\\
&= E[Y]\sum_{i=1}^{\infty}P[i\leq N]\\
&\overset{(c)}{=}E[Y]E[N]
\end{align}
where (a) holds because we can always pass expectations through an infinite sum of non-negative random variables; (b) holds by the Wald observation that $I_i$ depends only on $Y_1, ... Y_{i-1}$ and so is independent of $Y_i$;  (c) holds by the expectation identity for positive integer random variables $N$.
Equating these two different expressions for $E[\sum_{i=1}^NY_i]$ gives:
$$ E[N] = \frac{C + E[Overshoot]}{E[Y]} $$
This holds for any iid and nonnegative random variables $Y_i$ with $E[Y]>0$, which includes your case.  You can compute $E[Y]$ for your case.  The only difficulty is computing $E[Overshoot]$.  But you could perhaps bound that above and/or below considering the worst-case distribution on the last step.

Using the above technique on the problem from the previous link you gave, I get a slightly different answer (I suspect that previous answer had a minor mistake because the constant $c$ used there should have depended on time, i.e., $c(t)$).  That link was:
Average number of terms required in a sum of exponential variables to reach a specific limit
There, it looks like we have $Y_i = \max[X_i-t, 0]$ for $X_i$ exponential with rate $\lambda$. So:
$$ E[Y] = \int_{t}^{\infty} (x-t)\lambda e^{-\lambda x}dx = \frac{e^{-\lambda t}}{\lambda}$$
$$ E[Overshoot] =  1/\lambda $$
Then, using threshold $C=L$:
$$E[N] = \frac{L+E[Overshoot]}{E[Y]} = (L + 1/\lambda)\lambda e^{\lambda t} = L\lambda e^{\lambda t} + e^{\lambda t} $$
Edit: Joriki fixed his answer to indeed get the final "constant term" as  $c=e^{\lambda t}$, consistent with my answer.
Comment: @FrankMoses : It looks like your $Y_i$ depends only on $X_i$ and hence indeed your $\{Y_i\}$ values are iid. So they do indeed fit the framework of my answer above.
Comment: @FrankMoses : The $Y_i$ random variables are certainly not exponentially distributed. You can see that they are identically distributed (with a distribution more complex than exponential) since you would use the same software to generate each $Y_i$ variable (each run of that software calls a rand() function that gives an independent random value).  You would not need to write different software to generate each $Y_i$.
Comment: @FrankMoses Calculation of $E[Y]$ uses the law of total expectation:  $$E[Y]=E[Y|X>x_{lower}]e^{-\lambda x_{lower}}+E[Y|Xx_{lower}]=E[a+AX|X>x_{lower}]$ and so on.
Comment: A simple lower bound is $E[Overshoot] \geq 0$.  An upper bound is $$E[Overshoot]= E[Overshoot|X_{last}x_{lower}]P[>] \leq \max[E[Overshoot|X_{last}x_{lower}]]$$ Then $E[Overshoot|X_{last}x_{lower}]\leq a + Ax_{lower} + A/\lambda$, with the intuition that once we cross the threshold, either $X_{last}$ is already done, or it is not and we wait an additinoal $A/\lambda$ on average.
Comment: As far as I understand this method still assumes that same parameter is used for all the $Y_i$ however in my case it is slightly different because any particular $Y_i$ can have one of the two different parameters. The problem that I am facing is how to tackle two different parameters
Comment: I understand the independent part but I am unable to understand the identical part because they maybe all exponential but their parameters are different. If different parameter also comes under identical than I have no problem.
Comment: what I understood from the above explanation is that $E[overshoot]$ will be either $E[AX_i+a]$ or $E[BX_i+a]$. which ever is smaller if I want to get the lower bound and whichever is larger if i want to get the upper bound
Comment: As the final step for finding $E[N]$ can we write the upper bound of $E[N]$ as $E[N]=\frac{\lambda C}{Ae^{\frac{\lambda a}{A}}}+1$ if  $\frac{Ae^{\frac{\lambda a}{A}}}{\lambda}<\frac{Be^{\frac{\lambda a}{B}}}{\lambda}$ or otherwise the upper bound of $E[N]$ is $E[N]=\frac{\lambda C}{Be^{\frac{\lambda a}{B}}}+1$ if $\frac{Ae^{\frac{\lambda a}{A}}}{\lambda}>\frac{Be^{\frac{\lambda a}{B}}}{\lambda}$. Here, I used $E[AX_i+a]=\frac{Ae^{\frac{\lambda a}{A}}}{\lambda}$ and $E[BX_i+a]=\frac{Be^{\frac{\lambda a}{B}}}{\lambda}$
Comment: Actually I am confused about which value of $Y_i$ should be considered for finding $E[Y]$. $AX_i+a$ or $BX_i+a$. And further what should be the value of $E[overshoot]$. Thank you for your help.
Comment: and the $E[overshoot]$ will be equal to $E[X_i]$ or will it be different too?
Comment: This problem has become more complex than I thought initially. Is it possible to get a less complex value for $E[overshoot]$ if we always use $Y_i=X_i+a$ irrespective of the value of $X_i$.
Comment: in the above comment i wanted to say $Y_i=AX_i+a$ instead of $Y_i=X_i+a$
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/41223/discussion-between-michael-and-frank-moses).
Comment: I have sent a message on the online discussion
Comment: I am reading your paper entitled "Utility optimal scheduling in processing networks". I have some problem in understanding it. I have posted a question in SE at http://math.stackexchange.com/questions/1834125/optimal-average-utility-of-the-processing-network-needed. I will be very thankful to you if you can provide some answer. Thank you in advance.


Is the space of uniformly left continuous functions on [0,1] complete?

Question: We'll say that a function on $[0,1]$ is uniformly left continuous if for every $\epsilon > 0$ there exists $\delta > 0$ such that $x \in (y - \delta, y)$ implies $|f(x) - f(y)| < \epsilon$ for every $x, y \in [0,1]$.  I want to know if the space of all such functions is complete with respect to the uniform norm.
I'm interested in this space because I suspect that it is the completion of the space of piecewise constant functions which are continuous from the left.
Thanks in advance for the help!
EDIT:
As was pointed out in the comments, what I wrote above is equivalent to uniform continuity.  I think the following revised definition captures what I want.  $f$ is uniformly left continuous if for every $\epsilon$ there is a partition $0 = t_0 < t_1 < \ldots < t_n = 1$ such that $|f(x) - f(y)| < \epsilon$ whenever $t_0 \leq x \leq y \leq t_1$ or $t_i < x \leq y \leq t_{i+1}$ for $i > 0$.  So with this definition the characteristic function of $(1/2,1]$ is uniformly left continuous while the characteristic function of $[1/2,1]$ is not.
Here are the examples that I'm really trying to kill.  Take $f$ to be the function which is 0 on the interval $[0,1/2]$ and let $f(x) = 1/(x-1/2)$ on $(1/2,1]$.  This is left continuous, but it shouldn't be uniformly left continuous.  Even if you insist that $f$ be bounded, you could set $f(x) = \sin(1/(x-1/2))$ for $x$ in $(1/2,1]$ and get a left continuous function which is not uniformly left continuous.  If you can think of a better definition that captures this intuition, let me know.
Comment: Isn't that condition just the same as uniform continuity?
Comment: Isn't the condition "for every $\varepsilon>0$ and $y\in\left[0,1\right]$, there exists $\delta$ such that..."?
Comment: @Chris Eagle: You're quite right... I edited to give a better definition.
Comment: @Davide Giraudo: I don't think this will be as easy to prove as completeness of $C[0,1]$.  In the $C[0,1]$ case, you take a uniformly Cauchy sequence $f_n$, prove that its pointwise limit is continuous, and show that $f_n$ converges to its pointwise limit uniformly.  Proving that the pointwise limit of a uniformly Cauchy sequence is continuous is much easier than proving that it's uniformly continuous, but the two statements are equivalent in $C[0,1]$.  As my examples above show, this equivalence fails for left continuous functions (whatever uniformly left continuous actually means).
Answer: The standard $3\epsilon$ trick works.  Suppose $f_n$ is a Cauchy (in uniform norm) sequence of uniformly left continuous functions on $[0,1]$, and $f$ its pointwise limit.  Given $\epsilon > 0$, take $n$ large enough that
$|f_n(x) - f(x)| < \epsilon/3$ everywhere.  Let $0 = t_0 < \ldots < t_k = 1$ be a partition that satisfies your (revised) definition for the function $f_n$ with $\epsilon$ replaced by $\epsilon/3$.  Then for $t_0 \le x \le y \le t_1$ or $t_i < x \le y \le t_{i+1}$,
$|f(x) - f(y)| \le |f(x) - f_n(x)| + |f_n(x) - f_n(y)| + |f_n(y) - f(y)| < \epsilon$.
Comment: Quite right.  I unfortunately didn't go back and try to prove completeness after I revised my definition - maybe I would have discovered this argument myself.  Either way, thanks!


Why is return included in the alternative constructor?

Question: class Student:
    def __init__(self, first, last):
        self.first = first
        self.last = last

    @classmethod
    def from_string(cls, emp_str):
        first, last = emp_str.split("-")
        return cls(first, last)

Student_1 = Student("Cool", "Person")

Student_2 = "Another-One"

Student_2 = Student.from_string(Student_2)

Why is return used in this class method? I know you need it to work. But I'm not able to wrap my mind around why you need to include it. From what I know - in this example in the classmethod, cls(first, last) is doing the same thing as __init__(self, first, last). But why the need to include a return in there? Shouldn't just cls(first, last) be enough to call the __init__, which is what you already do when constructing the instance like Student_1?
Can you explain where my confusion lies?
Comment: Note that `__init__` is *not* a constructor. It is an initialiser for an already constructed object.
Answer:
Shouldn't just cls(first, last) be enough to call the __init__, which is what you already do when constructing the instance like Student_1?

Yes, calling the constructor like this will result in __init__ being called on a new instance of cls. However, without return, that new instance will be discarded and nothing will be returned from the from_string() method.
It might be more clear if you make it a global function rather than a class method. Can you see the difference between these two functions and why the first one doesn't work?
class Student:
    ...

def student_from_string(emp_str):
    first, last = emp_str.split("-")
    Student(first, last)

student_from_string("A-B")  # None

def student_from_string(emp_str):
    first, last = emp_str.split("-")
    return Student(first, last)

student_from_string("A-B")  # Student("A", "B")

Why isn't return needed in __init__? Because you're not calling student = [new student].__init__(...), you're using student = Student(...). __init__ is a special initialization method that is not expected to return anything. You rarely call it explicitly (except on super()), but it is called automatically during a normal constructor call.
See also: https://stackoverflow.com/a/674369/23649
Answer: You notice that from_string is a classmethod (not instance method).
In the line Student_2 = Student.from_string(Student_2)
When you call from_string, it is assigned to another variable. (you are assigning to the same Student_2 )
Without return, this assignment will not happen (None will return there.)
[Note that, cls function returns an object instance]
The __instance__ and from_string are not doing the same thing here.
Inside instance, you are assigning the values to instance properties.
But from_string, you are calling the constructor again, to assign the parameters in the instance properties.


Monitor MySQL Replication

Question: What is the best practice for monitoring a slave to make sure that it is
a) Still running
b) Not too far being the master
I would like to alert by email if it is behind, happy to write a script or two to hook into command line applications.
Answer: 1
you can use maatkit's mk-heartbeat
2
you can look at result of
show slave status;

run on sql slave but Seconds_Behind_Master is disturbingly inaccurate at times.
3
you can hack your own solution, similar to mine - i use it both for nagios monitoring and for feeding munin charts showing 'seconds behind master'.
on master server i have simple cron job:
* * * * * root /usr/local/bin/repltest

where repltest is:
#!/bin/bash
start=`date +%s`
d=0
while [ $d -lt 60 ] ; do
        echo "update repl_test set t= NOW(); " |mysql --defaults-file=/etc/mysql/debian.cnf repl_test
        sleep 3
        d=$(( `date +%s` - $start ))
done

on the slave i monitor value returned by:
echo "select UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(t) from repl_test" |  mysql --defaults-file=/etc/mysql/debian.cnf -N repl_test

local time on all servers is synchronized via ntp.
repl_test db contains:
CREATE TABLE IF NOT EXISTS `repl_test` (`t` datetime NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `repl_test` (`t`) VALUES(NOW());

if you run replication - i suggest you also set up mk-table-checksum to compare content of your sql servers from time to time.
Answer: pQd has it, checking 'show slave status' is the easiest way.  Regarding Seconds_behind_master being inaccurate, I wanted to mention that the value is the difference in the timestamp for the statement being read out of the relay log by the slave SQL thread; it's not related to an estimate of how long it will take to catch up.  For instance, a single long-running update that takes, say, an hour to run will cause the slave to appear up to an hour behind its master but once the statement completes it could very well only have 1 second of work left to do to catch up.
Also, you will want to grant 'REPLICATION CLIENT' to the user that you will be monitoring from in order to retrieve the slave status;
Comment: +1 for pointing problems with Seconds_behind_master inaccuracy
Answer: The obvious answer as others have said is to use some variation on SHOW SLAVE STATUS.  I use the checker built into Nagios personally, but that is because I do all kinds of other monitoring through nagios already.  There is a catch though, it is possible for SHOW SLAVE STATUS to show both processes running and yet for the slave to be hung.  From what we can tell (because we had the problem and looked into it), the problem occurs when there are network burps of some duration that is too short to kill the slave outright but too long for it to recover properly.  We came up with a work around where we look at the time stamp of the latest entry in a table that changes routinely and compare it between the master and slave then throw an alert if it is "too far" behind.  Not perfect and it would only work in certain circumstances, but consider yourself warned.
Comment: +1 for checking a table's timestamp
Answer: You can refer this blog post which mentions all tools open-source and Commercial which shows
http://blog.webyog.com/2012/11/20/how-to-monitor-mysql-replication/
Typically this blog includes tools like
pt-heartbeat: Convenient tool to monitor slave lag in real time.
pt-slave-restart: Watches and restarts Slave on error.
pt-slave-find: Finds replication hierarchy of the slaves.
pt-table-checksum: Checks if databases on the slaves are in sync with their master.
MySQL Enterprise Monitor: A "Virtual DBA Assistant" by Oracle is an agent based monitoring tool which has a neat web based GUI.  'Replication' tab which gives a topological view of all the Masters and their Slaves along with the output of SHOW SLAVE STATUS and SHOW MASTER STATUS.
MONyog-MySQL monitor and advisor: Which supports replication monitoring and managing include-'Replication' tab that give a topological view of all the Masters and their Slaves along with the SHOW SLAVE STATUS and SHOW MASTER STATUS.
Answer: You should execute the query SHOW SLAVE STATUS and make sure that both Slave_IO_Running and Slave_SQL_Running have a value of Yes. If not, the slave will NOT be able to recover automatically. If both are Yes then replication is still working, even though there may be a delay (Seconds_Behind_Master).
Answer: A fairly good tool is rep_mon, part of the MyCat suite, it's basically just a perl script in the style of pQd's third option, however it's easily configureable and well tested. Once configured you can run it as a quick test yourself, or schedule it in cron to send out emails if there's a problem.
When run, it basically just outputs either "OK", or what the error is. You can also have it alert you if the seconds-behind hits a certain threshold (set by you).
However, if it's just threshold monitoring you want, I'd suggest going for maatkit, it works by actually inserting and later querying using real SQL rather than the possibly inaccurate output of SHOW SLAVE STATUS.
Answer: Use
mysql_config_editor set --login-path=local --host=<< your slave >> --user=username --password

and
mysql_config_editor set --login-path=remote --host=<< your master >> --user=username --password

to set predefined login values to avoid Warning: Using a password on the command line interface can be insecure.
Use these to query both MySql servers:

Compare log position on master against Exec_Master_Log_Pos on slave:
master_log=$(mysql --login-path=remote  -e "show master status" | grep -v File | awk '{print $2}')
slave_exec=$(mysql --login-path=local -e "show slave status \G" | grep Exec_Master_Log_Pos | awk '{print $2}')
diff=$(( $master_log - $slave_exec ))
Check slave IO status to see if it's running:
IO_Status=$(mysql --login-path=local -e "show slave status \G" | grep Slave_IO_Running | awk '{print $2}')
Check slave SQL status to see if it's ok or not:
SQL_Status=$(mysql --login-path=local -e "show slave status \G" | grep "Slave_SQL_Running:" | awk '{print $2}')

You can then use the values of $diff, $SQL_Status, and $IO_Status to send warning emails if they didn't match certain values according to your preference
Answer: Here's how to do it with Zenoss: link text
Answer: You could use the check_mysql program from the Nagios Plugins project (https://github.com/nagios-plugins/nagios-plugins) like this:
/usr/lib/nagios/plugins/check_mysql -H <HOST> -u <MONITORING_USER> -p <PASSWORD> -S -w 60 -c 120

Where I think that depending on your use case you will need to update the values for the warning (-w) and critical (-c) seconds behind master thresholds.
Finally, note that the MONITORING_USER user only requires the REPLICATION CLIENT GRANT.
PS: You don't need a Nagios system to use the previous approach. You could use check_mysql alone.

Monitor MySQL Replication


Passar parâmetros de cabeçalho do Web Service?

Question: Estou tentando realizar uma chamada de web service no AngularJS, no entanto estou recebendo a seguinte mensagem de erro no console do navegador(testei no chrome e Firefox):

XMLHttpRequest cannot load
No 'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:8083' is therefore not allowed
  access.

Pelo o que entendi o soap reclamou que eu não enviei os cabeçalhos da requisição. Realmente o serviço exige cabeçalhos conforme abaixo, no entanto não sei como passá-los no parâmetro da chamada post, apenas enviei os parâmetros do body da requisição.
Parâmetros do cabeçalho: usuário e loja:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"

   <soapenv:Header>
      <v1:header>
         <usuario>?</usuario>
         <loja>?</loja>
      </v1:header>
   </soapenv:Header>
   <soapenv:Body>
      <v1:inImprimirFatura>
         <tipo-fatura>?</tipo-fatura>
         <numero-cpf>?</numero-cpf>
      </v1:inImprimirFatura>
   </soapenv:Body>
</soapenv:Envelope>

Service que faz a chamada post:

function GerarSegundaViaFaturaTotvsPDF()
{
 var metodo = 'imprimirFatura';
 var url = '
 var param = {};
 param.tipoFatura = "ATUAL";
 param.CPF =
 return $soap.post(url, metodo, {req: param});
}

Como passo os parâmetros de cabeçalho na chamada de forma simples sem mudar a estrutura do meu código?
Answer: Geralmente esse tipo de erro está relacionado com o CORS (Cross-Origin Resource Sharing).
Neste post https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource você pode verificar melhor e tem mais duas referências explicando o conceito. Uma delas cloquei acima.
Abaixo segue a citação do post que acredito que tenha a ver com o seu problema:

If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.


Calculate the equation of a sigmoid curve given (partial) data that looks like an exponential fit

Question: The data that I am modeling should follow a sigmoid curve, however, I am only given a partial amount of data that looks like an exponential trend.
How can I calculate the equation of a sigmoid curve that best fits this partial amount of data? I have attached an image further explaining the problem. The partial data I have fits a curve in black, I want to produce an equation for a sigmoid curve (in blue).
Any thoughts on the best way to approach this problem? TIA
Answer: First, you need to define what you mean by sigmoid curve. In this answer I will use
$$S(x;a,b)=\frac{a}{1-e^{-bx}}, \quad a,b \in \mathbb R,b\neq 0$$
Where $a,b$ are your parameters. e.g., increasing $|a|$ stretches your sigmoid along the y-axis, and changing $|b|$ stretches it along the x-axis. You could use more/less/other parameters.
Then is the question of finding the best fit. One common method is minimising the sum of the distances between your data points and your sigmoid (or least-squares method). There are other methods available, but for this simple problem, I assume this is the one you need.
Suppose your data is $(x_1,y_1),..., (x_n,y_n)$. Then your problem is about finding the values of $a$ and $b$ that minimise the quantity
$$F(a,b)=\sum_i ||y_i-S(x_i;a,b)||^2$$
If your dataset is small you can do it by hand. Otherwise, you can appeal to optimisation algorithms such as gradient descent or simulated annealing. Good luck!


Dropdown Item not making api call on first try

Question: Im having an issue where when I select a new Dropdown Item the Item isnt saved or the api call isnt made until I select the item again. So if I select Sales from the the Dropdown menu and and refresh the old value will still be there. Ive consoled out the value of the state (permission and adminID) and as soon as I select a dropdown item they are both set to the state so Im not sure whats causing it not to set on the first try.

const UserCard = (props) => {
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [permission, setPermission] = useState()
  const [adminID, setAdminID] = useState()

    const item = props.item;
    const toggle = () => {
      setDropdownOpen(prevState => !prevState)
    };
    const adminUpdate = (perm, id) => {
      setPermission(perm)
      if(!permission || !adminID){
        return
      }else{
        api.UserManagement.put(
          adminID,
          {permissions: [permission]}
        ).catch(err => {
          console.log("error", err, err.status)
        })
      }
    }
console.log(permission, adminID)
  return (
    <>

        {item.name || "-"}
        {item.email}
        {!permission ? item.permissions : permission}

        <Dropdown style={{ fontSize: "30px",borderColor: "white", backgroundColor: "white", color: "gray"}} isOpen={dropdownOpen} toggle={toggle}>
        <DropdownToggle
        tag="span"
        data-toggle="dropdown"
        aria-expanded={dropdownOpen}
      >
          ...
      </DropdownToggle>
      <DropdownMenu onClick={() => setAdminID(item.id)} key={item.id}>
        <DropdownItem value={"Admin"} onClick={e => adminUpdate(e.target.value)}>Admin</DropdownItem>
        <DropdownItem value={"Sales"} onClick={e => adminUpdate(e.target.value)}>Sales</DropdownItem>
        <DropdownItem value={"Medical"} onClick={e => adminUpdate(e.target.value)}>Medical</DropdownItem>
      </DropdownMenu>
        </Dropdown>

    </>
  );
};

const UserList = ({}) => {
  const [list, setList] = useState([]);
  const [errors, setErrors] = useState();

  useEffect(() => {
    api.UserManagement.list()
      .then((result) => {
        let list = [];
        if (result) {
          list = result.items;
        }
        setList(list);
      })
      .catch((err) => {
        if (err.status) {
          console.log("error", err, err.status);
          setErrors([err]);
        }
      });
  }, []);

  return (
    <>
      <ContentRow>
        <Row>
          <Col md="8">

              <Link to={"/"}>
                <Button color="link"><</Button>
              </Link>
              User Management

          </Col>

            <Link to={"/invitations"}>
              <Button className="header-button" block color="primary">
                Invite Users
              </Button>
            </Link>

          <Col md="4"></Col>
        </Row>
      </ContentRow>
      <ContentRow>
        <ErrorList errors={errors}/>

              User
              Email Address
              Role

            {!list ? (
              <PageLoadSpinner />
            ) : (
              list.map((item) => <UserCard item={item} />)
            )}

      </ContentRow>
    </>
  );
};

export default UserList;

Answer: Reason
The code is not working due to improper usage of useState hook. useState is asynchronous in nature. Due to this, the variables are not updated with proper values when you are using it. The current code is assuming variables to be updated in synchronous manner.

setPermission(perm) is done in one line and permission variable is used in next line. But permission variable won't be updated at that time.
Same seems for admin variable.

That's why for the first time, the code doesn't work (the variables are not updated). But when you click again, the older values are picked; condition is satisfied; making it work.
Read more about it here.
Fix
There can be two ways in which this code can be fixed.
Approach 1
In the if condition, you can use the function arguments directly instead of variable from use state.
The relevant fixed code will be:
const UserCard = (props) => {
    ...
    const adminUpdate = (perm, id) => {
      if(!perm || !id){ // Change this condition here
        return
      }else{
        api.UserManagement.put(
          id,
          {permissions: [perm]} // Change here as well
        ).catch(err => {
          console.log("error", err, err.status)
        })
      }
    }

  return (
    <>
      ...
      </DropdownToggle>
      <DropdownMenu onClick={() => setAdminID(item.id)} key={item.id}>
        // Pass id onClick of DropdownItem also
        <DropdownItem value={"Admin"} onClick={e => adminUpdate(e.target.value, item.id)}>Admin</DropdownItem>
        <DropdownItem value={"Sales"} onClick={e => adminUpdate(e.target.value, item.id)}>Sales</DropdownItem>
        <DropdownItem value={"Medical"} onClick={e => adminUpdate(e.target.value, item.id)}>Medical</DropdownItem>
      </DropdownMenu>
        </Dropdown>
      ...
    </>
  );
};

This approach almost removes the usage of useState hook as you are directly using variables passed from function
Approach 2
You can also use useEffect hook along with useState. useEffect takes dependency array as second argument and will trigger function call when any of the variable is changed. So, the logic will be splitted into 2 parts:

Variables will be updated separately by useState
Api call will be triggered when any of variable is updated in useEffect.

The relevant fixed code will be:
const UserCard = (props) => {
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [permission, setPermission] = useState()
  const [adminID, setAdminID] = useState()

    const item = props.item;
    const toggle = () => {
      setDropdownOpen(prevState => !prevState)
    };
  useEffect(() => {
    if (permission && adminID) {
        api.UserManagement.put(
          adminID,
          {permissions: [permission]}
        ).catch(err => {
          console.log("error", err, err.status)
        })
    }
}, [permission, adminID]) // This will trigger the function call when any of these 2 variables are modified.

  return (
    <>
      ...
      </DropdownToggle>
      // setAdminID on click
      <DropdownMenu onClick={() => setAdminID(item.id)} key={item.id}>
        // setPermission onClick
        <DropdownItem value={"Admin"} onClick={e => setPermission(e.target.value)}>Admin</DropdownItem>
        <DropdownItem value={"Sales"} onClick={e => setPermission(e.target.value)}>Sales</DropdownItem>
        <DropdownItem value={"Medical"} onClick={e => setPermission(e.target.value)}>Medical</DropdownItem>
      </DropdownMenu>
        </Dropdown>

    </>
  );
};

Approach 1 vs Approach 2
It's upto you which approach to chose from. Both will get you the result but differ in base approach. Approach 1 is triggering the API call directly on click of dropdown item but Approach 2 is updating the variables on click of dropdown items and the change of those variables is triggering the API call.
Hope it helps. Revert for any doubts/clarifications.


Cancellation laws in Rings

Question: In rings left and right cancellation laws generally don't hold.
can anyone generalize some cases so that we are ensured  when the cancellation laws hold in rings?(the case I found was in Integral domains they hold.)
Comment: That's just the class of "noncommutative domains"
Answer: Suppose that $ab = ac$ implies $b = c$ for non-zero $a$. Then $a(b-c) = 0$ implies $b-c = 0$. Suppose $a$ is a left zero divisor, i.e. $ad = 0$ for some non-zero $d$. Then taking $b = c+d$ gives $a(b-c) = ad = 0$. So $c = b = c+d$, so $d = 0$, which is a contradiction. So left cancellation implies that the ring has no zero divisors.
Similiarly, right cancellation also implies that the ring has no zero divisors.
Conversely, if a ring has no zero divisors (i.e. it is a domain) then $ab = ac$ ($a \neq 0$) implies $a(b-c) = 0$ implies $b - c = 0$ as $a$ is non-zero and there are no zero divisors, hence $b - c$. Similiarly right cancellation holds.
Conclusion: the following are equivalent for a ring $R$: $R$ has no zero divisors; the left cancellation law holds in $R$; the right cancellation law holds in $R$.
Comment: :Your choice of $b,b=c+d$ does'nt seems to be honest as just before  this assumption you chose $d$ to be non-zero,while just after this you chose $d=b-c$,which is  zero.
Answer: Let $R $ be a ring with cancellation laws holding.
Let $a,b\in R$.
Now,if $ab=ac$ then by left cancellation law we get,$b=c$.
Similarly,if $ba=ca$ then by right cancellation law we get,$b=c$.
Let $ab=0$ then if $a\neq 0$.So,$ab=a0,$by left cancellation law $b=0$.
Therefore,if $ab=0$ then either $a=0$ or $b=0$.

Cancellation laws in Rings


Angularjs $location.path() not redirecting

Question: why is it that I am not redirected to other URL when I use angular.js $location.path ?
.controller('CheckCtrl', function($scope, $localStorage, $location) {
    $scope.check = function(){

        if($localStorage.hasOwnProperty("accessToken") === true) {
            alert("CheckCtrl logged in" + $localStorage.accessToken);
            $location.path("/post-report");
        }else{
            alert("CheckCtrl not logged in" + $localStorage.accessToken);
            $location.path("home.login");
        }
    };

})

Even though $localStorage.hasOwnProperty is true already since it contains token from Facebook.
I also try $location.reload() but still no luck.
Comment: There are lots of the same questions here, but check [this](http://stackoverflow.com/questions/11784656/angularjs-location-not-changing-the-path) post out.
Comment: Actually, I already viewed that post and I try to add `$scope.apply` after `$location.path('home.login')` but still it doesn't work. I also `alert()` the path to check, it gives me the correct path.
Comment: it doesn't work for me too.
Comment: Try the solution from @PauloOliveira in this post, http://stackoverflow.com/questions/11784656/angularjs-location-not-changing-the-path i think is the last answer.
Answer: Use this :-
$location.path("/post-report").replace();
or
$location.path("/post-report");
if(!$scope.$$phase) $scope.$apply()

It replace your current location with the new location.
Comment: It doesn't work either. I'm using Ionic framework for mobile app.


How do I use system.reactive to perform a do while that uses a value from within per-iteration?

Question: For the sake of example, let's assume I've decided to start with the following:
var startingSequence = await GetLastSequence(database);

return Observable.Create<ExternalSourceChange>(async (observer) =>
{
    var currentSequence = startingSequence;

    var done = false;
    do
    {
        var changes = await CreateRequest()
            .AppendPathSegment(database)
            .AppendPathSegment("_changes")
            .SetQueryParams(new
            {
                since = currentSequence,
                include_docs = "true",
                limit = 1,
            })
            .GetJsonAsync<ExternalSourceChangeJson>();

        // note: If we've already processed past this sequence, skip it.
        if (string.CompareOrdinal(changes.last_seq, currentSequence) <= 0)
        {
            continue;
        }

        var result = changes.results.First();
        var deleted = result.doc.GetValue("_deleted")?.Value<bool>() ?? false;

        var databaseChange = new ExternalSourceChangeJson(result.id, result.doc.ToString())
        {
            Deleted = deleted,
        };

        observer.OnNext(databaseChange);

        currentSequence = ((List<ExternalSourceChangeListJson>)changes
            .results)
            .OrderBy((result) => result.seq)
            .LastOrDefault()?.seq
            ?? currentSequence;

        done = changes.pending == 0;

    } while (! done);

    await SetLastSequence(database, currentSequence);

    observer.OnCompleted();

    // note: Not sure I have anything to do here.
    return () => {};
});

Is there anything I can do with the above to golf it into leveraging more of system.reactive?

Changes<dynamic> is produced on each iteration
currentSequence and done are by far the two things I feel like I could be doing a better job of managing
Comment: Why not define just a `Subject` and call `OnNext()` with the `results.Payload` value?
Comment: Hmm, maybe?  I'm not sure how I'd wire in the use of `results.NextPageHash` in that case though so that I could tie the lifecycle of `currentPageHash` in as part of the stream?
Comment: `currentSequence` doesn't look like it's changing. Is it supposed to change? Could you clarify or post an MVCE?
Comment: For sure, apologies.  Example is now updated with what I'm currently using (and it works).
Comment: Using `Observable.Create` is not the way to go here. If ever you find yourself returning `return () => {}` or `return Disposable.Empty;` then you're doing something wrong.
Answer: Using Observable.Create is not the way to go here. If ever you find yourself returning return () => {}; (or return Disposable.Empty; which you see a lot) then you're doing something wrong.
There's almost always a way to use the built-in operators to get a good resilient query.
Now, since you've got a lot going on in your query that I can't easily replicate I'm going to make a simplified example of how you might do what you want.
To start with here's my extreme simplification for getting something from the database:
private static int __counter = 0;
public Task<int> GetCounterAsync() => Task.Run(() => __counter++);

Now I'm going to code up the wrong approach, based on your code, so that you can see how my final code will relate to yours. My goal here is to retrieve values from the "database" until I get a 10 and finish with that value.
IObservable<int> query =
    Observable.Create<int>(async observer =>
    {
        var done = false;
        do
        {
            var counter = await GetCounterAsync();
            observer.OnNext(counter);
            done = counter == 10;
        } while (!done);
        observer.OnCompleted();
        return () => { };
    });

This is designed to look like your code. I want to stress that this is not the way to do it.
Here's the correct way.
IObservable<int> query =
    Observable
        .Defer(() => Observable.FromAsync(() => GetCounterAsync()))
        .Repeat()
        .TakeUntil(x => x == 10);

The Observable.Defer is important as it causes the Observable.FromAsync(() => GetCounterAsync()) to be called anew each time the .Repeat() operator is triggered. Without it the result of the first call to Observable.FromAsync(() => GetCounterAsync()) is repeated indefinitely.
Now, if you need to include state within your query, which is often a reason that people use Observable.Create, then you can always wrap the whole thing in another Observable.Defer.
IObservable<int> query =
    Observable
        .Defer(() =>
        {
            var finish = 10;
            return
                Observable
                    .Defer(() => Observable.FromAsync(() => GetCounterAsync()))
                    .Repeat()
                    .TakeUntil(x => x == finish);
        });

In this way any state that is needed in your query is created again for each and every subscriber.
If you then need to do anything with the state at the end, you can do this:
IObservable<int> query =
    Observable
        .Defer(() =>
        {
            var finish = 10;
            return
                Observable
                    .Defer(() => Observable.FromAsync(() => GetCounterAsync()))
                    .Repeat()
                    .TakeUntil(x => x == finish)
                    .Finally(() => Console.WriteLine($"Finished at {finish}"));
        });

query.Subscribe(x => Console.WriteLine(x));

That produces:

0
1
2
3
4
5
6
7
8
9
10
Finished at 10

Let me know if this helps or if there's something I've missed in your question.
Comment: I'll try to adapt your suggestions to what I have and report back, looks promising though!  Also, I absolutely appreciate your simplification, that's honestly what I was hoping for.
Answer: Here is how you could make it more robust, by including error handling and reacting to unsubscription.
return Observable.Create<ExternalSourceChange>(observer =>
{
    var cts = new CancellationTokenSource();
    var fireAndForget = Task.Run(async () =>
    {
        try
        {
            while (true)
            {
                cts.Token.ThrowIfCancellationRequested();
                var changes = await CreateRequest().GetJsonAsync();
                //...
                observer.OnNext(databaseChange);
                //...
                if (changes.pending == 0) break;
            }
            observer.OnCompleted();
        }
        catch (OperationCanceledException ex) when (ex.CancellationToken == cts.Token)
        {
            // Do nothing (the subscriber unsubscribed)
        }
        catch (Exception ex)
        {
            observer.OnError(ex);
        }
    });

    return System.Reactive.Disposables.Disposable.Create(() =>
    {
        cts.Cancel();
    });
});

You could pass the cts.Token to any async methods you call that accept cancellation tokens, for even faster termination of the loop.

Update: I just noticed another overload of the Observable.Create method, that accepts an async delegate with CancellationToken parameter:
// Summary:
// Creates an observable sequence from a specified cancellable asynchronous Subscribe
// method. The CancellationToken passed to the asynchronous Subscribe method is
// tied to the returned disposable subscription, allowing best-effort cancellation.
public static IObservable<TResult> Create<TResult>(
    Func<IObserver<TResult>, CancellationToken, Task> subscribeAsync);

This could be used to simplify things, by getting rid of the fire-and-forget task, the CancellationTokenSource and the Disposable.Create at the end.
return Observable.Create<ExternalSourceChange>(async (observer, cancellationToken) =>
{ // etc...

Comment: You've clearly thought about this. That's good. I'd avoid the `cts.Token.ThrowIfCancellationRequested();`, though, and just go with a `if (changes.pending == 0 || cts.IsCancellationRequested) break;`. I don't think it's great idea to throw like that if it can be avoided.
Comment: @Enigmativity I wanted to avoid calling `observer.OnCompleted()` in case of unsubscription, although in may not be important.
Comment: Just check the token again. Throwing exceptions is usually a bad idea if they can be avoided.
Comment: @Enigmativity yes, or I could do `if (cts.IsCancellationRequested) return`. But if the token is passed to `GetJsonAsync()` then I will have to catch the exception anyway. Normally creating/subscribing/unsubscribing to observables is not something that happens in tight loops, so I don't think that matters too much.
Comment: If the exception happens in a different thread, does the thread get interrupted when the exception fires? If it does then that can cause issues. If it doesn't then the code can wait to inspect the token in the loop.
Comment: @Enigmativity I agree with you in general. The reason I would stick to the `ThrowIfCancellationRequested` pattern in this case is for having a single exit point from the method in case of unsubscription. I see it as a compromise between efficiency and simplicity.


Wordpress - Displaying a nav menu from functions.php using hooks

Question: I am trying to call a menu to display in a certain place of my page. The theme has a hook above the content that I want to use as the place to display the menu. I do not want to modify the core files of the theme, so the goal is to achieve this using only functions.php modifications
I am adding the following code to my functions.php
On my menu panel, I already have assigned the menu "categories" to the "catmenu" theme location.
register_nav_menu( 'catmenu', 'Categories Menu' );

//adds category menu on single post pages
function add_catmenu()
{
wp_nav_menu(array('menu'=>'categories'); }

add_action('thematic_abovecontent', 'add_catmenu');

Wordpress doesn't seem to be getting it. I get a Parse error: syntax error, unexpected ';' in C:...\functions.php on line 253
Line 253 is the one that has the wp_nav_menu call.
I have been trying modifications of this, like echoing that whole line 253, but again I get errors or it doesn't work.
I don't know how to accomplish this. Any suggestions? Thanks in advance!!
Answer: You're missing a closing parenthesis:
wp_nav_menu(array('menu'=>'categories')); }


how to change value of submit button of comment form?

Question: I wanted to change the default value of submit button in comment form from "Save" to "Post". I wanted to do that using a module , not javascript. So I wrote the following code in my module.
 function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id){

     $form['actions']['submit'] = array(

      '#value' => t('Post Comments'),
     );
     }

But instead of changing the value of submit button, this module is making the submit button hidden. If I add return $form  , then the submit button displays but with the same default text "Save". Any suggestions please. Thank you.
Answer: You're replacing the entire element at the moment (which is why it doesn't show). You can change a specific property in the array like so:
$form['actions']['submit']['#value'] = t('Post Comments');

That way you're just setting the #value property, and not removing the other properties that already exist for the element.
Comment: Yes. That was the mistake I was doing.It works now. Thank you for your quick response Clive.


how to show android wifi setting when wifi is off in unity3d?

Question: I have a online android game , I want my game check WIFI and if WIFI is off automatic open android WIFI settings . How can send parameter to Android core till show WIFI setting ?
Answer: Try to make Unity-Android plugin.
then you can check WIFI and if WIFI is off automatic open android WIFI settings
http://docs.unity3d.com/Documentation/Manual/PluginsForAndroid.html
Answer: Try
<code>startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS, 0);
</code>
Comment: The question here was how to open settings from Unity, not the Android SDK.


Referenciar componentes da Activity

Question: Pesquisei porém não encontrei resposta.
Eu preciso acessar um TextView que está presente na minha Activity dentro de uma Java Class que é independente da Java Class da própria Activity.
A forma que eu tentei foi criando uma referência: public static TextView txtJogo;, porém, está dando uma exception:

"Only the original thread that created a view hierarchy can touch its views."

Como estou tentando:
CadastroAnuncioActivity.txtJogo.setText(anuncio.getTitulo());

Segue a classe onde preciso ter acesso ao TextView:
public class IGDBHelper {

    //  public JSONArray json = new JSONArray();

    // public void setJsonArray(JSONArray jsonArray){
    //    this.json = jsonArray;
    // }

    public void pesquisarJogo(String string) {
        IGDBWrapper igdbWrapper = new IGDBWrapper("c59880bb3fdc0b21e75c85b89745fd8d", Version.STANDARD, false);
        Parameters parameters = new Parameters().addSearch(string).addFields("id,name,summary,popularity,total_rating").addLimit("1");
        igdbWrapper.search(Endpoints.GAMES, parameters, new OnSuccessCallback() {
            @Override
            public void onSuccess(@NotNull JSONArray jsonArray) {
                System.out.println(jsonArray + "anuncio");
                jsonToObj(jsonArray);
            }

            @Override
            public void onError(@NotNull Exception e) {

            }
        });

    }

    public void jsonToObj(JSONArray resultadoDaPesquisa) {
        Anuncio anuncio = new Anuncio();
        JSONObject jsonObject = null;
        try {
            for (int i = 0; i < resultadoDaPesquisa.length(); i++) {
                jsonObject = resultadoDaPesquisa.getJSONObject(i);
                String id = jsonObject.getString("id");
                String nome = jsonObject.getString("name");
                String descricao = jsonObject.getString("summary");
                String popularidade = jsonObject.getString("popularity");
                //String rating = jsonObject.getString("rating");

                anuncio.setUid(id);
                anuncio.setTitulo(nome);
                anuncio.setDescricao(descricao);
                anuncio.setPopularidade(popularidade);
                //anuncio.setRating(rating);

                System.out.println(anuncio.toString());
                CadastroAnuncioActivity.txtJogo.setText(anuncio.getTitulo());
                CadastroAnuncioActivity.txtId.setText(anuncio.getUid());
                CadastroAnuncioActivity.txtDescricao.setText(anuncio.getDescricao());
                CadastroAnuncioActivity.txtPopularidade.setText(anuncio.getPopularidade());
                //CadastroAnuncioActivity.txtRating.setText(anuncio.getRating());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Comment: Tem como vc colocar o código dessa Class ? Porque dependendo do que vc faz dentro dela, basta vc a partir da sua Activity chamar a class e colocar o seu retorno no setText do seu TextView
Comment: Não é uma boa pratica, o melhor caminho seria usar o ViewModel para fazer a lógica do JSON e um MutableLiveData do objeto que vai notificar a Activity e ai você da update nos campos de texto
Comment: Fazendo funcionar depois eu posso aperfeiçoar mas no momento, quero só fazer funcionar, independente da forma que vou usar pra isso
Answer: Como o próprio erro diz, outra thread, além da main, está tentando alterar views - o que não é permitido.
A solução é sempre executar o código que altera as views na main thread.
Se estiver dentro da activity:
runOnUiThread(() -> {
  // Seu codigo
});

Ou, quando fora de uma activity:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(() -> {
  // Seu codigo
});

Para também solucionar de forma "simples" o problema de ter que criar um campo estático, sugiro refatorar o seu código da seguinte maneira.
Crie uma interface, que poderá ser usada para callbacks:
public interface Consumer<T> {

    void accept(T t);

}

E faça seus métodos chamarem um callback quando o objeto tiver sido convertido:
public void pesquisarJogo(String string, Consumer<Anuncio> callback) {
    ...
        @Override
        public void onSuccess(@NotNull JSONArray jsonArray) {
            System.out.println(jsonArray + "anuncio");
            jsonToObj(jsonArray, callback);
        }
    ...
}

public void jsonToObj(JSONArray resultadoDaPesquisa, Consumer<Anuncio> callback) {
    ...
    anuncio.setUid(id);
    anuncio.setTitulo(nome);
    anuncio.setDescricao(descricao);
    anuncio.setPopularidade(popularidade);
    callback.accept(anuncio);
}

Agora na sua Activity você terá acesso ao anúncio dentro do callback:
// Na activity, sem campos estáticos
igdbHelper.pesquisarJogo("hello", (anuncio) -> {
    runOnUiThread(() -> atualizarCampos(anuncio));
})

private void atualizarCampos(Anuncio anuncio) {
    txtJogo.setText(anuncio.getTitulo());
    txtId.setText(anuncio.getUid());
    txtDescricao.setText(anuncio.getDescricao());
    txtPopularidade.setText(anuncio.getPopularidade());
}

Referenciar componentes da Activity


Compare the numbers in base $3$

Question: Let $x,y\in\ [0,1]$ a real numbers. Suppose that $$x=\sum_{n=1}^{+\infty}\frac{a_n}{3^n},\quad y=\sum_{n=1}^{+\infty} \frac{b_n}{3^n},\;a_n,b_n\in\{0,1,2\}$$
they are their ternary expansions.
Suppose we know only the ternary expressions and not actually the real number they represent.

Question Can I compare $x$ and $y$ working exclusively in base 3? Or rather, how can I determine if $x\le y$ or $y\le x$?

Thanks!
Comment: You know how to compare two numbers given their decimal expansions - the same thing obviously works for ternary expansions.
Comment: I don't understand what you mean by "compare"
Comment: @Klangen That is to say if $x\le y$ or $y\le x$.
Comment: Do you know the rule that defines the $a_n$ and $b_n$?
Answer: Yes you can, except for one small problem : some numbers have TWO different ternary developments.
Simple rule : if $a_n=b_n$ for all $n<n_0$, and $a_{n_0}<b_{n_0}$, then $x\le y$.
They can still be the same if $a_{n_0}=b_{n_0}-1$, and $a_n=2$ and $b_n=0$ for all $n>n_0$.
Comment: Just what I said above : consider the development of $y-x$ : if it is greater than $3^{-n_0}$, then some $a_n$ is strictly smaller then $b_n$ for $n\le n_0$.
Comment: $\frac13=0,1_3$, or $0,0\overline1_3$. If $x<\frac13$, consider the development of $\frac13-x$ : it's a strictly positive number, so it has to have some strictly positive coefficients. Consider the one with the smaller index.
Comment: Thanks for the answer. But if I already know that $x\le y$ can I say about $a_n$ and $b_n$?
Comment: For example $\frac{1}{3}=0,00\overline{2}_3$ and $1/3=0,0\overline{1}_3$, what can I say about the digits of the  numbers that are less than $1/3$?
Comment: Then if $x<\frac{1}{3}$, we can say with certainty that the first digit $a_1$ of $x$ is zero, if were $a_1=1$, then may be other digits other different from zero and then $x>\frac{1}{3}$ or $x=\frac{1}{3}$. Moreover if were $a_1=2$, then $x>\frac{1}{3}$. In any case we would get an absurdity. Quite right?

Compare the numbers in base $3$