text:
Q: How can I create an AD user via PowerShell prompting for options? I'm trying to create a PowerShell script which will create users based on template users I've created. The initial steps I'm trying to figure out are below:

*

*Upon execution of the script show a prompt asking for the employee's name

*Next show a prompt asking what department the user will work for (the departments should be linked to the template AD users to copy their group memberships)

*Next ask their location which will automatically add some group memberships

Can somebody please point me in the right direction of how I would go about getting started with this script?
Thanks in advance for any assistance!

A: Well, to prompt for user input you want to use the Read-Host cmdlet, such as
$name = Read-Host -Prompt 'Enter your name'

The most up to date information can be found on Microsoft's website for the cmdlet. I hope this points you in the right direction.
Beware, this is not suitable for password prompts!

A: This TechNet article and its children give you a very broad range of cmdlets related to Active Directory, most of which are very intuitively named. You'll probably be interested in ones such as:

*

*New-ADUser

*Add-ADGroupMember

*Add-ADPrincipalGroupMember
As mentioned in Answer #1, Read-Host will let you prompt for input.
In order to process a number of different options for location as per the third bullet point in your question, you may use a switch statement.
$Location = Read-Host "Enter user's location"
Switch ($Location) {
   "First Floor" { } #Add code to add user to First Floor Groups
   "Second Floor" { }
}

One issue you may run into here is that there is a very wide range of what the users of this script could potentially enter for the location, such as "First Floor" versus "first floor" versus "1st floor." As such, you may want to up the ante a bit and use System.Management.Automation.Host.ChoiceDescription for this task instead of Read-Host. Take a look at this TechNet article for more information.


text:
Q: UWP Ad Controls are broken I have a UWP app, published in store, here. The app hosts AdControl in some pages and the current version of the app has AdControl but I have no way of confirming if the app is working on other systems but it's not working on my laptop (Windows 10 Creators Update - clean install).
This issue has just recently popped up when my Store submission failed twice and the reason was that my app wasn't launching at all. The app was working fine in Debug mode but when I compiled the app in Release mode, it was actually not working. I have no other windows systems to check if it is a system specific issue just related to my laptop or maybe it is related to AdControls everywhere.
If the pages in my app doesn't have a AdControl the app works fine. I debugged the code and it would not pass through the Page Initializing function, and there I found out that while initializing the pages, the last thing to pass through was the AdControl and when I removed the AdControl the app was working fine and it would still navigate to those pages without AdControl.
Did someone else experience this issue? Maybe download my app and let me know if it works on your system.
this is how I am using the AdControl:
    xmlns:ads="using:Microsoft.Advertising.WinRT.UI"
    <ads:AdControl Grid.Row="4"
                   x:Name="Movies_AdControl"
                   Margin="0,10,0,0"
                   AutoRefreshIntervalInSeconds="15">
    </ads:AdControl>

and also in the VisualStateGroup
    <Setter Target="Movies_AdControl.Height"
            Value="50"/>
    <Setter Target="Movies_AdControl.Width"
            Value="320"/>

A: @Ahmar, there is a known issue with the Windows 10 UWP AdControl that started about a week ago. Unfortunately the AdControl is part of the framework ad sdk which means Microsoft can push out updates to it any time and break all the apps that use it (which is exactly what they did last week).
The reason your new project might work is because you are doing very little other work in the Page contructor. It seems to be a timing glitch that prevents the Loaded event from ever firing (not all of the controls on the page initialize). Try putting a bunch of other controls on the page and you might be right back to having the problem.
The good news is that the problem was finally fixed with the Ad SDK 10.0.5 which has internal version numbers of 10.1705.11001. The bad news is that even if you build your app with that version of the sdk and submit it to the Windows Store, it is still possible that your users have the older broken sdk and until that update is pushed to everybody, there will be problems.
The idea of store framework packages is a bad idea to me. Good in theory due to smaller downloads and potentially rapid and automatic deployments by Microsoft, but bad when Microsoft is sloppy like they were here.
Discussion:
https://social.msdn.microsoft.com/Forums/windowsapps/en-US/1d5e1f23-bd61-4384-b55c-2d0cae8d4a03/new-adcontrol-freezes-apps?forum=aiasdk

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copy files from pwd to another directory using Python I'd like to copy all files in my present working directory to another location.
I have tried variations of the below:
import shutil
shutil.copyfile('/*','/my/other/directory/location')

This gives the error: OSError: [Errno 2] No such file or directory: '/*'
I am thinking about using os.system and the cp command.
Has anyone got any better ideas?

A: I would use shutil. Is there a problem with that ?
Personally I tend to use:
shutil.copytree(src, dst, symlinks=False, ignore=None)

as it takes subdirs
update------
To get the current working directory use
os.getcwd()


text:
Q: What sort of drivers are used to connect Node.js applications to a database? If this question is inappropriate for stackoverflow please feel free to remove this question.
Typically when we connect to relational databases from applications (e.g. Java or .Net), a JDBC or ODBC driver is used.
What driver does a Node.js application use to connect to databases? It appears that there isn't a standard way (similar to JDBC or ODBC).
I observed that each vendor provides a driver for Node.js.
Here are a couple that I searched for MS SQLServer and Oracle.

*

*Node.js Driver for SQL Server

*Oracle Database driver for Node.js
There are other node.js libraries, some that uses ODBC under the covers.Is there a standard around this space (similar to JDBC for Java)?
Though this question is specifically for RBDMS, it is applicable to NoSQL databases too.
Note: I primarily use Java/JEE (and its ecosystem) for my solutions.

A: There is no standard Database access API for Node.js. However if you like the JDBC APIs you can use a JDBC driver in your Node application with Avatar.js. This works fine with Oracle's UCP and JDBC thin driver (and maybe other drivers). This technique requires a thread pool to turn the blocking JDBC calls into non-blocking calls. At 2016's JavaOne, new asynchronous Database APIs for Java were presented which will hopefully be part of JDK10 and when that happens these APIs will fit quite nicely from within Node.js.


text:
Q: Multiple redis calls or single call to Mongo or another DB engine I understand redis is fast and I find that I can implement many things using just redis. But at the expense of making multiple queries for example. In I use Mongo, I might have a model/schema like:
Chatrooms (Mongo)

*

*_id: ObjectId

*name: string

*users: array

With redis I need something abit more complex

*

*chatrooms:<<id>> where id needs to be manually generated

*

*name

*chatrooms:<<id>>:users to store the set of users

To retrieve chatroom details for mongo is straightforward, with mongo I need to incur 2 queries in this case. In a more complex use case, maybe more
So I wonder from a performance point of view, which is more efficient? From a development point of view, definitely, its simpler to use Mongo for example.

A:
So I wonder from a performance point of view, which is more efficient?
  From a development point of view, definitely, its simpler to use Mongo
  for example.

Redis supports Lua scripting using the EVAL/EVALSHA commands. What you call multiple queries can be simplified to just one of them, since Lua scripts are executed in Redis itself, and then you can call a cached Lua script by SHA from your Redis client.
In terms of performance, it will depend on your own code, but you can be sure that Redis should beat Mongo since Redis is an in-memory storage and it's asynchronously-persisted to disk (actually it creates snapshots overtime or based on some conditions).
About the simplicity, there's not something more simpler than using data structures like sets, hashes or lists, but anyway, simplicity is a subjective concept...
About Lua scripts
Pay attention to the fact that Lua scripts are atomically-executed, and since Redis can execute a command at once (an atomic operation is like a single command), you should not implement heavy operations in Lua because it may decrease the overall Redis performance.
Usually you implement Lua scripts to atomically write data like "set a string key, add a member to some set and remove if from who knows what sorted set". Since you don't want to have a chance of corrupting your data, you use Lua scripting or MULTI command to implement atomic operations.

A: That's one tricky question - you're basically asking to compare performance between two databases and contrast that with ease of use.
In terms of ease of use, I definitely believe MongoDB is more suitable for newcomers and, perhaps, developers who just want to use a database w/o understanding the pros/cons/strengths/weaknesses of each technology. MongoDB is an amazing piece of tech that is extremely accessible to a wide range of engineers at different levels - that's both its power and its downfall IMO: while you can do a lot with it, it is too generic for my taste to be really effective (sort of like a new Oracle).
Redis, OTOH, provides the basic building blocks - you need to understand how it works and how to put the blocks together to get at the needed result. This requires more effort for a developer - both for learning the Redis way and then implementing the solution with it.
So while MongoDB is easier to start using, I think Redis is more flexible in the long term and allows to have fine-grained control over every aspect of your database.
In terms of performance, I'm positive that Redis will outdo MongoDB any time. Yes, performance is affected by the "number of calls" but that's hardly a conclusive measure. The example provided (chatrooms) can be easily encapsulated in one or a few "calls" (e.g. use a Hash to contain all your objects and id) and that just one approach of doing it. Even assuming the OP's proposed "schema" and doing multiple calls to get the same data from Redis as one call from MongoDB provides, I'm sure that the data will come back faster from Redis than from any other database simply because Redis uses RAM whereas MongoDB is disk-based.
I suggest that in order to choose the right tech/solution, you take a minute to define and consider the requirements - if you need performance, Redis is your best bet.

A: It depends on what you want to index. If you just want to index by <id>, I don't see why you cannot get all the data in one query from redis. What you can do is to encode the name and users into, say, a JSON string, and retrieve it with just one query.
In general performance comparison is tricky. Less queries don't necessarily mean faster. I normally prefer redis or memcached type of in-memory caching if the data is not complex and does not require index over many fields.


text:
Q: Thunderbird Contacts sync with Ubuntu One on Ubuntu 12.10 How can I get Thunderbird Contacts to sync with Ubuntu One on Ubuntu 12.10 Quantal?

A: You cannot. It appears evolution-couchdb (and thus the Thunderbird extension which depended upon it) has been removed; likely due to API changes in upstream evolution-data-server, and no resources to update the plug-ins.
It's also worth noting that it was announced in November 2011 that desktopcouch/couchdb support would gradually removed from Ubuntu One. However, replacement infrastructure is being worked on in the form of u1db to replace the pieces which couchdb was being used for.


text:
Q: Gulp is not running successfully on my macOS https://ahmadawais.com/my-advanced-gulp-workflow-for-wordpress-themes/
I am following this tutorials and using the gulfile.js he has offered in the tutorial, but when i am installing the
npm install

i am getting plenty of issues, so i updated the file. but when I instantiate
glup

in my macOS terminal its giving me following errors and declining to run the command successfully.
[Browsersync] Serving files from: ./
[Browsersync] Watching files...
[23:36:59] gulp-notify: [Gulp notification] Custom scripts task complete
[23:36:59] Finished 'scriptsJs' after 388 ms
[23:36:59] gulp-notify: [Gulp notification] Vendor scripts task complete
[23:36:59] Finished 'vendorsJs' after 405 ms
[23:36:59] Starting 'default'...
[23:36:59] Finished 'default' after 135 ms
buffer.js:161
  throw new TypeError(kFromErrorMsg);
  ^

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
    at Function.Buffer.from (buffer.js:161:9)
    at new Buffer (buffer.js:131:17)
    at Transform.transform [as _transform] (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/index.js:152:21)
    at Transform._read (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at Transform._write (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_transform.js:172:12)
    at doWrite (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_writable.js:237:10)
    at writeOrBuffer (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_writable.js:227:5)
    at Transform.Writable.write (/Users/muzammil/Desktop/Themes/Theme2/node_modules/gulp-combine-media-queries/node_modules/readable-stream/lib/_stream_writable.js:194:11)
    at StreamFilter.ondata (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:612:20)
    at emitOne (events.js:115:13)
    at StreamFilter.emit (events.js:210:7)
    at addChunk (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:284:12)
    at readableAddChunk (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:271:11)
    at StreamFilter.Readable.push (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_readable.js:238:10)
    at StreamFilter.Transform.push (/Users/muzammil/Desktop/Themes/Theme2/node_modules/readable-stream/lib/_stream_transform.js:146:32)
    at StreamFilterCallback (/Users/muzammil/Desktop/Themes/Theme2/node_modules/streamfilter/src/index.js:30:15)

A: For anyone caught by this, I just ran into the same issue with a 4-yr old project I'm revisiting. It looks like the gulp-combine-media-queries module hasn't been updated since Node v4 (or thereabouts).
This fork of that module solved the issue for me:
https://www.npmjs.com/package/gulp-merge-media-queries
Cheers!


text:
Q: Firefox Addon builder: how to keep a panel shown I have done a firefox addon using the Addon Builder. This addon display a panel containing a web page.
The problem I have is that I would like to keep this panel displayed and probably had a close button to hide it. Actually the panel disappear when we click out of the panel.
This is the code I use to make my panel:
var HauteurPopup = 400;
var LargeurPopup = 650;

function getPanel(contentURL){
    var popupPanel = require("panel").Panel({
          width:LargeurPopup,
          height:HauteurPopup,
          contentURL: contentURL
         });
    return popupPanel;
}

var btn = require("toolbarbutton").ToolbarButton({
        id: 'propelink-button',
        label: 'Propulesez ce lien!',
        image: 'https://www.users.prplk.com/img/mini-logo-propel-bar.jpg',
        onCommand: function() {
            if (typeof(tabs.activeTab._worker) == 'undefined') {
                let worker = tabs.activeTab.attach({
                    contentScript: btnContentScript
                });
                tabs.activeTab._worker = worker;
            }
            tabs.activeTab._worker.port.emit("btnContentScript");
            var panelPopup = myPanel.getPanel("http://example.com");
            panelPopup.show();
        }
    });

Someone know how to keep this panel displayed and close it adding a button?
Thanks in advance

A: In xul based extensions there is an option in the creation of the panel to accomplish that (panel.noautohide). In firefox-addon-sdk it seems that it doesn't exist. See 595040 – Add a "isPersistent" attribute for panels
Although it is mentioned that you can do a workaround by editing panel.js, but i never tried to do that, but you may want to give it a try.


text:
Q: Prove that$ \frac{(n^2)!}{(n!)^n} \in$ Z Using permutation or otherwise, prove that$ \frac{(n^2)!}{(n!)^n}$an integer, where n is a positive integer.
Putting n=1,2,3.... I can prove that above quantity is an integer but this is not correct as it needs to be proved in a methodological way.


text:
Q: Laravel apply middleware "only", "except" options to Route groups The only reason I want to apply middleware options to my routes and not the controllers themselves is because I would like to build route groups from the same routes PHP file like the following, and I would like to do something like so:
Route::prefix('api')
     ->middleware('api')
     ->middleware('auth:api', ['only' => ['store', 'edit', 'delete']])
     ->middleware('auth:api', ['except' => ['index', 'show']])
     ->namespace($this->namespace)
     ->group(base_path('routes/api.php'));
Route::prefix('web')
    ->middleware('api')
    ->middleware('auth', ['only' => ['store', 'edit', 'delete']])
    ->middleware('auth', ['except' => ['index', 'show']])
    ->namespace($this->namespace)
    ->group(base_path('routes/api.php'));

However, obviously, the official documentation listed you can have multiple middlewares with this method in routes:
route->middleware('middleware1', 'middleware2')

Is there anyway to apply the "only these methods" and "except these methods" to route groups? If no, is there another way to go around this problem within my controllers, so that they know which route group the request is from and use different middlewares accordingly?

A: If I understand your question correctly, route groups (as suggested in the comments) are the "official" way to do what you're describing, particularly if you nest them.

Nested groups attempt to intelligently "merge" attributes with their parent group. Middleware and where conditions are merged while names, namespaces, and prefixes are appended. Namespace delimiters and slashes in URI prefixes are automatically added where appropriate.

You can also supply an array of options to the group method:
// routes/api.php
$namespaces = [
    'namespace1',
    'namespace2',
    'namespace3',
    ...
];

foreach ($namespaces as $namespace) {

    Route::group(['namespace' => $namespace], function() {

        Route::group([
            'prefix' => 'api',
            'middleware' => [
                'api',
                ['auth:api', ['only' => ['store', 'edit', 'delete']]],
                ['auth:api', ['except' => ['index', 'show']]]
            ],
        ], function() {

            // api controller methods here

        });

        Route::group([
            'prefix' => 'web',
            'middleware' => [
                'api',
                ['auth', ['only' => ['store', 'edit', 'delete']]],
                ['auth', ['except' => ['index', 'show']]]
            ],
        ], function() {

            // web controller methods here

        });

    });

}

Note however that you may need to rearrange the array order to get the desired effect:

Middleware are executed in the order they are listed in the array


text:
Q: Request for reference: uniform convergence for non 0-1 loss functions In the book "Understanding machine learning", there is Theorem 6.11 with the following statement

Let ${\cal H}$ be a class and let $\tau_{\cal H}$ be its growth function. Then, for every $\cal D$ and every $\delta \in (0, 1)$, with probability at least $1-\delta$ over the choice $S \sim {\cal D}^m$ we have
$$
|L_{\cal D}(h) - L_S(h)| \leq \frac{4 + \sqrt{\log{\tau_{\cal H}(2m)}}}{\delta \sqrt{2m}}.
$$

The theorem shows the uniform convergence property, though one can see that the proof utilizes the fact that the considered loss function is 0-1 loss. Where to read the similar proofs for other loss functions (say, for hinge loss)?


text:
Q: How to query another collection per document in mongoDB Sorry the title isn't really clear, I was struggling a bit with it.
I'm trying to get posts from all a user's followers using thier IDs
PostModel.find({ author: { $in: arr } }).limit(150).sort({ createdAt: -1 }).exec();

and get the top comments (determined by the number of likes) for each post, the schema for comments is below

Comment Schema

const commentSchema: Schema = new Schema({
    author: { type: Schema.Types.ObjectId, ref: 'User' },
    parentPost: {type: Schema.Types.ObjectId, ref: 'Post'}, // Post a user is commenting on
    createdAt: { type: Date, default: Date.now() },
    likedBy: [{type: Schema.Types.ObjectId, ref: 'User'}],
    likes: { type: Number, default: 0 },
});

Most of possible solutions I've come across has to do with agreggation but I'm not sure how to apply that here or if it's applicable, please how do I go about this ?

A: It is quite applicable with $lookup stage in aggregation: Perform a Single Equality Join with $lookup


text:
Q: Animate button from one point to another I have an expander containing some elements along with a button. When the expander is collapsed, I would like to display the button in the expander's header for easy access. When the expander is expanded, I want the button to be part of the expander's content.
I can get the button in the header to fade in and out when the expander is expanded and collapsed but I would like to take it a step further. I would like the button from the expander's content to move up to the location in the header when collapsed and move down to the content's location when expanded.
I can get somewhat close by using blend and drawing a line between the two buttons and converting it into a motion path. However, using this method it is very difficult to get the positioning exact. Part of me feels like drawing out the path is a bit over-complicating things. All I want is for Button A to animate to become Button B.
Currently I'm only concerned about the button's location. The two buttons are different sizes but animating the width and height of the button is more straight forward :)
This is an example program I quickly made to demonstrate what I'm working with. It's mainly just to provide a visual layout. The fading animation and path animations are not included in this example.

<Window x:Class="test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:test"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">

    <Window.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Margin" Value="5" />
            <Setter Property="Background" Value="Red" />
            <Setter Property="Foreground" Value="White" />
        </Style>
    </Window.Resources>

    <Grid>
        <Expander Margin="5" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Stretch" IsExpanded="True">
            <Expander.Header>
                <DockPanel Margin="5">
                    <TextBlock Margin="5" VerticalAlignment="Center">Hello World</TextBlock>
                    <Button Padding="5">Button</Button>
                </DockPanel>

            </Expander.Header>
            <Expander.Content>
                <StackPanel Orientation="Horizontal">
                    <Canvas Margin="5" Width="300" Background="Black" />

                    <StackPanel>
                        <StackPanel.Resources>
                            <Style TargetType="{x:Type RadioButton}">
                                <Setter Property="Margin" Value="5" />
                            </Style>
                        </StackPanel.Resources>
                        <RadioButton IsChecked="True">Option 1</RadioButton>
                        <RadioButton>Option 2</RadioButton>
                        <RadioButton>Option 3</RadioButton>
                        <RadioButton>Option 4</RadioButton>

                        <Button Width="100" Height="50">Button</Button>
                    </StackPanel>
                </StackPanel>
            </Expander.Content>
        </Expander>
    </Grid>
</Window>

Any help is greatly appreciated. I've tried to find some resources to help but all I've been able to find is moving an element along a path, not to a specific point unless I'm missing something obvious.
Thanks

A: This is not a trivial thing to do.
Basically you're trying to animate a button between two completely different parts of the visual tree, so you're going to have to template the whole thing and wrap everything up in a parent layout that contains both your expander and the button you're trying to animate.
Templating your expander shouldn't be too difficult, just move your cursor to it's XAML, go to the properties tab, select "Template" and click the little square to the right to generate all the code for the new ControlTemplate. I've done it for you in the code below, but the theming will probably be all wrong so you'll want to do it yourself.
Next step is to create two rectangles, one in the expanders header and one in its content  area. Set the size of these to whatever you want your button to be but set the fill to Transparent; they're only placeholders to help with layout, and you'll use them just to align your button control later on.
Now you'll need to go back to your ControlTemplate and wrap all the content (i.e. the top-level border) in a grid. You'll also want to place your actual button as a child of this grid.
Finally, you'll need a behaviour that binds to the two rectangles you created (so it can calculate From and To points), the parent grid (so that it has a parent control it can animate your button relative to) and the expander (so it can trigger animations in response to the expander expanding and collapsing). The actual animation itself can then be a ThicknessAnimation which animates the button's Margin.
Put all that together and you get this:
 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
 xmlns:behaviors="clr-namespace:WpfApp1.Behaviors"

<UserControl.Resources>
    <ControlTemplate x:Key="ExpanderControlTemplate1" TargetType="{x:Type Expander}">
        <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="3" SnapsToDevicePixels="True">
            <Grid x:Name="Grid">
                <DockPanel>
                    <ToggleButton x:Name="HeaderSite" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" DockPanel.Dock="Top" Foreground="{TemplateBinding Foreground}" FontWeight="{TemplateBinding FontWeight}" FontStyle="{TemplateBinding FontStyle}" FontStretch="{TemplateBinding FontStretch}" FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsChecked="{Binding IsExpanded, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Margin="1" MinWidth="0" MinHeight="0" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}">
                        <ToggleButton.FocusVisualStyle>
                            <Style>
                                <Setter Property="Control.Template">
                                    <Setter.Value>
                                        <ControlTemplate>
                                            <Border>
                                                <Rectangle Margin="0" SnapsToDevicePixels="True" Stroke="Black" StrokeThickness="1" StrokeDashArray="1 2"/>
                                            </Border>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </ToggleButton.FocusVisualStyle>
                        <ToggleButton.Style>
                            <Style TargetType="{x:Type ToggleButton}">
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate TargetType="{x:Type ToggleButton}">
                                            <Border Padding="{TemplateBinding Padding}">
                                                <Grid Background="Transparent" SnapsToDevicePixels="False">
                                                    <Grid.ColumnDefinitions>
                                                        <ColumnDefinition Width="19"/>
                                                        <ColumnDefinition Width="*"/>
                                                    </Grid.ColumnDefinitions>
                                                    <Ellipse x:Name="circle" Fill="White" HorizontalAlignment="Center" Height="19" Stroke="#FF333333" VerticalAlignment="Center" Width="19"/>
                                                    <Path x:Name="arrow" Data="M1,1.5L4.5,5 8,1.5" HorizontalAlignment="Center" SnapsToDevicePixels="False" Stroke="#FF333333" StrokeThickness="2" VerticalAlignment="Center"/>
                                                    <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Grid.Column="1" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Left" Margin="4,0,0,0" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Center"/>
                                                </Grid>
                                            </Border>
                                            <ControlTemplate.Triggers>
                                                <Trigger Property="IsChecked" Value="True">
                                                    <Setter Property="Data" TargetName="arrow" Value="M1,4.5L4.5,1 8,4.5"/>
                                                </Trigger>
                                                <Trigger Property="IsMouseOver" Value="True">
                                                    <Setter Property="Stroke" TargetName="circle" Value="#FF5593FF"/>
                                                    <Setter Property="Fill" TargetName="circle" Value="#FFF3F9FF"/>
                                                    <Setter Property="Stroke" TargetName="arrow" Value="Black"/>
                                                </Trigger>
                                                <Trigger Property="IsPressed" Value="True">
                                                    <Setter Property="Stroke" TargetName="circle" Value="#FF3C77DD"/>
                                                    <Setter Property="StrokeThickness" TargetName="circle" Value="1.5"/>
                                                    <Setter Property="Fill" TargetName="circle" Value="#FFD9ECFF"/>
                                                    <Setter Property="Stroke" TargetName="arrow" Value="Black"/>
                                                </Trigger>
                                                <Trigger Property="IsEnabled" Value="False">
                                                    <Setter Property="Stroke" TargetName="circle" Value="#FFBCBCBC"/>
                                                    <Setter Property="Fill" TargetName="circle" Value="#FFE6E6E6"/>
                                                    <Setter Property="Stroke" TargetName="arrow" Value="#FF707070"/>
                                                </Trigger>
                                            </ControlTemplate.Triggers>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                            </Style>
                        </ToggleButton.Style>
                    </ToggleButton>
                    <ContentPresenter x:Name="ExpandSite" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" DockPanel.Dock="Bottom" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" Visibility="Collapsed" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                </DockPanel>
                <Button Width="100" Height="50" Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top">
                    <i:Interaction.Behaviors>
                        <behaviors:AnimatedMarginBehavior ElementA="{Binding ElementName=ElementA}" ElementB="{Binding ElementName=ElementB}" Grid="{Binding ElementName=Grid}" Parent="{Binding RelativeSource={RelativeSource AncestorType=Expander}}" />
                    </i:Interaction.Behaviors>
                </Button>
            </Grid>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsExpanded" Value="True">
                <Setter Property="Visibility" TargetName="ExpandSite" Value="Visible"/>
            </Trigger>
            <Trigger Property="ExpandDirection" Value="Right">
                <Setter Property="DockPanel.Dock" TargetName="ExpandSite" Value="Right"/>
                <Setter Property="DockPanel.Dock" TargetName="HeaderSite" Value="Left"/>
                <Setter Property="Style" TargetName="HeaderSite">
                    <Setter.Value>
                        <Style TargetType="{x:Type ToggleButton}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type ToggleButton}">
                                        <Border Padding="{TemplateBinding Padding}">
                                            <Grid Background="Transparent" SnapsToDevicePixels="False">
                                                <Grid.RowDefinitions>
                                                    <RowDefinition Height="19"/>
                                                    <RowDefinition Height="*"/>
                                                </Grid.RowDefinitions>
                                                <Grid>
                                                    <Grid.LayoutTransform>
                                                        <TransformGroup>
                                                            <RotateTransform Angle="-90"/>
                                                        </TransformGroup>
                                                    </Grid.LayoutTransform>
                                                    <Ellipse x:Name="circle" Fill="White" HorizontalAlignment="Center" Height="19" Stroke="#FF333333" VerticalAlignment="Center" Width="19"/>
                                                    <Path x:Name="arrow" Data="M1,1.5L4.5,5 8,1.5" HorizontalAlignment="Center" SnapsToDevicePixels="False" Stroke="#FF333333" StrokeThickness="2" VerticalAlignment="Center"/>
                                                </Grid>
                                                <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Center" Margin="0,4,0,0" Grid.Row="1" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Top"/>
                                            </Grid>
                                        </Border>
                                        <ControlTemplate.Triggers>
                                            <Trigger Property="IsChecked" Value="True">
                                                <Setter Property="Data" TargetName="arrow" Value="M1,4.5L4.5,1 8,4.5"/>
                                            </Trigger>
                                            <Trigger Property="IsMouseOver" Value="True">
                                                <Setter Property="Stroke" TargetName="circle" Value="#FF5593FF"/>
                                                <Setter Property="Fill" TargetName="circle" Value="#FFF3F9FF"/>
                                                <Setter Property="Stroke" TargetName="arrow" Value="Black"/>
                                            </Trigger>
                                            <Trigger Property="IsPressed" Value="True">
                                                <Setter Property="Stroke" TargetName="circle" Value="#FF3C77DD"/>
                                                <Setter Property="StrokeThickness" TargetName="circle" Value="1.5"/>
                                                <Setter Property="Fill" TargetName="circle" Value="#FFD9ECFF"/>
                                                <Setter Property="Stroke" TargetName="arrow" Value="Black"/>
                                            </Trigger>
                                            <Trigger Property="IsEnabled" Value="False">
                                                <Setter Property="Stroke" TargetName="circle" Value="#FFBCBCBC"/>
                                                <Setter Property="Fill" TargetName="circle" Value="#FFE6E6E6"/>
                                                <Setter Property="Stroke" TargetName="arrow" Value="#FF707070"/>
                                            </Trigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Setter.Value>
                </Setter>
            </Trigger>
            <Trigger Property="ExpandDirection" Value="Up">
                <Setter Property="DockPanel.Dock" TargetName="ExpandSite" Value="Top"/>
                <Setter Property="DockPanel.Dock" TargetName="HeaderSite" Value="Bottom"/>
                <Setter Property="Style" TargetName="HeaderSite">
                    <Setter.Value>
                        <Style TargetType="{x:Type ToggleButton}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type ToggleButton}">
                                        <Border Padding="{TemplateBinding Padding}">
                                            <Grid Background="Transparent" SnapsToDevicePixels="False">
                                                <Grid.ColumnDefinitions>
                                                    <ColumnDefinition Width="19"/>
                                                    <ColumnDefinition Width="*"/>
                                                </Grid.ColumnDefinitions>
                                                <Grid>
                                                    <Grid.LayoutTransform>
                                                        <TransformGroup>
                                                            <RotateTransform Angle="180"/>
                                                        </TransformGroup>
                                                    </Grid.LayoutTransform>
                                                    <Ellipse x:Name="circle" Fill="White" HorizontalAlignment="Center" Height="19" Stroke="#FF333333" VerticalAlignment="Center" Width="19"/>
                                                    <Path x:Name="arrow" Data="M1,1.5L4.5,5 8,1.5" HorizontalAlignment="Center" SnapsToDevicePixels="False" Stroke="#FF333333" StrokeThickness="2" VerticalAlignment="Center"/>
                                                </Grid>
                                                <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Grid.Column="1" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Left" Margin="4,0,0,0" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Center"/>
                                            </Grid>
                                        </Border>
                                        <ControlTemplate.Triggers>
                                            <Trigger Property="IsChecked" Value="True">
                                                <Setter Property="Data" TargetName="arrow" Value="M1,4.5L4.5,1 8,4.5"/>
                                            </Trigger>
                                            <Trigger Property="IsMouseOver" Value="True">
                                                <Setter Property="Stroke" TargetName="circle" Value="#FF5593FF"/>
                                                <Setter Property="Fill" TargetName="circle" Value="#FFF3F9FF"/>
                                                <Setter Property="Stroke" TargetName="arrow" Value="Black"/>
                                            </Trigger>
                                            <Trigger Property="IsPressed" Value="True">
                                                <Setter Property="Stroke" TargetName="circle" Value="#FF3C77DD"/>
                                                <Setter Property="StrokeThickness" TargetName="circle" Value="1.5"/>
                                                <Setter Property="Fill" TargetName="circle" Value="#FFD9ECFF"/>
                                                <Setter Property="Stroke" TargetName="arrow" Value="Black"/>
                                            </Trigger>
                                            <Trigger Property="IsEnabled" Value="False">
                                                <Setter Property="Stroke" TargetName="circle" Value="#FFBCBCBC"/>
                                                <Setter Property="Fill" TargetName="circle" Value="#FFE6E6E6"/>
                                                <Setter Property="Stroke" TargetName="arrow" Value="#FF707070"/>
                                            </Trigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Setter.Value>
                </Setter>
            </Trigger>
            <Trigger Property="ExpandDirection" Value="Left">
                <Setter Property="DockPanel.Dock" TargetName="ExpandSite" Value="Left"/>
                <Setter Property="DockPanel.Dock" TargetName="HeaderSite" Value="Right"/>
                <Setter Property="Style" TargetName="HeaderSite">
                    <Setter.Value>
                        <Style TargetType="{x:Type ToggleButton}">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type ToggleButton}">
                                        <Border Padding="{TemplateBinding Padding}">
                                            <Grid Background="Transparent" SnapsToDevicePixels="False">
                                                <Grid.RowDefinitions>
                                                    <RowDefinition Height="19"/>
                                                    <RowDefinition Height="*"/>
                                                </Grid.RowDefinitions>
                                                <Grid>
                                                    <Grid.LayoutTransform>
                                                        <TransformGroup>
                                                            <RotateTransform Angle="90"/>
                                                        </TransformGroup>
                                                    </Grid.LayoutTransform>
                                                    <Ellipse x:Name="circle" Fill="White" HorizontalAlignment="Center" Height="19" Stroke="#FF333333" VerticalAlignment="Center" Width="19"/>
                                                    <Path x:Name="arrow" Data="M1,1.5L4.5,5 8,1.5" HorizontalAlignment="Center" SnapsToDevicePixels="False" Stroke="#FF333333" StrokeThickness="2" VerticalAlignment="Center"/>
                                                </Grid>
                                                <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="Center" Margin="0,4,0,0" Grid.Row="1" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Top"/>
                                            </Grid>
                                        </Border>
                                        <ControlTemplate.Triggers>
                                            <Trigger Property="IsChecked" Value="True">
                                                <Setter Property="Data" TargetName="arrow" Value="M1,4.5L4.5,1 8,4.5"/>
                                            </Trigger>
                                            <Trigger Property="IsMouseOver" Value="True">
                                                <Setter Property="Stroke" TargetName="circle" Value="#FF5593FF"/>
                                                <Setter Property="Fill" TargetName="circle" Value="#FFF3F9FF"/>
                                                <Setter Property="Stroke" TargetName="arrow" Value="Black"/>
                                            </Trigger>
                                            <Trigger Property="IsPressed" Value="True">
                                                <Setter Property="Stroke" TargetName="circle" Value="#FF3C77DD"/>
                                                <Setter Property="StrokeThickness" TargetName="circle" Value="1.5"/>
                                                <Setter Property="Fill" TargetName="circle" Value="#FFD9ECFF"/>
                                                <Setter Property="Stroke" TargetName="arrow" Value="Black"/>
                                            </Trigger>
                                            <Trigger Property="IsEnabled" Value="False">
                                                <Setter Property="Stroke" TargetName="circle" Value="#FFBCBCBC"/>
                                                <Setter Property="Fill" TargetName="circle" Value="#FFE6E6E6"/>
                                                <Setter Property="Stroke" TargetName="arrow" Value="#FF707070"/>
                                            </Trigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Setter.Value>
                </Setter>
            </Trigger>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</UserControl.Resources>

<Grid>
    <Expander Margin="5" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Stretch" IsExpanded="True" Template="{DynamicResource ExpanderControlTemplate1}">
        <Expander.Header>
            <DockPanel Margin="5">
                <TextBlock Margin="5" VerticalAlignment="Center">Hello World</TextBlock>
                <Rectangle x:Name="ElementA" Width="100" Height="50" Fill="Transparent" />
            </DockPanel>
        </Expander.Header>
        <Expander.Content>
            <StackPanel Orientation="Horizontal">
                <Canvas Margin="5" Width="300" Background="Black" />

                <StackPanel>
                    <StackPanel.Resources>
                        <Style TargetType="{x:Type RadioButton}">
                            <Setter Property="Margin" Value="5" />
                        </Style>
                    </StackPanel.Resources>
                    <RadioButton IsChecked="True">Option 1</RadioButton>
                    <RadioButton>Option 2</RadioButton>
                    <RadioButton>Option 3</RadioButton>
                    <RadioButton>Option 4</RadioButton>
                    <Rectangle x:Name="ElementB" Width="100" Height="50" Fill="Transparent" />
                </StackPanel>
            </StackPanel>
        </Expander.Content>
    </Expander>
</Grid>

And the behavior:
public class AnimatedMarginBehavior : Behavior<FrameworkElement>
{
    private ThicknessAnimation Animation = new ThicknessAnimation();

    public FrameworkElement ElementA
    {
        get { return GetValue(ElementAProperty) as FrameworkElement; }
        set { SetValue(ElementAProperty, value); }
    }

    public static readonly DependencyProperty ElementAProperty =
        DependencyProperty.Register("ElementA", typeof(FrameworkElement), typeof(AnimatedMarginBehavior),
            new PropertyMetadata(default(FrameworkElement), (d, e) => (d as AnimatedMarginBehavior).OnBindingChanged(e)));

    public FrameworkElement ElementB
    {
        get { return GetValue(ElementBProperty) as FrameworkElement; }
        set { SetValue(ElementBProperty, value); }
    }

    public static readonly DependencyProperty ElementBProperty =
        DependencyProperty.Register("ElementB", typeof(FrameworkElement), typeof(AnimatedMarginBehavior),
            new PropertyMetadata(default(FrameworkElement), (d, e) => (d as AnimatedMarginBehavior).OnBindingChanged(e)));

    public Expander Parent
    {
        get { return GetValue(ParentProperty) as Expander; }
        set { SetValue(ParentProperty, value); }
    }

    public static readonly DependencyProperty ParentProperty =
        DependencyProperty.Register("Parent", typeof(Expander), typeof(AnimatedMarginBehavior),
            new PropertyMetadata(default(Expander), (d, e) => (d as AnimatedMarginBehavior).OnBindingChanged(e)));

    public Grid Grid
    {
        get { return GetValue(GridProperty) as Grid; }
        set { SetValue(GridProperty, value); }
    }

    public static readonly DependencyProperty GridProperty =
        DependencyProperty.Register("Grid", typeof(Grid), typeof(AnimatedMarginBehavior),
            new PropertyMetadata(default(Grid), (d, e) => (d as AnimatedMarginBehavior).OnBindingChanged(e)));

    private void OnBindingChanged(DependencyPropertyChangedEventArgs e)
    {
        if (this.ElementA == null)
            return;
        if (this.ElementB == null)
            return;
        if (this.Parent == null)
            return;
        if (this.Grid == null)
            return;

        // set initial position based on whether or not the control is expanded
        var currentElement = this.Parent.IsExpanded ? this.ElementB : this.ElementA;
        UIElement container = VisualTreeHelper.GetParent(this.Grid) as UIElement;
        var pos = currentElement.TranslatePoint(new Point(0, 0), container);
        this.AssociatedObject.SetValue(FrameworkElement.MarginProperty, new Thickness(pos.X-1, pos.Y-1, 0, 0));

        // get notification when the expander changes state
        this.Parent.Collapsed += (_s1, _e1) =>
        {
            container = VisualTreeHelper.GetParent(this.Grid) as UIElement;
            var from = this.ElementB.TranslatePoint(new Point(0, 0), container);
            var to = this.ElementA.TranslatePoint(new Point(0, 0), container);
            this.Animation.From = new Thickness(from.X, from.Y, 0, 0);
            this.Animation.To = new Thickness(to.X, to.Y, 0, 0);
            this.Animation.Duration = TimeSpan.FromMilliseconds(500);
            this.Animation.EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseInOut };
            this.AssociatedObject.BeginAnimation(FrameworkElement.MarginProperty, this.Animation);
        };

        this.Parent.Expanded += (_s2, _e2) =>
        {
            container = VisualTreeHelper.GetParent(this.Grid) as UIElement;
            var from = this.ElementA.TranslatePoint(new Point(0, 0), container);
            var to = this.ElementB.TranslatePoint(new Point(0, 0), container);
            this.Animation.From = new Thickness(from.X, from.Y, 0, 0);
            this.Animation.To = new Thickness(to.X, to.Y, 0, 0);
            this.Animation.Duration = TimeSpan.FromMilliseconds(500);
            this.Animation.EasingFunction = new QuadraticEase { EasingMode = EasingMode.EaseInOut };
            this.AssociatedObject.BeginAnimation(FrameworkElement.MarginProperty, this.Animation);
        };
    }
}

That's a very rough-and-ready example that gives a general idea of how to do this, you'll definitely want to go over it in detail and clean it up a bit.
Result:

A: directly tried with xaml only without any c# code. hope this works for you.
  <Window.Resources>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Margin" Value="5" />
            <Setter Property="Background" Value="Red" />
            <Setter Property="Foreground" Value="White" />
        </Style>
        <Storyboard x:Key="Storyboard1">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="button">
                <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="221"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="button">
                <EasingDoubleKeyFrame KeyTime="0:0:0.0001" Value="161"/>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
        <Storyboard x:Key="Storyboard2">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="button">
                <EasingDoubleKeyFrame KeyTime="0" Value="221">
                    <EasingDoubleKeyFrame.EasingFunction>
                        <ElasticEase EasingMode="EaseInOut" Oscillations="0" Springiness="0"/>
                    </EasingDoubleKeyFrame.EasingFunction>
                </EasingDoubleKeyFrame>
                <EasingDoubleKeyFrame KeyTime="0" Value="161">
                    <EasingDoubleKeyFrame.EasingFunction>
                        <ElasticEase EasingMode="EaseInOut" Oscillations="0" Springiness="0"/>
                    </EasingDoubleKeyFrame.EasingFunction>
                </EasingDoubleKeyFrame>
                <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="-3">
                    <EasingDoubleKeyFrame.EasingFunction>
                        <ElasticEase EasingMode="EaseInOut" Oscillations="0" Springiness="0"/>
                    </EasingDoubleKeyFrame.EasingFunction>
                </EasingDoubleKeyFrame>
                <!-- <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="0"/> -->
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="button">
                <EasingDoubleKeyFrame KeyTime="0" Value="156">
                    <EasingDoubleKeyFrame.EasingFunction>
                        <ElasticEase EasingMode="EaseInOut" Oscillations="0" Springiness="0"/>
                    </EasingDoubleKeyFrame.EasingFunction>
                </EasingDoubleKeyFrame>
                <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="-1">
                    <EasingDoubleKeyFrame.EasingFunction>
                        <ElasticEase EasingMode="EaseInOut" Oscillations="0" Springiness="0"/>
                    </EasingDoubleKeyFrame.EasingFunction>
                </EasingDoubleKeyFrame>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </Window.Resources>
    <Window.Triggers>
        <EventTrigger RoutedEvent="FrameworkElement.Loaded" SourceName="window">
            <StopStoryboard x:Name="Storyboard1_Storyboard" BeginStoryboardName="Storyboard1_Storyboard"/>
            <BeginStoryboard x:Name="Storyboard1_BeginStoryboard" Storyboard="{StaticResource Storyboard1}"/>
        </EventTrigger>
        <EventTrigger RoutedEvent="Expander.Expanded" SourceName="expander">
            <BeginStoryboard Storyboard="{StaticResource Storyboard1}"/>
        </EventTrigger>
        <EventTrigger RoutedEvent="Expander.Collapsed" SourceName="expander">
            <BeginStoryboard Storyboard="{StaticResource Storyboard2}"/>
        </EventTrigger>
    </Window.Triggers>

    <Grid>
        <Expander x:Name="expander" Margin="5" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Stretch" IsExpanded="False">
            <Expander.Header>
                <StackPanel Width="195.313">
                    <Grid x:Name="grid" RenderTransformOrigin="0.5,0.5">
                        <Grid.RenderTransform>
                            <TransformGroup>
                                <ScaleTransform/>
                                <SkewTransform/>
                                <RotateTransform/>
                                <TranslateTransform/>
                            </TransformGroup>
                        </Grid.RenderTransform>
                        <TextBlock x:Name="textBlock" Margin="5" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5">
                            <TextBlock.RenderTransform>
                                <TransformGroup>
                                    <ScaleTransform/>
                                    <SkewTransform/>
                                    <RotateTransform/>
                                    <TranslateTransform/>
                                </TransformGroup>
                            </TextBlock.RenderTransform><Run Text="Hello World"/></TextBlock>
                        <Button x:Name="button" Padding="5" RenderTransformOrigin="0.5,0.5" Content="Button" Margin="93,5,5,5">
                            <Button.RenderTransform>
                                <TransformGroup>
                                    <ScaleTransform/>
                                    <SkewTransform/>
                                    <RotateTransform/>
                                    <TranslateTransform/>
                                </TransformGroup>
                            </Button.RenderTransform>
                        </Button>
                    </Grid>
                </StackPanel>

            </Expander.Header>
            <StackPanel Orientation="Horizontal">
                <Canvas Margin="5" Width="300" Background="Black" />

                <StackPanel>
                    <StackPanel.Resources>
                        <Style TargetType="{x:Type RadioButton}">
                            <Setter Property="Margin" Value="5" />
                        </Style>
                    </StackPanel.Resources>
                    <RadioButton IsChecked="True" Content="Option 1"/>
                    <RadioButton Content="Option 2"/>
                    <RadioButton Content="Option 3"/>
                    <RadioButton Content="Option 4"/>
                </StackPanel>
            </StackPanel>
        </Expander>
    </Grid>

be careful with the design.


text:
Q: Detecting specific wifi connections on a native mobile app I am looking at ways to detect when a specific connection is available. For example when the user gets home and the network is picked up they are able to be given a notification as to whether they would like to join the network. At the minute I am trying to do this in React so would be interested in what options I have available native or not.
I have seen this previous question which is along very similar lines but I am not currently looking specifically for android.
Android WIFI How To Detect When Specific WIFI Connection is Available

A: You should use NetInfo for this. You can find specific documentation here.
Here is a quick example of what you are trying to do:
NetInfo.addEventListener(
   'change',
   function(reach) {
       if(reach.toLowerCase() === 'wifi' ) {
           console.log('You are on wifi!');
       }
   }
);


text:
Q: Select values from same column from same table I've a column Question_Id from which I've to derive two sets of values based on a different column in SQL Server 2008.
Question_id and  ID

*

*243        73

*244        73

*245        73

*429        192

*430        192

*431        192

How can I get them like this: (This is only for temporary table)

*

*1   243        429

*2   243        430

*3   243        431

Thanks a lot in advance.
Manish

Thanks for your replies.
For those who weren't clear about the question - I want the result to be like that temporary table. Yesterday I realized that, Actually its not possible to select different values from same column.... I used two temporary tables
SELECT QUESTION_ID WHERE ID = 73 INTO #TEMP1 and SELECT QUESTION_ID WHERE ID = 192 INTO #TEMP2. Then I inner-joined both tables to use the data for some INSERT operation... Thank you.

A: You cannot.  There is no natural ordering in SQL databases, so without the 1, 2, 3 values in the original rows, there's no way to pair up, for instance, 243 and 429.

A: If you setup a cross join with something like:
SELECT t1.qid, t2.qid FROM table as t1, table as t2 WHERE t1.qid=243 AND t2.qid between 429 AND 431;
And insert that into a new table with an AI index, you could create something like your description.


text:
Q: How to add alias to alias_method_chain in Ruby on Rails? I have an alias method as:
alias :is_animal , :is_animal?

I am trying to declare an alias method chain for the above methods:
alias_method_chain :is_animal, :with_fourlegs

alias_method_chain :is_animal?, :with_fourlegs

Is there any better way that I can use alias for alias method chain?
P.S: I rather not like to declare alias method chain twice for the same alias method.


text:
Q: How to load Firebase DB Vaule on detail activity when ListView Item Clicked I am developing android application that uses Firebase Database as back End. List View items retrieved from my Json key. For example:-
 {
    "Player3" : {
        "LY" : "ewfw",
        "Ty" : "rwerw"
      }
 }

Then, "LY" and "TY" will be loaded on As list View Item(which works fine). and after What i want is when "LY" or "TY" (List View Item) clicked "ewfw" or "rwerw" will be shown on detail acitivity. The problem is only Key  is displayed on detail activity not Value. How can i load value for detail activity?
Here is my code...
ListItemActivity.Java
public class ListItemActivity5 extends Fragment {
    private static final String TAG = "Tab4Fragment";
    //String[] values = new String[]{"", "", "", "", "", "", "", "", ""};
    ListView listView;
    TextView textView;
    Array array;
    RelativeLayout relativeLayout;
    ViewGroup.LayoutParams layoutparams;
    private DatabaseReference mDatabase;
    RelativeLayout container;
    AnimationDrawable anim;
    Context context;

    //private TextView text;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_conferance, container, false);
        //text = (TextView) view.findViewById(R.id.textView1);
        listView = (ListView) view.findViewById(R.id.list);
        container = (RelativeLayout) view.findViewById(R.id.container5);
        final TextView textView1 = (TextView) view.findViewById(R.id.textView1);
        anim = (AnimationDrawable) container.getBackground();
        anim.setEnterFadeDuration(2000);
        anim.setExitFadeDuration(3000);
        final ListView listView = (ListView) view.findViewById(R.id.list);
        final ArrayList<String> friends = new ArrayList<String>();

        mDatabase = FirebaseDatabase.getInstance().getReference("Player");
        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(final DataSnapshot dataSnapshot) {
                friends.clear();
                for (final DataSnapshot player : dataSnapshot.getChildren()) {
                    Log.i("Player", player.getKey());
                    friends.add(player.getKey());
                    player.getValue();

                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        public void onItemClick(AdapterView<?> parent, View view,
                                                int position, long id) {
                            player.getValue();
                            //player2 = (String) String.valueOf(player.getValue());
                            //String topic = String.valueOf(player.getValue());
                            //topic = (String) parent.getItemAtPosition(position);
                            Intent intent = new Intent(getContext(), Details.class);

                            intent.putExtra("key", String.valueOf(player.getValue()));

                            startActivity(intent);

                        }

                    });
                }
                ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1,
                        friends) {

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {

                        View view = super.getView(position, convertView, parent);

                        layoutparams = view.getLayoutParams();
                        TextView textView = (TextView) view.findViewById(android.R.id.text1);

            /*YOUR CHOICE OF COLOR*/
                        textView.setTextColor(Color.WHITE);
                        textView.setTextSize(22);

                        //Define your height here.
                        //layoutparams.height = 240;

                        view.setLayoutParams(layoutparams);

                        return view;

                    }
                };
                listView.setAdapter(arrayAdapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }

        });

        return view;
    }

}

Details.Java
public class Details extends Activity {
    RelativeLayout container;
    AnimationDrawable anim;
    ScrollView mScrollView;
    TextView textView1;
    private DatabaseReference mDatabase;
    private ListItemActivity1 mylist1;
    private DataSnapshot dataSnapshot;
    FloatingActionButton floatingActionButton;
    private ListItemActivity5 listItemActivity5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ab1);

        textView1 = (TextView) findViewById(R.id.textView1);
        //mref = new Firebase("https://tafach-love-2.firebaseio.com/");
        Intent intent = getIntent();

        if(intent.hasExtra("key")){
            textView1.setText(intent.getStringExtra("key"));
        }
        textView1.setMovementMethod(new ScrollingMovementMethod());

 }
}

Thanks for your help.

A: I have got answer for my question. I put these lines to my code on List ItemActivity and set onclickListner in ChildEventListner instead of AddEventLister...
 mDatabase.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                final String playerName = dataSnapshot.getValue(String.class);
                hy.add(playerName);
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        //player.getValue();
                        //player2 = (String) String.valueOf(player.getValue());
                        //String topic = String.valueOf(player.getValue());
                        //topic = (String) parent.getItemAtPosition(position);
                        Intent intent = new Intent(getContext(), Details.class);

                        intent.putExtra("key", String.valueOf(hy.get(position)));

                        startActivity(intent);

                    }

                });
            }


text:
Q: Conditional expectation for $2X+3 \mid Y$
Given the pdf: $$f_{X,Y}(x,y)= \begin{cases} x+y,& 0 \le x \le 1, 0 \le y \le 1
\\0, & \text{otherwise}\end{cases}$$
  Find $E(2X + 3\mid Y )$.

Using the formula for conditional expectation:
$\int{xf(x|y)dx}$, where $x=2X+3$, so we have:
$$\int\limits_0^1{(2x+3)\frac{f(x,y)}{f_y(y)}dx}$$
Is this correct or do we have to do something different regarding the $2X+3$? Thanks.

A: Your approach is correct.
You can verify your result with Mathematica:
In[16]:= Expectation[
  2 X + 3 \[Conditioned] Y == y, {X, Y} \[Distributed]
   ProbabilityDistribution[x + y, {x, 0, 1}, {y, 0, 1}]] // Normal

Out[16]= (13 + 24 y)/(3 (1 + 2 y))

And the confirmation that the result is correct, using the law of total expectation:
In[21]:= Expectation[(13 + 24 y)/(3 (1 + 2 y)),
  y \[Distributed]
   MarginalDistribution[
    ProbabilityDistribution[x + y, {x, 0, 1}, {y, 0, 1}], 2]] ==
 Expectation[
  2 x + 3, {x, y} \[Distributed]
   ProbabilityDistribution[x + y, {x, 0, 1}, {y, 0, 1}]]

Out[21]= True


text:
Q: Mock an axios call in a vue method using Jest I have looked for a solution to this but other questions dont really match my use case.
I have a function in a Vue file:
getStatus () {
      const statusRetriveKey = 0
      // Sets parameters from external file
      const url = serverDetails.url
      const params = { ...serverDetails.params }
      axios
        .get(`${url}admin/${statusRetriveKey}`, {
          params
        })
        .then((response) => {
          this.systemStatus = response.data[0].systemStatus
          this.alert = response.data[0].alert
          this.awayMessage = response.data[0].awayMessage
        })
        // Catch and display errors
        .catch((error) => {
          this.error = error.toString()
          console.log('Error on check System status: ' + error)
        })
    },

I am trying to write a unit test in Jest that will check that the data variables; systemStatus,alert and awayMessage are set correctly if that is what is returned by the GET request.
So far I have the following:
    it("Should call axios and return data", async () => {
        mockAxios.get.mockImplementationOnce(() => Promise.resolve({
            data:{
                systemStatus: true,
                //the other variables
              }
        }))
        const response = await wrapper.vm.getStatus();
        console.log(response)
        expect(wrapper.vm.$data.systemStatus).toBe(true)
        expect(mockAxios.get).toHaveBeenCalledTimes(1);
    })

However I am receiving for the system status variable:
expect(received).toBe(expected) // Object.is equality
    Expected: true
    Received: null

I know that the mock is not feeding data into the method but not sure on how to resolve. Is it because I am not explicitly returning from the method in the vue file and rather using this to set the data values?

Solution:
// Import dependencies
import { shallowMount } from '@vue/test-utils'
import axios from 'axios'
// Import component
import Page from 'path'

jest.spyOn(axios, "get").mockImplementation(() => Promise.resolve({ data: [{ systemStatus: false, ...:..., ...:... }] }));

// Set Model data
const models = {
  ...
  }
}
describe('Page', () => {
  let wrapper
  beforeEach(() => {
    wrapper = shallowMount(Page, {
      propsData: {
        model: models
      },
    })
  })
  it("Should call axios and return data", async () => {
    await wrapper.vm.getStatus();
    expect(wrapper.vm.$data.systemStatus).toBe(false)
    expect(wrapper.vm.$data....).toBe('...')
    expect(wrapper.vm.$data....).toBe('...')
  },)
})

A: So not sure what is mockAxios here, is it some npm module?
One way you could do it is using spyOn
import axios from 'axios';

jest.spyOn(axios, "get").mockImplementationOnce(() => Promise.resolve({data: {/* Here you can add your data */}));

So in your test, notice mockImplementationOnce.
It will be mocked only for one call
    it("Should call axios and return data", async () => {
        await wrapper.vm.getStatus();
    })

Edit:
On the line where you log response you will always get undefined because you do not have return statement in the function getStatus.


text:
Q: How can I iterate an array object in javascript? I have been on this problem for some hours. The code work like these : someone does an image search, I fetch the answer from an API and I inject the images into a div to present the result. It can vary from 3 to 500 images, it's not fixed.
Except that I cannot manage to display only the right number of images. The problem is in the iteration or the way I present data, but after trying everything and anything I think I need help.
What I receive from the API comes in this form:
{"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}}

And here's my (simplified) code:
makeHTTPRequest('GET', url).then((resp) => {
        var parsedResp = JSON.parse(resp);
        var arrayicon = Object.keys(parsedResp).map(function(key) {
            return parsedResp[key]
        });
        injectIcons(arrayicon)
        };

        injectIcons = (icons) => {
        let htmlString = '';

        for (var i = 0; i < icons.length; i++) {
            const IconDiv = `src="${icons[i]}"`;
            htmlString = htmlString + IconDiv
        }

        document.getElementById('results').innerHTML = htmlString
    };

A: Try to change the code like this:
var response = {"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}}

var icons = response.icon;

for (var k in icons ) {
     const IconDiv = `src="${icons[k]}"`;
     htmlString = htmlString + IconDiv
}

A: In this case, a simple while loop could work (assuming you can't change the API to return an actual Array--which would be better):

const data = {"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}};

let i = 0;
while (data.icon[i]) {
  console.log(data.icon[i++]);
}

Edit: Your code is actually really close to working. You just need to access parsedResp.icon rather than parsedResp:

var parsedResp = {"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}};

var arrayicon = Object.keys(parsedResp.icon).map(function(key) {
  return parsedResp.icon[key]
});

console.log(arrayicon);


text:
Q: Ошибка TypeError: Cannot read property 'hasOwnProperty' of undefined VUE При попытке отправки формы выскакивает ошибка:
    at Errors.has (vue-app.js:7)
    at Proxy.eval (eval at makeFunction (vue.js:8238), <anonymous>:3:671)
    at Vue$3.Vue._render (vue.js:2954)
    at Vue$3.<anonymous> (vue.js:2191)
    at Watcher.get (vue.js:1656)
    at Watcher.run (vue.js:1725)
    at flushSchedulerQueue (vue.js:1543)
    at Array.<anonymous> (vue.js:475)
    at nextTickHandler (vue.js:424)
logError @ vue.js:437
Promise.catch (async)
timerFunc @ vue.js:439
queueNextTick @ vue.js:480
queueWatcher @ vue.js:1593
update @ vue.js:1715
notify @ vue.js:582
reactiveSetter @ vue.js:809
record @ vue-app.js:22
onFail @ vue-app.js:71
Promise.catch (async)
submit @ vue-app.js:61
onSubmit @ vue-app.js:88
boundFn @ vue.js:130
submit @ VM267:3
(anonymous) @ vue.js:2750

Не знаю, в чём конкретно заключается проблема и почему в hasOwnProperty передаётся undefined.
mainpage.blade.php:

<form method="post" name="boocking" action="/clients" @submit.prevent="onSubmit" @keydown="form.errors.clear($event.target.name)">

  Представьтесь:
  <input type = 'text' id = "client" name="client" v-model = "form.client">

  Номер телефона:
  <input type = 'text' id = "phone" name="phone" v-model = "form.phone">

  Email:
  <input type = 'text' id = "email" name="email" v-model = "form.email">

  <input type = 'submit' name = 'submitting-botton' value = 'Отправить заказ' :disabled = "form.errors.any()">

</form>

vue-app.js:
class Errors {
  constructor() {
    this.errors = {};
  }

  has(field) {
    return  this.errors.hasOwnProperty(field);
  }

  any() {
    return Object.keys(this.errors).length > 0;
  }

  get(field) {
    if(this.errors[field]) {
      return this.errors[field][0];
    }
  }

  record(errors) {
    this.errors = errors;
  }

  clear(field) {
    if (field) {
      delete this.errors[field];
      return;
    }
    this.errors = {};
  }
}

class Form {
  constructor(data) {
    this.originalData = data;

    for (let field in data) {
      this[field] = data[field];
    }

    this.errors = new Errors();
  }

  data() {
    let data = Object.assign({}, this);
    delete data.originalData;
    delete data.errors;
    return data;
  }

  reset() {
    for(let field in this.originalData) {
      this[field] = '';
    }
  }

  submit(requestType, url) {
    axios[requestType](url, this.data())
    .then(this.onSuccess.bind(this))
    .catch(this.onFail.bind(this))
  }

  onSuccess(response) {
    alert(response.data.message);
    this.errors.clear();
    this.reset();
  }

  onFail(error) {
    this.errors.record(error.response.data.errors);
  }
}

new Vue({
  el: '#app',
  data: {
    form: new Form({
      client: '',
      phone: '',
      email: ''
    })
  },

  methods: {
    onSubmit() {
      this.form.submit('post', '/clients');

    }
  }
});

Заранее спасибо за помощь.


text:
Q: Virtualbox VM only getting IPv6 over bridge connection. How to get IPv4 address I have launched Ubuntu16.04 in Oracle virtual box on windows 10 machine. I have used two type of adapters: NAT and Bridge Connection. The ip address on Bridge connection is getting IPv6 address and not IPv4. I have already tried updating preference in /etc/gai.conf file. But this change is not making any difference. Not sure what is happening.
I am connecting over (home or office) wifi.
This is what i am getting when i do ifconfig
osboxes@osboxes:~$ ifconfig
enp0s3    Link encap:Ethernet  HWaddr 08:00:27:9f:b2:ae
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0
          inet6 addr: fe80::d279:a2f3:ceec:7c63/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:4 errors:0 dropped:0 overruns:0 frame:0
          TX packets:58 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:930 (930.0 B)  TX bytes:6645 (6.6 KB)

enp0s8    Link encap:Ethernet  HWaddr 08:00:27:f1:ae:d5
          inet6 addr: fe80::1bc:78a1:8d5e:90ab/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:10 errors:0 dropped:0 overruns:0 frame:0
          TX packets:29 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1083 (1.0 KB)  TX bytes:4363 (4.3 KB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:32 errors:0 dropped:0 overruns:0 frame:0
          TX packets:32 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2386 (2.3 KB)  TX bytes:2386 (2.3 KB)

However, strange part is when i connect over wifi on mobile tethering, i am getting IPv4 for enp0s8
osboxes@osboxes:~$ ifconfig
enp0s3    Link encap:Ethernet  HWaddr 08:00:27:9f:b2:ae
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0
          inet6 addr: fe80::d279:a2f3:ceec:7c63/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:12 errors:0 dropped:0 overruns:0 frame:0
          TX packets:65 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1919 (1.9 KB)  TX bytes:7121 (7.1 KB)

enp0s8    Link encap:Ethernet  HWaddr 08:00:27:f1:ae:d5
          inet addr:192.168.43.175  Bcast:192.168.43.255  Mask:255.255.255.0
          inet6 addr: fe80::1bc:78a1:8d5e:90ab/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:28 errors:0 dropped:0 overruns:0 frame:0
          TX packets:52 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2751 (2.7 KB)  TX bytes:6492 (6.4 KB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:48 errors:0 dropped:0 overruns:0 frame:0
          TX packets:48 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:3402 (3.4 KB)  TX bytes:3402 (3.4 KB)

Please suggest how can i get IPv4 over Wifi connection.

A: This thread is old but I figured it might help someone else out there...
I also faced the same issue just now. What I did to fix it was to switch to NAT mode in the server settings and then restart networking on the virtual machine. service networking restart  and the just check if it you got a IPv4 address from Virtualbox.
After checking just go into the settings again and switch back to the bridged connection and restart your network on the VM --> service networking restart
Not sure why but this solved the issue for me.

A: The same happens to me when I change my host connection from Wifi to wired, But I was still using WiFi settings in VirtualBox adapter, I solved this changing the VirtualBox adapter for the name of my wired adapter.


text:
Q: SAPUI5 OData V2 Batch Operations with multiple differed groups I'm trying to do a batch operation with multiple groupids in a single batch request. and need to get results in two different batch responses.
But when I initiate the request only one group has been submitted and only get one batch response.
Here is my code
oModel = this.getOwnerComponent().getModel("mymodel");

                $.sap.itemArray.forEach(function (entry) {
                    if (p < $.sap.itemArray.length) {
                        var oData = {
                            "AUTO_ID": entry.Id,
                            "VALUE": entry.Value,

                        };
                        mParameters.groupId = "createGroup1";
                        oModel .create("/Table1", oData, mParameters);

                    }
                    p++;
                });

for (p = 0; p < $.sap.itemArray2.length; p++) {
                    var oData = {
                        "Item2ID" : $.sap.itemArray2[p].ItemsId,
                        "Value" : $.sap.itemArray2[p].Value

                    };

                    mParameters.groupId = "createGroup2";

                    oModel .create("/Table2", oData, mParameters);
                    }

    oModel.setDeferredGroups(["createGroup1","createGroup2"]);
                oStyleSizeModel.submitChanges({
                    success: function(recievedObject){
                          var responses = recievedObject.__batchResponses;
                      },
                    error: function (oError) {
                        var oBody = oError.responseText;

                    }
                });

Here is the response I got.

And here it only execute the first group's requests and only returned one batch response.
How to execute multiple batch requests with different group Ids and get each group's responses.

A: I believe you want to group each change separately. You need to use the concept of Change Set (not Group).

*

*Use createEntry method instead of create.

*For each call, use different changeSetId, but same groupId.

*Call submitChanges passing the groupId.


text:
Q: How to use set javascript variable value for use in Nativescript XML i'm using radlistview to load data from my remote server, i use if statement for some of the elements in the radlistview.
horizontalAlignment="{{ (seller != myemail) ? 'right' : 'left' }}

The issue i'm having is, seller is loaded from the remote server, while the value of myemail was set using viewModel.set("myemail", "example"); . but this doesn't work, it seems only the data loaded from the server can be used in the radlistview. is there a way i can also set values in my viewModel and use it in my xml
this is my radlistview code
 <lv:RadListView style="height:100%;" row="1" items="{{ dataItems }}" loaded="onListLoaded" loadOnDemandMode="Auto" loadMoreDataRequested="{{ onLoadMoreItemsRequested }}" itemLoading="{{ onItemLoading }}" class="list-group">
                            <lv:RadListView.listViewLayout>
                                <lv:ListViewLinearLayout scrollDirection="Vertical" dynamicItemSize="false" itemInsertAnimation="Scale" itemDeleteAnimation="Scale"/>
                            </lv:RadListView.listViewLayout>
                        <lv:RadListView.itemTemplate>
                            <StackLayout>
                            <StackLayout class="message-item" style="width:75%;" horizontalAlignment="{{ (seller != myemail) ? 'right' : 'left' }}">
                                <StackLayout class="message-block" verticalAlignment="top" horizontalAlignment="{{ (seller != sender) ? 'right' : 'left' }}"  borderTopRightRadius="{{ (seller !== sender) ? '0' : '10' }}" borderTopLeftRadius="{{ (seller != sender) ? '10' : '0' }}" style="{{ (seller != sender) ? 'background-color:#b9d4c8' : 'background-color:#cef5e9' }}">

                                </StackLayout>
                            </StackLayout>
                            </StackLayout>
                        </lv:RadListView.itemTemplate>
                    </lv:RadListView>

Thanks in advance, let me know if you need more info

A: The binding content for each item in a RadListView is the corresponding array entry, as you've discovered.  To reference the page's binding context, you can use $parents['Page'].myemail.


text:
Q: TypeError data.forEach is not a function So when I send a get request in postman I am catching my 404 error in postman saying the "scream not found" ok great, but in my terminal I am getting this.

TypeError: data.forEach is not a function
at F:\dev\stfu-functions\functions\handlers\screams.js:68:18
at processTicksAndRejections (internal/process/task_queues.js:97:5)
i  functions: Finished "api" in ~2s
(node:6672) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:526:11)
at ServerResponse.header (F:\dev\stfu-functions\functions\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (F:\dev\stfu-functions\functions\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (F:\dev\stfu-functions\functions\node_modules\express\lib\response.js:267:15)
at F:\dev\stfu-functions\functions\handlers\screams.js:75:29
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:6672) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by
rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6672) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Here is my code where the error is happening Any Help is greatly apreciated.
exports.getScream =(req, res) => {
    let screamData = {};
    db.doc(`/screams/${req.params.screamId}`)
        .get()
        .then((doc) => {
            if(!doc.exists){
                return res.status(404).json({ error: 'Scream not found' });
            }
            screamData = doc.data();
            screamData.screamId = doc.id;
            return db
            .collection('comments')
            .where('screamId', '==', req.params.screamId)
            .get();
        })
        .then((data) => {
            screamData.comments = [];
            data.forEach((doc) => {
                screamData.comments.push(doc.data());
            });
            return res.json(screamData);
        })
        .catch((err) => {
            console.error(err);
            res.status(500).json({ error: err.code });
        })
};


text:
Q: how to add a div for dynamic table Td (not Th)

 function table() {
            var body = document.body,
                     tbl = document.createElement('table'),
                     tableId = document.createAttribute('id');
            tableId.value = "table";
            tbl.setAttributeNode(tableId);
            tbl.className = 'table2';
            var id = 0;
            for (var i = 0; i < 30; i++) {
                var tr = tbl.insertRow();
                tr.setAttribute("data-id", i, 0);

                for (var j = 0; j < 4; j++) {

                    var td = tr.insertCell();
                    td.appendChild(document.createTextNode(""));

                    td.id = "td" + id ;
                    id++;
                }

            }

            $(".middletablediv").append(tbl);

        };
        table();

i have dynamic table which contain td and th  i add div for table td but it also effect the th .i don't want that div in th i want div only in div

$('tr:first-child').children('td').replaceWith(function(i, html) {
  return '' + html + '	';
});

this code is used for change first row td into th
and

$('#table td').wrapInner('
');

this for adding class to td

A: The only reason I could see is the order of your script execution.
If you are running the wrapping code first then the td->td conversion code then the divs will get added to the first row also.
So one solution is to fix the order and move the th  conversion code first.
If that is not possible then you can exclude the first row from wrapping
$('#table tr:not(:first-child) td').wrapInner('
');

A: If you know the specific, try to use append if it works for you.

...

this not be the exact answer you need, but might lead to proper direction.
like where you want to put div, then try this, i used this to my selector class to create 'div'
$("#SelectorID").append("
" + selectedList[empID] + " ×
");


text:
Q: Static does not loads static files in Django This is my directory structure
app_web
    _init_.py
    settings.py
    urls.py
    wsgi.py
upload_app
    migrations/
    static/
       js/
         alert.js
    templates/
       upload.html
    _init_.py
    admin.py
    apps.py
    models.py
    tests.py
    views.py
db.sqlite3
manage.py

In settings.py , my

STATIC_URL = '/static/'

and in my upload.html
{% load staticfiles %}
<script type="text/javascript" src="{% static "js/alert.js" %}"></script>

It does not works and throws 404 error everytime. I even tried load static but it still cannot load anything from static folder and throws 404 error.
I am using Windows 10 machine and Django==1.9

A: The idea was to create a static directory outside the upload_app folder. The reason is that in the settings.py the BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) . That means one directory above is the base directory, so it will start searching static/ from that directory. But it will never find it as I placed inside upload_app/static .
Also, I need to work on putting templates outside the app upload_app as it's not generally best practice to keep templates inside the app.
looking for other suggestions in structure


text:
Q: Zend Regex Route help I am trying to create a Zend_Controller_Router_Route_Regex route to process URLs in the following form:
search?q=chicken/page=2 where the first regex subpattern would be chicken and second one would be 2.  As for the second part where page=2, I want to make it optional if it is the first page, that is page=1. So another url such as search?q=chicken would also be valid and is equivalent to search?q=chicken/page=1.
Here is my attempt albeit without any success, but to give you a better picture of what I am trying to do.

        $route = new Zend_Controller_Router_Route_Regex(
            'search\?q=([a-zA-Z0-9]+)(?:/page=(\d+))',
            array(
                'page'=> '1',
             'module' => 'default',
             'controller' => 'search',
             'action' => 'index' ),
            array( 1 => 'query', 2 => 'page' ),
            'search?=%s/page=%d');
        $router->addRoute('search', $route);

The problem here is I cant compose the correct regex.
Thanks in advance.
EDIT #1
The correct regex, as pointed out by MA4, is 'search\?q=([a-zA-Z0-9]+)(?:/page=(\d+))?'
The real problem is pointed by Darryl.  Here is a little bit more info to put things into perspective.
My search text box and button

    <form action="/search" method="get">
            <input type="text" name="q" />
            <input type="submit" value="Search" />
    </form>

Every time I press the search button, I get the search?q=[text] request.  How do I force it to go through the regex match route?
Here is what i want to do, however the code does not work
    if($this->getRequest()->getParam('query')){
        // redirect success
    } else {
        $url = "search?q=" . $this->_getParam('q');
        $this->_redirect(route('search'), array('code' => 301 ));
    }

A: /search?q=chicken/page=2 is not parsable by Zend Frameworks' router.  The router will only see /search.
The router relies on the Path Info provided by the server and anything after the ? is the query string.
You would need to use a path such as this:
/search/[word]        (default page 1)
/search/[word]/[page]

In which case your regex would become much simpler.

A: make the second part optionnal by adding a ? after it:
search\?q=([a-zA-Z0-9]+)(?:/page=(\d+))?


text:
Q: When do you need a Google Maps API Key? Following Google's Example - Street View Service I was able to make a very simple map to get myself started. I haven't signed up for an API Key though.
Tutorials I've read such as Tutsplus - Getting creative with the Google Maps API says it should be the first step.
That I should have a line:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_GOES_HERE&sensor=true"></script>
But at least in this initial example from Google it works just fine with:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
I read:

*

*Google Map API Issue. Using without API key

*Google Map needs an API or not?
But they don't really answer my more generalized question. When is it needed that I signup for the API Key? What limitations do I face by not signing up and just using the ..js?v=3.exp instead? Is there some other thing I should be using... one of those two SO questions mentions ...maps/api/js?sensor=false for example?

A: You don't need an API key but it allows you to monitor your application. Also you'll need an API key if you want to take a license.
Source : https://developers.google.com/maps/signup