text:
Q: Looking for a space epic where the main characters are an A.I. and a woman Years ago I bought a new Sci-Fi book. Likely published between 1998-2006. It stood out to me because I think it had won some sort of award and it was featured in a bookstore that did not predominatantly sell Sci-Fi.
The size of the book was larger than the typical soft cover printing and there was a design some of some darkened space scene on the front (I know, I know, not helpful)
The Plot: I have forgotten the main part of the action/adventure. But what struck me was the fact that the main character (female) was trying to figure out who her true enemies were throughout most of the book. At times this included her non-corporeal A.I. (her spaceship?) that had been with her most of her life.
The enemies are vanquished in the end. And as all things are revealed, it turns out to be a beautiful love story between the woman and the A.I. One that is not bound by conventions of gender or form. I believe that they are able to share their consciousness directly with each other somehow.
The description of this melding of souls was something that haunted me over the years and regret immediately giving the book away to a friend. I have even had a few dreams about it... which I hope has not further muddled my memory of the story.
It was suggested to me that it might be Ancillary Justice, but the plot and the  publishing date aren't quite right. Still, it is next on my list to read, I hear it is good.

A: BOOK FOUND!!! (courtesy of Borderland Books, San Francisco)
Spin State by Chris Moriarty
Winner of the Philip K. Dick Award 2006
It is very good I highly recommend it:

Synopsis:
UN Peacekeeper Major Catherine Li has made thirty-seven faster-than-light jumps in her lifetime—and has probably forgotten more than most people remember. But that's what backup hard drives are for. And Li should know; she's been hacking her memory for fifteen years in order to pass as human. But no memory upgrade can prepare Li for what she finds on Compson's World: a mining colony she once called home and to which she is sent after a botched raid puts her on the bad side of the powers that be. A dead physicist who just happens to be her cloned twin. A missing dataset that could change the interstellar balance of power and turn a cold war hot. And a mining "accident" that is starting to look more and more like murder...
Suddenly Li is chasing a killer in an alien world miles underground where everyone has a secret. And one wrong turn in streamspace, one misstep in the dark alleys of blackmarket tech and interstellar espionage, one risky hookup with an AI could literally blow her mind.

A: Possibly Scott Westerfield's Evolution's Darling, published April 2000.

From the Amazon link:

Does a clone have a soul? Darling, an astronavigational control unit
  and personal companion, achieves sentience and wants to know. Now, 200
  years and an artificial body later, he is off in search of a dead
  artist, a living artwork, and the forces behind a mystery that spans
  the universe. Accompanied by a female assassin, he'll confront the
  Maker and get the answer.

A: It doesn't quite match up with what you're saying, but since you seem pretty fuzzy on a lot of things, could it be Old Soldiers? It involves a woman commanding a sentient Bolo tank, defending against alien invasion. During the course of the story they communicate by a neural interface, in the end she's fatally wounded and her consciousness is 'uploaded' to fuse with the tank's consciousness. I wouldn't really call it a love story.


text:
Q: cannot transform PCollection containing type Map - "wrong number of arguments" I'm trying to apply a transform to a PCollection of Map objects in Apache beam with ParDo. I specified Map as the output type of the first DoFn, and specified Map as the input type of the next DoFn. However, I'm getting the following error:

[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java (default-cli) on
  project word-count-beam: An exception occured while executing the Java
  class. error when invoking Coder factory method public static
  org.apache.beam.sdk.coders.MapCoder
  org.apache.beam.sdk.coders.MapCoder.of(org.apache.beam.sdk.coders.Coder,org.apache.beam.sdk.coders.Coder):
  wrong number of arguments -> [Help 1]

Here's my code:
  static class GetProductName extends DoFn<String, Map> {
    @ProcessElement
    public void processElement(ProcessContext c) {
      {...}
      Map<String, String> properties = new HashMap<>();
      properties.put("name", "test_name");
      properties.put("sku", "test_sku");

      // Use ProcessContext.output to emit the output element.
      c.output(properties);
    }
  }

  static class FormatForDatastore extends DoFn<Map, Entity> {
    @ProcessElement
    public void processElement(ProcessContext c) {
      Map<String, String> product = new HashMap<>();
      product = c.element();
    {...}
    }
  }

  public static void main(String[] args) {
    WordCountOptions options = PipelineOptionsFactory.fromArgs(args).withValidation().as(WordCountOptions.class);
    Pipeline p = Pipeline.create(options);

    // apply transforms
    p.apply("ReadJSONLines", TextIO.read().from(options.getInputFile()))
     .apply(ParDo.of(new GetProductName()))
     .apply(ParDo.of(new FormatForDatastore()))
     {...}
   }

Any ideas what the issue is?
I'm not sure how to interpret the error. I did some testing by editing the code to transform PCollection of type String instead of type Map, and it works without issues. However, I would like a way to pass multiple key value pairs between these transforms. Suggestions for alternatives are welcome.

A: You're using the raw type Map. Try using the proper generic type Map<String,String>.

redpajama_set_name: RedPajamaStackExchange


text:
Q: @MessageMapping not trigger controller when message push from Javascript via WebSocket I am try to do the WebSocket demo using Spring 4.1.1, Stomp 2.3.3, sockjs 0.3.4
On server side :
There is a config file
@Configuration
@EnableWebSocketMessageBroker
public class AppWebSocketConfig extends
        AbstractWebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic/");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/hello").withSockJS();
    }
}

And the is a controller to proccess the message
@Controller
public class EBConsoleWebSocketController {

    private static final Logger LOG = Logger
            .getLogger(EBConsoleWebSocketController.class);

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        LOG.info(message.getName());
        return new Greeting("Hello, " + message.getName() + "!");
    }

    public class HelloMessage implements Serializable {

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }

    public class Greeting implements Serializable {
        private String content;

        public Greeting(String content) {
            super();
            this.content = content;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

    }
}

The problem is seem the @MessageMapping do not trigger greeting method.
Here is the client side javascript.
var stompClient = null;

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        document.getElementById('response').innerHTML = '';
    }

    function connect() {
        var socket = new SockJS("<c:url value='/hello'/>");
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function(frame) {
            setConnected(true);
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/greetings', function(greeting) {
                showGreeting(JSON.parse(greeting.body).content);
            });
        });
    }

    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {
        var name = document.getElementById('name').value;
        stompClient.send("/app/hello", {}, JSON.stringify({
            'name' : name
        }));
    }

    function showGreeting(message) {
        var response = document.getElementById('response');
        var p = document.createElement('p');
        p.style.wordWrap = 'break-word';
        p.appendChild(document.createTextNode(message));
        response.appendChild(p);
    }


text:
Q: What is a female or gender neutral form of gentleman that relays the same tone of respect? At my office when referring to customers or external vendors I often use the word gentleman. I do this in effort to show that I'm speaking respectfully about them so the content and tone of my statement is less likely to be mistaken. For example, "I spoke with the gentleman about the issue he was having and it turned out he forgot to turn his computer on."
However, when the subject is a female the use of the word lady doesn't seem to project the same level of intended respect.
Is there an alternative female or gender neutral word that I could use in these cases?

A: Gentlemen and ladies lend me your ears! You seem to be looking for lady.

A: Unfortunately, 'lady' has a paternalistic connotation, and it is best to refer to both sexes as clients, customers, vendors, manager, assistant...  -when possible.  IOW, avoid referring to their sex but only their position.

A: A gender-neutral, respectful word to describe a customer is "customer". Even in communications that are likely to be shared with said customer, in practice I've found that the word is far less likely to offend. This is especially true in those cases where your customer sounds like a "gentleman" on the phone, but is in fact a "lady" (or vice versa).
Your example phrase would therefore sound just as professional and respectful if spoken thusly:
"I spoke with the customer about the issue he was having and it turned out he forgot to turn his computer on."
Of course, using "he" in the same sentence negates the gender neutrality of the term you use no matter how carefully you choose it, but that's far too broad to properly cover in detail here.

A: Perhaps the most obvious word here is gentlefolks, which until the nineteenth century appeared only and always in the plural.  Shakespeare used it in the plural, as did Thackeray.  Eventually, however, writers towards latter end of Victorian era began to use gentlefolk in the singular.
But it does seem a long word, doesn't it?  As a shorter version, the courageous might make fair use of the noun gentles, especially in the plural.  It's mostly just an "abbreviation" (as it were), of gentlefolks.
From A Midsummer Night's Dream, Act V Scene I:

Gentles, perchance you wonder at this show.
  But wonder on, till truth make all things plain.
  This man is Pyramus, if you would know.
  This beauteous lady Thisbe is certain.

Or at the finale, in Puck's final address to the audience:

If we shadows have offended,
  Think but this, and all is mended,
  That you have but slumber'd here
  While these visions did appear.
  And this weak and idle theme,
  No more yielding but a dream,
Gentles, do not reprehend:
  If you pardon, we will mend.
  And, as I'm an honest Puck,
  If we have unearned luck
  Now to 'scape the serpent's tongue,
  We will make amends ere long;
  Else the Puck a liar call:
  So, good night unto you all.
  Give me your hands, if we be friends,
  And Robin shall restore amends.

The OED does note that gentle is rarely used in the singular, but describes this sense as

One who is of gentle birth or rank.

Nonetheless, saying a gentle rather than gentles in general is long gone.  Even in olden days, simples were opposed to gentles, as in this OED citation:

*

*1882 Mrs. Raven's Tempt. III. 8  The simples are not bound to pick up what the gentles throw away.

It is now perceived as archaic, but could work for vocative uses in the right setting — especially if you wish to impart an air of formality or antiquity.
A few examples of using gentles this way, which might be a comic "vulgarism" for gentlefolks, given by the OED are:

*

*C. 1590 Greene Fr. Bacon x. 16  Now, courteous Gentles, if the Keepers girle Hath pleas'd the liking fancy of you both [etc.].

*1591 Troub. Raigne K. John, To Gentlem. Rdrs. (1611) 70  Gentles, we left King John repleate with blisse.

*1599 B. Jonson Ev. Man out of Hum. (1600) Prol.,  Gentles, all I can say for him is, you are welcome.

*1638 Cowley Love's Riddle v,  It's no matter for that; farewell gentles.

*1641 Marmion Antiq. ɪɪɪ. F 4 a,  Gentles I would entreat you a courtesie.

A: Gentleman was initially a compound noun, composed of Gentle and man. Gentle, here, is derived from French gentil, meaning of nobility by birth. As such, Gentleman can be considered a sort of synonym or Lord, a title for men with female counterpart Lady.
With regards to a gender-neutral version, initially Noble could be a title used for either gender. Now, though, because the word does not have the exact same meaning, it may not be used as such.

A: How about Madame? Though it isn't a direct parallel to gentlemen I think it shows respect

A: "Lady" is the accepted term; perhaps use a capital L.

A: Consider gentlelady, gentlewoman, and the gender-neutral gentle-person.

gentlelady: US a form of address for a woman
gentlewoman: (archaic, now rare) a civilized, educated, sensitive, or well-mannered woman; lady
gentle-person: a person of good family and position; gentleman or lady


text:
Q: creating object from array in php I need to be able to create an object from an array. The data is coming from a terrible API. Here is an example of the data.
Array
(
[0] => stdClass Object
    (
        [no] => 1
        [FL] => Array
            (
                [0] => stdClass Object
                    (
                        [content] => 1505250000001141005
                        [val] => ACCOUNTID
                    )

                [1] => stdClass Object
                    (
                        [content] => 1505250000000091001
                        [val] => SMOWNERID
                    )

                [2] => stdClass Object
                    (
                        [content] => name here
                        [val] => Account Owner
                    )
ETC...

The [no] value is insignificant. the [FL] content is everything I need in the object.
So the outcome I would like is all of the values will be variable names and content will be the values. Can anyone suggestion anything to help please?
EDIT
I think I need to clarify what I need. I'm creating a class called Account which will hold all the information from the api call in an object. I will instantiate the object then call a method for example valuesFromArray() and pass it the [FL] array given by the api call. it will use [val] as the variable name and [content] as its value.

A:      $json_url = "API URL";
    //  Initiate curl
    $ch_curl = curl_init();
    // Disable SSL verification
    curl_setopt($ch_curl, CURLOPT_SSL_VERIFYPEER, false);
    // Will return the response, if false it print the response
    curl_setopt($ch_curl, CURLOPT_RETURNTRANSFER, true);
    // Set the url
    curl_setopt($ch_curl, CURLOPT_URL, $json_url);
    // Execute
    $result = curl_exec($ch_curl);
    // Closing
    curl_close($ch_curl);
    $data = json_decode($result, true);//true--> Convert object to array format

This is the curl method to fetch data from API.Use json_decode($result, true) use json decode convert object to array format.
I hope this is usefull for your question.
Please review,
Thanks!


text:
Q: Split string assignment In a Play template file I would like to split a string and assign each part to a variable. However, the following does not work:
@for(x <- a) {
   @defining(x.split("""\.""")) { Array(x1, x2) =>
      ...
   }
}

Any ideas?

A: You forgot the case keyword.
@for(x <- a) {
   @defining(x.split("""\.""")) { case Array(x1, x2) =>
      ...
   }
}


text:
Q: Azure Function to use Windows Authentication for On-Premises SQL DB We already have an express route configured between azure and our local domain. Local AD is also synced with Azure AD. Azure Function is under a VNet which can access on-premises resources.
The problem is when Azure Function tries to access on-premises SQL using Windows Authentication, it gets the error "Logon Failed" (which proves that the server is accessible but the user doesn't have permission). Event Log shows DWASSVC as the account trying to access DB.
Is there a way we can change the context of Azure Function to run under a specific user which has access to on-Premises SQL DB and any call from Azure Function is generated under that account?

A: Windows Authentication is not possible on Azure App service platform ( Azure web app, Azure Function).
To access on-prem SQL server, you can use Hybrid connection manager
https://learn.microsoft.com/en-us/azure/app-service/app-service-hybrid-connections
Or Put Azure Function in VNET ( ASE) and then make site to site connection.


text:
Q: import XML in google spreadsheet with specified tag one more problem.
I have following structure of XML:
<player>
 <id>12</id>
 <name>pl_name</name>
 <experience>
  <points>147</points>
  <level>10</level>
 </experience>
 <skills>
  <fight>0.00</fight>
  <defend>3.45</defend>
 </skills>
</player>

i want to be written just fight skill in my gdoc.
so something like this:
=ImportXML("http://api.mysite.net/xml/user/id/"&C5; "/*(what here?)")

If it's possible :)
thank you

A: =ImportXML("http://api.mysite.net/xml/user/id/"&C5; "//player/skills/fight")

thanks :)


text:
Q: jQuery Mobile showPageLoadingMsg()/hidePageLoadingMsg() methods not working on initial page loadn I am writing a webapp using jQuery Mobile that calls a function to load records into localStorage and create a listview from a remote JSON file when the page is initially created (using the live.pagecreate() event for the page). At the beginning of this function is the jQuery Mobile method $.mobile.showPageLoadingMsg() and $.mobile.hidePageLoadingMsg() is at the end of the function.
On the initial pagecreate, the loading message does not appear (on iPhone 4 with iOS 4.3 Safari, Chrome 13 and Firefox 5). However, I also have a refresh button on the page; this button clears the associated records in localStorage then calls the same function used to initially populate the listview. However, when calling the same function from the refresh button the showPageLoadingMsg() and hidePageLoadingMsg() both work correctly and the Loading screen appears and disappears as it should. Am I missing something here?
ETA Here is the gist of the code (not in front of the actual code right now, if you need more I will put it in tonight). I also should mention that I've tried to put showPageLoadingMsg in (document).ready and have tried to bind it to mobileinit and neither have worked:
function loadListView(){
   $.mobile.showPageLoadingMsg();
   //ajax call to pull JSON
   //$.each loop to load localStorage and listview
   $.listview.refresh('list');
   $.mobile.hidePageLoadingMsg();
}

$(#listpage).live('pagecreate', function(event){
   loadListView(); // showPageLoadingMsg() and hidePageLoadingMsg do not work when the function is called here
});

function clearList(){
   //for loop that clears each item in localStorage that matches the key prefix set in loadListView
}

//runs when refresh button is clicked
$('listrefresh').live('click',function(){
   clearList();
   loadListView(); //showPageLoadingMsg() and hidePageLoadingMsg() work when the function is called here
});

A:
For these handlers to be invoked during the initial page
  load, you must bind them before jQuery Mobile executes. This can be
  done in the mobileinit handler, as described on the global config
  page.

Docs:

*

*http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/api/events.html

Triggered on the page being initialized, after initialization occurs.
  We recommend binding to this event instead of DOM ready() because this
  will work regardless of whether the page is loaded directly or if the
  content is pulled into another page as part of the Ajax navigation
  system.

Example:

*

*http://jsfiddle.net/phillpafford/mKn8Y/8/
In the example none of the live events fire on initial page load, you have to configure this type of action in the mobileinit:

*

*http://jquerymobile.com/demos/1.0b2/#/demos/1.0b2/docs/api/globalconfig.html


text: Q: How can i call a richfaces component from xhtml page I am including  jasper report's exported  xhtml to a jsf page.  I want to put some export option to jasper report template and when user viewing report on browser if he click  this option(pdf image) i want to pop up a pane and get export options (page ranges) and then call a jsf  bean metod.I am using jsf 1.2 and richfaces so  I need  to know how i can call a


text:
Q: Unity Admob Showing Mix of Test and Real ads I am working in Unity 2020.3.13 using the Google Mobile Ads SDK v6.0.1 package running banners, interstitials, and rewarded ads. My Admob account is in fine standing and has other apps showing real ads without issue, and none of the Admob Ids described below were recently created.
In the Unity editor everything shows as a test ad even though I have set the real app ID and Ad Unit IDs from Admob.  The problem is that once the app builds in Xcode the banner ads show as real ads, while the rewarded ads show as test ads still.  I have double and triple checked the Ad Unit IDs they are all correct.  Any ideas why I am seeing real ads for banners but test ads for Rewarded?

A: Some where in your code you've added your device as a test device or you are testing using emulator.
To verify this use another phone that you did not use before.


text:
Q: "An Introduction to Manifolds", Loring W.Tu, Example 8.19 Loring Tu's "An Introduction to Manifolds", P95, Example 8.19

My problem is: How to verify that the final sentence " $\frac{d}{dt}|_{t=0}gc(t)=gc^\prime(0) $ by $\Bbb R-$linearity and Proposition 8.15 "  ?
here, $g$ is a matrix, $c^\prime(t)$ is not the calculus derivative(derivative of a real-valued function), but the velocity vector(linear map of tangent spaces)
I really appreciate any help you can provide
Proposition 8.15  as follows

A: Let $g$ have entries $(g)_{i,j}$, and similarly for each $t$ let the value of the curve $c(t)$ have entries $(c(t))_{i,j}$. Then the formula for matrix multiplcation says
$$
(g c(t))_{i,j} = \sum_{k = 1}^n (g)_{i, k} (c(t))_{k, j}.
$$
Differentiating this we obtain (we can differentiate a matrix by differentiating it entrywise)
$$
\frac{d}{d t} (g c(t))_{i,j} = \frac{d}{d t}\sum_{k = 1}^n (g)_{i, k} (c(t))_{k, j} = \sum_{k = 1}^n (g)_{i, k} \frac{d}{d t}(c(t))_{k, j},
$$
since each of the entries $(g)_{i, k}$ are just constant. But the entries $\frac{d}{d t}(c(t))_{k, j}$ are exactly the entries of the matrix $c'(t)$, so we obtain
$$
\frac{d}{d t} (g c(t))_{i,j} = \sum_{k = 1}^n (g)_{i, k} (c'(t))_{k, j} = (g c'(t))_{i,j}.
$$
Hence the derivative at $0$ the entries are $(g c'(0))_{i,j}$, i.e. $\frac{d}{d t}\lvert_{t = 0} g c(t) = g c'(0)$, as desired.


text:
Q: Dropdown list option selection not generating second dropdown list options Hi I'm new to javascript but I want to automate a simple web form which includes 2 dropdown lists. Upon the selection of an item in first dropdown list the second dropdown list should appear.
I used the following code to run in Chrome browser's console to select the value "Dubai" from the first drop down list:
document.querySelector(".trigger-section select").selectedIndex = 4;

But it only selects an option from first dropdown list and not generate the second dropdown list. The second dropdown list remains invisible.
When I click via mouse on an option in first dropdown list, the second list is generated without any problem. But when I run the script it only select an option from first and stops.
The following is the HTML code for the element of dropdown lists taken from InspectElement:

<triggersection mode="visibility" question="unrateable_explanation" class="trigger-section" webpage-id="unrateable_explanation" style="">

Select the country

    <listboxquestion name="unrateable_explanation" class="question-element list-box-question" webpage-id="unrateable_explanation" required-question="true">

      <select><option value="Select One">Select One</option>
       <option value="1">Norway</option>
       <option value="2">Ireland</option>
       <option value="3">India</option>
       <option value="4">Dubai</option>
      </select>

    </listboxquestion>

 <triggersection mode="visibility" question="unrateable_explanation_dubai" class="trigger-section" webpage-id="unrateable_explanation_dubai" style="">
  <listboxquestion name="unrateable_explanation_dubai" class="question-element list-box-question" webpage-id="unrateable_explanation_dubai">

    <select>
     <option value="Select One">Select One</option>
     <option value="1">Seoul/option>
     <option value="2">Oocla</option>
     <option value="3">Pdpd</option>
     <option value="4">Algeria</option>
     <option value="5">Gaba</option>
     <option value="6">Adaq</option>
     <option value="0">Osmania</option>
    </select>

  </listboxquestion>
 </triggersection>
</triggersection>

I have also noticed that this required-question="true" is not present when I click via mouse in the following code but it is present when I run the script.
<listboxquestion name="unrateable_explanation" class="question-element list-box-question" webpage-id="unrateable_explanation">

But it is present in the code when I try to access via javascript code in browser's console. Maybe by turning this to "false" will generate the second list, I'm not sure. I don't know how to do that. Also there is no "id" tag but a "webpage-id" tag, so I'm not sure if this can be used as "id" for an element.
I want to select the option from first list and that should generate the second list. Can somebody please recommend something that could resolve this issue?


text:
Q: TemplateBinding not working inside a DrawingImage in a Button Style I want to use a GeometryDrawing as a button icon, inside a ControlTemplate, and I want its Brush property to be bound to the button's Foreground property, but it's not working. On the other hand, if I set the Brush explicitly, it works.
Here is my (non-working) code:
    <Style x:Key="SimpleButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="LightGray"/>
        <Setter Property="Foreground" Value="Black"/>
        <Setter Property="BorderThickness" Value="2"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="border"
                            BorderBrush="{TemplateBinding Foreground}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}"
                            SnapsToDevicePixels="true">
                        <StackPanel Orientation="Vertical">
                            <Image x:Name="buttonImage" Height="20" Width="20">
                                <Image.Source>
                                    <DrawingImage>
                                        <DrawingImage.Drawing>

                                            <!-- line below does not work -->
                                            <GeometryDrawing Brush="{TemplateBinding Foreground}">

                                                <GeometryDrawing.Geometry>
                                                    <EllipseGeometry RadiusX="15" RadiusY="15"/>
                                                </GeometryDrawing.Geometry>
                                            </GeometryDrawing>
                                        </DrawingImage.Drawing>
                                    </DrawingImage>
                                </Image.Source>
                            </Image>
                            <ContentPresenter x:Name="contentPresenter"/>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

A: See this WPF TemplateBinding vs RelativeSource TemplatedParent - Paul Fischer's answer. In particular, this part regarding TemplateBinding:
•Doesn't work with properties on Freezables
If you look at GeometryDrawing you can see its inheritance hierarchy includes Freezable: GeometryDrawing:Drawing:Animatable:Freezable:DependencyObject:DispatcherObject:Object
So, you can't use a TemplateBinding on the Brush property of the Freezable GeometryDrawing.
You can use the TemplateBinding on the Border's BorderBrush property because Border does not inherit from Freezable: Border:Decorator:FrameworkElement:UIElement:Visual:DependencyObject:DispatcherObject:Object


text:
Q: Improving search speed on text column I have a table called 'Products' where i have nearly 100,000 records. I have a field in the table called 'Product name' which is a varchar(255) field and contains name of products which could be around 5 - 15 word text. I perform search operation on this table with user input keywords... i do like...
 select * from products where product_name like '%USER_KEY%' limit 5;

when user search for single term (ex. iphone) it would look like this...
 select * from products where product_name like '%iphone%' limit 5;

This query runs in 0.89 seconds approx which is fine.
when user search for multiple terms (ex. iphone 5gb) it would look like this...
 select * from products where product_name like '%iphone%5gb%' limit 5;

This query takes about 4.02 seconds approx. The product name is a unique key indexed already. Can someone help me what can i do on this to get this search to result in lesser time ?
Anything to be done with db ? or any setting change in mysql helps improving query speed ?


text:
Q: how to check if XML is loaded in VB6 I have this code in VB6 for search a postcode  in Brazil:
MousePointer = 11
Dim xlink As String
Set myXML = New DOMDocument
myXML.resolveExternals = True
myXML.validateOnParse = True
myXML.async = False
xlink = "http://cep.republicavirtual.com.br/web_cep.php?cep=" & cep & "&formato=xml"
myXML.Load (xlink)

The URL fails many times i want to add a second link
xlink2 = "https://viacep.com.br/ws/" & cep & " /xml"

I want to know if myxml have loaded 15  sec , if delay more than 15 load another link.
Thanks in advance


text:
Q: Denormalizing data structures for private data access in Firebase? I would like to create data that scales (to track private data of a user).
The Firebase documentation recommends to nest the child objects under the parent like this:
{
  "users": {
    "google:1234567890": {
      "displayName" : "Username A",
      "provider" : "google",
      "provider_id" : "1234567890",
      "todos": {
          "rec_id1": "Walk the dog",
          "rec_id2": "Buy milk",
          "rec_id3": "Win a gold medal in the Olympics",
          ...
      }
    }, ...
  }
}

(Where rec_id is a unique key generated by Firebase.push().)
But as mentioned in Denormalizing Your Data is Normal I think it would be better to structure it this way:
{
  "users" : {
    "google:1234567890" : {
      "displayName" : "Username A",
      "provider" : "google",
      "provider_id" : "1234567890"
    }, ...
  },
  "todos" : {
    "google:1234567890" : {
      "rec_id1" : {
        "todo" : "Walk the dog"
      },
      "rec_id2" : {
        "todo" : "Buy milk"
      },
      "rec_id3" : {
        "todo" : "Win a gold medal in the Olympics"
      }, ...
    }, ...
  }
}

And then to only allow the user to write/read it's own data apply the following security rules:
{
  "rules": {
    "users": {
      "$uid": {
        // grants write and read access to the owner of this user account whose uid must exactly match the key ($uid)
        ".write": "auth !== null && auth.uid === $uid",
        ".read": "auth !== null && auth.uid === $uid"
      }
    },
    "todos": {
      "$uid": {
        // grants write and read access to the owner of this user account whose uid must exactly match the key ($uid)
        ".write": "auth !== null && auth.uid === $uid",
        ".read": "auth !== null && auth.uid === $uid"
      }
    }
  }
}

As I'm new to this kind of databases I wonder if there are any downsides the way I'd like to structure it.
Would it be better to nest all todos directly under the user as recommended in the first example?

A: First, a couple resources if you haven't run into them yet:

*

*"Structuring Your Data" portion of the Getting Started Guide in the Firebase Docs?

*"Creating Data That Scales" section of that guide is the important part, as you've said.

*Also, check out this answer to "Clarification on Firebase denormalization blog post"

EDIT: You have obviously ran into these resources since it's linked in your question, but I would suggest re-reading over the Structuring Your Data guide a few more times.

*

*EDIT 2: See this answer @Frank van Puffelen posted for In firebase, is modeling many-many relationships using a separate endpoint a good idea?

*

*And this

*I'd also suggest reading up on normalization [1][2] and denormalization [3][4], I think there might be some confusion on which of the two exactly you're referring to.

That brings us to your scenario...
The two ways you have your data set up actually accomplish almost the same thing!
You'll notice though, that the first example is actually listed as an anti-pattern in the "Structuring Your Data" guide.

*

*Doing it your second way would be useful if you want to load a users data, and then that user's todos at a different time.

*The way you have it set up is fine if you only have one user accessing each todo list.

*

*For example, I do this in an app where I know that each user has one single location in a history list, and I only want to load the history of a user in certain scenarios.

*/users/$userUid gives me the user data and /history/$userUid gives me the user's history.

*It makes it easy to segment the loading.

*However, this structure doesn't give any benefits if the todo lists are shared between different users and have to be updated from multiple sources.

*If you want shared access, you're on the right track and just need to make use of keys as references.

The different approach is:

*

*Instead of explicitly setting todo objects under /todos/$uid, you can push a new todo object to /todos so that it gets a new unique ID (called key).

*Then, you add that key to the correct user object's todos child.

*This will allow you to load the user's data first and get only the indices (keys) of the todos to which the user belongs, and

*You can then load all those todos the user belongs to independently.

Doing it this way would:

*

*Prevent user objects from getting huge

*Allow multiple users to update a single todo, without having to update it's child parameters across multiple location.

*Have scalable data by splitting it into separate paths.

Here is the last data sample from the "Creating Data That Scales" section of the guide: (with some comments I added)
  // An index to track Mary's memberships
  {
    "users": {
      "mchen": {
        "name": "Mary Chen",
        // index Mary's groups in her profile
        "groups": {
           // the value here doesn't matter, just that the key exists
           // these keys are used to figure out which groups should
           // be loaded (at whatever appropriate time) for Mary,
           // without having to load all the group's data initially (just the keys).
           "alpha": true,
           "charlie": true
        }
      },
      ...
    },
    // Here is /groups. In here, there would be a group with the key
    // 'alpha' and another one with the key 'charlie'. Once Mary's
    // data is loaded on the client, you would then proceed to load
    // the groups from this list, since you know what keys to look for.
    "groups": { ... }
  }

This achieves a flatter structure.
As the documentation says,

Yes. This is a necessary redundancy for two-way relationships. It allows us to quickly and efficiently fetch Mary's memberships, even when the list of users or groups scales into the millions, or when Security and Firebase Rules would prevent access to some of the records.

So the question is, how could your data look in order to allow a user to have multiple todo lists which can be shared with other users as well?
Here is an example:
{
  "users" : {
    "google:1234567890" : {
      "displayName" : "Username A",
      "provider" : "google",
      "provider_id" : "1234567890",
      "todoLists" : {
        "todoList1": true,
        "todoList2": true
      }
    },
    "google:0987654321" : {
      "displayName" : "Username B",
      "provider" : "google",
      "provider_id" : "0987654321",
      "todoLists" : {
        "todoList2": true
      }
    }
  },
  "todoLists" : {
    "todoList1" : {
      // 'members' user for rules
      "members" : {
        "google:1234567890" : true
      },
      "records" : {
        "rec_id1" : {
          "todo" : "Walk the dog",
          "createdAt" : "1426240376047"
        },
        "rec_id2" : {
          "todo" : "Buy milk",
          "createdAt" : "1426240376301"
        },
        "rec_id3" : {
          "todo" : "Win a gold medal in the Olympics",
          "createdAt" : "1426240376301"
        }
      }
    },
    "todoList2" : {
      "members" : {
        "google:1234567890" : true,
        "google:0987654321" : true
      },
      "records" : {
        "rec_id4" : {
          "todo" : "Get present",
          "createdAt" : "1426240388047"
        },
        "rec_id5" : {
          "todo" : "Run a mile",
          "createdAt" : "1426240399301"
        },
        "rec_id6" : {
          "todo" : "Pet a cat",
          "createdAt" : "1426240400301"
        }
      }
    }
  }
}

*

*In this case, user A would load both lists, but user B would only load the second list. If you set up your rules correctly, all would be well.

*In operation, you would first load the user's data, then load each todo list in a users todoLists, from /todoList

*

*But really, all of this is totally unnecessary if you're making an app where one user has one todo list with todo items that just have a single content.

*Side note, these "ids" should probably be a unique key, which can be accomplished using Firebase.push().

*

*See this answer for using push to generate a new ID.

In conclusion, it all really comes down to how and when your app needs your data, how often data is updated and by whom, and also to minimizing unnecessary reads and watchers. Space is usually cheap, operations (and watchers) usually aren't.
Last but not least, rules and security are another extremely important consideration. The last part of the guide says:

"Thus, the index is faster and a good deal more efficient. Later, when we talk about securing data, this structure will also be very important. Since Security and Firebase Rules cannot do any sort of "contains" on a list of child nodes, we'll rely on using keys like this extensively."

It's early and I hope I'm not blabbering, but I ran into these same questions when I first went from only knowing MySql to using unstructured, so I hope that helps!


text:
Q: Removing the namespace from SOAP request I have imported a WSDL and use it to send a SOAP request. It looks like this:
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <SOAP-ENV:Body>
        <Calculate xmlns="urn:xx.WSDL.xxxxxWebService">
            <ContractdocumentIn>
                <AL>
                ...More XML...

The problem is the xmlns="urn:xx.WSDL.xxxxxWebService" part in the Calculate element. The web service cannot accept this. The web service doesn't like namespaces like this...
Using SoapUI I found this request to work just fine:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:col="http://example.com.service.xxx/">
    <SOAP-ENV:Body>
        <col:Calculate>
            <ContractdocumentIn>
                <AL>
                    ...More XML...

So, how do I change the request from the first to the second version? (Without using dirty tricks!) (Re-importing is not a problem if this would result in the proper request format.)
Again: no dirty tricks allowed, like hacking the request stream to modify it!

And while I haven't completely tested it, it seems that C#/VS2010 and Delphi 2010 are also unable to use the web service that I'm trying to call. A web service that seems to be written in Java. SoapUI happens to be written in Java, thus we have a Java client talking to a Java service, which seems to work just fine. But any other client?
Anyways, time to add two more tags: "Java", since it's a Java service, and "vs2010" because .NET also dislikes this service.And I was about to write a wrapper around this service in .NET, hoping that would work... It doesn't. So this is a very serious flaw, possibly a Java flaw...

A: OMG! It took lots of coffee and plenty of sleep depravation but I managed to solve my problem! It's reasonable simple too...First I import the WSDL, as expected. This will generate several TRemotable classes. Then, for each TRemotable which needs a different namespace, I override the ObjectToSOAP() method! (And include XMLIntf to the WSDL source.) In my case with code like this for several of the remotable types:
function AL2.ObjectToSOAP( RootNode, ParentNode: IXMLNode; const ObjConverter: IObjConverter; const NodeName, NodeNamespace, ChildNamespace: InvString; ObjConvOpts: TObjectConvertOptions; out RefID: InvString ): IXMLNode;
begin
  Result := inherited ObjectToSOAP( RootNode, ParentNode, ObjConverter, NodeName, '', '', ObjConvOpts, RefID );
end;

Which worked in Delphi XE. In Delphi 2007 I had to use units XMLIntf and XMLDoc plus this code on the input type:
function ContractdocumentInType.ObjectToSOAP(RootNode, ParentNode: IXMLNode; const ObjConverter: IObjConverter; const Name, URI: InvString; ObjConvOpts: TObjectConvertOptions; out RefID: InvString): IXMLNode;

  procedure AlterChildren(Child: IXMLNode);
  var
    I: Integer;
  begin
    if (Child.NodeType = ntElement) then Child.SetAttributeNS('xmlns', '', '');
    for I := 0 to Pred(Child.ChildNodes.Count) do
      AlterChildren(Child.ChildNodes[I]);
  end;

begin
  Result := inherited ObjectToSOAP(RootNode, ParentNode, ObjConverter, Name, '', ObjConvOpts, RefID);
  AlterChildren(Result);
end;

It is a hack, in my opinion. But it's not a very dirty one. It's a bit of experimenting, capturing the SOAP requests and responses to check their content and to see if it uses the proper namespaces. Unfortunately, Delphi XE does a far better job at this than Delphi 2007.
Still, I keep this Q open for any better solutions...

Btw, to add the col: to the output, I also had to change this line in the WSDL RemClassRegistry.RegisterXSClass(Calculate, 'http://colan.ogconnect.service.wzp/', 'Calculate'); to this: RemClassRegistry.RegisterXSClass(Calculate, 'http://colan.ogconnect.service.wzp/', 'cal:Calculate');. The result then becomes <cal:Calculate xmlns:cal="http://example.webservice/">. Ont more thing needs to be done, though: moving that xmlns:cal to the xml header. But as it is now, it works for me.

Another note: for the WSDL I used the following settings: 'One Outparam is return', 'Unwind literal params', 'Generate destructors', 'Warning comments', 'emit literal types', 'Map string to widestring'. Other options are: 'Generate verbose information about types and interfaces', 'Ignore porttypes with HTTP Bindings', 'Validate enumeration members', 'Import fault types', 'Import header types', 'Process included and imported schemas', 'Generate class alias as class types', 'Allow Out parameters' and 'Process nillable and optional elements'. The emit literal types was practical because it generates a class around the single method that I was calling. Unfortunately, this won't help much either, although the class would help you to modify the SOAP request on the upper level within the envelope by overriding the ObjectToSOAP() method.Creation of the envelope itself is in the SOAPEnv unit and it's used in the OPToSOAPDomConv unit. Unfortunately, I haven't found an easy method to access the envelope itself to alter the header to add this additional namespace. Then again, I could override the TSOAPDomConv class with my own version that does add the additional namespace. But the code is working for me now, and as my father told me, when he learned me to program: never fix anything that isn't broken.

A: If a Service expects:
  <col:Calculate>
     <ContractdocumentIn>
         <AL>

and Delphi SOAP is sending...
    <Calculate xmlns="urn:xx.WSDL.xxxxxWebService">
        <ContractdocumentIn>
            <AL>

... the problem is that ContractdocumentIn is an unqualified element and (until Delphi XE) Delphi SOAP did not support unqualified elements that are top level elements of an operation. Top level elements are parameters of the function and there is nowhere to store the fact that the underlying element must be unqualified; for elements that map to properties, we use the Index of the property to store away the IS_UNQL flag.
BTW, it's not necessary to use a prefix. The Service will (should) also accept:
    <Calculate xmlns="urn:xx.WSDL.xxxxxWebService">
        <ContractdocumentIn xmlns="">
            <AL>

The latter is more verbose but it's equivalent to the prefix case.
In Delphi XE the importer stores away the fact that a particular parameter maps to an unqualified element and the runtime acts on this information. I've posted patches based on the XE implementation for D2010 and D2007 in the newsgroup when it came up in a thread recently:
https://forums.embarcadero.com/thread.jspa?threadID=43057
If someone needs access to them (they were in the attachments area but might have scrolled off), please email me and I'll make them available. [bbabet at embarcadero dot com]
Cheers,
Bruneau


text:
Q: How to choose multiple columns from a sympy matrix? Broken indexing? I'm trying to pick multiple columns from a sympy matrix. However, the indexing does not work as expected. The code
import sympy as sp

stdA = sp.Matrix(
  [
    [-2, 1, 1, 0],
    [1, 1, 0, 1]
  ]
)

b = sp.Matrix(
  [
    [3],
    [2]
  ]
)

B1 = stdA[:, [0, 1]]
B2 = stdA[:, [0, 2]]
B3 = stdA[:, [0, 3]]
B4 = stdA[:, [1, 2]]
B5 = stdA[:, [1, 3]]
B6 = stdA[:, [2, 3]]

print("std A =", stdA)
print("b =", b)

print("B1 =", B1)
print("B2 =", B2)
print("B3 =", B3)
print("B4 =", B4)
print("B5 =", B5)
print("B6 =", B6)

prints

See the issue with B3, and the matrices after it? It' supposed to read B3 = Matrix([[-2, 1], [0, 1]]). I thought slicing Sympy matrices produces copies of them, so stdA shouldn't be altered in place.
What is causing this erraneous behaviour, and how can I choose specific columns from a matrix with simple indexing?

A: You requested all rows and columns 0 and 3. That is what you got:
>>> B3
Matrix([
[-2, 0],
[ 1, 1]])

Matrix presents the contents as a list of rows.


text:
Q: GetContext() не работает подскажите пожалуйста почему здесь не получается залить область окна браузера чёрным цветом?
A: starCanvas = $('#starCanvas')

jQuery возвращает свой объект, а не элемент. Чтобы получить элемент этого объекта, нужно написать следующим образом:
starCanvas = $('#starCanvas')[0];


text:
Q: How to invoke msbuild default target from powershell script? Can anyone help me to know how can we invoke msbuild default target from a Powershell script?
msbuild script:
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0" DefaultTargets="TestMethod">
   <Target Name="TestMethod">
      <Message Text="Test Method Invoke Finished..." Importance="high"/>
   </Target>
</Project>

I want to invoke the target TestMethod from a Powershell script.
Thanks & Regards,
Santosh Kumar Patro

A: Just call
msbuild /path/to/projectfile

If you do not specify a target, msbuild automatically picks the DefaultTargets. Or if that is not available, it calls the first one encountered.

A: I was able to find the solution to invoke the msbuild default target (i.e. target =TestMethod) from a powershell script. Please find the example below :
Powershell Script:
MSBUILD Path
$msbuildexe = (get-itemproperty -path "HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0").MSBuildToolsPath + 'msbuild.exe'
Function to Invoke TestMethod
function Invoke-TestMethodFromPowershell([string]$testProjFile)
{
  echo "Calling msbuild Started ..."
  &$msbuildexe $testProjFile
  echo "Calling msbuild Completed ..."
}
Invoke-VeracodeScanSubmissionProcess("C:\Temp\HelloWorldTest\TestBuild.proj");
Screenshot:


text:
Q: How to generate numeric mapping for categorical columns in pandas? I want to manipulate categorical data using pandas data frame and then convert them to numpy array for model training.
Say I have the following data frame in pandas.
import pandas as pd
df2 = pd.DataFrame({"c1": ['a','b',None], "c2": ['d','e','f']})

>>> df2
     c1 c2
0     a  d
1     b  e
2  None  f

And now I want "compress the categories" horizontally as the following:
   compressed_categories
0     c1-a,   c2-d           <--- this could be a string, ex. "c1-a, c2-d" or array ["c1-a", "c2-d"] or categorical data
1     c1-b,   c2-e
2     c1-nan, c2-f

Next I want to generate a dictionary/vocabulary based on the unique occurrences plus "nan" columns in compressed_categories, ex:
volcab = {
"c1-a": 0,
"c1-b": 1,
"c1-c": 2,
"c1-nan": 3,
"c2-d": 4,
"c2-e": 5,
"c2-f": 6,
"c2-nan": 7,

}

So I can further numerically encoding then as follows:
   compressed_categories_numeric
0     [0,   4]
1     [1,   5]
2     [3,   6]

So my ultimate goal is to make it easy to convert them to numpy array for each row and thus I can further convert it to tensor.
input_data = np.asarray(df['compressed_categories_numeric'].tolist())

then I can train my model using input_data.
Can anyone please show me an example how to make this series of conversion? Thanks in advance!

A: To build volcab dictionary and compressed_categories_numeric, you can use:
df3 = df2.fillna(np.nan).astype(str).apply(lambda x: x.name + '-' + x)
volcab = {k: v for v, k in enumerate(np.unique(df3))}
df2['compressed_categories_numeric'] = df3.replace(volcab).agg(list, axis=1)

Output:
>>> volcab
{'c1-a': 0, 'c1-b': 1, 'c1-nan': 2, 'c2-d': 3, 'c2-e': 4, 'c2-f': 5}

>>> df2
     c1 c2 compressed_categories_numeric
0     a  d                        [0, 3]
1     b  e                        [1, 4]
2  None  f                        [2, 5]

>>> np.array(df2['compressed_categories_numeric'].tolist())
array([[0, 3],
       [1, 4],
       [2, 5]])


text:
Q: Como gerar urls dinâmicas Eu estou trabalhando num projeto para escritores publicar poemas e poesias. As urls serão separadas pelo gênero, por exemplo: site.com/poemas/flores-do-campo/
No entanto, eu preciso evitar a duplicidade de títulos. Devido a isso eu pensei eu fazer um esquema semelhante ao wattpad que cria a url assim: wattpad.com/127883554-the-new-avenger
Eles inserem o código "127883554" antes do título. Porém tenho algumas dúvidas:
1 - Como gero esse código representando dia, mes e ano sem que seja 26052019 ?
2 - Como vou montar a url de modo que codigo+titulo sejam separado pelo "-".
O laravel tem algum recurso pra montar essas urls de um modo inteligente?

A: Você pode fazer isso na hora de cadastrar exemplo:
public function cadastrar(Request $request) {
       $request->validate([
            $request->titulo => 'required',
            ...
       ]);

       Model::create([
          'table_titulo' => $request->titulo,
          'table_url' => mt_rand(0, 9999999).'-'.mt_rand(0,10).$request->titulo,
          ...
       ]);

}

Dessa forma você cadastra a URL e titulo, na hora de acessar algo exemplo wattpad, só fazer uma rota dessa forma;
Route::get('/{url}', 'livroController@index');

controller ficara dessa forma
public function index(Request $request) {
     $livro = Livros::where('url', $request->only('url'))->first();

     return view('index', compact('livro'));

}

Faz um teste se funcionar da um Alo ai...
OBS: Se não funcionar com Request troque por $url o parâmetro ser recebido...


text:
Q: Why would I want to wrap my script commands in double quotes? I'm working through Red Hat Academy and one of the sample scripts provided differed from mine in a key way that I haven't been able to understand:
#!/usr/bin/bash
#
USR='student'
OUT='/home/student/output'
#
for SRV in servera serverb
  do
ssh ${USR}@${SRV} "hostname -f" > ${OUT}-${SRV}
echo "#####" >> ${OUT}-${SRV}
ssh ${USR}@${SRV} "lscpu | grep '^CPU'" >> ${OUT}-${SRV}
echo "#####" >> ${OUT}-${SRV}
ssh ${USR}@${SRV} "grep -v '^$' /etc/selinux/config|grep -v '^#'" >> ${OUT}-${SRV}
echo "#####" >> ${OUT}-${SRV}
ssh ${USR}@${SRV} "sudo grep 'Failed password' /var/log/secure" >> ${OUT}-${SRV}
echo "#####" >> ${OUT}-${SRV}
done

On each line after the variable expansion, they've wrapped most of the rest of the command in double quotes.  Now, I understand the usage of double quotes and single quotes when it comes to suppressing expansion/substitution, but the main takeaway I've learned is straight from the RH Academy:

It is recommended practice to use single quotation marks to
encapsulate the regular expression to protect any shell metacharacters
(such as the $, *, and {} characters). Encapsulating the regular
expression ensures that the characters are interpreted by the intended
command and not by the shell.

I can see that they're doing that here to make sure the regular expressions are properly passed to grep in a couple of lines, but I can't figure out the purpose of the double quotes.  My questions are:

*

*Why are they there?

*Why are they only wrapped around a portion of
each line?

*Is this a common practice?

A: As pointed out by others, the example provided has issues of being malformed for the intended purpose.  Specifically, the 3rd ssh requires the "$" in '^$' to be escaped, to avoid the shell's attempt at substitution at your end.  Otherwise, the remote host will see '^' !!!
Their usage of double-quotes is intended to "encapsulate" a construct meant to be executed as is on the remote server, hence around everything after the target host reference.
Issues arise if you need to expand variable values before sending to remote ... AND ... when you need such expansion to NOT occur.  Single-quotes are meant to contain literals meant to be passed as-is, but if that is contained within another set of double-quotes, the contents of those are not "protected" and the shell attempts the usual substitutions whenever "$" is encountered.
For simple constructs, one-line commands are OK.
BUT ... when things get more complex (with multiple levels of "\" for escaping single-/double-quotes), it might be best to create a job-script, massage that into what is required for the remote host before calling ssh, then have ssh reference that in the following manner:
ssh user@remote 'bash -s' < local_script.sh

As for the line doing the check for failed password, I would never leave that to the end.  I would have that as the first line, check the output, and abandon if the password failed, avoiding the likely failed attempts for the other commands, which at that point serves no purpose.


text:
Q: Passing base64 encoded strings in URL Is it safe to pass raw base64 encoded strings via GET parameters?

A: @joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.
$str = 'Some String';

$encoded = urlencode( base64_encode( $str ) );
$decoded = base64_decode( urldecode( $encoded ) );

A: I don't think that this is safe because e.g. the "=" character is used in raw base 64 and is also used in differentiating the parameters from the values in an HTTP GET.

A:
Introductory Note I'm inclined to post a few clarifications since some of the answers here were a little misleading (if not incorrect).

The answer is NO, you cannot simply pass a base64 encoded parameter within a URL query string since plus signs are converted to a SPACE inside the $_GET global array. In other words, if you sent test.php?myVar=stringwith+sign to
//test.php
print $_GET['myVar'];

the result would be:
stringwith sign
The easy way to solve this is to simply urlencode() your base64 string before adding it to the query string to escape the +, =, and / characters to %## codes.
For instance, urlencode("stringwith+sign") returns stringwith%2Bsign
When you process the action, PHP takes care of decoding the query string automatically when it populates the $_GET global.
For example, if I sent test.php?myVar=stringwith%2Bsign to
//test.php
print $_GET['myVar'];

the result would is:
stringwith+sign
You do not want to urldecode() the returned $_GET string as +'s will be converted to spaces.
In other words if I sent the same test.php?myVar=stringwith%2Bsign to
//test.php
$string = urldecode($_GET['myVar']);
print $string;

the result is an unexpected:
stringwith sign
It would be safe to rawurldecode() the input, however, it would be redundant and therefore unnecessary.

A: There are additional base64 specs.  (See the table here for specifics ).  But essentially you need 65 chars to encode: 26 lowercase + 26 uppercase + 10 digits = 62.
You need two more ['+', '/'] and a padding char '='.  But none of them are url friendly, so just use different chars for them and you're set.  The standard ones from the chart above are ['-', '_'], but you could use other chars as long as you decoded them the same, and didn't need to share with others.
I'd recommend just writing your own helpers.  Like these from the comments on the php manual page for base64_encode:
function base64_url_encode($input) {
 return strtr(base64_encode($input), '+/=', '._-');
}

function base64_url_decode($input) {
 return base64_decode(strtr($input, '._-', '+/='));
}

A: No, you would need to url-encode it, since base64 strings can contain the "+", "=" and "/" characters which could alter the meaning of your data - look like a sub-folder.
Valid base64 characters are below.
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=

A: If you have sodium extension installed and need to encode binary data, you can use sodium_bin2base64 function which allows you to select url safe variant.
for example encoding can be done like that:
$string = sodium_bin2base64($binData, SODIUM_BASE64_VARIANT_URLSAFE);

and decoding:
$result = sodium_base642bin($base64String, SODIUM_BASE64_VARIANT_URLSAFE);

For more info about usage, check out php docs:
https://www.php.net/manual/en/function.sodium-bin2base64.php
https://www.php.net/manual/en/function.sodium-base642bin.php

A: Yes and no.
The basic charset of base64 may in some cases collide with traditional conventions used in URLs. But many of base64 implementations allow you to change the charset to match URLs better or even come with one (like Python's urlsafe_b64encode()).
Another issue you may be facing is the limit of URL length or rather — lack of such limit. Because standards do not specify any maximum length, browsers, servers, libraries and other software working with HTTP protocol may define its' own limits.

A: Its a base64url encode you can try out, its just extension of joeshmo's code above.
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}

A: In theory, yes, as long as you don't exceed the maximum url and/oor query string length for the client or server.
In practice, things can get a bit trickier.  For example, it can trigger an HttpRequestValidationException on ASP.NET if the value happens to contain an "on" and you leave in the trailing "==".

A: For url safe encode, like base64.urlsafe_b64encode(...) in Python the code below, works to me for 100%
function base64UrlSafeEncode(string $input)
{
   return str_replace(['+', '/'], ['-', '_'], base64_encode($input));
}


text:
Q: AWS Elastic Beanstalk Worker Environment - HTTP POST Requests PHP I have setup SQS on my application server to send messages to my queue.
I'm able to send and get messages from my queue manually.
Now I've spun up the EB Worker Environment to get these messages automatically. It sends them as HTTP POST Request.
My question is how do I catch these messages. I'm using PHP. I have tried the below but no joy;
$entityBody = file_get_contents('php://input');
$entityBody = stream_get_contents(STDIN);

The end goal is to get the message, decode it and use it to send an email.
FYI, I'm able to do this manually. I just need a way to automate the worker.


text:
Q: Error while using the Precision metric for MNIST digit classification I am trying to achieve a high Precision score on the MNIST dataset using Tensorflow and Keras. My code is working if I set the metric to accuracy but when I set it to precision, it gives the following error:
ValueError: Shapes (32, 10) and (32, 1) are incompatible

Here is my code:
import tensorflow as tf
import keras
from tensorflow.keras.datasets import mnist

def bulid_model(n = 1, neuron=30,lr = 3e-3,input_shape=(784,)):
    model = keras.models.Sequential()
    model.add(keras.layers.InputLayer(input_shape=input_shape))
    for layer in range(n):
        model.add(keras.layers.Dense(neuron, activation = 'relu'))
    model.add(keras.layers.Dense(10,activation='softmax'))
    optimizer = keras.optimizers.Adam(lr = lr)
    model.compile(loss = 'sparse_categorical_crossentropy',optimizer=optimizer,metrics = [keras.metrics.Precision()])
    return model

if __name__ == "__main__":
    (X_train,Y_train),(X_test,Y_test) = mnist.load_data()

    X_train = X_train.reshape(60000, 784)
    X_test = X_test.reshape(10000, 784)
    X_train = X_train.astype('float32')
    X_test = X_test.astype('float32')

    X_train /= 255
    X_test /= 255

    model = bulid_model(3,20,0.0156)

    history = model.fit(X_train,Y_train,epochs=50)

Can anyone help me with this?

A: Precision, is a metric for binary classification. It computes true_positives and false_positives then simply divides true_positives by the sum of true_positives and false_positives.

But Accuracy metric can be used for multi-class classification like MNIST, because it calculates how often predictions equal labels.


text:
Q: Induction in Stages: $\textrm{Ind}_H^G = \textrm{Ind}_N^G \textrm{Ind}_H^N$ $\DeclareMathOperator{\Ind}{Ind}$ Let $H \subseteq N \subseteq G$ be closed subgroups of a td-type group $G$. Then $\Ind_H^G$ and $\Ind_N^G \circ \Ind_H^N$ are additive functors from the category of smooth representations of $H$ to the category of smooth representations of $G$.  I'm trying to understand why these functors are naturally isomorphic.  To a smooth representation $(\sigma,W)$ of $H$, we need to define a $G$-linear isomorphism
$$T_{\sigma}: \Ind_N^G \Ind_H^N(\sigma) \rightarrow \Ind_H^G(\sigma)$$
which is natural in $\sigma$.

A: $\DeclareMathOperator{\Ind}{Ind}$We are fixing a representation space $(\pi,W)$ of $H$.
Fix $F \in \Ind_N^G \Ind_H^N(\sigma)$.  To each $g \in G$, we have a function $F(g): N \rightarrow W$ such that $F(g)(hn) = \sigma(h) F(g)(n)$ for all $h \in H, n \in N$, and such that $F(g)(nk) = F(g)(n)$ for all $n \in N$ and all $k$ in some open compact subgroup of $N$, depending on $F$ and $g$.
We also have that $F(ng)(n') = F(g)(n'n)$ for all $g \in G, n,n' \in N$.  Finally, $G$ acts by right translation on these functions $F$: $g \cdot F(g') := F(g'g)$, and for each $g \in G$ there exists an open compact subgroup $K$ of $G$ such that the functions $F(gk)$ and $F(g)$ are equal.
Define $T_{\sigma}(F): G \rightarrow W$ by $T_{\sigma}(F)(g) = F(g)(1_N)$.  This defines our map $T_{\sigma}: \Ind_N^G \Ind_H^N(\sigma) \rightarrow \Ind_H^G(\sigma)$.  There are several things to check:

1 .  $T_{\sigma}(F)$ lies in $\Ind_H^N(\sigma)$.

First, for any $h \in H$ and $g \in G$, we have
$$T_{\sigma}(F)(hg) = F(hg)(1_N) = F(g)(h) = F(g)(h1_N) = \sigma(h)F(g)(1_N) = \sigma(h)T_{\sigma}(F)(g)$$
Next, for each $g \in G$, there exists an open compact subgroup $K$ of $G$ such that $F(gk)$ and $F(g)$ are the same function $N \rightarrow W$.  In particular, $T_{\sigma}(gk) = F(gk)(1_N) = F(g)(1_N) = T_{\sigma}(g)$.

2 .  $T_{\sigma}$ is a $G$-map.

It is immediate that $T_{\sigma}$ is a linear transformation, so we just need to show that $T_{\sigma}$ preserves the action of $G$.  For $g, g' \in G$, and $F \in \Ind_N^G \Ind_H^N(\sigma)$ we have
$$T_{\sigma}(g \cdot F)(g') = (g \cdot F)(g')(1_N) = F(g'g)(1_N) = T_{\sigma}(F)(g'g) = g \cdot T_{\sigma}(F)(g)$$
So $T_{\sigma}(g \cdot F) = g \cdot T_{\sigma}(F)$.

3 .  $T_{\sigma}$ is a bijection.

For injectivity, suppose $T_{\sigma}(F)$ is the zero map.  This means that for all $g \in G$, $F(g)(1_N)$ is zero in $W$.  But for any $n \in N$ and any $g \in G$, we have $0 = F(ng)(1_N) = F(g)(n)$, so this says that for each $g \in G$, $F(g): N \rightarrow W$ is the zero function.  Hence $F = 0$.
For surjectivity, let $f \in \Ind_H^G(\sigma)$.  For each $g \in G$, define a function $F(g): N \rightarrow W$ by $F(g)(n) = f(ng)$.  If we can show that $F(g)$ lies in $\Ind_H^N(\sigma)$, and that moreover the function $F: G \rightarrow \Ind_H^N(\sigma)$ itself lies in $\Ind_N^G \Ind_H^N(\sigma)$, then we will have
$$T_{\sigma}(F)(g) = F(g)(1_N) = f(g)$$
and hence $T_{\sigma}(F) = f$, as required.
First, to show $F(g)$ lies in $\Ind_H^N(\sigma)$ for a fixed $g$.  For $h \in H, n \in N$, we have
$$F(g)(hn) = f(hng) = \sigma(h) f(ng) = \sigma(h)F(g)(n)$$
To finish showing that $F(g)$ lies in $\Ind_H^N(\sigma)$, we need to find an open compact subgroup of $N$ for which $F(g)$ is right invariant.  Let $K$ be an open compact subgroup of $G$ such that $f$ is right $K$-invariant.  Then $N \cap gKg^{-1}$ is a compact open subgroup of $N$, and for $n \in N, k \in N \cap gKg^{-1}$, we have
$$F(g)(nk) = f(nkg) = f(ngg^{-1}kg) = f(ng) = F(g)(n)$$
Finally, we need to show that $F: G \rightarrow \textrm{Ind}_H^N(\sigma)$ lies in $\Ind_N^G \Ind_H^N(\sigma)$.
We first show that $F$ appropriately distributes the action of $N$, i.e. $F(ng)(n') = F(g)(n'n)$ for all $g \in G, n, n' \in N$.  This is immediate, since $F(ng)(n') = f(n'ng) = F(g)(n'n)$.
Next, we show that $F$ is right invariant for some open compact subgroup of $G$.  An open compact subgroup $K$ of $G$ such that $f$ is right $K$-invariant will do:
$$F(gk)(n) = f(ngk) = f(ng) = F(g)(n)$$

4 .  $T_{\sigma}$ is natural.

Let $\phi:(W,\sigma) \rightarrow (U,\tau)$ be a morphism of smooth $H$-representations.
This is a nasty definition check.  Let $F \in \Ind_N^G \Ind_H^N(\sigma)$.
First, we have to look at $(\Ind_N^G \Ind_H^N(\phi))(F)$, which is an element of $\Ind_N^G \Ind_H^N(\tau)$.  This is by definition a function from $G$ to $\Ind_H^N(\tau)$.  If we evaluate this function at a given $g$, this is by definition the element $\Ind_H^N(\phi)(F(g))$, which is a function from $N$ to $U$.  If we further evaluate this function at a given $n$, then this is by definition $\phi(F(g)(n))$.  Thus
$$T_{\tau} \circ [\Ind_N^G \Ind_H^N(\phi)](F)(g) = [\Ind_N^G \Ind_H^N(\phi)]F(g)(1_N) = \phi(F(g)(1_N))$$
On the other hand, we have $\Ind_H^G(\phi) \circ T_{\sigma}(F)(g) = \phi(T_{\sigma}(F)(g)) = \phi(F(g)(1_N))$.  This establishes the naturality.


text:
Q: Know which firmware my linux kernel has loaded since booting On routinely updating my Debian system, I've never took the time to pick which firmware packages I do really need; basically I have them all installed, and always up-to-date.
I've been wondering how can I pick which ones I do really need. I was thinking of using every device I have in my system (even the ones I rarely use like bluetooth, ethernet, camera, touchpad, multimedia keys and so on) and look at the list of loaded firmware.
Is there an easy way to find out which firmware is currently loaded, or were loaded since last kernel boot?

A: If your kernel is built with dynamic debug support (CONFIG_DYNAMIC_DEBUG), you can use a boot parameter to enable debug messages for the firmware loader. It should catch all firmware loads, unless a particular driver does something strange and does not use the kernel's firmware loading API for some reason.
Add the following to your boot parameters:
For kernels 2.6 - 4.16: dyndbg="file drivers/base/firmware_class.c +fmp"
For kernels 4.17 and later: dyndbg="file drivers/base/firmware_loader/main.c +fmp"
(For reference, file blah/foo.c +fmp means "for all debug calls in the kernel source file blah/foo.c, enable dynamic debug printing, and make the message show the filename and module name". See the kernel docs for more detail.)
After booting, run dmesg | grep firmware_class. Of particular interest are lines with firmware_class:fw_get_filesystem_firmware, which should be sandwiched between calls to __allocate_fw_priv and __free_fw_priv.
All firmware loads will be logged until you reboot or disable dynamic debugging.

Background information:
You cannot query for "currently loaded" firmware, because firmware doesn't necessarily remain in system memory. It is often uploaded to some chip in some device outside the system. Drivers usually load a firmware file into a kernel buffer, use that buffer to program the device, then discard the buffer without keeping any record of what the file was. And the standard kernel firmware API does not keep a log by default. Some drivers do log their firmware loading to the kernel log, but it's not universal.
The first thought I had was to "get between" the kernel and whatever userspace program is responsible for grabbing firmware files so that I could add some debug messages. But it turns out this is not always possible: the kernel itself it capable of getting firmware straight from the filesystem, no userspace mechanism involved. (In fact, the kernel prefers to direct load straight from /lib/firmware/ when possible.)
The next thought I had was to use kprobe or some other tracing system to trace kernel function calls that are involved in firmware loading. But it turns out I didn't have to go that far: the firmware loader conveniently includes some debug messages that — once enabled — are enough to see all what files are being loaded. The dyndbg above takes advantage of these.

Other information:
The kernel's firmware loading API is generally accessed by calls to request_firmware() or request_firmware_nowait(). A driver calls one of these functions with the name of the firmware file it wants, and the kernel attempts to load it using this process:

*

*Check for firmware in the kernel image, load from there if found.

*Check for firmware on the filesystem, load from there if found.

*[If kernel is configured for it] use a sysfs "fallback": create /sys/firmware/<xxx>/loading, wait for some program to write firmware to it.

*

*[If kernel is configured for it] create a uevent to inform udev or whoever is listening that "it would be really great if you could write to this file".

*If too much time passes (specifically whatever length of time is in /sys/firmware/timeout), give up with an error.

A: There are multiple commands, depends what you need.
Start with lspci -vvvvv it will show you which module/driver is the device using. (look for values Kernel module and Kernel driver) To get the list of currently used modules/loaded you can use lsmod.
To obtain more details check the Wiki Lspci there are listed other commands, but you may need to install extra packages.
These will provide you info about the HW itself:
dmidecode and hwinfo or lshw
EDIT:
To find out which drivers are loading during boot you usually search in (depends sys-vinit/systemd):
/var/log/bootlog
/var/log/syslog
/var/log/kern.log

or command dmesg to find out what's loading in systemd journalctl -k kernel or journalctl -b for current/last boot. Consult the man pages for each command.


text:
Q: Passing in API Key and Parameters with RestClient In my application I have a user pass in a form that fires out an API request and then displays the results of the query.
I allow the user to to select many or few parameters.  The problem I  get is a 401 Authorization error and I believe that is because the apikey isn't being recognized (there is no password, username needed for the api and no limits).
Application:
post '/search' do

    phrase = params.fetch "phrase" #mandatory
    @delimiters = ""

    start_date = params.fetch "start_date"
    start_date.empty? ? start_date = "" : @delimiters << "From #{start_date},"

    end_date = params.fetch "end_date"
    end_date.empty? ? end_date = "" : @delimiters << "To #{end_date}"

    api_result = RestClient::Request.execute(method: :get, url: "capitolwords.org/api/1/text.json?phrase=#{phrase}
                                         &page=0&apikey=",
                                         headers: {params: {:start_date => start_date,
                                         :end_date => end_date},
                                         :Authorization => ENV['SUNLIGHT_API_KEY']},
                                         timeout: 10)
end

The delimiter is what I'm using to catch all the parameters passed in so I can show the user what they searched by.  I've read the documentation at https://github.com/rest-client/rest-client and they don't mention passing in api keys.
This is part of a refactoring process - passing in the parameters one by one as #{@parameter_example} works but makes my code less readable and I then manually must set up @parameter_example = "&parameter_example=#{parameter_example}" which seems overly verbose.

A: Judging from the capitalwords.org documentation, it seems that the api key along with the phrase, start_date, end_date params should be passed as part of the query string. So your rest-client request should look like this:
api_result = RestClient::Request.execute(method: :get,
                                            url: "capitolwords.org/api/1/text.json",
                                        headers: {params: {:phrase => phrase,
                                                           :start_date => start_date,
                                                           :end_date => end_date,
                                                           :page => 0,
                                                           :apikey => ENV['SUNLIGHT_API_KEY']}},
                                        timeout: 10)

I think that in order to pass params like this (using headers params hash) to RestClient::Requeest.execute then the url you request should not include any params or else rest-client fails to produce the correct url. That's why I moved page and phrase from url into params phrase hash.

A: Did you remember to do the following at the top of the file?
require 'dotenv'
Dotenv.load


text:
Q: Find $\frac{dy}{dx}$ if $x\sqrt{1+y}+y\sqrt{1+x}=0$
Find $\frac{dy}{dx}$ if $x\sqrt{1+y}+y\sqrt{1+x}=0$ for $-1\leq x\leq 1$

$$\frac{dy}{dx}=\frac{-1}{(1+x)^2}\text{ if }x\neq y$$
If it was like $y=\sqrt{1+x}$ i think i know how to do it
D[Sqrt[1+x],x]

but how do i differentiate the functions like the one above ?

A: Perhaps not the most optimal method, but you could:

*

*Take the total derivative with respect to x

*Solve for y'[x]

*Solve the given equation for y

*Substitute (3) in (2)

*Simplify, assuming bounds for x given
Simplify[
       Solve[Dt[x \[Sqrt](1 + y) + y \[Sqrt](1 + x), x] == 0,
             Dt[y, x]] /.
           y -> Solve[x \[Sqrt](1 + y) + y \[Sqrt](1 + x) == 0, y][[1, 1, 2]],
        Assumptions -> {x >= -1, x <= 1}][[1, 1, 2]]

output:
-(1/(1 + x)^2)

Edit: @Nasser gives the "more optimal" method I suggested in the beginning.  I do too much solving and differentiating.
Instead of Differentiating, Solving, Solving, Substituting, and Simplifying (5 steps); why not just Substitute, Solve, Differentiate, and Simplify (4 steps) (Nasser's improvement)?  Alternatively (my slight improvement), just Solve, Differentiate, and Simplify (3 steps):
Dt[Solve[x √(1 + y) + y √(1 + x) == 0, y],
  x] // Simplify

Out:
{{Dt[y, x] -> -(1/(1 + x)^2)}}

Easier to look at version:

It turns out that including the bounds on x are redundant!  However, if you wish to include them (again, unnecessary):
Simplify[Dt[Solve[Sqrt[x + 1] y + x Sqrt[y + 1] == 0, y], {x}],
 Assumptions -> {x >= -1 && x <= 1}]

A: Just substitude  y->y[x]
First atttempt:
Solve[0 == D[x Sqrt[1 + y[x]] + y[x] Sqrt[1 + x], x], y'[x]][[1]]
(*{Derivative[1][y][x] -> (Sqrt[1 + y[x]] (y[x] + 2 Sqrt[1 + x] Sqrt[1 + y[x]]))/(Sqrt[1 + x] (-x - 2 Sqrt[1 + x] Sqrt[1 + y[x]]))} *)

Everything is ok but knowledge about y is not included.
Final answer
eq= x \[Sqrt](1 + y[x]) + y[x] \[Sqrt](1 + x);
sol=Solve[{eq==0,D[eq,x]==0},{y[x],y'[x]}];
Simplify[sol,-1<=x<=1][[1]];
(* {y[x] -> -(x/(1 + x)), Derivative[1][y][x] -> -(1/(1 + x)^2)} *)

A: Why not just
ClearAll[y,x]
expr = x Sqrt[1+y]+y Sqrt[1+x]==0;
expr = expr/.y->y[x];
D[Solve[expr,y[x]],x]//Simplify

I am not sure if this is what the above answer is doing, but I get different output, from each so I thought to post this. If it turns out to be just a extra simplification step is needed, will delete my answer.

A: The function and its implicit derivative both vanish, so that gives a system of two equations in the two variables {y[x],y'[x]} to solve in terms of x.
expr = x *Sqrt[1 + y] + y*Sqrt[1 + x];
eyx = expr /. y -> y[x];
Simplify[y'[x] /. First[Solve[{D[eyx, x], eyx} == 0, {y[x], y'[x]}]]]

(* Out[43]= (
4 x + 3 x^2 - 4 Sqrt[1/(1 + x)] (1 + x)^(5/2))/((1 + x)^2 (2 + x)^2) *)


text:
Q: How to convert a video for a Samsung Tablet on OS X or Unix I have different kinds of files, mostly MKV and MP4. They are in 720p (ca. 1280x800).
As far as I know, video for this my Samsung tablet should be 1024x768 maximum. It should also use the h.264 AVC codec. Which settings for ffmpeg or mencoder should I use? Any OS X program would be great too.

A: Note that when you re-encode videos, you will always lose quality. Depending on the content and the settings chosen, this can make your videos look really bad.
Handbrake
If you still want or need to do it, you can download and install Handbrake.
Open your source video, open "Picture Settings". Here, select "Anamorphic – None", and change the width/height accordingly.

The rest of the options shouldn't matter that much. "H.264 AVC" is the default codec, so leave this selected. You can play with the "Constant quality" slider to reduce/improve the quality of your result videos.
Which options should you use?

*

*You can also choose the iPad preset and see if that works, as it already is optimized for the iPad's 1024x768 display.

*If Android doesn't support the output video, you can try with the iPod Legacy preset. iPod Legacy should use a very basic ("Baseline") profile that is supported by Android. Don't forget to change back the video size when you switch profiles.

When you're done, click the "Start" button to convert your video.
FFmpeg
I was able to find a rather complicated iPad preset that might work on an Android tablet.
ffmpeg -y -i input.avi -acodec aac -ar 48000 -ab 128k -ac 2 -s 1024×768 \
-vcodec libx264 -b 1200k -flags +loop+mv4 -cmp 256 \
-partitions +parti4x4+partp8x8+partb8x8 -subq 7 -trellis 1 -refs 5 -coder 0 \
-me_range 16 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -bt 1200k \
-maxrate 1200k -bufsize 1200k -rc_eq 'blurCplx^(1-qComp)' \
-qcomp 0.6 -qmin 10 -qmax 51 -qdiff 4 -level 30 -aspect 16:9 -r 30 -g 90 -async 2 \
output.mp4

If Android doesn't support the videos – as mentioned above – it's time to use another profile. Ubuntu also has a documentation for encoding for Android, which you can probably adopt for the tablet. Generally, any tutorial valid for the iPod should also be valid for an Android Tablet.


text:
Q: How to externalise repeated SOAP response attributes in mule dataweave? I am constructing a SOAP response in Dataweave. Certain components (ESBHeader) of the response are repeated in multiple flows. I also need to set the Status code and message per request.
I need a generic/common way of loading these repeated lines into a common dwl file for code optimisation. How do I do it?
Example Response Message1 of flow1
{
        ns1#ResponseMsg1: {
            ns0#ESBHeader: {
                ns0#InitialContext @(CreationTime: flowVars.req.ResponseMsg1.ESBHeader.InitialContext.@CreationTime, TrackingID: flowVars.req.ResponseMsg1.ESBHeader.InitialContext.@TrackingID): {
                    ns0#Actor @(Component: flowVars.req.ResponseMsg1.ESBHeader.InitialContext.Actor.@Component , Operation: flowVars.req.ResponseMsg1.ESBHeader.InitialContext.Actor.@Operation): null
                },
                ns0#MessageContext  : {
                    ns0#Actor @(Component: flowVars.req.ResponseMsg1.ESBHeader.MessageContext.Actor.@Component  , Operation: flowVars.req.ResponseMsg1.ESBHeader.MessageContext.Actor.@Operation): null
                },
                ns0#Status: {
                    ns0#Code: "Success",
                    ns0#Message: ""
                }
            },
            ns1#var1: flowVars.var1
        }
    }

Example Response Message2 of flow2
{
        ns1#ResponseMsg2: {
            ns0#ESBHeader: {
                ns0#InitialContext @(CreationTime: flowVars.req.ResponseMsg2.ESBHeader.InitialContext.@CreationTime, TrackingID: flowVars.req.ResponseMsg2.ESBHeader.InitialContext.@TrackingID): {
                    ns0#Actor @(Component: flowVars.req.ResponseMsg2.ESBHeader.InitialContext.Actor.@Component , Operation: flowVars.req.ResponseMsg2.ESBHeader.InitialContext.Actor.@Operation): null
                },
                ns0#MessageContext  : {
                    ns0#Actor @(Component: flowVars.req.ResponseMsg2.ESBHeader.MessageContext.Actor.@Component  , Operation: flowVars.req.ResponseMsg2.ESBHeader.MessageContext.Actor.@Operation): null
                },
                ns0#Status: {
                    ns0#Code: "Failure",
                    ns0#Message: ""
                }
            },
            ns1#var1: flowVars.var1,
            ns1#var2: flowVars.x.var2
        }
    }

Any pointers are greatly appreciated.
Thanks a lot.

A: If you are using Mule 4 it is easy to create and import a DataWeave module.
In Mule 3 there is a similar method but it is not really supported and you could run into some issues. From your script it looks like Mule 3. This blog post explains the method.


text:
Q: Elasticsearch how to index text files using the command line I started playing with Elasticsearch. I want to create index for a textfile. I mean that I have multiple text files in a folder. I want to create  index on these text files so that I can perform text search on these files. Is there a way to do this using command line or . Please guide me with an example.

A: yes, you can by using the FS river + mapper attachment plugin. Here is a link to the source page.
I ran a few tests with it a little while ago. It works fine. Be aware though, that the file has to be local for this to work (even if you can mount a remote file to a local path).
Hope this helps.


text:
Q: Reading file in C++ giving weird characters after the actual file content I'm fairly new to C++ and I'm trying to read a JSON file into a char array/char *. But whenever I read a file, it give some weird character  after the actual file content like so:

{"Image": "myImg.jpg"}ts;C:\Ureßr

Why is this happening? How do I fix it?
This is my current code:
char* read_file(const char *file)
{
    std::ifstream infile;
    infile.open(file, std::ios_base::in | std::ios_base::binary);
    if (infile)
    {
        infile.seekg(0, std::ifstream::end);
        int len = infile.tellg();
        infile.seekg(0, std::ifstream::beg);
        char *data = new char[len];
        infile.read(data, len);
        return data;
    }
    return nullptr;
}

A: So-called "C-Style" character strings need to be nul-terminated in order to work with any of the standard functions, such as are used for displaying them.
In order for your data buffer to conform to this, you need to increase the allocated buffer size to allow for this terminator character, and also make sure that the last element is actually the nul character (zero or '\0').
char* read_file(const char *file)
{
    std::ifstream infile;
    infile.open(file, std::ios_base::in | std::ios_base::binary);
    if (infile)
    {
        infile.seekg(0, std::ifstream::end);
        int len = infile.tellg();
        infile.seekg(0, std::ifstream::beg);
        char *data = new char[len + 1]; // Add space for the nul terminator ...
        infile.read(data, len);
        data[len] = '\0';               // ... and set the last element to "nul"
        return data;
    }
    return nullptr;
}

Without the proper terminator, a call like cout << data to display your character array will keep outputting characters until it does (by chance) find a zero byte in the buffer it is given (or, maybe it will crash before it does so). The 'weird' characters you are seeing represent the data that happen to be in memory, just after the data buffer you have allocated.

A:     char *data = new char[len];
    infile.read(data, len);

This reads everything from the file into a char buffer. And nothing more. Nothing else.
If you attempt to print the contents of this char buffer using any means that expects to see a C-style character string, you are going to forget a small detail: C-style character strings are terminated by a '\0', which this code neglects to add to the read contents, so whichever C or C++ library function you're using to do this, will simply look for the '\0' character. And keep looking. And keep loking. And keep looking.
You simply need to new an additional byte up front (len+1 instead of len), and drop a '\0' in there, after the read file contents.


text:
Q: DynamoDB - Single Table Many-To-Many relationships modeling To better understand how to design a single DynamoDB table I tried to develop a small movie database application.
This is my current DynamoDB table design:
╔══════════╦════════════╦═══════════════╗
║ PK       ║ SK         ║ Title         ║
╠══════════╬════════════╬═══════════════╣
║ pk_1     ║ movie      ║ Die Hard      ║
║ pk_1     ║ actor_pk_3 ║ Bruce Willis  ║
║ pk_1     ║ tag_pk5    ║ Action        ║
║          ║            ║               ║
║ pk_2     ║ movie      ║ Looper        ║
║ pk_2     ║ actor_pk_3 ║ Bruce Willis  ║
║ pk_2     ║ actor_pk_4 ║ Emily Blunt   ║
║ pk_2     ║ tag_pk5    ║ Action        ║
║          ║            ║               ║
║ pk_3     ║ actor      ║ Bruce Willis  ║
║ pk_3     ║ movie_pk_1 ║ Die Hard      ║
║ pk_3     ║ movie_pk_2 ║ Looper        ║
║          ║            ║               ║
║ pk_4     ║ actor      ║ Emily Blunt   ║
║ pk_4     ║ movie_pk_2 ║ Looper        ║
║          ║            ║               ║
║ pk_5     ║ tag        ║ Action        ║
║ pk_5     ║ movie_pk_1 ║ Die Hard      ║
║ pk_5     ║ movie_pk_2 ║ Looper        ║
╚══════════╩════════════╩═══════════════╝

* The table has one GSI, it is just the PK and SK reversed.

I tried to design the database so that I can always get all the data that I want with one query (a single roundtrip).
The design works and it currently satisfies most of the acces patterns that I'm going for.
Some examples:

*

*If I want everything to the movie "Die Hard" I would just query the
"pk_1" on the normal table.

*If I want all movies I query the GSI with
"movie"

*If I want all actors to the movie "Die Hard" I query "pk_1"
and the SK begins with "actor"

*... and so on

Here is my big questions:

*

*Is this a good DynamoDB table design or is it wrong / bad?

If the table design is not bad than these are my follow up questions:

*

*Is the duplicated data normal and should I do it like this?

*Is it normal to have so much business logic getting, inserting and updating data?

*What is the best way to "securely" insert the data?
First adding the movie, then adding "actor_" and "tag_" feels wrong and is bound to fail at one point

*How can I assure that the duplicated data always stays the same as the "master"?

*How can I handle updates on relationships that could have millions of entries?
For example if I rename the tag "Action" to "ACTION" I would have to update every movie with this tag.
Currently I only see me updating it in batches so the data is not consistent for a certain amount of time.
Currently I doubt every decision I do on this table because it just feels wrong coming from relational databases...

A: I don't quite understand the design you've written so feel free to correct me if I misunderstood any parts. Mainly, I don't get what PK_1 even means. If I tell you to get me all the information about Die Hard, I don't understand how you will be able to fetch this for me simply with your data base structure. I get the pk_1 has all the information, but how do you know pk_1 == die hard unless you check "pk_1" + "movie" (sort key), which will mean you will need to check every such movie.
I'll try to answer your questions first and then come up with a design afterwards:

*

*Q. [Is this design good/bad]. For good dynamoDb design, as long as you satisfy all your use cases and don't have bad partitioning, you have somewhere to start from. This means optimizing frequent writes & reads.

*Q [Duplicate data] Data is cheap. Duplication is fine if it makes your querying faster. Ideally, all the information you need to fulfil a request should come from a single read operation.

*Q [Lot of logic for writes] NO! Based on 1 & 2, you should try to model it in such a way that your writes are ezpz.

*Q [What are your write operations looking like? If you give your use cases (expansive) for writing, then it becomes a lot easier to model a ddb to suit your needs. The problem however is if you get a new use case. This might need some database redesign so think of most usecases in the beginning itself.

*Q [Duplicate data stays the same as master] Use fully consistent reads and you will always read from the master which is in sync. You will not need to maintain this.

How I would design this
Use case for writes
Movie information comes with list of metadata including genre and a list of actors.
Save primary key as movie with sort key as METADATA. Now store movies with sort key as actor_ as the sort key. This will be an extra overhead while saving the movie information. You can do this using the batch write pretty easily.
GSI having inverted sort key and primary key. If you get an actor name as input, search database GSI for action_ to get their movies. Similar this can be extended if you want to save directors, producers etc. Create another GSI against the attribute you have stored genre in and have the sort key as movies.
You will have two indexes in this way, but I feel writes would be slightly easier.


text:
Q: DotNetOpenAuth CTP Source Code Hosted? Where is the source code hosted?  Git Hub?  I cannot find it anywhere.

A: Yes, it's on GitHub with the rest of the project.  It's under the master branch.
https://github.com/AArnott/dotnetopenid/tree/master

A: See
http://www.dotnetopenauth.net/
https://github.com/AArnott/dotnetopenid/
Update:
OK CTP 3.5 is hosted here:
http://sourceforge.net/projects/dnoa/files/CTP/OAuth2/


text:
Q: What is the difference between a private field in an abstract superclass and a private field in a nonabstract superclass? public abstract class PlayableItem{
    private int duration;
    protected PlayableItem(int duration){
    this.duration = duration;
    }

    //getters and setters

    public abstract String play();

public Song extends PlayableItem(){
    private String name = name;
    private String title = title;

    protected Song(int duration, String name, String title){
        super(duration);
        this.name = name;
        this.title = title;
    }

    //getters and setters

    @Override
    public String play(){
    return "artist name - " + name + "song title - " + title + "duration - "
            + duration;
    }

For some reason I keep getting an error on the Override method, specifically on duration. But my professor wants me to keep the private int field in the abstract class. All the lessons we had on abstract classes used private fields but never actually used as part of the parameter in the subclasses. I can't help but think that we overlooked something very important during our lessons because clearly it seems that the fields in an abstract class is treated differently from regular superclass fields.
Namely, in a regular superclass of Animals that has a private String field type
public class Animals{
    private String type;

    public Animals(String type){
         this.type = type;
    }
 }

public class Pet extends Animals{
    private String color;

    public Pet(String type, String color){
        super(type);
        this.color = color;
    }
 }

when creating a Pet object, you are required to use the Parent class parameter but for abstract classes it seems different. Can someone explain?


text:
Q: Why is the output of an `each do` statement different when it is put in a view helper in RoR? Description of Query
I moved some logic used a lot in my Views to a View helper. Exact same logic, but instead of getting the same result, I get a hash return instead of parsed data.
Language Versions
/Gemfile
ruby '2.6.5'
gem 'rails',        '~> 6.0.1'

Code
--> Controller
/app/controllers/blogs_controller.rb

def index
    @search = ""

    if params[:section]
        @posts = Post.in_section(params[:section]).where(status: "published").includes(member: [:profile]).reverse
    elsif params[:category]
        @posts = Post.categorized_as(params[:category]).where(status: "published").includes(member: [:profile]).reverse
    elsif params[:tag]
        @posts = Post.tagged_with(params[:tag]).where(status: "published").includes(member: [:profile]).reverse
    else
        @posts = Post.where(status: "published").includes(member: [:profile]).reverse
    end

    @sections = Section.where(id: SectionBlogMap.all.select(:section_id)).select(:id, :name, :slug, :order).sort_by{|o| o[:order]}
    @categories = Category.where(id: CategoryMap.all.select(:category_id)).select(:id, :name, :slug).sort_by{|n| n[:name]}.to_a
    @tags = Tag.where(id: TagMap.all.select(:tag_id)).select(:id, :name, :slug).sort_by{|n| n[:name]}.to_a
end

--> Helper
/app/helpers/posts_helper.rb

def tag_links(tag_name, tag_slug)
  link_to tag_name, tag_path(tag_slug)
end

def tag_links2(tags)
    tags.each do |tag|
        link_to tag.name, tag_path(tag.slug)
    end
end

--> View
/app/views/blogs/index.html.erb

Tags

<% @tags.each do |tag| %>
  <%= link_to tag.name, tag_path(tag.slug) %>
<% end %>

<%= tag_links2(@tags) %>

--> Result
**Tags**

Active     Blue     Red     Tag 10     Tag 6     Tag 7     Tag 8     Tag 9     Yellow

[#<Tag id: 1, name: "Active", slug: "active">, #<Tag id: 3, name: "Blue", slug: "blue">, #<Tag id: 5, name: "Red", slug: "red">, #<Tag id: 10, name: "Tag 10", slug: "tag-10">, #<Tag id: 6, name: "Tag 6", slug: "tag-6">, #<Tag id: 7, name: "Tag 7", slug: "tag-7">, #<Tag id: 8, name: "Tag 8", slug: "tag-8">, #<Tag id: 9, name: "Tag 9", slug: "tag-9">, #<Tag id: 4, name: "Yellow", slug: "yellow">]

Question
Using the byebug gem I checked the code and variables being passed and nothing changes from the view to the helper. So, I am unsure why moving the each do logic to a helper causes this. As I am a self-taught Ruby developer, I am guessing there is an explaination that correlates with the view/helper relationship that I am just not familar. Can someone shed some light for me?

A: This:
def tag_links2(tags)
  tags.each do |tag|
    link_to tag.name, tag_path(tag.slug)
  end
end

...returns tags, not the result of the link_to method contained within the do block.
Instead, try perhaps:
def tag_links2(tags)
  tags.each_with_object("") do |tag, to_return|
    to_return << link_to(tag.name, tag_path(tag.slug))
  end.html_safe
end

You may not need that html_safe on there.

A: When you are running code in a loop in ERB each iteration outputs to the buffer:
<% @tags.each do |tag| %>
  <%= link_to tag.name, tag_path(tag.slug) %>
<% end %>

Its actually like running:
@tags.each do |tag|
  puts link_to tag.name, tag_path(tag.slug)
end

However this does not happen when you are in a helper. Rails provides concat that can be used to output in helpers:
def tag_links2(tags)
  tags.each do |tag|
    concat link_to tag.name, tag_path(tag.slug)
    concat ' ,' unless tag == tags.last
  end
end