text:
Q: Getting Python and AutoIT to work together using win32com: what's up with those window handles? I have a program with a GUI interface whose initial set-up I need to do manually. AutoIt has been superbly helpful for that so far, as it provides very easy ways to work even with complex-to-access GUI objects (drop down lists, appear-on-hover menus, etc.).
However, the script that I'll eventually be needing in order to do the program setup will need to be passed a large array/list of variables - there are a lot of different settings that need to be changed.
I've set up the logic for deciding what these set-up variables will be using a Python script. Now I'm trying to figure out how to get Python and AutoIt to talk to each other.
Calling a custom AutoIt script from the command line using Python is mostly out of the question because of the large number of variables that would need to be passed. Doesn't feel pretty. I could try and have Python write an AutoIt "key file", which AutoIt could then read in order to set its initial variables, but I'd like to make sure I've exhausted all options for Python to work directly with AutoIt first.
To that end, I've been trying to use Python along with the win32com library to interface with AutoIt. Things seem to be working well - as long as I reference windows/menus/objects by their string titles rather than their (memory?) handles. This is problematic, as my set-up scripts might be running in parallel, setting up two or more separate files at the same time. If this is the case, opening up a box with a title string "Open file..." in each file at the same time might confuse things.
The obvious way to get around this in AutoIt is to work with the "handles" of the objects in question, which I believe are memory addresses of some kind, rather than their string titles. I'm guessing these are memory addresses as the AutoIt Window Info tool, when pointed to a particular Window/GUI object option lists a hexadecimal number as the object's handle value.
AutoIt has a suite of functions that get the handles of windows, menus, etc. They are implemented in the AutoIt COM dll, but I've not been able to get them to work in Python. The handle functions return a unicode object in Python, not a hex string as in AutoIt. I think this is the reason why functions which then try to use this "handle" in Python don't work.
Example:
autoIt = win32com.client.Dispatch("AutoItX3.Control")
windowHandle = autoIt.WinGetHandle(knownWindowTitle)
returnedWindowTitle = autoIt.WinGetTitle(windowHandle)

Usually, returnedWindowTitle and knownWindowTitle do not match as returnedWindowTitle always seems to be "0". hat's happening here?
Are there other ways for me to call custom AutoIt functions apart from using win32com, the command line, or using an AutoIt keyfile?
Thanks for your help.
EDIT: I forgot to mention that the unicode strings do in fact match the hexadecimal numbers that I get when I print out the handle variable in AutoIt.
For example, in Python, the handle variable when printed out gives me u'000C0326'. In AutoIt it gives me '0x000C0326'.
EDIT: Some trials based on Mat's suggestions:
In: autoIt = win32com.client.Dispatch("AutoItX3.Control")
In: mainWindowTitle = "Untitled"
In: mainWindowHandle = autoIt.WinGetHandle(mainWindowTitle)
In: mainWindowHandle
Out: u'000204AC'
In: testHandle = int(mainWindowHandle, 16)
In: testHandle
Out: 132268
In: autoIt.WinGetTitle(testHandle)
Out: u'0'

EDIT: I found out the type of the window handle object: it's a Microsoft HWND object. AutoIt has a function that can "convert" a base 16 number into an HWND object (i.e. find the HWND object with that base 16 number memory/handle/etc.). Just my luck that they didn't put that function into AutoItX (the COM dll). So, if I really want to run with this, I'll have to try and figure out how to return whatever object it is that's pointed to by the base 16 address, and then transfer it the right way to AutoItX? I'm probably sounding very confused, because all of this is not super clear in my head right now.

A: The type of window handles is string. The reason for that is WinList returns both the window handle and the window title. A title cannot be fit into a handle type, but a handle can be fit into a string type (for title). My guess is that they took that design descision and applied it to other functions as well. If you look at the documentation for WinGetHandle it will tell you the return type for a handle: It's a string.

AutoIt has a function that can "convert" a base 16 number into an HWND object.

Exactly! That's the key. AutoIt does this for you. You're trying to convert the handle into something useful for AutoIt, but AutoIt can already use those handles stored as strings.
Your test should be:
In: autoIt = win32com.client.Dispatch("AutoItX3.Control")
In: mainWindowTitle = "Untitled"
In: mainWindowHandle = autoIt.WinGetHandle(mainWindowTitle)
In: mainWindowHandle
Out: u'000204AC'
In: autoIt.WinGetTitle(mainWindowHandle)
Out: u'Untitled - Notepad'

When you want to use that handle in other libraries, you may run into some problems. I would recommend then that you try to parse the number like you did in your tests, and pass it along. AutoIt is 'smart' enough to figure out what to do in most cases, maybe the library isn't though.

A: For the sake of search, I'll post the solution that I've found.
Here's the code:
In: autoIt = win32com.client.Dispatch("AutoItX3.Control")
In: autoIt.AutoItSetOption("WinTitleMatchMode", 4)
In: mainWindowTitle = "Untitled"
In: mainWindowHandle = autoIt.WinGetHandle(mainWindowTitle)
In: mainWindowHandle
Out: u'000204AC'
In: testHandle = "[HANDLE:%s]" % mainWindowHandle
In: autoIt.WinGetTitle(testHandle)
Out: u'Untitled - Notepad'

autoIt.AutoItSetOption("WinTitleMatchMode", 4) tells autoit to use advanced title matching, which allows us to specify a window handle with the [HANDLE:000204AC] string.
No need for the actual window handle here.
By the way, I discovered this solution by stumbling on this forum post. I've found that it's often helpful to not restrict my searches to the specific language I'm looking for. Most of the time, a solution can be found in a different language which can be easily ported to the language of your choice.


text:
Q: How to set ItemStyle of first item in Combobox i've set up a style for a combobox and all items inside the chooser are written in white because i specified it. The only text that is still black is the first item. Do i need to set something specific for the first item?

This is the xaml code for it:
 <SolidColorBrush x:Key="ComboBoxNormalBorderBrush" Color="#e3e9ef" />
        <SolidColorBrush x:Key="ComboBoxNormalBackgroundBrush" Color="#fff" />
        <SolidColorBrush x:Key="ComboBoxDisabledForegroundBrush" Color="#888" />
        <SolidColorBrush x:Key="ComboBoxDisabledBackgroundBrush" Color="#eee" />
        <SolidColorBrush x:Key="ComboBoxDisabledBorderBrush" Color="#888" />

        <ControlTemplate TargetType="ToggleButton" x:Key="ComboBoxToggleButtonTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition Width="20" />
                </Grid.ColumnDefinitions>
                <Border Grid.ColumnSpan="2" Name="Border"
          BorderBrush="{StaticResource ComboBoxNormalBorderBrush}"
          CornerRadius="0" BorderThickness="1, 1, 1, 1"
          Background="{StaticResource MainButtonBackground}" />
                <Border Grid.Column="1" Margin="1, 1, 1, 1" BorderBrush="#444" Name="ButtonBorder"
          CornerRadius="0, 0, 0, 0" BorderThickness="0, 0, 0, 0"
          Background="{StaticResource MainButtonBackground}"
                                      />

                <Path Name="Arrow" Grid.Column="1"
                      Data="M0,0 L0,2 L4,6 L8,2 L8,0 L4,4 z"
                      HorizontalAlignment="Center"
                      VerticalAlignment="Center" Fill="WhiteSmoke">
                </Path>
            </Grid>
            <ControlTemplate.Triggers>
                <Trigger Property="UIElement.IsMouseOver" Value="True">
                    <Setter Property="Panel.Background" TargetName="ButtonBorder" Value="WhiteSmoke"/>
                    <Setter Property="Shape.Fill" TargetName="Arrow" Value="{StaticResource MainButtonBackground}"/>
                </Trigger>
                <Trigger Property="ToggleButton.IsChecked" Value="True">
                    <Setter Property="Panel.Background" TargetName="ButtonBorder" Value="{StaticResource MainButtonBackground}"/>
                    <Setter Property="Shape.Fill" TargetName="Arrow" Value="WhiteSmoke"/>
                </Trigger>
                <Trigger Property="UIElement.IsEnabled" Value="False">
                    <Setter Property="Panel.Background" TargetName="Border" Value="{StaticResource ComboBoxDisabledBackgroundBrush}"/>
                    <Setter Property="Panel.Background" TargetName="ButtonBorder" Value="{StaticResource ComboBoxDisabledBackgroundBrush}"/>
                    <Setter Property="Border.BorderBrush" TargetName="ButtonBorder" Value="{StaticResource ComboBoxDisabledBorderBrush}"/>
                    <Setter Property="TextElement.Foreground" Value="{StaticResource ComboBoxDisabledForegroundBrush}"/>
                    <Setter Property="Shape.Fill" TargetName="Arrow" Value="#999"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>

        <Style TargetType="ComboBoxItem">
            <Setter Property="Foreground" Value="WhiteSmoke"/>
            <Setter Property="Background" Value="{StaticResource MainButtonBackground}"/>
        </Style>

        <Style x:Key="ComboBoxFlatStyle"  TargetType="{x:Type ComboBox}">
            <Setter Property="UIElement.SnapsToDevicePixels" Value="True"/>
            <Setter Property="FrameworkElement.OverridesDefaultStyle" Value="True"/>
            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
            <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
            <Setter Property="ScrollViewer.CanContentScroll" Value="True"/>
            <Setter Property="TextElement.Foreground" Value="Black"/>
            <Setter Property="FrameworkElement.FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="Control.Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ComboBox">
                        <Grid>
                            <ToggleButton Name="ToggleButton" Grid.Column="2"
            ClickMode="Press" Focusable="False" Background="{StaticResource MainButtonBackground}"
                                          Foreground="{StaticResource WindowForeColor}"
            IsChecked="{Binding Path=IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}"
            Template="{StaticResource ComboBoxToggleButtonTemplate}"/>

                            <ContentPresenter Name="ContentSite" Margin="5, 3, 23, 3" IsHitTestVisible="False"
                          HorizontalAlignment="Left" VerticalAlignment="Center"
                          Content="{TemplateBinding ComboBox.SelectionBoxItem}"
                          ContentTemplate="{TemplateBinding ComboBox.SelectionBoxItemTemplate}"
                          ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"/>
                            <TextBox Name="PART_EditableTextBox" Margin="3, 3, 23, 3"    Background="{StaticResource MainButtonBackground}"
                                          Foreground="{StaticResource WindowForeColor}"
                 IsReadOnly="{TemplateBinding IsReadOnly}"
                 Visibility="Hidden"
                 HorizontalAlignment="Left" VerticalAlignment="Center"
                 Focusable="True" >
                                <TextBox.Template>
                                    <ControlTemplate TargetType="TextBox" >
                                        <Border Name="PART_ContentHost" Focusable="False"  />
                                    </ControlTemplate>
                                </TextBox.Template>
                            </TextBox>
                            <!-- Popup showing items -->
                            <Popup Name="Popup" Placement="Bottom"
               Focusable="False" AllowsTransparency="True"
               IsOpen="{TemplateBinding ComboBox.IsDropDownOpen}"
               PopupAnimation="Slide">
                                <Grid Name="DropDown" SnapsToDevicePixels="True"
                MinWidth="{TemplateBinding FrameworkElement.ActualWidth}"
                MaxHeight="{TemplateBinding ComboBox.MaxDropDownHeight}">
                                    <Border Name="DropDownBorder" Background="{StaticResource MainButtonBackground}" Margin="0, 1, 0, 0"
                    CornerRadius="0" BorderThickness="1,1,1,1"
                    BorderBrush="{StaticResource ComboBoxNormalBorderBrush}"/>
                                    <ScrollViewer Margin="4" SnapsToDevicePixels="True">
                                        <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Contained" />
                                    </ScrollViewer>
                                </Grid>
                            </Popup>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="ItemsControl.HasItems" Value="False">
                                <Setter Property="FrameworkElement.MinHeight" TargetName="DropDownBorder" Value="95"/>
                            </Trigger>
                            <Trigger Property="UIElement.IsEnabled" Value="False">
                                <Setter Property="TextElement.Foreground" Value="{StaticResource ComboBoxDisabledForegroundBrush}"/>
                            </Trigger>
                            <Trigger Property="ItemsControl.IsGrouping" Value="True">
                                <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
                            </Trigger>
                            <Trigger Property="ComboBox.IsEditable" Value="True">
                                <Setter Property="KeyboardNavigation.IsTabStop" Value="False"/>
                                <Setter Property="UIElement.Visibility" TargetName="PART_EditableTextBox" Value="Visible"/>
                                <Setter Property="UIElement.Visibility" TargetName="ContentSite" Value="Hidden"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

I don't know how to set the foreground for the item that is still written in black. Would love some help (=
Solution edit:
I had to change the TextElement.Foreground property of my ComboBoxFlatStyle...
<Style x:Key="ComboBoxFlatStyle"  TargetType="{x:Type ComboBox}">
.
.
.
                <Setter Property="TextElement.Foreground" Value="WhiteSmoke"/>
.
.
.
</Style>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Iterating over a list stored in webElement I am learning appium (mobile automation) using python.
I have a scenario where I have a listView and I have to iterate through each item and then click back until all items are clicked.
I am using following code:
def test_selectingEveryOption(self):
        availableOptions = self.driver.find_elements_by_xpath('//android.widget.ListView')
        for options in availableOptions:
            availableOptions[options].click()
            self.driver.back()

availableOptions is the webElement that have the list. When I run above piece of code, I get TypeError: list indices must be integers or slices, not WebElement
Since availableOptions is webElement, how can I get its list items as integers and then iterate over them?

A: browser.find_elements_by_class_name("myClass") returns a list of WebElements. So.. in your for-loop, each iteration produces a WebElement, not an integer index... you don't need to use indexes at all.
for element in self.driver.find_elements_by_xpath('//android.widget.ListView'):
    element_contents = element.get_attribute('innerHTML')


text:
Q: Conditional formatting for what my Javascript find in table cell Im attempting to generate a site to show customer sites status's. I am stuck on some conditional formatting from within jave script.

The problem that I am having is the last section of the script. What I would like is some assitance, in getting the script to look for the word "UP" or "DOWN" in the example XML tag called . Setting different color and text according to the word. Anything else has its own seperate formatting.
For some reason (must be a really silly reason for it), the table cell called STATUS is only showing the last part of the formatting. So instead of looking for the word "UP" or "DOWN" its using the formating for everytrhing else instead. So instead of using this:
if (STAT=="UP")
        {
        document.write('
UP
')
        }

It is using this:
else
        {
        document.write('
UNKNOWN
')
        }

An example output is here: http://echelonservices.co.uk/test/CUSTOMERS.html
Can anyone assist?

A: In this code:
var STAT=xmlDoc.getElementsByTagName("STATUS");
document.write(STAT)
if (STAT=="UP")

...you're comparing an element (the STATUS element) with a string. I think you probably meant:
var STAT=xmlDoc.getElementsByTagName("STATUS")[0].firstChild.nodeValue;
document.write(STAT)
if (STAT=="UP")

...so that you get the value of its first text node. Or you may want [x] instead of [0], it's not clear.
Or actually, looking at the surrounding code:
var STAT = x[i].getElementsByTagName("STATUS")[0].childNodes[0].nodeValue;
document.write(STAT);
if (STAT=="UP")

(But note that you can use firstChild rather than childNodes[0].)

But can I just strongly suggest not using synchronous ajax requests, and not using document.write. Instead, put a placeholder in your HTML where you want this table to go:

...and then put this at the end of the page:
(function() {
    var xmlhttp;

    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = handleReadyStateChange;
    xmlhttp.open("GET", "example.xml"); // Async, not sync
    xmlhttp.send();

    function handleReadyStateChange() {
        if (xmlhttp.readyState == 4 &&
            xmlhttp.status >= 200 &&
            xmlhttp.status < 300) {

            buildTable(xmlhttp.responseXML);
        }
    }

    function buildTable(xmlDoc) {
        var markup, x, i, stat;

        // Build the markup in an array
        markup = ["

"];
        markup.push("SITE:	");
        markup.push("URL:	");
        markup.push("STATUS:	");
        x = xmlDoc.getElementsByTagName("CD");
        for (i = 0; i < x.length; i++) {
            markup.push("
");
            markup.push(x[i].getElementsByTagName("SITE")[0].firstChild.nodeValue);
            markup.push("	");
            markup.push(x[i].getElementsByTagName("URL")[0].firstChild.nodeValue);
            markup.push("	");
            stat = x[i].getElementsByTagName("STATUS")[0].firstChild.nodeValue;
            markup.push(stat);
            switch (stat) {
                case "UP":
                    markup.push('
UP
')
                    break;
                case "DOWN":
                    markup.push('
DOWN
')
                    break;
                default:
                    markup.push('
UNKNOWN
')
                    break;
            }
            markup.push("
");
        }
        markup.push("
");

        // Put it in the placeholder
        document.getElementById("placeholder").innerHTML = markup.join("");
    }
})();

That's a minimal rewrite, note how little actually changed. I basically did these things:

*

*Making it an asynchronous request.

*Building the markup in an array.

*Changed childNodes[0] to firstChild.

*Putting the table on the page by assigning to innerHTML on a placeholder.

*Declaring all variables at the top of the function (as that's where they are anyway).

*Ensuring all variales are in fact declared (you may have had them declared in code you didn't show, but just in case), so we don't fall prey to The Horror of Implicit Globals.

*Put everything within a scoping function so we didn't create any globals.

(I had to change the indentation style, I'm afraid I didn't quite "grok" yours.)


text:
Q: Accessing Google Secret Manager from AI Platform training job with custom container I am trying to access a secret stored in Google Secret Manager from an AI Platform Training job that runs in a custom container. I am using the following Python code to retrieve secrets:
# Standard library imports
import os

# Import the Secret Manager client library.
from google.cloud import secretmanager

def access_secret_version(secret_id, version_id, project_id=os.environ.get("GCP_PROJECT")):
     # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the secret version.
    name = client.secret_version_path(project_id, secret_id, version_id)

    # Access the secret version.
    response = client.access_secret_version(name)

    # Return the secret payload.
    return response.payload.data.decode("UTF-8")

I have added the Secret Manager Secret Accessor role to the default Cloud ML service account (service-XXX@cloud-ml.google.com.iam.gserviceaccount.com), but access is still denied:
google.api_core.exceptions.PermissionDenied: 403 Request had insufficient authentication scopes.

Have I granted the correct role to the correct service account or I am missing something else?

A: We have an alpha feature to enable your use case. Can you send us an email to cloudml-feedback@google.com please?


text:
Q: In liferay, how can I transform an mbdiscussion into a standard MBMessage? I would like to move a few comments on a page layout to become standard messages in a message board.
How can I do that?
thanks in advance

A: AFAIK there's no magic flag to change on such a message. As you'll have different metadata, you'll have to read the comment (through the API) and create a message-board message in a category that you'll find appropriate. As it's all text content, you'll just contain the message board message with the same content and author. But all of the other metadata (category, threading etc) you'll have to handle for yourself


text:
Q: Different equation with bounded condition $$y' = 2x(π+y)$$
$y$ being bounded when $x\to + ∞$
There is a singular solution $~y = -π~$ and it was the answer.
But general solution $y = ce^{x^2} - π$ ;$(|c| = e^{c})$ and $~c~$ must not be $~0~$.
$y - π = 0 = ce^{x^2}$ then $~c = 0~$?  why $~c~$  can be $~0~$ in this case?
And how do you know $~y = -π~$  satisfy the bounded condition?

A: Put $z=y+\pi $. then
$$\frac {z'}{z}=2x $$
and
$$z=\lambda e^{x^2} $$
$$y(x)=\lambda e^{x^2}-\pi $$
if $\lambda\neq 0$ then
$$\lim_{x\to+\infty}y (x)=\infty $$
but $y $ is bounded, thus
$\lambda=0$ and
$$y (x)=-\pi $$
is the only bounded solution.

A: $$y'-2xy=2x\pi$$
$$IF=e^{-x^2}$$
$$\int d(ye^{-x^2})=2\pi\int xe^{-x^2}dx+C $$
$$ye^{-x^2}=-2\pi(\frac{e^{-x^2}}{2})+C \tag{1}$$
as $x\rightarrow \infty$ $C\rightarrow0$
$$y=-\pi$$
Hope it solved it for you?


text:
Q: Android Plugin for Eclipse problem I am using a laptop with Windows 7 Home Prem x64. I have installed Java JDK1.6.0_18 and Eclipse Gallileo. I have downloaded and installed the latest version of Android SDK with several Platforms loaded and a AVD defined. I can install the Android Eclipse plugin from the remote site stated in the instructions. The plugin installation performs without any errors and I can verify that the plugins are indeed installed. My problem begins when I go to Windows -> Preferences, there is no Android section to configure. And when I go to File -> New -> Project, there is no Android Project to choose.
I have uninstalled the plugin and reinstalled at least 10 times, trying different things and still no luck. I originally had the 64 bit version of the JDK installed, but removed it and installed the 32 bit version.
Has anyone heard of this type of problem? Is it because I am using Windows 7?
Thanks for any help.
tbneff

A: Have you tried doing the following and have it manually install from there:
Help -> Software Updates -> Add site -> http://dl-ssl.google.com/android/eclipse
I didn't see it on the website regarding if the ADT or the SDK is not compatible with Windows 7.
When you said you installed the 32-bit version, did you get it working or not at all?

A: maybe you have space in your Eclipse or Android SDK path? do not use spaces in path. I had similar problems and that's because spaces.

A: I encountered the same problem on my Mac, and found out what my problem was. When I was futzing around with stuff I had renamed the config.ini file in the eclipse/configuration folder. When I renamed it back to config.ini and restarted eclipse everything Android was back in the menus for me.


text:
Q: How to stop both widgets in a stack from responding to touch I have a Stack Widget which contains a map (covering the whole page) and a listview at the bottom and above the map. But when you swipe the listview, the map also moves. How do I stop the map from moving as well? The Listview is in front of the Map so I am unsure as to why the map also responds to me moving the listview.
Stack(
   children <Widget> [
      Map(),
      ListView( ... ),
   ]
)

Thank you

A: Use the IgnorePointer widget to wrap the map
IgnorePointer(ignoring: false, ...)

and adjust this attribute by changing the bool value of ignoring:

A: Use absorb pointer where you don't wish to pass the gesture to the map. In the stack use this heirarchy
Stack(
 children: [
  Map(),
  Positioned(
    bottom :0,
    child: AbsorbPointer(//this will absorb the pointer from going to the map
     child : Container(
       height: 300 // edit this to the required height
     width: MediaQuery.of(context).size.width
     )
   )
  ),
 // Listview here
]
)


text:
Q: Pipe microphone to speakers with no delay I want to plug a microphone into my computer and pipe the sound out to speakers, and I want to have as little delay as possible.  And I would prefer to use command line to do this.
Any ideas?
Thanks.
(I'm thinking of putting this in my van, so we can use it like a PA system. Our van has a 1/8 inch audio jack line in.  Actually, it's so that my wife can read a book to our kids without having to yell.)
Edit: About my system:  I'll use whatever software I need to.  For hardware, I was hoping to use a Raspberry Pi, but I would consider a laptop if I have to.


text:
Q: Installing Hadoop in full distributed mode using VM VirtualBox on Windows Machines I have installed Hadoop in Pseudo-Distribution Mode using Oracle VM VirtualBox (https://github.com/AmanpreetSingh-GitHub/Hadoop) on Windows 10 machine and it is working perfectly fine and running my MapReduce, Pig, Hive, Sqoop programs.
Now I want to install Hadoop in full distributed mode using Oracle VM VirtualBox on four Windows 10 machines. Could you please let me know how to proceed for this? Any links to resources that briefly tells that will be really helpful.


text:
Q: Move vector> to a vector> I have two classes, say Base and Derived: public Base and two std::vectors, one holding elements of type unique_ptr<Base> and other one holds elements of type unique_ptr<Derived> How can I transfer ownership of all elements from second vector into first one? I already tried:
vector<unique_ptr<Base>> v1;
vector<unique_ptr<Derived>> v2;
// do something
std::move(v2.begin(),v2.end(),v1.begin()); // This line crashed
v1 = std::move(v2); // And this gives a compiler error

A: You need to make sure v1 is the proper size before moving into it.  For example:
#include <algorithm>
#include <vector>
#include <memory>

using std::vector;
using std::unique_ptr;

struct Base {
};

struct Derived : Base {
};

int main()
{
  vector<unique_ptr<Base>> v1;
  vector<unique_ptr<Derived>> v2;
  v2.push_back(unique_ptr<Derived>(new Derived));
  v2.push_back(unique_ptr<Derived>(new Derived));
  v2.push_back(unique_ptr<Derived>(new Derived));
  v1.resize(v2.size());
  std::move(v2.begin(),v2.end(),v1.begin());
}

This is because the move algorithm doesn't change the size of the container itself.  It is implemented like this (taken from http://en.cppreference.com/w/cpp/algorithm/move):
template<class InputIt, class OutputIt>
OutputIt move(InputIt first, InputIt last, OutputIt d_first)
{
    while (first != last) {
        *d_first++ = std::move(*first++);
    }
    return d_first;
}

A: As I did not see this answer elsewhere, I wanted to remind everyone of the very simple member function assign of vector:
vector<unique_ptr<Base>> v1;
vector<unique_ptr<Derived>> v2;
// do something
v1.assign(make_move_iterator(v2.begin()), make_move_iterator(v2.end()));

A: Do it elementwise.
for (auto&& elem : v2)
{
    v1.push_back(std::move(elem));
}

A: You may use the following:
std::vector<std::unique_ptr<Base>> v1(v2.size());

std::copy(std::make_move_iterator(v2.begin()), std::make_move_iterator(v2.end()), v1.begin());

A: template<class Dest, class Src>
void move_contents_to(Dest&dest, Src const& src)=delete;
template<class Dest, class Src>
void move_contents_to(Dest&dest, Src& src)=delete;
template<class Dest, class Src>
void move_contents_to(Dest&dest, Src&& src){
  using std::begin; using std::end;
  dest = Dest{std::make_move_iterator(begin(src)),std::make_move_iterator(end(src))};
}

the above will work for most std containers, and will work with raw C style arrays on the right.  For safety, I require the src to be an rvalue reference, so which is being moved is clear.


text:
Q: What format should be the boxplot [echarts] data to avoid the transform function, is it possible? Set of parameters [min, Q1, median, Q3, max] for boxplot I have initially, how can I render them in echarts
echarts for boxplot transforms the original data to the set [min, Q1, median, Q3, max], can I avoid this step ? My source data already consists of [min, Q1, median, Q3, max] sets, how do I pass such a set to render?

A: Just your parameters for the data attribute.
series: {
 name: 'boxplot',
 type: 'boxplot',
 data:[[min, Q1, median, Q3, max]]
}

Link for Echarts documentation https://echarts.apache.org/en/option.html#series-boxplot.data


text:
Q: How can I get integrating factor for $y(2x-y-1)dx+x(2y-x-1)dy=0$ How can I solve this DE using an integrating factor to make it exact DE ? What is the method used to determine the integrating factor , or we just try ?
$y(2x-y-1)dx+x(2y-x-1)dy=0$

A: $$y(2x-y-1)dx+x(2y-x-1)dy=0 \tag 1$$
I will try another method than integrating factor.
The symmetry draw us to change of variables :
$$\begin{cases}
s=x+y\\
p=xy
\end{cases} \quad\to\quad
\begin{cases}
x=\frac12\left(s+\sqrt{s^2-4p} \right)\\
y=\frac12\left(s-\sqrt{s^2-4p} \right)
\end{cases}$$
$$\begin{cases}
dx=\left(\frac12+\frac{s}{2\sqrt{s^2-4p}}\right)ds - \frac{s}{\sqrt{s^2-4p}}dp\\
dy=\left(\frac12-\frac{s}{2\sqrt{s^2-4p}}\right)ds + \frac{s}{\sqrt{s^2-4p}}dp\end{cases}$$
We put the above equations $x,y,dx,dy$ into Eq.$(1)$. This leads to a big equation. After simplification the remaining terms are :
$$3p\,ds-(s+1)dp=0$$
This surprisingly simple ODE is easy to solve :
$$(s+1)^3=c\,p$$
The solution of the ODE $(1)$ , expressed on the form of implicit equation, is :
$$(x+y+1)^3=c\,xy \tag 2$$
where $c$ is an arbitrary constant.
If you want the explicit form $y(x)$, you will have to solve for $y$ the cubic equation :
$$y^3+3(x+1)y^2+(3(x+1)^2-cx)y+(x+1)^3=0$$
NOTE : Since the solution is now known on the very simple form $(2)$, it is probably possible to work backward in order to find an other method of solving which might appears smarter afterwards.
INTEGRATING FACTOR :
An integrating factor for Eq.$(1)$ is :$\quad\frac{(x+y+1)^2}{x^2y^2}$
I must confess that this integrating factor was found in working backward from Eq.$(2)$. Of course, that is a back-door route, not recommended for a straightforward search of integrating factor.


text:
Q: wordpress plugin translation I have a plugin (lets say that it is called my_plugin), in which I generated the .po file, and subsequently the .mo file. I saved the files in a folder called languages. I called the files my_plugin-en_US.po and my_plugin-en_US.mo.
Summary of structure:
plugins (dir)
--my_plugin (dir)
----languages (dir)
------my_plugin-en_US.po (file)
------my_plugin-en_US.mo (file)
The translation still does not show (the original plugin is not in English).
What am I doing wrong?
Thanks

A: You need to explicitly load the translation with load_plugin_textdomain.


text:
Q: why when I press (trigger the OnClick) it doesnt work but when it written outside the onclick it does work enter image description here
why when I press (trigger the OnClick) it doesnt work but when it written outside the onclick it does work? (OnClick of the  and the function one line after)

A: When you add parentheses at the end of a function name, you are indirectly invoking them at the time they are parsed in the browser. Therefore, trying removing the parentheses and it should work as expected.
EDIT: Newer Answer
So, what you can do is, use setState to change what the user should see at any point of time. Initially, that will be the default screen and then when the user click the image it will be deck screen. So your useState will look something like this:
const [screenName, setScreenName] = useState("default");

Now that you have this, store the two components i.e. your default screen with the image, and the deck screen with cards.map().... into two separate components inside your original function of Gamepage.js. The return of this(the main) function should look like the following:
return(<>{
    screenName === "default" ? <DefaultComponent /> : <DeckComponent />
}</>);

After doing this, you just make a small change to the onClick of the DefaultComponent so that it does the following:
setScreenName("deck");

This should do the job, lmk if you need any further help.


text:
Q: How do you use multiple data models in a diffable data source? I've currently hit a wall while trying to develop the search view within my application. I've attempted to place a collection view within a table view cell, as well as use the traditional collection view data source delegates (cell for row at etc.) however either of these implementations seems to be far from optimal in a modern application. Our application is using three models for 'Friends', 'Users', and 'Venues'.
We've successfully got one of our models to populate in the search view using a Diffable Data Source and compositional layout, but when I try to add the others I get the following error:
""*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: section != NSNotFound'
terminating with uncaught exception of type NSException""
Heres the SearchViewController
import UIKit

fileprivate typealias DataSource  = UICollectionViewDiffableDataSource<Section, SearchV2VC.DataType>
fileprivate typealias SourceSnapshot = NSDiffableDataSourceSnapshot<Section, SearchV2VC.DataType>

class SearchV2VC: UIViewController {

    var collectionView: UICollectionView! = nil
    private var dataSource: DataSource!
    var friendData = [FollowingInfo]()
    var userData = [FriendInfo]()
    var venueData = [Venue]()

    override func viewDidLoad() {
        super.viewDidLoad()

        configureHierarchy()
        configureDataSource()

    }

    private func firstLayoutSection() -> NSCollectionLayoutSection {

        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(0.5))

        let item = NSCollectionLayoutItem(layoutSize: itemSize)
        item.contentInsets.bottom = 15

        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.9), heightDimension: .fractionalWidth(0.5))

        let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [item])
        group.contentInsets = .init(top: 0, leading: 15, bottom: 0, trailing: 2)

        let section = NSCollectionLayoutSection(group: group)

        //section.orthogonalScrollingBehavior = .groupPaging
        section.orthogonalScrollingBehavior = .none

        return section
    }
    private func secondLayoutSection() -> NSCollectionLayoutSection {

        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(0.5))

        let item = NSCollectionLayoutItem(layoutSize: itemSize)
        item.contentInsets.bottom = 15

        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.9), heightDimension: .fractionalWidth(0.5))

        let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [item])
        group.contentInsets = .init(top: 0, leading: 15, bottom: 0, trailing: 2)

        let section = NSCollectionLayoutSection(group: group)

        //section.orthogonalScrollingBehavior = .groupPaging
        section.orthogonalScrollingBehavior = .none

        return section
    }

    private func thirdLayoutSection() -> NSCollectionLayoutSection {

        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(2))

        let item = NSCollectionLayoutItem(layoutSize: itemSize)
        item.contentInsets.bottom = 15

        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.35), heightDimension: .fractionalWidth(0.35))

        let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
        group.contentInsets = .init(top: 0, leading: 15, bottom: 0, trailing: 0)

        let section = NSCollectionLayoutSection(group: group)

        navigationItem.title = "You a Bitch"

        section.orthogonalScrollingBehavior = .continuous

        return section
    }
}
extension SearchV2VC {
private func createLayout() -> UICollectionViewCompositionalLayout {

    return UICollectionViewCompositionalLayout { (sectionNumber, env) -> NSCollectionLayoutSection? in

     switch sectionNumber {

     case 0: return self.firstLayoutSection()
     case 1: return self.secondLayoutSection()
     default: return self.thirdLayoutSection()

     }
   }
}
}
    //MARK: - UICollectionViewDataSource Methods

extension SearchV2VC {
    private func configureHierarchy() {
        //collectionView.delegate = self
        collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: createLayout())
        collectionView.delegate = self
        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        collectionView.backgroundColor = .white

        collectionView.register(UserCell.self, forCellWithReuseIdentifier: UserCell.reuseIdentifier)
        collectionView.register(FriendCell.self, forCellWithReuseIdentifier: FriendCell.reuseIdentifier)
        collectionView.register(VenueCell.self, forCellWithReuseIdentifier: VenueCell.reuseIdentifier)
        view.addSubview(collectionView)

    }
}
extension SearchV2VC {

    func configureDataSource(){

        dataSource = DataSource(collectionView: collectionView, cellProvider: { (collectionView, index, friend) -> UICollectionViewCell in

            switch friend{
            case .user(let user):
                guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserCell.reuseIdentifier, for: index) as? UserCell else {fatalError("Couldn't Create New Cell")}
                cell.viewModel = UserCellViewModel(user: user)
                return cell

            case .friend(let friend):
                guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FriendCell.reuseIdentifier, for: index) as? FriendCell else {fatalError("Couldn't Create New Cell")}
                cell.viewModel = FriendCellViewModel(user: friend)
                return cell
            case .venue(let venue):
                guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: VenueCell.reuseIdentifier, for: index) as? VenueCell else {fatalError("Couldn't Create New Cell")}
                cell.viewModel = VenueCellViewModel(venue: venue)
                return cell
            }

        })

        dataSource.apply(snapshotForCurrentState(), animatingDifferences: false)

    }

func snapshotForCurrentState() -> NSDiffableDataSourceSnapshot<Section, DataType>{
    var snapshot = NSDiffableDataSourceSnapshot<Section, DataType>()
    snapshot.appendSections(Section.allSections)

    let userItems = userData.map { DataType.user($0) }
    snapshot.appendItems(userItems, toSection: Section.users)

    let friendItems = friendData.map { DataType.friend($0) }
    snapshot.appendItems(friendItems, toSection: Section.friends)

    let venueItems = venueData.map { DataType.venue($0) }
    snapshot.appendItems(venueItems, toSection: Section.venue)
    return snapshot
    }
}
extension SearchV2VC: UICollectionViewDelegate  {

    enum DataType: Hashable {
        case user(FriendInfo)

        case friend(FollowingInfo)

        case venue(Venue)
    }

     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
         collectionView.deselectItem(at: indexPath, animated: true)
         guard let user = dataSource.itemIdentifier(for: indexPath) else { return }
        print(user)
     }

}

This is what our models look like:
import Foundation
import Firebase
import Mapbox

struct Venue: Hashable {

    static func == (lhs: Venue, rhs: Venue) -> Bool {
        lhs.venID == rhs.venID
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(venID)
    }

    var venID: String?
    var latitude: Double?
    var longitude: Double?
    var name: String?
    var description: String?
    var image: String?
    var address: String?

}

struct FriendInfo: Hashable {

    static func == (lhs: FriendInfo, rhs: FriendInfo) -> Bool {
        lhs.userID == rhs.userID
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(userID)
    }

    var displayName: String?
    var userID: String?
    var userName: String?
    var providerID: String?
    var profileImageURL: String?
    var isFriend = false
    var stats: UserStats?
    var isCurrentUser: Bool { return Auth.auth().currentUser?.uid == providerID }
}

struct FollowingInfo: Hashable {

    static func == (lhs: FollowingInfo, rhs: FollowingInfo) -> Bool {
        lhs.userID == rhs.userID
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(userID)
    }

    var displayName: String?
    var userID: String?
    var profileURL: String?
    var userName: String?
}

Lastly here is the Custom Section Class we are using instead of the usual 'enum section' located in the controller, and this is most likely where the problem lies:
import UIKit

struct Section: Hashable {
    var id = UUID()

    var title: String
    var data: [Any]

    init(title: String, data: [Any]) {
        self.title = title
        self.data = data
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    static func == (lhs: Section, rhs: Section) -> Bool {
        lhs.id == rhs.id
    }

}

extension Section {
    static var allSections: [Section] = [
        Section(title: "Users", data: [FriendInfo]()),
        Section(title: "Friends", data: [FollowingInfo]()),
        Section(title: "Venue", data: [Venue]())
    ]
}

extension Section {
    static var users: Section =
    Section(title: "Users", data: [FriendInfo]())
}

extension Section {
    static var friends: Section =
    Section(title: "Friends", data: [FollowingInfo]())
}

extension Section {
    static var venue: Section =
    Section(title: "Venue", data: [Venue]())
}

Lastly, I should mention we are setting these 3 models with completely different Data via an API call to Firebase. (The data is operating as expected everywhere else in the application) The collection view cells are utilizing a view model hence the 'cell.viewModel = ...' seen in the view controller.
I've been trying to get this functioning as expected for several days now. I have watched every video from Apple, thoroughly inspected all the example projects, and visited nearly every link google has to offer on the topic.
This is my first stack question so I apologize if I missed any crucial information. Surely someone has implemented something like this design, I am open to any ways of achieving this. Thanks!

A: I actually found your post while trying to figure this out for myself, and just got it to work. You're definitely on the right track by using enums. I'm sorry I can't tell you exactly what that error means, but here is the gist of what worked for me. I have only two different models (Event and Filter), but obviously it could be expanded to work with 3+.
typealias EventsDataSource = UICollectionViewDiffableDataSource<Section, Item>
typealias EventsSnapshot = NSDiffableDataSourceSnapshot<Section, Item>

struct Filter {
    let text: String
}

struct Event {
    let description: String
    let startTime: Date
    let endTime: Date
}

enum Item: Hashable {
    case filter(Filter)
    case event(Event)
}

struct Section: Hashable {
    let items: [Item]
    let title: String?
}

Donny Wals has a particularly good Diffable Datasources article.
(And if you're looking to integrate Core Data into your Diffable Datasource, Julian Schiavo's article is immensely helpful too.)

A: You get this error Invalid parameter not satisfying: section != NSNotFound when you add ItemIdentifier instances to a SectionIdentifier instance which is not yet added to the snapshot. That's the reason for the message - you have not added the section to the data source and UIKit does not know what indexPath.section is for the added items.
Thus don't forget to do snapshot.appendSections([...]) before doing snapshot.appendItems([...], toSection:...)


text:
Q: Python - Calling methods inside a class, from inside a class I am currently trying to create a little piece of code that will return a full deck of cards. I am trying to call the createDeck() method from within the init() method. For some reason there is an error showing up. Can anyone explain a solution around this, or why it is not working? I tried removing the class, and only having the methods, and it worked perfectly.
class FullDeck():
    '''
    Returns a full 52 card deck
    '''
    names = ('Ace','One','Two','Three','Four','Five','Six','Seven','Eight',
                'Nine','Ten','Jack','Queen','King')
    suits = ('Hearts','Spades','Clubs','Diamonds')
    def __init__(self):
        self.deck = createDeck()

    def createDeck(self):
        currentDeck = []
        for it1 in FullDeck.names:
            for it2 in FullDeck.suits:
                currentDeck.append(it1 + ' of ' + it2)
        return currentDeck

A: Unlike other languages, Python classes don't have an implicit reference to themselves. You must explicitly use a reference if you want to call any methods on the same object.
self.deck = self.createDeck()

Also note that since the method is only used to create the attribute on the object, it should perform that operation itself.
def __init__(self):
     ...
    self.createDeck()

def createDeck(self):
    currentDeck = []
         ...
    self.deck = currentDeck

A: As one of the comments suggested, you need to use
def __init__(self):
    self.deck = self.createdeck()

to get the result you're looking for.


text:
Q: reading data off website in C#         private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        try
        {
            HtmlDocument doc = logger.Document;
            HtmlElement username = doc.GetElementById("loginUsername");
            HtmlElement password = doc.GetElementById("loginPassword");
            HtmlElement submit = doc.GetElementById("loginSubmit");
            username.SetAttribute("value", "myusername");
            password.SetAttribute("value", "mypassword");
            submit.InvokeMember("click");
        }
        catch
        {

        }
    }

Hello, I am trying to make a program that will log onto a website, and read some texts off to display it to the user. With the code above, I've made the webbrowser log in automatically so far.
On the page after logging in,

I want the program to click on the Timetable element. But it doesn't have its own id. How can I get access to it?
Is this even a right way to do it? How can I achieve what I want here? I couldn't do it myself so I put this question here!

A: From the MSDN page it would seem that your options are limited.
What you can try though, it to use Selenium instead. It will allow your application to interact with web components and also consume them through ID's, XPath and CSS Selectors, which would allow you for more flexibility than what you are currently using.
Selenium comes with its own C# wrapper. This tutorial should help you.

A: You don't need to click on the button, as you have the URL. You can call the URL directly and read the code that has been returned:
var req = (HttpWebRequest)WebRequest.Create(URL);
req.Method = "GET";
var resp = req.GetResponse();

using(var sr = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.UTF8))
{
    string result = sr.ReadToEnd();
}

myResponse.Close();

You can see the data returned if you use a tool such as Fiddler.

A: It's here. Just some foreach code.
    bool login = false;
    bool nav = false;
    bool beware = true;

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        try
        {
            HtmlDocument doc = webBrowser1.Document;
            if (login && !nav)
            {
                HtmlElement timetable = null;
                foreach (HtmlElement link in doc.GetElementsByTagName("li"))
                {
                    Console.WriteLine(link.InnerText);
                    if (beware)
                    {
                        timetable = link; //Avoiding NullExceptions
                    }
                    if (link.InnerText.Contains("Timetablelol"))
                    {
                        timetable = link; //Set the Timetable var.
                        beware = false; //Keep Timetable the kept element.
                    }
                }
                timetable.InvokeMember("click"); //Clicking on timetable link.
                nav = true;
            }
            if (!login && !nav)
            {
                HtmlElement username = doc.GetElementById("loginUsername");
                HtmlElement password = doc.GetElementById("loginPassword");
                HtmlElement submit = doc.GetElementById("loginSubmit");
                username.SetAttribute("value", "myusername");
                password.SetAttribute("value", "mypassword");
                submit.InvokeMember("click");
                login = true;
            }

        }
        catch
        {
            Console.WriteLine("Didn't work");
        }
    }


text:
Q: Fixed "Every derived table must have its own alias" now getting column doesn't exist error I'm trying to make this query work. Sorry I'm new to mysql.
$sql = "SELECT * FROM mutamba_posts
        INNER JOIN ( SELECT aluno_id FROM mutamba_amigos GROUP BY aluno_id)
        ON mutamba_amigos.aluno_id  = mutamba_posts.post_aluno_id
        WHERE mutamba_amigos.amizade_id IN (SELECT amizade_id FROM mutamba_amigos WHERE aluno_id = '{$myid}')
        ORDER BY mutamba_posts.post_date DESC LIMIT {$start}, {$limit}";

getting the error: Every derived table must have its own alias
I changed it to :
   $sql = "SELECT * FROM mutamba_posts
           INNER JOIN ( SELECT aluno_id  AS aluno_id, amizade_id as amizade_id FROM mutamba_amigos GROUP BY aluno_id)
           aluno_id ON mutamba_amigos.aluno_id  = mutamba_posts.post_aluno_id
           WHERE mutamba_amigos.amizade_id IN (SELECT amizade_id AS amizade_id FROM mutamba_amigos WHERE aluno_id = '{$myid}')
           ORDER BY mutamba_posts.post_date DESC LIMIT {$start}, {$limit}";

Now I'm getting the error: " Unknown column 'mutamba_amigos.amizade_id' in 'IN/ALL/ANY subquery'"
Any help please?

A: You need to give an alias name to every temp table from a subquery
SELECT *
FROM mutamba_posts
INNER JOIN
(
   SELECT aluno_id
   FROM mutamba_amigos
   WHERE mutamba_amigos.amizade_id IN
   (
      SELECT amizade_id FROM mutamba_amigos WHERE aluno_id = '{$myid}'
   )
   GROUP BY aluno_id
) mutamba_amigos ON mutamba_amigos.aluno_id  = mutamba_posts.post_aluno_id
ORDER BY mutamba_posts.post_date DESC
LIMIT {$start}, {$limit}

A: Your first inner join subquery, you assigned an alias of "aluno_id" which I don't think you meant.  I think the restructure of your query would be simplified to...
SELECT
      mp.*
   FROM
      mutamba_posts mp
         JOIN mutamba_amigos ma
            ON mp.post_aluno_id = ma.aluno_id
   WHERE
      mp.post_aluno_id = '{$myid}'
   ORDER BY
      mp.post_date DESC
   LIMIT {$start}, {$limit}

In summary, your query was starting with the POSTS table, then looking into the AMIGOS table by the "aluno_id" to get AMIZADE_ID.  But then you use the AMIZADE_ID back to the AMIGOS table by it's "aluno_id". So, it appears you are looking for any posts that are by the person "aluno_id" provided order by the DATE(desc).  It looks like you were double-qualifying records to get back to the original underlying "aluno_id" value.
For the future, for things like this, you should try to post some sample data of each and show a sample of what you are trying to get out.  Simple (even abbreviated) table structures of respective columns in the query, and data with spaces between columns as tabs don't work well.


text:
Q: Run File From Address Using hostname there is a script I'm trying to use for Blogger. It works when you enter your domain URL into the src, but I'm trying to find a way to do it using hostname to insert the domain.
Original script:
<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=INSERT-YOUR-URL-HERE&ShowHowMany=5&_id=390e906036f48772b2ed4b5d837af4cd&_callback=getYpipePP&_render=json" />

I tried:
<script type="text/javascript">
    var excuteTopCommentators = "http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&ShowHowMany=5&_id=390e906036f48772b2ed4b5d837af4cd&_callback=getYpipePP&_render=json"
    return excuteTopCommentators
</script>

I also tried document.write:
<script type="text/javascript">
    document.write('<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&ShowHowMany=5&_id=390e906036f48772b2ed4b5d837af4cd&_callback=getYpipePP&_render=json"></script>');
</script>

Neither of the attempts seem to work. Any ideas on how to do this without manually inserting the domain URL into the script src?

A: Perhaps the problem is that you get the script, but it is never executed.
Maybe try jQuery's getScript http://api.jquery.com/jquery.getscript/
function getIt() {
  return $.getScript('http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&ShowHowMany=5&_id=390e906036f48772b2ed4b5d837af4cd&_callback=getYpipePP&_render=json');
}

A: Your second option looks fine:
<script type="text/javascript">
    document.write('<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&ShowHowMany=5&_id=390e906036f48772b2ed4b5d837af4cd&_callback=getYpipePP&_render=json"></script>');
</script>

The script is downloaded but do nothing. this is because it is a JSONP, not an script
So, you need a callback function to get it working: (note that is data, not code)
<script type="text/javascript">
    // JSONP Callback
    function getYpipePP(data) {
        alert(JSON.stringify(data));
    }

    document.write('<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&ShowHowMany=5&_id=390e906036f48772b2ed4b5d837af4cd&_callback=getYpipePP&_render=json"></script>');

</script>

http://plnkr.co/edit/HhYZtH09EcdPZbwS9rfq?p=preview
Look the query, say _callback=getYpipePP and _render=json
Related: What is JSONP all about?

A: Try this (the problem you're having is the end "script" tag):
<script type="text/javascript">
        document.write('<script language="javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'
                     + window.location.hostname
                     + '&ShowHowMany=5&_id=390e906036f48772b2ed4b5d837af4cd&_callback=getYpipePP&_render=json" type="text/javascript"><\/script>')
    </script>


text:
Q: Drop down menu not working after adding jQuery Datepicker Dropdown in my navigation bar not working after adding datepicker header files and jQuery code.
My datepicker header files:
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet">

Navigation bar having dropdown which is not working

        Hello,    <?php echo $username;?>

        <a class="dropdown-item mt-2"  href='studentprofile.php?username=<?php  echo $username ?>'>
            View profile

        <a class="dropdown-item" href='changepassword.php?username=<?php  echo $username ?>'>
            Change Password

            Sign Out

A: Try changing your JQuery to


text:
Q: Joint distribution of S1 and S2 is uniform on a square when S1, S2 are uniform symmetric distributions across 0. I am reading this paper, on page 4 section 2.3 it says that the joint distribution of s1, s2 is uniform on a square when s1 and s2 are uniform distributions symmetric across 0 and  they have same distributions. Isn't this problem same as the square of a uniform distribution which is symmetric across 0, Like another question here? I'm confused why the joint distribution is uniform on square here.
$$p(s_i) = \begin{cases} \frac{1}{2\sqrt{3}}, & \text{if}  \ |s_i| \leq \sqrt{3} \\0,& \text{otherwise} \end{cases}  $$

A: This has nothing to do with symmetry. If $S_1$ is uniform on the interval $[a_1, b_1]$, and $S_2$ is uniform on the interval $[a_2, b_2]$, and the two random variables are independent, then the joint distribution of $(s_1, s_2)$ is uniform on the rectangle with vertices $(a_1, a_2)$, $(a_1, b_2)$, $(b_1, a_2)$, and $(b_1, b_2)$.
This can be seen by noting that the joint density is the product of the two marginal densities.
$$p_{S_1,S_2}(s_1, s_2) = p_{S_1}(s_1) p_{S_2}(s_2) = \begin{cases}\frac{1}{b_1-a_1} \cdot \frac{1}{b_2 - a_2} & a_1 \le s_1 \le b_1, a_2 \le s_2 \le b_2 \\ 0 & \text{otherwise} \end{cases}$$


text:
Q: Adding to array inside linked list C I currently have a text file as follows
# This is the small address book file.
# Each line of this file contains a phone book entry.
# The order of the data is: ID,Name,Telephones
#
# Note: Lines starting with # are comments and should be ignored.
#
100,Alice,0411112221
101,Bob,0411112222,0422221111
102,Ali,0411112223,0422221112,0422221113
103,Reza,0411112224
104,Ryan,0411112225,0422221114,0422221115,0422221116
105,Aaron,0411112226
106,Jessica,0411112227,0422221117
107,Xudong,0411112228
108,James,0411112229
109,Shaahin,0411112230
110,Matthew,0411112231
111,Paul
112,Elton,0411112233
113,Joe,0411112234,0422221118,0422221119,0422221120
114,Daniel,0411112235
115,Anthony,0411112236
116,Kelvin,0411112237
117,Harry,0411112238
118,Zhaowei,0411112239
119,Lei,0411112240,0422221121,0422221122,0422221123
120,Forest

I am supposed to tokenize each element separated by a comma:
ID: 100 Name: Alice Phone: 0411112221
ID: 101 Name: Bob Phone: 0411112222,0422221111

This is my load command that is supposed to read the file.
AddressBookList *commandLoad(char *fileName)
{

    AddressBookList *addressBookList;
    AddressBookNode *addressBookNode;
    AddressBookArray *addressBookArray;
    int id, i, j, count;
    char *ptr;
    char line[BUFSIZ];
    char name[NAME_LENGTH];
    char telestring[BUFSIZ];
    char telephone[TELEPHONE_LENGTH];
    FILE *fp;
    fp = fopen(fileName, "r");
    if (fp == NULL)
    {
        printf("> Failed to load\n");
        return NULL;
    }
    else
    {
        addressBookList = createAddressBookList();
        addressBookArray = createAddressBookArray();
        printf("> Opening the file ");
        printf("%s.\n", fileName);
        printf("> Loading the file ...\n");
        while (fgets(line, sizeof(line), fp) != NULL)
        {
            char *p = line;
            if (*p == '#')
                continue;
            for (i = 0, count = 0; i < line[i]; i++)
            {
                count += (line[i] == ',');
            }
            if (count == 1)
            {
                id = strtol(strtok(line, ",\n"), &ptr, 10);
                strcpy(name, strtok(NULL, ",\n"));
                addressBookNode = createAddressBookNode(id, name);
                insertNode(addressBookList, addressBookNode);
            }
            else if (count >= 2)
            {
                int j = 0;
                id = strtol(strtok(line, ",\n"), &ptr, 10);
                strcpy(name, strtok(NULL, ",\n"));
                strcpy(telestring, strtok(NULL, "\n"));
                telephone[j] = strtok(telestring, ",");
                while(telephone[j] != NULL)
                {
                    telephone[j++] = strtok(NULL, ",");
                }
                addressBookNode = createAddressBookNode(id, name);
                insertNode(addressBookList, addressBookNode);
                addTelephone(addressBookArray, telephone);
                printf("%s\n", telephone);
            }
            else
            {
                printf("Unable to load file");
            }
        }
        printf("> %d phone book entries have been loaded from the file\n", addressBookList->size);
        return addressBookList;
    }
    return addressBookList;
}

And this is my method that is supposed to add the telephone into the array.
Boolean addTelephone(AddressBookArray * array, char * telephone)
{
    int i;
    char * newTelephone = malloc(TELEPHONE_LENGTH);
    strcpy(newTelephone, telephone);
    for(i = 0; i < array->size; i++)
    {
        if(strcmp(newTelephone, array->telephones[i]) == 0)
        {
            return FALSE;
        }
    }
    array->telephones = realloc(array->telephones, sizeof(*array->telephones) *(array->size + 1));
    array->telephones[array->size] = newTelephone;
    printf("%s\n", array->telephones[array->size]);
    array->size++;
    return TRUE;
}

These are the structs that are related to this question
typedef struct addressBookArray
{
    int size;
    char ** telephones;
} AddressBookArray;

typedef struct addressBookNode
{
    int id;
    char name[NAME_LENGTH];
    AddressBookArray * array;
    struct addressBookNode * previousNode; /* The previous node in the linked-list */
    struct addressBookNode * nextNode; /* The next node in the linked-list */
} AddressBookNode;

typedef struct addressBookList
{
    int size;
    AddressBookNode * head;
    AddressBookNode * tail;
    AddressBookNode * current;
} AddressBookList;

I don't know how to add these telephones into the array.
The char ** telephone is also confusing me, I'm not sure how I am supposed to use that.


text:
Q: Writing a background program with command line interaction I'm just playing around and want to write a c++ program that monitors my CPU temperature, (i know there is no need to do it, i know i can get that info without writing a program). I'm willing to design the whole thing as a background process in linux and be able to communicate with it via command line.
let's say my program name is: cputemp
i want to be able to run the command cputemp -temp and get the temp values.
I've never done anything like this before and hope you guys can help me out

A: You need to write a daemon. Daemons are background processes without user interactions. You can call it cputempd.
Then you need to make a client called cputemp that connects to your daemon and gets information.
Writing daemons is explained here with further references: Creating a daemon in Linux
For communication between your client program and your daemon there are different methods of Interprocess Communication although you can simply use socket programming.
on IPC: http://www.tldp.org/LDP/lpg/node7.html


text:
Q: Create a file in /public using dist file I'm using Play 2.5 and I have written a code, in Java, to create a file in /app/public folder, I parametrized the path in application.conf. After that I created a dist file and when I tried to call that method from my dist file, the file is not getting generated in /public folder. Is it not able to detect the path?
file.create{
  path = "public/"
}
Edit: Java Code -
String filePath = conf.getString("file.create.path") + "Excel_file.xlsx";
FileOutputStream fos = new FileOutputStream(filePath);


text:
Q: Testing that an $interval gets fired 3 times in AngularJS I have an AngularJS service that looks like this (I've removed the unrelevant code):
myApp.factory('myService', ['$interval', function ($interval) {
  return {
    startWatch: function(onSuccess) {
      var watcher = $interval(onSuccess, 250);
      return watcher;
    },

    stopWatch: function(watcher) {
      $interval.cancel(watcher);
    }
  };
}]);

To test this service, I have the following:
describe('myApp', function() {
    beforeEach(function() {
        module('myApp');
    });

    describe('myService', function () {
        var myService = null;
        beforeEach(inject(function (myService) {
            myService = myService;
        }));

        it('should run successfully 3 times', function() {
          var count = 0;

          var w = myService.startWatch(function() {
            count = count + 1;
            console.log('fired ' + count + ' times.');
          });
        });
    });
});

When the test gets ran, it just races through it one time. I do not understand how to actually test 1. the interval piece 2. the number of times it gets fired. There will be information in the service that changes over time. I want to test that the information is behaving as expected. For that reason, I'm trying to test a number of things over time. How do I do this?
Thank you for your help!

A: Try $interval.flush(millis):
describe('myApp', function() {
    beforeEach(function() {
        module('myApp');
    });

    describe('myService', function () {
        var myService = null;
        var $interval = null;
        beforeEach(inject(function (myService) {
            myService = myService;
            $interval = _$interval_;
        }));

        it('should run successfully 3 times', function() {
          var count = 0;

          var w = myService.startWatch(function() {
            count = count + 1;
          });

          $interval.flush(751); // greater than 250 * 3
          expect(count).toEqual(3);
        });
    });
});

Remember to reference angular mock to your test: http://code.angularjs.org/1.2.0/angular-mocks.js .The version should be the same with your angular version.


text:
Q: In C# How to verify JWT using ECDSA public key which was signed with ECDSA private key I want to verify jwt which was signed through ECDSA SHA256 algorithm. Dot net library I am using is System.IdentityModel.Tokens.Jwt .
I have access to public key.

A: If you have the access to the public key, one way of doing it is to utilise JwtSecurityTokenHandler class which is also used to generate the Jwt. It is under the same namespace (System.IdentityModel.Tokens).
Sample code:
bool ValidateEcdsa384JwtToken(string tokenString, ECDsa pubKey)
{
    try
    {
        var securityToken = new JwtSecurityToken(tokenString);
        var securityTokenHandler = new JwtSecurityTokenHandler();
        var validationParameters = new TokenValidationParameters() {
            ValidIssuer = securityToken.Issuer,
            ValidAudience = securityToken.Audiences.First(),
            IssuerSigningKey = new ECDsaSecurityKey(pubKey)
        };

        SecurityToken stoken;
        var claims = securityTokenHandler.ValidateToken(tokenString, validationParameters, out stoken);
        return true;
    }
    catch (System.Exception e)
    {
        return false;
    }
}

A: // using System.Security.Cryptography;
// using System.Text.RegularExpressions;
// using Microsoft.IdentityModel.Tokens;

// `openssl ecparam -name prime256v1 -genkey -noout -out es256-private.pem`
// `openssl ec -in es256-private.pem -pubout -out es256-public.pem`
const string es256PublicKey = @"-----BEGIN PUBLIC KEY-----
  MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEWWNSXIcIZ7iKiSnNVOzzkZEEpDvf
  sPux0GlqPl1aamHIiZgj364xcIrmaazMb1dsZaNBGLyvyJk0xRKk7BSSrg==
  -----END PUBLIC KEY-----";

// Remove all whitespace and also remove '-----XXX YYY-----'
// '\s+' Matches one or more whitespace characters
// '|' Is a logical OR operator
// '(?:        )' Is a non-capturing group
// '-+[^-]+-+' Matches one or more hyphens, followed by one or more non-hyphens, followed by one or more hyphens
var pemData = Regex.Replace(es256PublicKey, @"\s+|(?:-+[^-]+-+)", string.Empty);

var keyBytes = Convert.FromBase64String(keyData);

// Example of DER encoded P-256 curve at https://tools.ietf.org/html/rfc5759
var pointBytes = keyBytes.TakeLast(64);
var pubKeyX = pointBytes.Take(32).ToArray();
var pubKeyY = pointBytes.TakeLast(32).ToArray();

var ecdsa = ECDsa.Create(new ECParameters
  {
    Curve = ECCurve.NamedCurves.nistP256,
    Q = new ECPoint
    {
      X = pubKeyX,
      Y = pubKeyY
    }
  });

var tokenValidationParameters = new TokenValidationParameters
  {
    IssuerSigningKey = new ECDsaSecurityKey(ECDsaPublic.Value),
    ValidAlgorithms = new[]
    {
      @"ES256"
    }
  };

// https://stackoverflow.com/a/39974628/414655
var handler = new JwtSecurityTokenHandler();
var claimsPrincipal = handler.ValidateToken(jwt, tokenValidationParameters, out SecurityToken securityToken);


text:
Q: Adding JavaScript Command to a buttom in an existing template in Magento I'm using a 3rd Party Checkout and I want over override there login feature with a custom login.
Here is the code that I am working with in Magento.
<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>

<?php echo $this->__('LOGIN')?>


text:
Q: How to display validation messages in Windows Phone 8 I want to display Windows Phone 8 page validations in an elegant and unit testable manner.  I am thinking about using DataBinding rather than MessageBox modal messages.  What is the standard or best practice for Windows Phone?
Thanks in advance.

A: I would follow the Telerik controls style, or use them anyway, they have a TextBox with validation and I think is a simple binding to an errors collection. You can download the Telerik Examples apps to test it in your phone and see if you like the implementation.


text:
Q: python + variable doing wrong math I have posted data coming from a webform, and I am trying to convert lb's to oz's for shipping labels.
The webform is set to just post numbers.
<input type="number" step="1" name="lbs" id="lbs" class="form-control input-lg" placeholder="Lb's" tabindex="7">

Below is the python code
llb = request.form['lbs']
lw = (llb*16)
return lw

It always returns the wrong number.
2 for llb returns 2222222222222222 when it should be 32. I tried messing with 0o16 etc with no success.
I even tried making sure llb was an int with
llb = int(request.form['lbs'])

I can't figure this out for the life of me. For all I know I could be over thinking this.
I even tried everything mentioned on Wrong math with Python? and a few others I could find simlar.

A: Try:
llb = request.form['lbs']
lw = (int(llb)*16)
return lw

Since your request.form['lbs'] is str type you need to cast it to int type before multiplication.
Multiplication sign * works with strings in such a way that it copies them given amount of times.
Example:
'^'*5
>> '^^^^^'

EDIT
Your problem seems to be that you have overwritten the built-in int with some other variable.
Example:
>>> lbs = '2'
>>> lbs
'2'
>>> lw = lbs*16
>>> lw
'2222222222222222'
>>> lw = int(lbs)*16
>>> lw
32
>>> int = 7
>>> lw = int(lbs)*16
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del int
>>> lw = int(lbs)*16
>>> lw
32

You should never overwrite built-in names such as int, list, set, dict and so on: Why can you assign values to built-in functions in Python?

A: llb variable is a string. You need to cast it if you want an int.
'2'*16 will print 16 times the character 2.
If llb is supposed to be an int, just do:
lw = (int(llb)*16)


text:
Q: Orthogonal polynomial expansion for bivariate noncentral chi-square and bi-variate noncentral student t distribution This is a research question for which I am not able to find any existing reference. So, I am reaching out for help. The project is related to studying the sequence of rejections in multiple hypothesis testing. But I cannot give out details on my strategy.
However, a key step is to obtain orthogonal polynomial expansion for bi-variate noncentral chi-square and bi-variate noncentral student t distribution. I have searched online but was only able to find such expansion for univariate non-central chi-square and univariate non-central student t distribution.
I would greatly appreciate if you can point out a general method (or reference, if existent) to construct orthogonal polynomials with respect to bi-variate densities (different thant that given by G. K. Eagleson's "Polynomial expanions of bivariate distributions" and Meixner's paper cited therein, since the methods there do not seem to work for bi-variate non-central chi-square or student t distribution). Thank you in advance.
Best regards,
Chee


text:
Q: search multiple ora error messages using java regular expressions I´m trying to figure out how to search multiple ora error messages using java regular expressions: ORA-6XXX , ORA-1578 , ORA-0060, ORA-01157 and ORA-27048
I have found for ORA-6XXX would be: ORA-6[0-9][0-9][0-9] but if I want to add/include the other ORA error #, Which regular expression will meet this?
Thanks in advance!

A: Try this expression
ORA-\d+. That will give you any number of digits.

A: Simply try
ORA-[0-9]{4,5}$

Which is allow ORA-XXXX or ORA-XXXXX

A: I am not sure what you need so

*

*if you want to accept ORA with number containing 3, 4 or 5 digits then you can use ORA-\\d{3,5}

*if you want to accept ORA with any 3 digits but for 4 digits only 1578 , 0060 and for 5 digits only 01157, 27048 then try
ORA-(\\d{3}|1578|0060|01157|27048)(?!\\d)

This will accept ORA with any 3 digits OR 1578 OR 0060 OR 01157 OR 27048 after it. Additionally I make sure that there is no digit after this match.


text:
Q: how do I allow cross origin resource sharing? I don't know why my ajax CORS doesn't work..
ajax
 $(document).ready(function(){
        var xhr = new XMLHttpRequest();
        $.ajax({
            url: "SERVER_URL_AND_PARAMETERS",
            type:"POST",
            beforeSend:function(xhr){
                xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
                xhr.setRequestHeader("Access-Control-Allow-Methods", "GET, POST");
            },
            dataType:"json",
            crossDomain: true,
            success:function(data, textStatus, xhr){
                alert(data);
            },
            error:function(xhr,status,error){
                alert("code:"+xhr.textStatus+"\n"+"message:"+error.responseText+"\n"+"error:"+error.log);

            }

        });

    });

response headers
 Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
    Cache-Control:no-cache="set-cookie, set-cookie2"
    Connection:Keep-Alive
    Content-Language:ko-KR
    Content-Length:0
    Content-Type:text/plain
    Date:Mon, 02 Nov 2015 07:19:54 GMT
    Expires:Thu, 01 Dec 1994 16:00:00 GMT
    Keep-Alive:timeout=10, max=100
    Set-Cookie:SOME_COOKIES; Expires=Tue, 01-Nov-16 07:19:53 GMT; Path=/
    X-UA-Compatible:IE=EmulateIE8, requiresActiveX=true

request headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, access-control-allow-headers, access-control-allow-methods, access-control-allow-origin
Access-Control-Request-Method:POST
Connection:keep-alive
Host:SERVER_URL
Origin:http://CLIENT_URL
Referer:http://CLIENT_URL/AND/JSP_FILE_PATH.jsp?lineCd=CODE1&prdtCode=CODE2
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36

chrome error detail
MLHttpRequest cannot load SERVER_URL_AND_PARAMETER Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'CLIENT_URL' is therefore not allowed access.

I don't know what is the problem on my code. I am working on CLIENT_URL side web application.

A: CORS headers such as "Access-Control-Allow-Origin" MUST be set by the server, not by the client.  It is the server that grants CORS access to clients, not the other way around.  You can't give yourself CORS access from the browser.
From the MDN section on CORS, here's a descriptive quote:

The Cross-Origin Resource Sharing standard works by adding new HTTP
  headers that allow servers to describe the set of origins that are
  permitted to read that information using a web browser.  Additionally,
  for HTTP request methods that can cause side-effects on user data (in
  particular, for HTTP methods other than GET, or for POST usage with
  certain MIME types), the specification mandates that browsers
  "preflight" the request, soliciting supported methods from the server
  with an HTTP OPTIONS request method, and then, upon "approval" from
  the server, sending the actual request with the actual HTTP request
  method.  Servers can also notify clients whether "credentials"
  (including Cookies and HTTP Authentication data) should be sent with
  requests.

In particular, note the part that says "allow servers to describe the set of origins that are permitted to read that information using a web browser".


text:
Q: How to get the client app (not user) IP or domain with Laravel - Angular I want to check if the incoming requests come from few allowed domains (my own angular clients), so I could secure my app even if the token is sent in each request.
I've tried (from my online app) to access the ip address  with $request->getClientIp(); but I always get the same ip: 172.17.0.1 when I acces from postman and the angular client.
I've also tried to get the origin and User-Agent, but it's very easy to change the header from postman, so it would not be secure.
Is there any way to know the client app domain or ip (which is secure over https) from the Laravel restful app?
Edit:
I'm serving my app over Dokku


text:
Q: Update statement not working getting error ORA-01031: Insufficient privileges My update table query not working. if i am runing this query as a sub part it's working but as soon as i am runing as a whole it giving me exception  ORA-01031: Insufficient privileges.
 declare
         var_sqlString varchar2(2500);
         begin
    var_sqlString :='UPDATE (select ''A''||registration_id from sde.table_registry where table_name=''OPENPOINT'' and OWNER=''EDGIS'')
    SET OPERATINGVOLTAGE=''21'' where GLOBALID=''{3B5C4257-12D8-4CA9-82E4-427AC9D79BB0}''' ;
    dbms_output.put_line(var_sqlString);
          EXECUTE immediate var_sqlString;
          commit;
         end;

When i am executing this query dbms_output.put_line giving me bellow result.
UPDATE (select 'A'||registration_id from sde.table_registry where table_name='OPENPOINT' and OWNER='EDGIS')
SET OPERATINGVOLTAGE='21' where GLOBALID='{3B5C4257-12D8-4CA9-82E4-427AC9D79BB0}'

And when i am runing the above query than also i am getting the same error. Now the problem is when i am executing part one which is: select 'A'||registration_id from sde.table_registry where table_name='OPENPOINT' and OWNER='EDGIS'
Its giving me the result  which is A126 and then i am passing that result in my update statement, the update statement works fine. But as a whole is not working .....???

A: The error Insufficient privileges tells you that you are not allowed to do an UPDATE statement on this table.
Check the user rights on the user you are using for this query. You should grant UPDATE privileges for the user you are using.
You can read the Oracle documentation on how to manage user privileges.

A: I Found the solution, Problem was Oracle was treating table retrieval statement as a whole staring not a table, So that was the cause of my problem. So i added select statement at the beginning of my query and got the output.
So updated query would be
set serveroutput on
declare
     var_sqlString varchar2(2500);
     begin

select 'UPDATE edgis.' ||
(select 'A'||registration_id from sde.table_registry where table_name='OPENPOINT' and OWNER='EDGIS')
|| ' SET OPERATINGVOLTAGE=''21'' where GLOBALID=''{3B5C4257-12D8-4CA9-82E4-427AC9D79BB0}'''  into var_sqlString from dual;
dbms_output.put_line(var_sqlString);
      EXECUTE immediate var_sqlString;
     commit;
     end;

Thanks! For helping me but i found the solution.


text:
Q: Big problems with MFC/WinAPI I need to create a SDI form with a formview that has two tabs, which encapsulate multiple dialogs as the tab content. But the form has to have a colored background.
And things like these makes me hate programming.
First, I tried CTabControl, via resource editor, tried different things, but the undocumented behavior and the quirks with no answers led me into a roadblock.
After many hours of searching, I found that there is a control called property sheet, which is actually what I need.
Some more searching later, I found that property sheet can even be actually embedded onto CFormView like so: http://www.codeguru.com/Cpp/controls/propertysheet/article.php/c591
And that the dialog classes derived from CPropertyPage can be directly added as pages via AddPage method of CPropertySheet.
Great! Not quite so... Some of the controls didn't worked, and were not created, ran into weird asserts. Turns out the DS_CONTROL style was missing from the dialogs. Found it completely accidentaly on Link, no word about that on MSDN!!!! Property page must have: DS_3DLOOK | DS_CONTROL | WS_CHILD | WS_TABSTOP, and can have: DS_SHELLFONT | DS_LOCALEDIT | WS_CLIPCHILDREN styles! Not any other, which are created by default with resource editor. Sweet, super hidden information for software developers!
The quote in comments on that page: "OMG.  That's where that behavior came from...
It turns out that the PlaySound API relied on that behavior when playing sounds on 64bit machines." by Larry Osterman, who as I understand works for Microsoft for 20 years, got me laughing out loud.
Anyway, fixed that, the dialog-controls(CPropertyPages) are created as expected now, and that part looks something remotely promising, but the next part with color is dead end again!
Normally you override WM_CTLCOLOR, check for control ID or hwnd and supply the necessary brush to set the color you need. Not quite so with CPropertySheet, the whole top row stays gray! For CTabCtrl it somehow works, for CPropertySheet it doesn't.
Why? Seems that the CPropertySheet is kinda embedded inside CTabControl or something, because if I override WM_ERASEBKGND, only the internal part changes the color.
Now it seems that there is a GetTabControl() method in the CPropertySheet, that returns the actual CTabCtrl* of the CPropertySheet. But since it's constructed internally, I can't find how to override it's WM_CTLCOLOR message processing.
There seems to be a way to subclass the windowproc, but after multiple tries I can't find any good source on how to do it. SubclassWindow doc on MSDN says: "The window must not already be attached to an MFC object when this function is called."?! What's that?
I tried creating a custom CCustomTabCtrl class based on CTabCtrl via MFC wizard, created an instance of it, called SubclassWindow from one of the CCustomPropertySheet handlers to override the internal CTabCtrl, but nothing works, mystical crashes deep inside MFC.
Tried setting WindowLong with GCL_HBRBACKGROUND for the internal CTabCtrl, nothing changed.
And worst of all, I can't find any sort of useful documentation or tutorials on the topic.
Most I can find is how to ownerdraw the tab control, but this is seriously wrong on so many ways, I want a standard control behavior minus background color, I don't want to support different color schemes, windows versions, IAccesible interfaces and all this stuff, and none of the ownerdraw samples I've seen can get even 10% of all the standard control behavior right. I have no illusion that I will create something better, I wont with the resources at hand.
I stumbled upon this thread, and I can't agree with the author more: http://arstechnica.com/civis/viewtopic.php?f=20&t=169886&sid=aad002424e80121e514548d428cf09c6 owner draw controls are undocumented PITA, that are impossible to do right, and there is NULL information on MSDN to help.
So is there anything I have missed or haven't tried yet? How to change the top strip background color of the CPropertySheet? Anyone?

A: Your only option is to ownerdraw the tab control. It's not that hard. Well, it is frustrating because MFC doesn't tell you how to make the necessary Win32 calls.
In your CPropertySheet-derived class, overwrite OnInitDialog() and add:
GetTabControl()->ModifyStyle(0,TCS_OWNERDRAWFIXED);
This puts your CPropertySheet-derived class in charge of drawing the tab control. Add a handler for WM_DRAWITEM (OnDrawItem) and change backgroundColor and textColor to match whatever colors you wanted. Code for OnDrawItem follows:
void CPropSht::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{
    if (ODT_TAB != lpDrawItemStruct->CtlType)
    {
        CPropertySheet::OnDrawItem(nIDCtl, lpDrawItemStruct);
        return;
    }

    // prepare to draw the tab control
    COLORREF backgroundColor = RGB(0,255,0);
    COLORREF textColor = RGB(0,0,255);
    CTabCtrl *c_Tab = GetTabControl();

    //  Get the current tab item text.
    TCHAR buffer[256] = {0};
    TC_ITEM tcItem;
    tcItem.pszText = buffer;
    tcItem.cchTextMax = 256;
    tcItem.mask = TCIF_TEXT;

    if (!c_Tab->GetItem(c_Tab->GetCurSel(), &tcItem )) return;

    // draw it
    CDC aDC;
    aDC.Attach(lpDrawItemStruct->hDC);
    int nSavedDC = aDC.SaveDC();

    CBrush newBrush;
    newBrush.CreateSolidBrush(backgroundColor);
    aDC.SelectObject(&newBrush);
    aDC.FillRect(&lpDrawItemStruct->rcItem, &newBrush);
    aDC.SetBkMode(TRANSPARENT);
    aDC.SetTextColor(textColor);
    aDC.DrawText(tcItem.pszText, &lpDrawItemStruct->rcItem, DT_CENTER|DT_VCENTER|DT_SINGLELINE);

    aDC.RestoreDC(nSavedDC);

    aDC.Detach();
}

A: Thank you for this solution but...
The above solution works well with one tab, but when you have multiple tabs it seems rename the wrong tabs. I needed to change the if statement for GetItem to:
if (!c_Tab->GetItem(lpDrawItemStruct->itemID, &tcItem )) return;

Needed lpDrawItemStruct->itemID to get the tabs named correctly


text:
Q: fmod function returning wrong result I'm getting fmod returning wrong result, am i doing anything wrong?
for($i = 0.00; $i < 1; $i = $i + 0.05) {
    var_dump($i." = ".fmod($i, 0.05));
}

Output:
0.= 0
0.05 = 0
0.1 = 0
0.15 = 1.3877787807814E-17
0.2 = 0
0.25 = 0.05
0.3 = 0.05
0.35 = 0.05
0.4 = 0.05
0.45 = 0.05
0.5 = 0.05
0.55 = 0.05
0.6 = 0.05
0.65 = 0.05
0.7 = 2.7755575615629E-17
0.75 = 6.9388939039072E-17
0.8 = 1.1102230246252E-16
0.85 = 1.5265566588596E-16
0.9 = 1.942890293094E-16
0.95 = 2.3592239273285E-16

I was expecting every result to be the same: 0.

A: First, fmod is exact. Because it can: when x and y are floating-point numbers, the mathematical result of fmod(x,y) can be represented exactly as a floating-point number.
Second, when you write 0.05, you do not get exactly that number, because 5/100 on the other hand cannot be represented exactly as a floating-point number; and when you write +, you do not get mathematical addition in general because the result of that mathematical addition cannot always be represented as a floating-point number(*).
Starting from 0.0 and repeatedly adding 0.05 will soon get you into inaccurate + territory, because in binary, the best representation of 0.05 has many digits. As the sum gets larger, the last digits progressively have to be dropped. This is where the inaccuracy of + comes from, and ultimately is the reason why fmod does not give you the results you expect.
It wouldn't matter that 0.05 is not exactly 5/100 if repeatedly adding it to zero always was exact. But since the floating-point number 0.05 has many digits in binary (as opposed to decimal) and since some of these digits must be lost when computing multiples of 0.05, the value you get for most multiples y of 0.05 when computing fmod(y, 0.05) is not zero but represents the difference between the mathematical multiplication of the appropriate integer by 0.05 and the approximation y of that number.
(*) when the mathematical sum can be represented, the mathematical sum is what you get, but sometimes it just cannot.

A: This answer relates to the first revision of the question:
https://stackoverflow.com/revisions/28372286/1
All is working fine! You can calculate it for yourself:
fmod(0.5, 0.25);
fmod(0.5, 0.23);
fmod(0.5, 0.20);

0.25 * 2 = 0.50   | Rest 0.00
0.23 * 2 = 0.46   | Rest 0.04
0.20 * 2 = 0.40   | Rest 0.10


text:
Q: How to use structs for column names and values? I'm playing around with Spark in Scala. I have this structure:
case class MovieRatings(movieName: String, rating: Double)
case class MovieCritics(name: String, movieRatings: List[MovieRatings])

The first class a movie and a rating given by some critic. It could be something like this:
MovieRatings("Logan", 1.5)

and a second class that accepts the name of the critic and a list of movies classified by him. With this I've come up with a List of MovieCritics and each element of the list has a name and a list of MovieRatings.
So far so good. Now I want to transform this List in a spark dataFrame to display the data in a more user friendly. Something like this:
Critic | Logan | Zoolander | John Wick | ...
Manuel    1.5       3            2.5
John      2         3.5          3
...

The firs column reflects the movie critic and the following columns represent the movie and the respective rating given by the critic.
My question is how to transform a
List(MovieCritics(name: String, movieRatings: List[MovieRatings]))

in that view.

A: If you have data of movies as
val movieCritics = List(
  MovieCritics("Manual", List(MovieRatings("Logan", 1.5), MovieRatings("Zoolander", 3), MovieRatings("John Wick", 2.5))),
  MovieCritics("John", List(MovieRatings("Logan", 2), MovieRatings("Zoolander", 3.5), MovieRatings("John Wick", 3)))
)

You can create dataframe just by calling toDF as
import sqlContext.implicits._
val df = movieCritics.toDF

Which should be
+------+-----------------------------------------------+
|name  |movieRatings                                   |
+------+-----------------------------------------------+
|Manual|[[Logan,1.5], [Zoolander,3.0], [John Wick,2.5]]|
|John  |[[Logan,2.0], [Zoolander,3.5], [John Wick,3.0]]|
+------+-----------------------------------------------+

Now simple select from above dataframe should get you the output you need
import org.apache.spark.sql.functions._
df.select(col("name"), col("movieRatings")(0)("rating").as("Logan"), col("movieRatings")(1)("rating").as("Zoolander"), col("movieRatings")(2)("rating").as("John Wick")).show(false)

This should result the final dataframe as
+------+-----+---------+---------+
|name  |Logan|Zoolander|John Wick|
+------+-----+---------+---------+
|Manual|1.5  |3.0      |2.5      |
|John  |2.0  |3.5      |3.0      |
+------+-----+---------+---------+

A:
how to transform List(MovieCritics(name: String, movieRatings: List[MovieRatings]))

That's as simple as using toDS on the List. That is only available when you have SparkSession's implicits in scope which is (again) as simple as the following:
val sparkSession = SparkSession.builder.getOrCreate()
import sparkSession.implicits._

If you work with scala.collection.immutable.Iterable[MovieCritics] or similar collection data structure you have to "map" it using toSeq or toArray before toDS to "escape" from Iterable. Implicits are not available for Iterables.
Given the list is critics you'd have to do the following:
critics.toDS

Now I want to transform this List in a spark dataFrame to display the data in a more user friendly.

That's the most entertaining part of your question (took me a couple of hours to finally understand and write a solution). I'd appreciate comments to make it prettier.
case class MovieRatings(movieName: String, rating: Double)
case class MovieCritics(name: String, movieRatings: Seq[MovieRatings])
val movies_critics = Seq(
  MovieCritics("Manuel", Seq(MovieRatings("Logan", 1.5), MovieRatings("Zoolander", 3), MovieRatings("John Wick", 2.5))),
  MovieCritics("John", Seq(MovieRatings("Logan", 2), MovieRatings("Zoolander", 3.5), MovieRatings("John Wick", 3))))

With the input dataset set, here comes the solution.
val ratings = movies_critics.toDF
scala> ratings.show(false)
+------+-----------------------------------------------+
|name  |movieRatings                                   |
+------+-----------------------------------------------+
|Manuel|[[Logan,1.5], [Zoolander,3.0], [John Wick,2.5]]|
|John  |[[Logan,2.0], [Zoolander,3.5], [John Wick,3.0]]|
+------+-----------------------------------------------+

val ratingsCount = ratings.
  withColumn("size", size($"movieRatings")).
  select(max("size")).
  as[Int].
  head

val names_ratings = (0 until ratingsCount).
  foldLeft(ratings) { case (ds, counter) => ds.
    withColumn(s"name_$counter", $"movieRatings"(counter)("movieName")).
    withColumn(s"rating_$counter", $"movieRatings"(counter)("rating")) }

val movieColumns = names_ratings.
  columns.
  drop(1).
  filter(name => name.startsWith("name")).
  map(col)
val movieNames = names_ratings.select(movieColumns: _*).head.toSeq.map(_.toString)
val ratingNames = movieNames.indices.map(idx => s"rating_$idx")
val cols = movieNames.zip(ratingNames).map { case (movie, rn) =>
  col(rn) as movie
}
val solution = names_ratings.select(($"name" +: cols): _*)
scala> solution.show
+------+-----+---------+---------+
|  name|Logan|Zoolander|John Wick|
+------+-----+---------+---------+
|Manuel|  1.5|      3.0|      2.5|
|  John|  2.0|      3.5|      3.0|
+------+-----+---------+---------+

A: ratings.selectExpr("name","explode(movieRatings) as mr").select("name",
"mr.movieName", "mr.rating")
.groupBy("name")
.pivot("movieName")
.agg(first("rating"))
.show(10,false)


text:
Q: Laws of Motion: A man pushing an immovable wall
If a man pushes an immovable, rigid wall while standing on rough ground, would the man be in equilibrium?

Here's my attempt:
The man would be in equilibrium in the vertical direction, since gravitational force (due to Earth) on the man; and the normal reaction force from the ground to the man cancel out each other.
The horizontal direction is what I'm not too sure about. The wall would certainly push back on the man. Would friction (due to rough ground) act on the man in the opposite direction? If it does, wouldn't its value be at maximum $\mu N$? Since the man can exert a force larger than it's own weight, shouldn't the equilibrium state depend on the force exerted by the man?

A: We could consider two ways a man could push on the wall, one is by using his weight and the other by using his muscles.
To illustrate and, if needed, to analyze the action of the weight, we could just use a log.

Here red arrows represent forces acting on the log, while blue arrows represent forces the log exerts on the wall and the floor.
From this picture, we can see that the weight is balanced by the vertical component of the floor reaction and the wall friction force, which provides additional support for the log.
The horizontal equilibrium is achieved between the friction force on the floor and the horizontal reaction of the wall.
If the log position is close to vertical, its push on the wall is very weak, since there is a very short lever for the weight to develop any significant force. A man would have to lean, at least a little bit, to produce any horizontal push without using muscles.
If the log position is close to horizontal, the total force on the wall is more significant, but its horizontal component is getting close to nothing. Also, we can expect that, due to the reduced pressure on the floor, the friction force will be very low and the log will be likely to slip.
So, we must conclude that the log will exert a maximum horizontal push on the wall when it is at some intermediate angle and that push will not exceed a fraction of its weight.
The action of man's muscles could be simplistically modeled as a compression spring pinned at some angle between the wall and the floor and pushing on both. As shown on the picture below with green arrows, these spring-like forces originate somewhere in the man's core.

Of course we still have to have equilibrium between all horizontal and vertical forces, but the forces are not limited by man's weight. One of the differences here is that, if the man is moderately strong, the net vertical component of of the force he exerts on the wall could be pointing up (not down as was the case with the log). Correspondingly, the wall is pushing down.
As a result, the pressure on the floor could significantly exceed man's weight and therefore the resulting high friction force could balance very strong horizontal reaction of the wall. The assumption here is that floor and wall surfaces are reasonably coarse.
So, again, by using his muscles, a man can not only significantly increase the horizontal push on the wall (in comparison with the weight based mechanism), but, by directing his push upwards, he can also increase the pressure on the floor and, therefore, the friction force, which can balance the horizontal reaction of the wall.


text:
Q: How to read array values in Javascript? I have a response from PHP I am trying to read this on JS but didn't get the value. I want to get the value of responseCode. But it returns me undefined.

Response Code :

Array
(
    [request] =>
    [receiptId] => 11233-555
    [responseCode] => 0
    [message] => PSI-3217:Maximum number of attempts reached.
    [transTime] => 4/2/2021 8:50:09 PM
    [merchantEmail] => johndoe@gmail.com
    [merchantId] => 19
)

JS Code :

           $.ajax({
                method: "POST",
                url: "https://john.com/ca/pay.php",
                data: objData,
                success: function (data, status) {

                    console.log(data['responseCode']);

                },
                error: function (error) {
                }
            })

A: Simply use "json_encode" in your php code and return to the request the array in json