text:
Q: Powershell equivalent of C# List with Coordinates I'm trying to translate some C# code to Powershell code.
The problem I am having is trying to make an array in Powershell that will be in the same form as this array in C#:
List<Coordinate> coordinates = new List<Coordinate>();
    coordinates.Add(new Coordinate(0, 0));
    coordinates.Add(new Coordinate(500, 100));
    coordinates.Add(new Coordinate(200, 400));

My best attempt in Powershell is this:
$Coordinates = @((0,0),(500,100),(200,400))

But when I use $Coordinates, it doesn't work with the API I'm feeding it to like the C# coordinates works with the same API. What am I missing here?

A: Translate the code directly - with the caveat that you need to use the fully qualified type name for the constructors:
$coordinates = New-Object 'System.Collections.Generic.List[Namespace.Coordinate]'
$coordinates.Add($(New-Object Namespace.Coordinate 0,0))
$coordinates.Add($(New-Object Namespace.Coordinate 500,100))
$coordinates.Add($(New-Object Namespace.Coordinate 200,400))


text:
Q: How to construct Windows::UI::Xaml::Style class programmatically I'm trying to programmatically construct a winrt::Windows::UI::Xaml::Style object for all buttons. But, some of the style Setter doesn't work I expect.
In summary, Setters for BorderThickness, BorderBrush, Foreground and Margin properties doesn't work. On the other hand, Setters for FontSize and Background properties work right. How can I correct this matter.
a Style object is constructed like this code.
void MainPage::SetStylePropertySetters()
{
    coloredButtonStyle.Setters().Append(Setter{ // doesn't work
        Control::BorderThicknessProperty(),
        box_value(ThicknessHelper::FromUniformLength(10.5)) });

    coloredButtonStyle.Setters().Append(Setter{ // doesn't work
        Control::BorderBrushProperty(),
        box_value(Colors::Black()) });

    coloredButtonStyle.Setters().Append(Setter{ // works right
        Control::FontSizeProperty(),
        box_value(50) });

    coloredButtonStyle.Setters().Append(Setter{ // doesn't work
        Control::ForegroundProperty(),
        box_value(Colors::White()) });

    coloredButtonStyle.Setters().Append(Setter{ // doesn't work
        FrameworkElement::MarginProperty(),
        box_value(ThicknessHelper::FromLengths(10, 10, 0, 0)) });

    coloredButtonStyle.Setters().Append(Setter{ // works right
        Control::BackgroundProperty(),
        GenerateGradient() });
}

LinearGradientBrush MainPage::GenerateGradient()
{
    GradientStopCollection gradientStopCollection{};

    GradientStop gs1;
    gs1.Color(Colors::Yellow());
    gs1.Offset(0);
    gradientStopCollection.Append(gs1);

    GradientStop gs2;
    gs2.Color(Colors::Orange());
    gs2.Offset(0.5);
    gradientStopCollection.Append(gs2);

    GradientStop gs3;
    gs3.Color(Colors::Red());
    gs3.Offset(1.0);
    gradientStopCollection.Append(gs3);

    return LinearGradientBrush(gradientStopCollection, 0.0);
}

Then the style is applied to a button in the constructor of the MainPage.
MainPage::MainPage() :
    coloredButtonStyle{ xaml_typename<Button>() }
{
    InitializeComponent();

    // Apply a style to a button named DefaultButton
    SetStylePropertySetters();
    DefaultButton().Style(coloredButtonStyle);
}

The main page has one button named DefaultButton.
<Page
    x:Class="HeadedAppDesign.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HeadedAppDesign"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel>
        <Button x:Name="DefaultButton" Content="Button"/>
    </StackPanel>
</Page>

This produces the following result:

A: For Thickness type properties, pass string object as the same
 format in XAML markup. And for Brush type properties, pass one of the derived class object of Brush class.
void MainPage::SetStylePropertySetters()
{
    coloredButtonStyle.Setters().Append(Setter{
        Control::BorderThicknessProperty(),
        box_value(L"10.5") });

    coloredButtonStyle.Setters().Append(Setter{
        Control::BorderBrushProperty(),
        SolidColorBrush(Colors::Black()) });

    coloredButtonStyle.Setters().Append(Setter{
        Control::FontSizeProperty(),
        box_value(50) });

    coloredButtonStyle.Setters().Append(Setter{
        Control::ForegroundProperty(),
        SolidColorBrush(Colors::White()) });

    coloredButtonStyle.Setters().Append(Setter{
        FrameworkElement::MarginProperty(),
        box_value(L"10, 10, 0, 0") });

    coloredButtonStyle.Setters().Append(Setter{
        Control::BackgroundProperty(),
        GenerateGradient() });
}

The margin, border width and color, font size and color and background gradient of the button all applied as I expected.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to web scrape followers from Instagram web browser? Can anyone tell me how to access the underlying URL to view a given user's Instagram followers? I am able to do this with Instagram API, but given the pending changes to the approval process, I have decided to switch to scraping.
The Instagram web browser allows you to view the follower list for any given public user - for example, to view Instagram's followers, visit "https://www.instagram.com/instagram", and then click on the followers URL to open a window that paginates through viewers (note: you must be logged in to your account to view this).
I note that the URL changes to "https://www.instagram.com/instagram/followers" when this window pops up, but I can't seem to view the underlying page source for this URL.
Since it appears on my browser window, I assume that I will be able to scrape. But do I have to use a package like Selenium? Does anyone know what the underlying URL is, so I don't have to use Selenium?
As an example, I am able to directly access the underlying feed data by visiting "instagram.com/instagram/media/", from which I can scrape and paginate through all iterations. I would like to do something similar with the list of followers, and access this data directly (rather than using Selenium).

A: Update: March 2020
This is just the Levi answer with a small updates in some parts because as it is now, it didn't quit the driver successfully. This also gets by default all the followers, as everyone else have said, it's not intended for a lot of followers.
import itertools

from explicit import waiter, XPATH
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from time import sleep

def login(driver):
    username = ""  # <username here>
    password = ""  # <password here>

    # Load page
    driver.get("https://www.instagram.com/accounts/login/")
    sleep(3)
    # Login
    driver.find_element_by_name("username").send_keys(username)
    driver.find_element_by_name("password").send_keys(password)
    submit = driver.find_element_by_tag_name('form')
    submit.submit()

    # Wait for the user dashboard page to load
    WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.LINK_TEXT, "See All")))

def scrape_followers(driver, account):
    # Load account page
    driver.get("https://www.instagram.com/{0}/".format(account))

    # Click the 'Follower(s)' link
    # driver.find_element_by_partial_link_text("follower").click
    sleep(2)
    driver.find_element_by_partial_link_text("follower").click()

    # Wait for the followers modal to load
    waiter.find_element(driver, "//div[@role='dialog']", by=XPATH)
    allfoll = int(driver.find_element_by_xpath("//li[2]/a/span").text)
    # At this point a Followers modal pops open. If you immediately scroll to the bottom,
    # you hit a stopping point and a "See All Suggestions" link. If you fiddle with the
    # model by scrolling up and down, you can force it to load additional followers for
    # that person.

    # Now the modal will begin loading followers every time you scroll to the bottom.
    # Keep scrolling in a loop until you've hit the desired number of followers.
    # In this instance, I'm using a generator to return followers one-by-one
    follower_css = "ul div li:nth-child({}) a.notranslate"  # Taking advange of CSS's nth-child functionality
    for group in itertools.count(start=1, step=12):
        for follower_index in range(group, group + 12):
            if follower_index > allfoll:
                raise StopIteration
            yield waiter.find_element(driver, follower_css.format(follower_index)).text

        # Instagram loads followers 12 at a time. Find the last follower element
        # and scroll it into view, forcing instagram to load another 12
        # Even though we just found this elem in the previous for loop, there can
        # potentially be large amount of time between that call and this one,
        # and the element might have gone stale. Lets just re-acquire it to avoid
        # tha
        last_follower = waiter.find_element(driver, follower_css.format(group+11))
        driver.execute_script("arguments[0].scrollIntoView();", last_follower)

if __name__ == "__main__":
    account = ""  # <account to check>
    driver = webdriver.Firefox(executable_path="./geckodriver")
    try:
        login(driver)
        print('Followers of the "{}" account'.format(account))
        for count, follower in enumerate(scrape_followers(driver, account=account), 1):
            print("\t{:>3}: {}".format(count, follower))
    finally:
        driver.quit()

A: EDIT: Dec 2018 Update:
Things have changed in Insta land since this was posted. Here is an updated script that is a bit more pythonic and better utilizes XPATH/CSS paths.
Note that to use this updated script, you must install the explicit package (pip install explicit), or convert each line with waiter to a pure selenium explicit wait.
import itertools

from explicit import waiter, XPATH
from selenium import webdriver

def login(driver):
    username = ""  # <username here>
    password = ""  # <password here>

    # Load page
    driver.get("https://www.instagram.com/accounts/login/")

    # Login
    waiter.find_write(driver, "//div/input[@name='username']", username, by=XPATH)
    waiter.find_write(driver, "//div/input[@name='password']", password, by=XPATH)
    waiter.find_element(driver, "//div/button[@type='submit']", by=XPATH).click()

    # Wait for the user dashboard page to load
    waiter.find_element(driver, "//a/span[@aria-label='Find People']", by=XPATH)

def scrape_followers(driver, account):
    # Load account page
    driver.get("https://www.instagram.com/{0}/".format(account))

    # Click the 'Follower(s)' link
    # driver.find_element_by_partial_link_text("follower").click()
    waiter.find_element(driver, "//a[@href='/instagram/followers/']", by=XPATH).click()

    # Wait for the followers modal to load
    waiter.find_element(driver, "//div[@role='dialog']", by=XPATH)

    # At this point a Followers modal pops open. If you immediately scroll to the bottom,
    # you hit a stopping point and a "See All Suggestions" link. If you fiddle with the
    # model by scrolling up and down, you can force it to load additional followers for
    # that person.

    # Now the modal will begin loading followers every time you scroll to the bottom.
    # Keep scrolling in a loop until you've hit the desired number of followers.
    # In this instance, I'm using a generator to return followers one-by-one
    follower_css = "ul div li:nth-child({}) a.notranslate"  # Taking advange of CSS's nth-child functionality
    for group in itertools.count(start=1, step=12):
        for follower_index in range(group, group + 12):
            yield waiter.find_element(driver, follower_css.format(follower_index)).text

        # Instagram loads followers 12 at a time. Find the last follower element
        # and scroll it into view, forcing instagram to load another 12
        # Even though we just found this elem in the previous for loop, there can
        # potentially be large amount of time between that call and this one,
        # and the element might have gone stale. Lets just re-acquire it to avoid
        # that
        last_follower = waiter.find_element(driver, follower_css.format(follower_index))
        driver.execute_script("arguments[0].scrollIntoView();", last_follower)

if __name__ == "__main__":
    account = 'instagram'
    driver = webdriver.Chrome()
    try:
        login(driver)
        # Print the first 75 followers for the "instagram" account
        print('Followers of the "{}" account'.format(account))
        for count, follower in enumerate(scrape_followers(driver, account=account), 1):
            print("\t{:>3}: {}".format(count, follower))
            if count >= 75:
                break
    finally:
        driver.quit()

I did a quick benchmark to show how performance decreases exponentially the more followers you attempt to scrape this way:
$ python example.py
Followers of the "instagram" account
Found    100 followers in 11 seconds
Found    200 followers in 19 seconds
Found    300 followers in 29 seconds
Found    400 followers in 47 seconds
Found    500 followers in 71 seconds
Found    600 followers in 106 seconds
Found    700 followers in 157 seconds
Found    800 followers in 213 seconds
Found    900 followers in 284 seconds
Found   1000 followers in 375 seconds

Original post:
Your question is a little confusing. For instance, I'm not really sure what "from which I can scrape and paginate through all iterations" actually means. What are you currently using to scrape and paginate?
Regardless, instagram.com/instagram/media/ is not the same type of endpoint as instagram.com/instagram/followers. The media endpoint appears to be a REST API, configured to return an easily parseable JSON object.
The followers endpoint isn't really a RESTful endpoint from what I can tell. Rather, Instagram AJAXs in the information to the page source (using React?) after you click the Followers button. I don't think you will be able to get that information without using something like Selenium, which can load/render the javascript that displays the followers to the user.
This example code will work:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def login(driver):
    username = ""  # <username here>
    password = ""  # <password here>

    # Load page
    driver.get("https://www.instagram.com/accounts/login/")

    # Login
    driver.find_element_by_xpath("//div/input[@name='username']").send_keys(username)
    driver.find_element_by_xpath("//div/input[@name='password']").send_keys(password)
    driver.find_element_by_xpath("//span/button").click()

    # Wait for the login page to load
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.LINK_TEXT, "See All")))

def scrape_followers(driver, account):
    # Load account page
    driver.get("https://www.instagram.com/{0}/".format(account))

    # Click the 'Follower(s)' link
    driver.find_element_by_partial_link_text("follower").click()

    # Wait for the followers modal to load
    xpath = "//div[@style='position: relative; z-index: 1;']/div/div[2]/div/div[1]"
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, xpath)))

    # You'll need to figure out some scrolling magic here. Something that can
    # scroll to the bottom of the followers modal, and know when its reached
    # the bottom. This is pretty impractical for people with a lot of followers

    # Finally, scrape the followers
    xpath = "//div[@style='position: relative; z-index: 1;']//ul/li/div/div/div/div/a"
    followers_elems = driver.find_elements_by_xpath(xpath)

    return [e.text for e in followers_elems]

if __name__ == "__main__":
    driver = webdriver.Chrome()
    try:
        login(driver)
        followers = scrape_followers(driver, "instagram")
        print(followers)
    finally:
        driver.quit()

This approach is problematic for a number of reasons, chief among them being how slow it is, relative to the the API.

A: I noticed that the previous answer no longer works, so I made an updated version based on the previous answer, which includes the scrolling feature (to get all the users in the list, not just those loaded initially). In addition, this scrapes both followers and following. (You'll need to download chromedriver as well)
import time
from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# The account you want to check
account = ""

# Chrome executable
chrome_binary = r"chrome.exe"   # Add your path here

def login(driver):
    username = ""   # Your username
    password = ""   # Your password

    # Load page
    driver.get("https://www.instagram.com/accounts/login/")

    # Login
    driver.find_element_by_xpath("//div/input[@name='username']").send_keys(username)
    driver.find_element_by_xpath("//div/input[@name='password']").send_keys(password)
    driver.find_element_by_xpath("//span/button").click()

    # Wait for the login page to load
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.LINK_TEXT, "See All")))

def scrape_followers(driver, account):
    # Load account page
    driver.get("https://www.instagram.com/{0}/".format(account))

    # Click the 'Follower(s)' link
    driver.find_element_by_partial_link_text("follower").click()

    # Wait for the followers modal to load
    xpath = "/html/body/div[4]/div/div/div[2]/div/div[2]"
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, xpath)))

    SCROLL_PAUSE = 0.5  # Pause to allow loading of content
    driver.execute_script("followersbox = document.getElementsByClassName('_gs38e')[0];")
    last_height = driver.execute_script("return followersbox.scrollHeight;")

    # We need to scroll the followers modal to ensure that all followers are loaded
    while True:
        driver.execute_script("followersbox.scrollTo(0, followersbox.scrollHeight);")

        # Wait for page to load
        time.sleep(SCROLL_PAUSE)

        # Calculate new scrollHeight and compare with the previous
        new_height = driver.execute_script("return followersbox.scrollHeight;")
        if new_height == last_height:
            break
        last_height = new_height

    # Finally, scrape the followers
    xpath = "/html/body/div[4]/div/div/div[2]/div/div[2]/ul/li"
    followers_elems = driver.find_elements_by_xpath(xpath)

    followers_temp = [e.text for e in followers_elems]  # List of followers (username, full name, follow text)
    followers = []  # List of followers (usernames only)

    # Go through each entry in the list, append the username to the followers list
    for i in followers_temp:
        username, sep, name = i.partition('\n')
        followers.append(username)

    print("______________________________________")
    print("FOLLOWERS")

    return followers

def scrape_following(driver, account):
    # Load account page
    driver.get("https://www.instagram.com/{0}/".format(account))

    # Click the 'Following' link
    driver.find_element_by_partial_link_text("following").click()

    # Wait for the following modal to load
    xpath = "/html/body/div[4]/div/div/div[2]/div/div[2]"
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, xpath)))

    SCROLL_PAUSE = 0.5  # Pause to allow loading of content
    driver.execute_script("followingbox = document.getElementsByClassName('_gs38e')[0];")
    last_height = driver.execute_script("return followingbox.scrollHeight;")

    # We need to scroll the following modal to ensure that all following are loaded
    while True:
        driver.execute_script("followingbox.scrollTo(0, followingbox.scrollHeight);")

        # Wait for page to load
        time.sleep(SCROLL_PAUSE)

        # Calculate new scrollHeight and compare with the previous
        new_height = driver.execute_script("return followingbox.scrollHeight;")
        if new_height == last_height:
            break
        last_height = new_height

    # Finally, scrape the following
    xpath = "/html/body/div[4]/div/div/div[2]/div/div[2]/ul/li"
    following_elems = driver.find_elements_by_xpath(xpath)

    following_temp = [e.text for e in following_elems]  # List of following (username, full name, follow text)
    following = []  # List of following (usernames only)

    # Go through each entry in the list, append the username to the following list
    for i in following_temp:
        username, sep, name = i.partition('\n')
        following.append(username)

    print("\n______________________________________")
    print("FOLLOWING")
    return following

if __name__ == "__main__":
    options = wd.ChromeOptions()
    options.binary_location = chrome_binary # chrome.exe
    driver_binary = r"chromedriver.exe"
    driver = wd.Chrome(driver_binary, chrome_options=options)
    try:
        login(driver)
        followers = scrape_followers(driver, account)
        print(followers)
        following = scrape_following(driver, account)
        print(following)
    finally:
        driver.quit()


text:
Q: Custom tag attributes are leaking into children Our application is using Mojarra 2.1.29-03 and we are having a problem with attributes in our custom tags as they are being copied to nested tags as well.
For example, given the following tag definition:
cc.taglib.xml
<?xml version="1.0" encoding="UTF-8" ?>
<facelet-taglib version="2.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facelettaglibrary_2_0.xsd">
    <namespace>http://temp.com/jsf/customcomponents</namespace>
    <tag>
        <tag-name>wrapper</tag-name>
        <source>wrapper.xhtml</source>
        <attribute>
            <description>The style class for the component</description>
            <name>styleClass</name>
        </attribute>
    </tag>
</facelet-taglib>

wrapper.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <ui:component xmlns:ui="http://java.sun.com/jsf/facelets">

styleClass: #{styleClass}

            <ui:insert />

    </ui:component>

And a client page:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

     <h:body>
        <cc:wrapper styleClass="cc-style">
            <cc:wrapper />
        </cc:wrapper>
    </h:body>

The result is as follows:
styleClass: cc-style

styleClass: cc-style

... so the styleClass attribute is also being applied to the inner tag even though the client page does not set it.
We have noted that we can workaround this by processing all our client pages to set styleClass="" if it is not explicitly set but this is an approach we would like to avoid (it's a very ugly solution and cannot be enforced going forward).
Is this a bug? Is there any way to work around it other than that mentioned above - preferably with the workaround in the tag rather than the client pages?
Thanks
Ivor

A: This is not strictly a bug, but this is indeed unintuitive and undesired behavior which should have been addressed in the JSF/Facelets spec.
The work around solution is not trivial, a custom taghandler is needed to clear out the Facelet scope. JSF utility library OmniFaces has since version 2.1 exactly such one: <o:tagAttribute> (source code here).
Usage (do note that prolog, doctype and html tags are unnecessary, this is the file in its entirety):
<ui:composition
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:o="http://omnifaces.org/ui"
>
    <o:tagAttribute name="styleClass" />

styleClass: #{styleClass}

        <ui:insert />

</ui:composition>

Unrelated to the concrete problem, this is not a custom component, but a tagfile. And, in JSF 2.x, the term "cc" is usually associated with composite components, which is a completely different subject altogether. To get your knowledge and terminology right (so that you don't confuse yourself or others while reading your or other's code), head to When to use <ui:include>, tag files, composite components and/or custom components?

A: For info we identifed an alternative approach that might be of use to others as it is slightly easier to implement and understand.
First I need to add a bit of context to the situation that we found ourselves in ... we had recently migrated from 2.1.12 to 2.1.29-03 and as part of that process we changed one of our building blocks from a composite component (which has isolated scope for its attributes) to a custom tag (which has the behaviour described above). The same behaviour regarding custom tag attributes existed in 2.1.12 but we were unaware of it so we considered the following approach instead as it would restore the behaviour we had prior to migration because we would only need to apply it to the component that we changed.
wrapper.xhtml (I've changed the namespace to 'ct' rather than 'cc')
<ui:component xmlns:ct="http://temp.com/jsf/customtags" xmlns:ui="http://java.sun.com/jsf/facelets">
    <ct:tagAttribute name="styleClass" />

styleClass: #{styleClass}

        <ct:eraseAttribute name="styleClass" />
        <ui:insert />

</ui:component>

Where tagAttribute is the solution suggested by BalusC to prevent the tag inheriting attributes from its parents and in addition we call eraseAttribute tag before calling ui:insert to remove the attribute from scope (this obviously requires that the custom tag is finished with the attribute). This means that this one tag neither inherits nor leaks attributes and other tags could remain unchanged and maintain the same behaviour they had prior to migration.
ct.taglib.xhtml (snippet)
<tag>
    <tag-name>eraseAttribute</tag-name>
    <handler-class>com.temp.jsf.customtags.EraseTagAttribute</handler-class>
    <attribute>
        <name>name</name>
        <required>true</required>
        <type>java.lang.String</type>
    </attribute>
</tag>

EraseTagAttribute.java
package com.temp.jsf.customtags;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.view.facelets.FaceletContext;
import javax.faces.view.facelets.TagConfig;
import javax.faces.view.facelets.TagHandler;

public class EraseTagAttribute extends TagHandler {

    private final String name;

    public EraseTagAttribute(TagConfig config) {

        super(config);

        name = getRequiredAttribute("name").getValue();
    }

    public void apply(FaceletContext context, UIComponent parent) throws IOException {

        context.getVariableMapper().setVariable(name, null);
    }
}

Ultimately we did not use it however as we felt the answer provided by BalusC (which we applied to every attribute in all our custom tags) was the correct and cleaner approach even though it might have additional consequences in our very specific situation.


text:
Q: UITableView cell with collection view I have created a .xib file for TableView cell, and I want to add a collection view into that cell. picture The gray rectangle shown in the picture is a collection view, my question is why the collection view doesn't show a prototype cell. What did I do wrong? Or this is what it should be, then how can I add a prototype cell? By making another .xib file for the UICollectionVew Cell?

A:
my question is why the collection view doesn't show a prototype cell

Because it's a .xib. Prototype cells are a storyboard feature.


text:
Q: How to add an extra feature to a maven dependency plugin I use maven-dependency-plugin to copy jar files of artifactItem, instead of giving artifactItem details at pom.xml as shown below
<artifactItem>
                                <groupId>junit</groupId>
                                <artifactId>junit</artifactId>
                                <version>3.8.2</version>
                                <overWrite>true</overWrite>
                                <outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
                                <destFileName>junit.jar</destFileName>
                            </artifactItem>

i am trying to extend the pluging to give artifactItems detail progamatically,by using below class
                package com.nuwaza.aqua.sample.dependencymanager;

            import java.io.File;
            import java.util.ArrayList;
            import java.util.List;

            import org.apache.maven.artifact.Artifact;
            import org.apache.maven.artifact.DefaultArtifact;
            import org.apache.maven.artifact.factory.ArtifactFactory;
            import org.apache.maven.artifact.factory.DefaultArtifactFactory;
            import org.apache.maven.artifact.handler.ArtifactHandler;
            import org.apache.maven.artifact.handler.DefaultArtifactHandler;
            import org.apache.maven.artifact.repository.ArtifactRepository;
            import org.apache.maven.artifact.repository.DefaultArtifactRepository;
            import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
            import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout;
            import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
            import org.apache.maven.artifact.versioning.VersionRange;
            import org.apache.maven.plugin.MojoExecutionException;
            import org.apache.maven.plugin.dependency.fromConfiguration.AbstractFromConfigurationMojo;
            import org.apache.maven.plugin.dependency.fromConfiguration.ArtifactItem;
            import org.apache.maven.plugin.dependency.fromConfiguration.CopyMojo;
            import org.apache.maven.plugin.logging.Log;
            import org.apache.maven.plugins.annotations.Component;
            import org.apache.maven.plugins.annotations.Parameter;
            import org.apache.maven.artifact.versioning.VersionRange;

            /**
             *
             * @id copy
             * @goal copy
             * @phase package
             * @author anoopab
             */
            public class BundleDataMojo extends CopyMojo {

                @Parameter(required = true)
                private List<ArtifactItem> artifactItems;

                @Component
                protected static ArtifactFactory factory;

                public void execute() throws MojoExecutionException {
                    super.setArtifactItems(setArtifactDetail());

                    super.execute();
                }

                private List<ArtifactItem> setArtifactDetail() {

                    artifactItems = new ArrayList<ArtifactItem>();
                    ArtifactItem bundle = new ArtifactItem();
                    bundle.setGroupId("junit");
                    bundle.setArtifactId("junit");
                    bundle.setVersion("3.8.2");
                    bundle.setDestFileName("samplejunit.jar");
                    bundle.setType("jar");
                    bundle.setOverWrite("true");

                    artifactItems.add(bundle);
                    return artifactItems;
                }
            }

but i getting the following erorr
[info] Configured Artifact: junit:junit:3.8.2:jar

Exception in thread "main" java.lang.NullPointerException
    at org.apache.maven.plugin.dependency.fromConfiguration.AbstractFromConfigurationMojo.getArtifact(AbstractFromConfigurationMojo.java:221)
    at org.apache.maven.plugin.dependency.fromConfiguration.AbstractFromConfigurationMojo.getProcessedArtifactItems(AbstractFromConfigurationMojo.java:166)
    at org.apache.maven.plugin.dependency.fromConfiguration.CopyMojo.execute(CopyMojo.java:67)
    at com.nuwaza.aqua.sample.dependencymanager.BundleDataMojo.execute(BundleDataMojo.java:52)
    at com.nuwaza.aqua.sample.dependencymanager.BundleDataMojo.main(BundleDataMojo.java:118)
that is
/**
 * Used to look up Artifacts in the remote repository.
 */
@Component
protected ArtifactFactory factory;

this factory getting null value.....
ArtifactFactory  interface at  org.apache.maven.artifact.factory
I'm really confused by these. Could anyone give any help? Thanks a lot!


text:
Q: jQuery click event only works once (but fires always!) Please help a jQuery newby with the following. I have a form and I'm trying to add successive chunks of form fields when an #addMore button is clicked. With the help of this board, I have that working now. But it only works once. I've whittled things down to a minimal case:

<title>Reserves Form</title>

lorem ipsum blah blah

<button type="button" id="addMore">Add Another Paragraph</button>

When I load the page and click the button, I see the debugging alert and then a clone of the "content" paragraph appears as expected. When I click the button again, I get the alert, but not the new paragraph. Why would one response to the click work, but not the other? And how can I get them both to work?

A: put the chunk = $('.content').clone(true); inside the click event to be like this
$(document).ready(function() {

 $('#addMore').live('click', function() {
    var chunk = $('.content').clone(true);
     alert('debug!');
     $('#container').append(chunk);
 });
});

and something else not related to your question: do you really want to use live?

A: You are appending the same object again and again to the same container so you won't see any difference as if it is not doing anything.
Try this which will clone the first .content element inside the click handler and append it.
$(document).ready(function() {
   $('#addMore').live('click', function() {
       alert('debug!');
       $('#container').append($('.content:first').clone(true));
   });
});

Alternatively you can try this which will append html string instead of cloned object. In this approach the clone is used only once because string appending can be done any number of times so it is better than previous approach.
$(document).ready(function() {
   var content = $('
').append($('.content').clone(true)).html();

   $('#addMore').live('click', function() {
       alert('debug!');
       $('#container').append(content);
   });

});

A: A very similar question has already been asked.  You need to clone the element every time your handler is executed.
$(document).ready(function() {
 $('#addMore').live('click', function() {
     var chunk = $('.content').clone(true);
     alert('debug!');
     $('#container').append(chunk);
 });
});

A: If you want this to occur every time, you need to clone the paragraph inside of your live handler. Your script is appending a one-time clone (cached) copy of that paragraph. Move the clone statement into your click handler for expected results.

A: You're only cloning once. After that first assignment you are just referring to the cloned element, thus it's just moving it from where it is to where you want it to be. You can fix it by making chunk a function that returns the cloned element:
var chunk = function() {
   return $('.content').clone(true);
}


text:
Q: Does downsampling a random sequence make it less random? Is there a principle/theorem that shows this? I'm wondering whether downsampling a random (or psuedorandom) sequence makes it less random or preserves its randomness. For example, if you take a series of psuedorandom bytes, as shown in the code below, and throw out all but the alphanumeric characters, is the resulting string of alphanumeric characters still psuedorandom? What about for a random case?
Is there a mathematical or computing principle or theorem that shows this one way or the other?
I looked at this question:
Is a subset of a random sequence also random?
But this does not cover specifically a selection process that includes knowledge of the values that are being selected. The answer by MusiGenesis seems to say that this might cause less randomness.
// Open the /dev/urandom file to read random bytes
ifstream rand_file("/dev/urandom");

if (!rand_file) {
    cout << "Cannot open /dev/urandom!" << endl;
    return return_code::err_cannot_open_file;
}

string password("");
vector<char> rand_vec(rand_vec_length, 0);
while (password.length() < pwd_length) {
     fill_rand_vec(rand_vec, rand_file);

    // Iterate through the vector of psuedo-random bytes and add
    // printable chars to the password
    for (auto rand_char : rand_vec) {
        if (isprint(rand_char) && !isspace(rand_char)) {
            password += rand_char;
        }

        if (password.length() >= pwd_length) {
            break;
        }
    }
}

A: I'm not a mathematician, but it would seem to me that, assuming your initial sequence of bytes was uniformly distributed, after throwing out all the bytes that were not in your desired range, the remaining bytes must still be uniformly distributed. It's just that you have no idea in advance how many random bytes you will have to take to end up with a given desired number of random alphanumeric characters. It may actually take arbitrarily long, which makes this method not particularly efficient. But the method by which you arrived at the output values did not prefer any alphanumeric character value over any other, so the resulting alphanumeric characters, however many they may be, cannot really be anything but uniformly distributed as well.
It would seem to me that what you're describing is basically Rejection Sampling, which is a standard technique capable of generating samples from arbitrary probability distributions. You may want to read up on that for mathematical proofs. I believe your particular example can be viewed as rejection sampling a probability distribution where alphanumeric character values have probability 1/36 (I presume, depends on what exactly you consider alphanumeric) while every other value has probability 0…


text:
Q: Mailchimp - Delete a list via api Is there a way to delete a list using MailChimp api? currently I am using listUnsubscribe but I want to completely remove the list.

A: The list-related API docs don't have any hooks to delete a list, just members from a list.

A: MailChimp API v3 supports deleting a list.
You can delete the MailChimp list by sending a DELETE request to the lists/{list_id}/ endpoint.
An example request,
curl --request DELETE \
--url 'https://usX.api.mailchimp.com/3.0/lists/4ca5becb8d' \
--user 'anystring:apikey' \
--include

Please note that by deleting a list, you'll lose the list history—including subscriber activity, unsubscribes, complaints, and bounces. You'll also lose subscribers' email addresses unless you exported and backed up your list.

A: listBatchUnsubscribe has the option to delete_member:
https://apidocs.mailchimp.com/api/1.3/listbatchunsubscribe.func.php


text:
Q: Timezones and mentions of days/weeks/months for badges and elsewhere
Possible Duplicate:
What is an SE "day"? When does each day start?

I just wondered if things like the rules for badges get +200 rep in one day, and the displays of rep per day/week/month took into account timezones.

A: Yes, insofar as they all obey "StackExchange Standard Time", which happens to bear a strong resemblance to UTC.


text:
Q: Scala REPL only runs as root user, gives error when run as non-root I'm running 64-bit OpenSUSE 12.1, today I downloaded the latest Scala 2.9.2 from the official website, after unpacking the tgz and go to scala-2.9.2/bin directory, I executed "scala" and got this error message:
[init] error: error while loading <root>, error in opening zip file

Failed to initialize compiler: object scala not found.
** Note that as of 2.8 scala does not assume use of the java classpath.
** For the old behavior pass -usejavacp to scala, or if using a Settings
** object programatically, settings.usejavacp.value = true.

I attempted to run scala -usejavacp but it doesn't help.
I've been using Scala a lot in many other distros and have never got this error before.
My OpenSUSE installation has OpenJDK 6 installed.
Please suggest your opinions, thank you!
I have made the following attempts to solve the problem:

*

*Install Oracle JDK 1.7 and run scala, confirmed that scala REPL reports running in hotspot JVM 1.7, same error occurs.

*Installed sbt and run "console" from sbt, same error occurs.

*strace and diff the output between sudo scala and scala as normal user, there is no difference except the  error message above.

*scala -Ylog-classpath as su and normal user, then diff the output, same as above.

*disabled AppArmor and tried again, same error message.

*Download other scala versions (all of 2.9x, and 2.10 milestone 4), all of their REPL give the same error message.

*Made sure fsc is not running before scala REPL runs

*Made sure that the hostname is resolvable

well this is a really interesting problem, I'll definitely post a solution if I can luckily find it.
Thanks a lot for your help!
Last edit:
Thanks for everyone here and on reddit (http://www.reddit.com/r/scala/comments/w5s0m/please_help_scala_only_runs_as_root_user_gives/) who offered very valuable suggestions to help me figure out this very strange issue. See my answer below for the solution.

A: Do not put sbt-launch.jar in your $SCALA_HOME/lib directory, your project's lib directory, or anywhere it will be put on a classpath.

A: I have just found out the reason:
A closer examination of the output of "strace -f scala" as normal user yields an interesting output:
[pid 11919] open("/usr/lib64/jvm/java-1.6.0-openjdk-1.6.0/jre/lib/ext/gnome-java-bridge.jar", O_RDONLY) = -1 EACCES (Permission denied)

Soon follow that, is the system call to inform user that scala REPL failed to initialize:
[pid 11919] write(1, "\nFailed to initialize compiler: "..., 260

The gnome-java-bridge.jar has permission 400, I changed it to 444 and problem is solved!
The permission issue seems to have been listed as OpenSUSE bug:
http://lists.opensuse.org/opensuse-bugs/2012-07/msg00920.html

A: It looks like it's not being able to open `scala-library.jar´, or one of the other jar files required for REPL.
You did not say whether scalac works or not. That might give a clue.
At any rate, I'd make sure all of the jar files are a+r, and the directory they are in, as well as all other parent directories, are a+rx.

A: This is most probably caused by jdk-xxx/jre/lib/ext containing jars that is not readable. Please look for file starting with "."jar and "._jar" and remove them.


text:
Q: date format in angular from json     .controller('feedCtrl', ['$scope', '$http', function($scope, $http) {
  $http.get('items.json').then(function(response) {
    $scope.items = response.data;
    $scope.user = localStorage.getItem("glittrLoggedin");

  });

}])

JSON file:

[
  {
    "_id": "55e76d010ea262760117d43c",
    "title": "sit",
    "picture": "https://placeimg.com/640/480/any",
    "company": {
      "title": "COMVEYOR",
      "email": "hello@gmail.com",
      "phone": "+1 (845) 472-3160"
    },
    "about": "Tempor aute incididunt commodo ad aute do sint laboris. Officia adipisicing enim adipisicing aliquip laborum amet dolore ullamco. Id sunt enim consectetur aute adipisicing ullamco ad non tempor commodo proident. Irure pariatur quis fugiat ad mollit minim commodo pariatur do velit excepteur laboris ipsum culpa. Ea ea exercitation nostrud laborum laborum quis nisi. Aliqua ipsum enim occaecat velit mollit commodo pariatur. Magna ea laboris est et elit quis excepteur incididunt aute anim pariatur dolore irure cupidatat.",
    "createdAt": "Wed Apr 30 2014 18:57:48 GMT+0000 (UTC)"
  },
  {
    "_id": "55e76d017700a7889c317092",
    "title": "in",
    "picture": "https://placeimg.com/640/480/any",
    "company": {
      "title": "RODEMCO",
      "email": "hello@gmail.com",
      "phone": "+1 (821) 468-2057"
    },
    "about": "Ea in minim cupidatat id reprehenderit. Ut voluptate do mollit sit ullamco aliquip. Esse dolore labore velit ullamco nostrud tempor sit exercitation aute consectetur excepteur dolore occaecat. Tempor elit incididunt laborum esse dolor magna.",
    "createdAt": "Tue Apr 29 2014 20:52:30 GMT+0000 (UTC)"
  }
]

I am trying to format the 'createdAT' in the format yyyy-MM-dd. I tried the following in my HTML but still get the code in the same format.
 {{item.createdAt | date :'yyyy-MM-dd'}}

Link to code: plunkrlink

A: You need to convert the string of date to date object to apply date filter  on it, for that you need to create a function inside your controller convertToDate that will provide you the date object, afterwards apply an filter on it.
Markup
<text fill="#ffffff" font-size="10" font-family="Verdana" x="20" y="66">
   {{convertToDate(item.createdAt)| date: 'yyyy-MM-dd'}}
</text>

Code
$scope.convertToDate = function(date) {
    var dateOut = new Date(date);
    dateOut.setDate(new Date(date).getDate() + 1);
    return dateOut;
};

Working Demo


text:
Q: ocaml-top does not compile past (pattern matching) Warning 8 With ocaml-top 1.1.5 and ocaml 4.02.3 on macOS High Sierra:
When compiling a file where a function triggers a (pattern matching) Warning 8, the warning is displayed in red (in the Windows ocaml-top version I usually use it would be yellow) ; the function itself seems to compile and gives a type, but functions below it in the file cannot be compiled (as if the Warning was an actual compilation error).
How can I compile past that? My missing cases are obviously intentional.
EDIT: with no ocaml-top specific answer, I'm just completing all my pattern matchings with _-> failwith "blabla"   type statements. Should I use something else than ocaml-top, anything not too hard to install on macOS for somebody who has not idea how package dependency and so on work?

A: Most likely the difference in the two environments is in the compiler options. Warnings (by definition) don't terminate compilation. But each warning (by number) can be made fatal with the -w option like this:
ocamlc -w @8  ...

If you can find this setting you can remove it to get the default treatment for warning 8.
Compiler options are described in Section 8.2 of the OCaml manual.
As @vonaka says, you can also use attributes in the source to turn off a warning for just one function like this:
let [@warning "-8"] myfun x =
    match x with None -> 18

Attributes are described in Section 7.18 of the OCaml manual. Built-in attributes like [@warning ...] are described in section 7.18.1.


text:
Q: Xamarin Forms IOS Remove IconImageSource ToolbarItems with IconImageSource are causing my app to crash on iOS. So I am willing to remove them only on iOS but show the icons on Android. How Can I do that? Thank you!
<TabbedPage.ToolbarItems>
    <ToolbarItem x:Name="searchOptn" IconImageSource="{local:ImageResource Bufib.Logos.search.png}" Clicked="searchOptn_Clicked" />
    <ToolbarItem x:Name="syncOptn" IconImageSource="{local:ImageResource Bufib.Logos.sync.png}" Clicked="syncOptn_Clicked"/>
    <ToolbarItem x:Name="favouriteOptn" Clicked="favouriteOptn_Clicked" Order="Secondary"/>
    <ToolbarItem x:Name="visibilityOptn" Clicked="visibilityOptn_Clicked"  Order="Secondary"/>
</TabbedPage.ToolbarItems>

A: In Xamarin.Forms, using Device.RuntimePlatform can be used to obtain the mobile phone platform used by the current user.
Judgment and data processing by using the above code.
Here is my background code for your reference:
public partial class TabbedPage1 : TabbedPage
{
    public TabbedPage1()
    {
        InitializeComponent();
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        if (Device.RuntimePlatform == "Android")//Determine whether it is Android, if it is, add a picture
        {
            mytest.IconImageSource = "xxx.jpg";
        }
    }
}


text:
Q: Are we all moving at $c$? Is it true to say that all matter in the universe is travelling with velocity c through spacetime, but that for baryonic matter most of that velocity is through the time dimensions rather than the XYZ axes?

A:
Is it true to say that all matter in the universe is travelling with velocity c through spacetime?

Actually, no. Because there is no motion through spacetime. Spacetime models motion through space over time, but because it includes the time dimension, it's totally static. And whilst this  model works very well, we live in a world of space and motion, not a "block universe". To appreciate this, imagine I throw a red ball across the room, and you film it with an old-style cine camera. Then you develop the film and cut it up into individual frames, and stack them into a block. There's a red streak in the block, that's like the ball's worldline. But the ball isn't moving up the block. The map is not the territory.

for baryonic matter most of that velocity is through the time dimensions rather than the XYZ axes?

No. Time is a dimension of measure, not a dimension that offers freedom of motion. I can hop forward a metre, but you can't hop forwards a second. There's no motion through time, just as there's no motion through spacetime. A good way to "get" this is to think of the science-fiction device called a stasis box. No motion of any kind occurs in the stasis box. Light doesn't move, electrochemical signals don't move, nothing moves at all. So when I shut you inside the stasis box for five years then open the door, you think I opened it immediately. You "travelled to the future" by not moving at all whilst everything else did. However having said all that, the wave nature of matter is not in doubt, and such waves are associated with motion at c. Hence the Dirac equation:
$$\left(\beta mc^2 + c(\alpha_1 p_1 + \alpha_2 p_2 + \alpha_3 p_3)\right) \psi (x,t) = i \hbar \frac{\partial\psi(x,t) }{\partial t}$$
It's a relativistic wave equation which describes spin-½ particles such as  electrons and quarks. So it is reasonable to say that all matter in the universe is associated with motion at c.


text:
Q: How to pass constant value to AWS Step Function using Cloudwatch I want to pass some payload to Step Function triggered by Cloudwatch rule. After passing payload, who can I receive it in Step Function ?

A: If you want to pass a payload to the step function you should pass in a constant, this will be a fixed JSON string that gets passed during every trigger.

From the image above you can see the ability to specify a JSON string, this will replace any of the previous input that would have been passed into the step function (the event JSON).


text:
Q: ReactiveCocoa 4: Observing an Action's completed event I'm observing a reactive cocoa 4 action, so I can run some code when the action is executed.
Here's my action's defintion:
buttonAction = Action<Bool, Void, NoError>() { value in

    return SignalProducer<Void, NoError> { observer, _ in
        dataProvider.addNewTestProduct()

        observer.sendNext()
        observer.sendCompleted()
    }

Here's how I'm doing the observing:
vm.buttonAction.events.observeCompleted {
    print("observed completed")
}
vm.buttonAction.events.observeNext {
    print("observed next")
}

The observation of Next events works correctly. When the action is triggered by a UIButton, the print statement is executed.
However, my problem is that for some reason the observation of the completed event is never triggered. Could this be a bug in ReactiveCocoa or am I doing something incorrect?
Thanks!

A: I've asked the same question on the ReactiveCocoa github page and got an answer (from @ikesyo). For completeness, I'm providing the answer here:
This is intended behavior. Since the signature is public let events: Signal<Event<Output, Error>, NoError>, you can observe the inner producer's Completed events as follows:
vm.buttonAction.events.observeNext { event in
    switch event {
    case let .Next(value): ... // A Next event from the inner producer
    case .Completed: ... // A Completed event from the inner producer
    default: break
    }
}

Source:
https://github.com/ReactiveCocoa/ReactiveCocoa/issues/2784


text:
Q: DateTime.fromMillisecondsSinceEpoch not returning an exact DateTime object I'm trying to construct a DateTime object from an int I get from a database, but the returned object is not equal to the original one, here's some test code:
void main() {
  final d = DateTime.now();
  final ms = d.millisecondsSinceEpoch;
  final d1 = DateTime.fromMillisecondsSinceEpoch(ms).;
  print(d);
  print(d1);
  print(d1 == d);
}

which outputs (Running as a console app in android studio):
2020-03-18 20:57:14.887582
2020-03-18 20:57:14.887
false

However, running this code in a DartPad outputs that the two objects are equal.
What am I missing?

A:
However, running this code in a DartPad outputs that the two objects are equal. What am I missing?

When you run the Dart code on the web, including DartPad, note that printing the result of DateTime.now() does not print a time with microsecond precision.  Your question therefore actually is not about the equality check (both objects do represent the same time and should be equal), it's why DateTime is not as precise in DartPad as on other platforms.
Modern web browsers have explicitly reduced timer precision in an effort to thwart timing-based attacks (e.g. Spectre).  See:

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#reduced_time_precision

*https://v8.dev/blog/spectre#high-precision-timers.

Additionally, Dart for the web is transpiled to JavaScript and also is subject to limitations of JavaScript.  JavaScript Date objects simply don't support microseconds, so Dart DateTime objects also won't report microseconds in that environment. (Also see https://github.com/dart-lang/sdk/issues/44876.)


text:
Q: Unable to connect to the server when using ansible I created a droplet using digitalocean and I'm able to connect to my droplet using ssh root@37.139.14.547 without problems.
I just downloaded ansible and added this in my /etc/ansible/hosts:
root@37.139.14.547
Afterwards I'm running ansible all -m ping but I receive an error:
root@37.139.14.547 | UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: Permission denied (publickey).\r\n",
    "unreachable": true
}

What am I doing wrong? Do I need to tell ansible that my ssh public key is located in ~/.ssh/id_rsa.pub or something?

A: First make sure you've got all the packages installed at you local machine...
pip install --user --upgrade setuptools
pip install --user --upgrade ansible
Check the updates;
ansible --version ````
ansible 2.3.2.0
  config file =
  configured module search path = Default w/o overrides
  python version = 2.7.10 (default, Feb  7 2017, 00:08:15) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] ```
Also in your remote as the Ubuntu Server 16.04 LTS on AWS doesn't come with the python installed, so ssh into remote server and run this before connect to your remote.
sudo apt-get install python-minimal -y
I am using EC2 as my remote server
Then try this...
[webserver]
37.170.254.200 ansible_ssh_private_key_file=/home/username/.ssh/my_key.pem
Make sure you can connect to you remote as ssh -i "my_key.pem`" ubuntu@37.170.254.200
If you can connect "SUCCESS", run the " ansible Ad-Hoc Commands " to ping
ansible webserver -m ping -u ubuntu
37.170.254.200 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
OR try to check the memory usage of your remote
ansible webserver -a "free -m" -u ubuntu
If "SUCCESS" you are connect to your remote server

A: Please read how Ansible inventory looks like.
Change your hosts to:
37.139.14.547 ansible_user=root


text:
Q: Primefaces: RequestContext.execute - Javascript called twice I'm using primefaces and have a problem executing JavaScript at the end of an ajax call. I add some action to the RequestContext, and it is executed twice!
RequestContext.getCurrentInstance().execute("alert('I'm here!')");

It is also embedded twice in the XML which I get back from the server - two times the same component and same  node.
Primefaces Version is 5.3.10
Any ideas what is going wrong here? Thanks.

A: It has been a while since last answer and problem seems to be solved but I believe I know what is going on and the reason new deployment solved the problem.
It seems it happens when you have more than one primefaces*.jar inside EAR (i.e. EAR/lib and WAR/WEB-INF/lib.
If anyone else is facing this problem, try to remove from EAR/lib (or EAR root), keep only one primefaces*.jar in EAR.

A: I avoided such error by changing version of Primefaces from 6.0 to 6.1 in POM. (6.1 version was in libs of server Payara)

A: OK, it seems that it was a deployment-problem. We deployed it again and the problem is solved...


text:
Q: Python TypeError: Unicode-objects must be encoded before hashing I have looked at the other 4 questions on here but still cannot figure out where to put the .encode() or .encode('utf-8').  I have commented it out to show the various places I have tried.
import hashlib as hasher

    class Block:
        def __init__(self, index, timestamp, data, previous_hash):
            self.index = index
            self.timestamp = timestamp
            self.data = data
            self.previous_hash = previous_hash #these four items used to calculate crypHash of each block
            self.hash = self.hash_block() #helps ensure integrity throughout blockchain

        def hash_block(self):
            sha = hasher.sha256() #.encode('utf-8')
            sha.update(str(self.index)+
                str(self.timestamp)+
                str(self.data)+
                str(self.previous_hash)) #.encode() inside brackets
            return sha.hexdigest()

Here is the Traceback (reading bottom up):
Traceback (most recent call last):
  File "blockchain.py", line 7, in <module>
    blockchain = [create_genesis_block()]
  File "/media/nobu/win10Files/Blockchain/SnakeCoin/genesis.py", line 8, in create_genesis_block
    return Block(0, date.datetime.now(), "Genesis Block", "0")
  File "/media/nobu/win10Files/Blockchain/SnakeCoin/block.py", line 9, in __init__
    self.hash = self.hash_block() #helps ensure integrity throughout blockchain
  File "/media/nobu/win10Files/Blockchain/SnakeCoin/block.py", line 16, in hash_block
    str(self.previous_hash))
TypeError: Unicode-objects must be encoded before hashing

which seems to indicate that the line str(self.previous_hash)) #.encode() inside brackets should be str(self.previous_hash).encode()) but that gives me this other error:
Traceback (most recent call last):
  File "blockchain.py", line 7, in <module>
    blockchain = [create_genesis_block()]
  File "/media/nobu/win10Files/Blockchain/SnakeCoin/genesis.py", line 8, in create_genesis_block
    return Block(0, date.datetime.now(), "Genesis Block", "0")
  File "/media/nobu/win10Files/Blockchain/SnakeCoin/block.py", line 9, in __init__
    self.hash = self.hash_block() #helps ensure integrity throughout blockchain
  File "/media/nobu/win10Files/Blockchain/SnakeCoin/block.py", line 16, in hash_block
    str(self.previous_hash).encode())
TypeError: must be str, not bytes

So I tried encode() and decode() in various combinations with brackets but that only gets me alternating between errors.
Thus, I am quite lost and would appreciate some guidance.
Btw this code is from a Medium article here:  Medium Snake Coin

A: Only bytes strings can be hashed.  str is a Unicode string.  Encode to bytes, decode to Unicode.
In your .update(), all four items are being converted to str.  So once you concatenate them together, .encode() the whole thing to bytes:
import hashlib as hasher

class Block:
    def __init__(self, index, timestamp, data, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash #these four items used to calculate crypHash of each block
        self.hash = self.hash_block() #helps ensure integrity throughout blockchain

    def hash_block(self):
        sha = hasher.sha256()
        to_hash = str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash)
        sha.update(to_hash.encode())
        return sha.hexdigest()


text:
Q: gradle nod set up fails installing node x86_64 I'm using gradle node plugin for my project and when I run the nodeSetup task it tries to install the node dist from https://nodejs.org/dist/v12.6.0/node-v12.6.0-darwin-x86_64.tar.gz which I know does not exists. The correct URL should be https://nodejs.org/dist/v12.6.0/node-v12.6.0-darwin-x64.tar.gz I'm not sure why its adding x86_64 instead of x64 and I was wondering if there is any way to directly specify the complete dist URL for gradle node plugin.
Here is my node config inside my build.gradle
node {
    version = '12.6.0'
    npmVersion = '6.0.0'
    yarnVersion = '1.13.0'
    download = true

    workDir = file("${buildDepsDir}/nodejs")
    npmWorkDir = file("${buildDepsDir}/npm")
    yarnWorkDir = file("${buildDepsDir}/yarn")
    nodeModulesDir = file("${project.projectDir}")
}

A: It sounds like you may be using an old version of the plugin, this exact issue has been fixed in 3.2.1


text:
Q: htaccess redirects but issue with https I need to redirect
https://www.example.com/test
to
https://user.example.com/test
I did it using
RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)?example\.com$ [NC]
RewriteRule ^test/?$ https://user.example.com/test [NC,R=301,L]

Now my issue is, if I load user.example.com/test or http://user.example.com/test
I get user.example.com/test but I need to get https://user.example.com/test
How do I modify or add a rule to do so?

A: You need to check for https in your rule.
RewriteEngine On
RewriteCond %{HTTPS} !^on [OR]
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^test/?$ https://user.example.com/test [NC,R=301,L]


text:
Q: Вставка текста в командную строку bash программно Как запустить bash консоль с набранной командой в командной строке?

A: Можно так (понадобится установить expect).
#!/usr/bin/expect -f
spawn /bin/bash
send "my text to be posted"
interact
exit


text:
Q: JavaScript Namespaces + Setter Well, I'm using object orientation in JavaScript, but instead of using new, I just call the method from the namespace. In the moment, I have the following code:
var Component = {
    Button: function(_text, use_image) {
        button = $.createElement('button')
        if (use_image != false)
        {
            button.innerHTML = _text;
        }
        else
        {
            button.innerHTML = _text
        }
        var text = _text
        return button
    }
}

When I want to return a button, I do:
x = Component.Button("Click me")

And after I can use x. But if I want to change the text of x, I must use x.textContent. I'd like to instantiate this and use a setter to apply its text, this way:
x = new Component.Button("Click me")
x.text = "Don't click me"
document.getElementsByTagName("body")[0].appendChild(x)

And if I try to apply the setter text, it becomes global, I want to have a unique for each button. Mix namespaces with get/set.
Thank you in advance

A: One way can be like, I am not sure if this is the best approach. Looking for more answers
var Component = {
    Button: function(_text, use_image) {
        var button = {
            node : document.createElement('button'),
            setText : function(txt){this.node.innerHTML = txt;}
        };
        if(_text){button.setText(_text);}
        return button;
    }
};

x = Component.Button("Click me");
x.setText("Don't click me");
document.getElementsByTagName("body")[0].appendChild(x.node);

y = Component.Button("Click me2");
y.setText("Don't click me2");
document.getElementsByTagName("body")[0].appendChild(y.node);

http://jsfiddle.net/2LCyn/

A: How about something like this:
var Component = (function($){

    var buttonCount = 0;

    function Button(text, use_image){
        this.id = ++buttonCount;
        this.text = text;
        this.use_image = use_image;
        this.$element = $('<button/>').text(text);
        this.bindEvents();
    }

    Button.prototype.bindEvents = function(){
        var that = this;
        this.$element.on('click', function(){
            console.log('hello, I\'m button ' + that.id);
        });
    };

    Button.prototype.setText = function(text){
        this.text = text;
        this.$element.text(text);
    };

    return {
        Button: Button
    }

})(jQuery);

var button1 = new Component.Button('hello', false);
button1.setText('helloooo');
$('body').append(button1.$element);

var button2 = new Component.Button('world', true);
$('body').append(button2.$element);

http://jsfiddle.net/ATmAx/1/


text:
Q: variable AS (SELECT...) SQL This is a very silly question, but I keep bashing myself off the wall and I can't figure out even what exactly to google.
I have a database, and I am doing some SQL-queries. This one is working fine.
SELECT
year(datetime_buy),
month(datetime_buy),
count(distinct email) AS number
FROM ticket
WHERE year(datetime_buy)=2018
AND email IN (
    SELECT DISTINCT email
    FROM ticket
    WHERE Month(datetime_buy)=1
    AND Year(datetime_buy)=2018 AND datetime_cancel IS NULL)
GROUP BY 1, 2;

But when I am trying to save some SELECT for the future (such as jan_tickets):
jan_tickets AS (
SELECT DISTINCT email
FROM ticket
WHERE Month(datetime_buy)=1
AND Year(datetime_buy)=2018
AND datetime_cancel IS NULL),

SELECT
year(datetime_buy),
month(datetime_buy),
count(distinct email) AS number
FROM ticket
WHERE year(datetime_buy)=2018
AND email IN jan_tickets
GROUP BY 1, 2;

I am getting an error:
Error SQL (1064): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'jan_tickets AS (SELECT DISTINCT email FROM ticket
WHERE Month(datetime_buy)=1 AN' at line 1

Update: I use MySQL 5.6.

A: Assuming you were running MySQL 8+, then the following update to your would work:
WITH jan_tickets AS (
    SELECT DISTINCT email
    FROM ticket
    WHERE DATE_FORMAT(datetime_buy, '%Y-%m') = '2018-01' AND datetime_cancel IS NULL
)

SELECT
    YEAR(datetime_buy),
    MONTH(datetime_buy),
    COUNT(DISTINCT email) AS number
FROM ticket
WHERE
    YEAR(datetime_buy) = 2018 AND
    email IN (SELECT email FROM jan_tickets)
GROUP BY 1, 2;

Notes here include that a CTE definition has to begin using WITH.  Subsequence CTEs that follow do not use WITH, but should be separated by comma.  There is no comma after the last CTE definition, before the query which consumes it.  In your case, you need a subquery in the WHERE clause which selects emails from the CTE.
Edit:
Since you are only using MySQL 5.6, you can't use common table expressions.  So, we may inline the subquery contained in the CTE:
SELECT
    YEAR(datetime_buy),
    MONTH(datetime_buy),
    COUNT(DISTINCT email) AS number
FROM ticket
WHERE
    YEAR(datetime_buy) = 2018 AND
    email IN (
        SELECT DISTINCT email
        FROM ticket
        WHERE DATE_FORMAT(datetime_buy, '%Y-%m') = '2018-01' AND
              datetime_cancel IS NULL
    )
GROUP BY 1, 2;


text:
Q: How to get the column name with reference to an object in r I have multiple csv files for which I want to access second column for every file and do a regex which will remove all strings after ";". this Pattern is same for all the files.
I have referred this
In R, how to get an object's name after it is sent to a function?
This is a sample of my file
ID  POLL
1   1,2:ksd ksj
2   3:jj
3   6:ok0j

This is what I have tried
 setwd("D:/Data/STN")
    temp = list.files(pattern="*.csv")

    for(i in 1:length(temp)){
      DF1=read.csv(temp[i])
      col2=colnames(DF1)[2]
      assign(paste(DF1,"$"),col2)
      DF1$col2 = gsub(":.*","",DF1$col2)

In temp I have all names of all files, I tried with assign but no output.
Thanks in advance

A: We can use lapply to loop over the list of data.frames and replace the suffix part in the second column using sub.
lst1 <- lapply(lst, function(x) {x[,2] <- sub(":.*", "", x[,2])
                        x})

As noted below, the data.frames are read into a list
data
temp <- list.files(pattern="*.csv")
lst <- lapply(temp, read.csv, stringsAsFactors=FALSE)


text:
Q: What is the best way to send multiple data type data from excel to Testng Dataprovider using Apache POI I am new to java.I have been trying to automate a website using selenium using TestNG in POM model.I need to enter data for a web form,the data which is stored in a .xlsx file.There are multiple data in multiple columns having o data type string,integer,boolean.I am using Apache POI to extract data from the file using the following code:
ArrayList<Object> arrlist = new ArrayList<Object>(); try {

      FileInputStream file = new FileInputStream( new File("C:\\Users\\dell i7\\Desktop\\imp docs\\TestData.xlsx"));

      // Create Workbook instance holding reference to .xlsx file

      XSSFWorkbook workbook = new XSSFWorkbook(file);

      // Get first/desired sheet from the workbook XSSFSheet sheet =
      workbook.getSheetAt(0);

      // Iterate through each rows one by one
      Iterator<Row> rowIterator =sheet.iterator();
      while (rowIterator.hasNext())
      { Row row = rowIterator.next(); // For each row, iterate through all the columns
      Iterator<Cell> cellIterator = row.cellIterator();

      while (cellIterator.hasNext()) { Cell cell = cellIterator.next();
      // Check the cell type and format accordingly switch (cell.getCellType()) {
      case NUMERIC:
      //System.out.println((int) cell.getNumericCellValue());
      arrlist.add((int) cell.getNumericCellValue());
      break;
      case STRING:
      System.out.println(cell.getStringCellValue());
      arrlist.add(cell.getStringCellValue());
      break;
      default: break; } }
      System.out.println("");

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

Now a TestNG Data provider requires an Object[][] to get the data and send it to the Test method.What is the best way to do so?

A: @DataProvider(name ="Testlogin")
public Object[][]  getData()
{
    //your data from excel sheet
    return data;
}


text:
Q: What's the best classical physics (mechanics, electromagnetism, etc) textbook to read as a regular book? Looking for recommendations for someone who loves physics but is not in college/university. I'm a 39-year old engineer.

A: I highly recommend Six ideas that shaped Physics by Thomas Moore.  Every volume in the series just oozes physics, emphasizing symmetries and how the physics flows from some core concept.
It's written at the first year University level, but I think it's too rich in physics for the typical 1st year student mostly interested in just passing a required course.


text:
Q: pyephem, libnova, stellarium, JPL Horizons disagree on moon RA/DEC? MINOR EDIT: I say below that JPL's Horizons library is not open source. Actually, it is, and it's available here: http://naif.jpl.nasa.gov/naif/tutorials.html
At 2013-01-01 00:00:00 UTC at 0 degrees north latitude, 0 degrees east
latitude, sea level elevation, what is the J2000 epoch right ascension
and declination of the moon?
Sadly, different libraries give slightly different answers. Converted
to degrees, the summarized results (RA first):
Stellarium: 141.9408333000, 9.8899166666 [precision: .0004166640, .0000277777]
Pyephem: 142.1278749990,  9.8274722221 [precision .0000416655, .0000277777]
Libnova: 141.320712606865, 9.76909442356909 [precision unknown]
Horizons: 141.9455833320, 9.8878888888 [precision: .0000416655, .0000277777]

My question: why? Notes:

*

*I realize these differences are small, but:

*

*I use pyephem and libnova to calculate sun/moon rise/set, and
these times can be very sensitive to position at higher latitudes
(eg, midnight sun).

*I can understand JPL's Horizons library not being open source,
but the other three are. Shouldn't someone work out the
differences in these libraries and merge them? This is my main
complaint. Do the stellarium/pyephem/libnova library authors have
a fundamental difference in how to make these calculations, or do
they just need to merge their code?

*I also realize there might be other reasons the calculations are
different, and would appreciate any help in rectifying these
possible errors:

*

*Pyephem and Libnova may be using the epoch of the date instead of J2000

*The moon is close enough that observer location can affect its
RA/DEC (parallax effect).

*I'm using Perl's Astro::Nova and Python's pyephem, not the
original C implementations of these libraries. However, if these
differences are caused by using Perl/Python, that is important in
my opinion.

*My code (w/ raw results):

*

*First, Perl and Astro::Nova:

#!/bin/perl

# RA/DEC of moon at 0N 0E at 0000 UTC 01 Jan 2013
use Astro::Nova;
# 1356998400 == 01 Jan 2013 0000 UTC
$jd = Astro::Nova::get_julian_from_timet(1356998400);
$coords = Astro::Nova::get_lunar_equ_coords($jd);
print join(",",($coords->get_ra(), $coords->get_dec())),"\n";

RESULT: 141.320712606865,9.76909442356909

- Second, Python and pyephem:

#!/usr/local/bin/python

# RA/DEC of moon at 0N 0E at 0000 UTC 01 Jan 2013
import ephem; e = ephem.Observer(); e.date = '2013/01/01 00:00:00';
moon = ephem.Moon(); moon.compute(e); print moon.ra, moon.dec

RESULT: 9:28:30.69 9:49:38.9

- The stellarium result (snapshot):

- The JPL Horizons result (snapshot):

[JPL Horizons requires POST data (not really, but pretend), so I
couldn't post a URL].

*

*I haven't linked them (lazy), but I believe there are many
unanswered questions on stackoverflow that effectively reduce to
this question (inconsistency of precision astronomical libraries),
including some of my own questions.

*I'm playing w this stuff at: https://github.com/barrycarter/bcapps/tree/master/ASTRO

A: I have no idea what Stellarium is doing, but I think I know about the other three. You are correct that only Horizons is using J2000 instead of the epoch-of-date for this apparent, locale-specific observation. You can bring it into close agreement with PyEphem by clicking "change" next to the "Table Settings" and switching from "1. Astrometric RA & DEC" to "2. Apparent RA & DEC."
The difference with Libnova is a bit trickier, but my late-night guess is that Libnova uses UT instead of Ephemeris Time, and so to make PyEphem give the same answer you have to convert from one time to the other:
import ephem
moon, e = ephem.Moon(), ephem.Observer()
e.date = '2013/01/01 00:00:00'
e.date -= ephem.delta_t() * ephem.second
moon.compute(e)
print moon.a_ra / ephem.degree, moon.a_dec / ephem.degree

This outputs:
141.320681918 9.77023197401

Which is, at least, much closer than before. Note that you might also want to do this in your PyEphem code if you want it to ignore refraction like you have asked Horizons to; though for this particular observation I am not seeing it make any difference:
e.pressure = 0

Any residual difference is probably (but not definitely; there could be other sources of error that are not occurring to me right now) due to the different programs using different formulae to predict where the planets will be. PyEphem uses the old but popular VSOP87. Horizons uses the much more recent — and exact — DE405 and DE406, as stated in its output. I do not know what models of the solar system the other products use.


text:
Q: How to implement message Queue one per client? I currently implementing a peer to peer messaging application in java. Currently I am bit stuck with one issue. In my application I want a message queue that will be residing in each peer and Other peer which wants to communication other peer actually goes ahead and write there message in other peers MQ (message Queue).
For Eg. A and B are two different peers/Nodes in a network.
Now A wants to sent a message to B, then it goes ahead and writes its message to B's Queue. And B will keep on pulling messages from it's own MQ.
I don't know what Java library to use which could easily allow me to implement this.
I have searched a lot about this and never found a proper solution for this.
Can any one suggest me a good way to implement this.

A: Phisically sending messages from A to B is simple enough, just open the sockets or use a non blocking networking library such as Netty or Apache Mina. Both provide several examples of implementing network communications on top of their stacks.
You'll probably need to decide how the network topology is, if there are just 2-3-4 peers connected, you can simply have each peer have an open socket for each of the other peers.
If there are expected to be many peers, having a socket for each would be difficult or even impossible, and a different topology is necessary:

*

*Each peer has knowledge of just a few of its neighbours, the other peers are reachable by hopping from peer to peer using some routing logic.

*Another solution is to have a centralized node where all peers checkin (this is how Skype or most other IM networks work).

A: I think I could use RMI for this Purpose. In my case each peer will act as a server and run rmiregistry. And my interface file will contain apis to populate the Message Queue. other peer will use RMI to call API's to update the Queue. Indirectly my other peers will update the Message Queue on the peer which it want to communicate.
I don't know whether this is a correct way to implement it, All suggestions are still welcome.


text:
Q: How to make browser to download the Django CSV file response I am following the Django doc here to create a CSV file. In my urls.py I have url(r'^reports/csv_list_report/$',  'csv_list_report').
I want user to download the CSV file when clicking on the download button. So I use jQuery for here:
$('#download_button').click(function(){
    $.get('/reports/csv_list_report/');
});

I can see the response in the firebug, but the browser does not download the file.
Here is my view:
def csv_list_report(request):
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename="reports.csv"'
    writer = csv.writer(response)
    writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])
    writer.writerow(['Second row', 'A', 'B', 'C', '"Testing"', "Here's a quote"])

return response

So maybe after the GET I need to write something to handle the response on success? Searched around, there are plenty answers on how to create CSV files, but didn't find any answers including what one need to do to handle the response.

A: You can't make the browser download a file through AJAX (that's what jQuery is doing when you use $.get). You have to make a direct synchronous HTTP connection.
Instead of $.get, try this:
location.replace('/reports/csv_list_report/');

Related: Force download through js or query


text:
Q: Ansible add_host not being applied in Azure dynamic inventory I am trying to add a host in Ansible to the Azure dynamic inventory at run time.
First I log the "before add_host" contents of the 'ansible_play_hosts_all' inventory variable
Then I use "add_host" to add a new host
When I log the "after add_host" contents of the 'ansible_play_hosts_all' inventory variable, I can see my new host added to the list.
But when the next task in the playbook is run, it is not run on the newly added host.
I have also tried using "meta: refresh_inventory", but to no avail.
Any help is appreciated - thanks
     - name: "Log the contents of the 'ansible_play_hosts_all' magic inventory variable before testing ssh connectivity"
       debug:
         msg: "{{ ansible_play_hosts_all }}"

# Wait for vm_to_be_added to become contactable via ssh, then refresh the inventory
     - name: Waits for SSH port 22 of the EPMP host to become available
       wait_for:
         host: vm_to_be_added
         port: 22
         state: started
         timeout: 600

# Add vm_to_be_added host to the dynamic inventory
     - name: Add vm_to_be_addedhost to the dynamic inventory
       add_host:
         hostname: "vm_to_be_added"
         group: tag_workspace_cluster

# Log the contents of the 'ansible_play_hosts_all' magic inventory variable after testing ssh connectivity
     - name: "Log the contents of the 'ansible_play_hosts_all' magic inventory variable after testing ssh connectivity"
       debug:
         msg: "{{ ansible_play_hosts_all }}"

     # Record the IP of the machine currently running(hosting) Ansible.
     - set_fact: ANSIBLE_HOST_IP="{{lookup("pipe","hostname -I")}}"

A: The solution I have ended up with is:
I removed add_host and used meta: refresh_inventory (after I had waited for a connection & confirmed I could shh to the new server )
After the refresh I then started a new play. This is important, as it is only in the new play I see the new host now added to the dynamic inventory group.
In short it now looks like this:
- name: Play 1
  hosts: localhost
  become: true
  pre_tasks:

     - name: Waits for SSH port 22 of the host to become available
       wait_for:
            host: vm_to_be_added
            port: 22
            state: started
            timeout: 600

     # Now that we know that the vm_to_be_added is contactable, refresh to have it included in the inventory.
     # The newly refreshed inventory will only be availble to the next play.
     - meta: refresh_inventory

- name: Play 2
  hosts: dynamic_group
  become: true
  pre_tasks:

     # This task will be run against the newly added host
     - set_fact: ANSIBLE_HOST_IP="{{lookup("pipe","hostname -I")}}"


text:
Q: SCTP - Protocol Unreachable Error I am working on basic SCTP message exchange (Novice in SCTP) and getting the "ICMP Protocol Unreachable Error".
I am using two linux machines 'A' (Source) and 'B' (Destination). In B machine sipp tool is listening over SCTP on 5080 port (This is verified using netstat).
Firstly machine B is reachable from my machine A, i must not get "Destination Unreachable|Host Unreachable". Secondly netstat has verified that listening port is 5080 so i must not get "Port Unreachable" also.
Now i am sending INIT from A (28232 port) to B (5080 port). Interestingly i am getting "ICMP - Protocol Unreachable" ? I am not able to co-relate this ICMP error.
After searching the internet i found few posts (outside stackoverflow) saying "ICMP Protocol Unreachable error and SCTP connect have some race condition". I am not able to locate any such issue in linux kernel website.
I am using RHEL machine with kernel version 3.10.0-327.28.2.el7.x86_64 .
Can someone help me in explaining the expected behavior.
Sudhansu

A: From the Kernel Version you have shared,
You seem to be running RHEL 7.2
You might need to check if there is a firewall firewall is on..(SCTP is not allowed by default on the Linux firewall)
try
1:stopping the firewall and see if the error clears
2:If the error clears on the point 1 above then you can allow the specific SCTP port on your firewall and it should work without an problem.
let me know if this one works or if you get stuck at any point.


text:
Q: Reliable multicast libraries Thinking to implement Reliable Multicast for a Desktop Application.
Gone through JRMS and found that there is no proper documentation for it.
Is JRMS still in use?? Or otherwise how JGroups can be effective for Reliable Multicast?
Is there any other reliable multicast libraries available, which is available for many languages like Java, C++, etc.,


text:
Q: Connecting To Firestore Using Laravel 6 Not Working I've been trying to insert data into firestore using my laravel 6 application and it looks like its trying to connect to mysql.
I've tried to remove the db part in my .env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

But it doesnt seem to work.
First off this is the error am getting when i try to insert:
"message": "SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)

This is my php code:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Google\Cloud\Firestore\FirestoreClient;
use Google\Cloud\Firestore\FireStoreDocument;

class LogisticsController extends Controller
{

    public $firestoreClient;

    /**
     * __construct initialize firestore client
     *
     * @return void
     */
    public function __construct()
    {

        $this->firestoreClient = new FirestoreClient([
            'projectId' => 'my-project-id',
        ]);

    }

    /**
     * create  a new logistics company
     *
     * @return
     */
    protected function create(Request $request)
    {

        //get and validate form data
        $validatedData = $request->validate([
            'company_name' => 'required|unique:company_name|max:255',
            'registration_no' => 'required'
        ]);

        $company_name = $request->company_name;
        $registration_no = $request->registration_no;

        $this->firestoreClient->addDocument('Logistics_Companies', [
            'company_name' =>  $company_name,
            'registration_no' => $registration_no,
            'created_at' => new FirestoreTimestamp,
            'updated_at' => '',
            'deleted_at' => ''
        ]);
    }
}

I dont know why its trying to connect using mysql. Anyone know what i need to do or what am doing wrong ???.
Every form of help is highly appreciated. Cheers!!!!

A: The env file is only used to override the default database defined in the config/databases.php file, within that file you'll need to modify this line if you don't want to use mysql:
'default' => env('DB_CONNECTION', 'mysql')

However, since it's trying to connect to a mysql database, somewhere in your project you're using Laravel's orm (eloquent) and will need to integrate Firestore at a deeper level into Laravel or refrain from using Eloquent.


text:
Q: Making an iterative way to add GIST indexes to spatial tables I am attempting to make a generic way to add GIST indexes to my postgres/postgis databank. The problem is that some tables have already a GIST index so I would like to ignore those. I might make a new database in the future so I would like to make this as generic as possible so I am using the structural tables.. I am making use of the Do block but I don't see why the system doesn't want to proceed.
I get a very unspecific error and I don't know how to proceed.
DO $$
DECLARE
  table_name text;
BEGIN
    FOR table_name IN (SELECT f_table_name FROM information_schema.tables WHERE geometry_columns where not(f_table_name ilike '%view%') and not(f_geometry_column ilike '%st_union%') LOOP
        BEGIN;
            EXECUTE format('CREATE INDEX "gist_%I" ON %I USING GIST (geom);', table_name || '_index', table_name);
        EXCEPTION WHEN others THEN
            RAISE notice  'Error occurred creating index for table %: %', table_name, SQLERRM;
        END;
    END LOOP;
END $$;

SQL Error [25P02]: ERROR: current transaction is aborted, commands ignored until end of transaction block
Error position: line: 1 pos: 1


text:
Q: How to filter FormGroup values? I have a massive FormGroup, it has many FormControls and many nested FormArrays, and i need to get the value of the top FormGroup except some controls. These controls may be situated very deep in nested FormArrays
Is there any angular way to filter form_group.value or form_group.getRawValue()?

A: Looks like there is no built in function for that, so I had to implement some functions that manually collect values:
getFormValue(form_group: FormGroup): any {
  const value = {};

  Object.keys(form_group.controls).forEach(control_name => {
    if (/* condition that shows that the value should not be filtered out */) {
      value[control_name] = this.getFormItemValue(form_group.controls[control_name]);
    }
  });

  return value;
}

getFormItemValue(item: AbstractControl): any {
  if (item instanceof FormControl) {
    return item.value;
  }
  if (item instanceof FormArray) {
    return item.controls.map(form_group => {
      return this.getFormValue(form_group as FormGroup);
    });
  }
}


text:
Q: Save subclass of SKShapeNode using NSCoding I have a subclass of SKShapenode with 2 extra attributes
@property(assign)float size;
@property(assign)float weight;

But when I save a NSMutableArray, with core data, containing some subclasses of my node, the information about size + weight is lost.
newLevel.tractorObjects = [NSKeyedArchiver archivedDataWithRootObject:arrayTractorObjects];

How can I solve this problem?

A: Since you appear to be using NSCoding to encode the nodes, you need to implement NSCoding in your subclass. Right now SKShapeNode is doing all of the encoding, but it doesn't know about your subclass attributes. To get your attributes encoded, you need to implement encodeWithCoder and initWithCoder. Both of these should call super's implementation so that SKShapeNode can encode itself, and then add/extract your own attributes.


text:
Q: Como contar las cadenas de caracteres de un data frame y ponerlo en el dataframeoriginal Agradezco su ayuda con esta situación:

*

*Quiero contar los caracteres de cada uno de los registros de un data frame Ejemplo:
saludo = "Counselor, Log Cabin Ranch"
caracteres = len(saludo)
print(caracteres)
26

En phyton por medio de una funcion , ya que lo quiero aplicar a una columna completa de un dataframe , intente por medio de una funcion
def contar(x):
for i in x:
caracteres = len(x)
print(caracteres)
y Luego quiero agregar una columna nueva a mi dataframe principal con el resultado de esa lista de conteo:
sal['len'] = sal['JobTitle'].apply(contar);
Esta parte me trae el conteo en una lista , como lo necesito

Mi problema es que en el data frame resultante los registros de esta nueva columna me salen None

Agradezco su colaboración

A: Buen día,
Hay una forma más fácil de hacer lo que quieres
Las columnas tienen un método str (String) para evaluar su contenido y los string tienen un método len() que devuelve el número de caracteres del string
Puedes hacer esto:
sal['len'] = sal['JobTitle'].str.len()


text:
Q: Create and log in to a web site with http POST request without using HttpUrlConnection library or other libraries I am trying to create a http post request without using any library such as java.net.HttpUrlConnection, java.net.URLConnection, URL.openConnection() etc in Java. But every example on the internet has used libraries such as HttpUrlConnection. Can anyone please help me to create a Post request for login in a web site in java?

A: You will need to use low level networking working directly with java.net.Socket objects. Perhaps the best place to start is the Java sockets tutorial, and then check out the sample echo client therein. That will show you how to connect to a server and then read and write data to/from it.
In order to construct the required messages you also need to understand HTTP POST. The topic is far too detailed to discuss here, so you will need to some reading.
Here is a program that sends a simple hard-coded POST request to a server running on localhost:1234:
import java.io.*;
import java.net.*;

public class SendPost {
    public static void main(String[] args) {
        try {
            String post_request = "POST /login HTTP/1.1\r\nHost: localhost:1234\r\nContent-Length: 41\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\nusername=bob%40test.com&password=i+forget";

            Socket s = new Socket("localhost", 1234);
            DataOutputStream out = new DataOutputStream(s.getOutputStream());
            out.writeBytes(post_request);
            s.close();
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

This just sends a POST request containing a user name and a password using the same format that your browser would if you were using it to submit a login form.
The (heavily simplified) request looks like this:

POST /login HTTP/1.1
Host: localhost:1234
Content-Length: 41
Content-Type: application/x-www-form-urlencoded

username=bob%40test.com&password=i+forget


text:
Q: Writing dynamic CSS with Jade I'm trying to write out some dynamic CSS using Jade, like so:
style(type='text/css')
    each item in colors
        .#{item.class} { background-color : #{item.background}; color: #{item.foreground}; }

However this gives the following error:
ReferenceError: media='print')
    7|  style(type='text/css')
  > 8|      - for(var item in colors)
    9|          .#{item.class} { background-color : #{item.background}; color: #{item.foreground}; }
    10| block Content
    11|     include scheduleTemplate

item is not defined

If I remove the style tag, it renders fine. Is there any way to use iteration within a style block?

A: You could use Stylus. It's made by the same people that created Jade and is almost identical to Jade within reason.

A: Another way is to import your own css stylesheet. In the Jade doc, you can see that you can include a style sheet with such code:
html
  head
    style
      include style.css

Then, you can define any CSS in a separate file that you can reference.

A: Because style tags only allow text in Jade, it's treating your each item in colors as plain text. Then it encounters the #{item.class} and attempts to parse that, but it fails because it didn't define item on the previous line.
Unfortunately, I'm not sure that there is a good way to do this in Jade. You might just have to define all of your css ahead of time in JS and then insert it like so:
style(type='text/css')
    #{predefined_css}

At that point though, it might be simpler to just move the styles to an external stylesheet that gets generated for each user and then serve it with some reasonable caching headers. That would avoid the difficulties with trying to make Jade do dynamic CSS and speed up subsequent page loads for your users.

A: I ran into a similar issue where I wanted to add a specific class to the body tag depending on the route, similar to what I've done in PHP. In the end, I used jade's template inheritance to achieve a similar result.