text:
Q: InvalidOperationException when Scrolling DataGrid: The binding expression already belongs to a BindingGroup When trying to scroll down on a DataGrid, I'm getting an InvalidOperationException stating, "The binding expression already belongs to a BindingGroup;  it cannot be added to a different BindingGroup". I don't know of any BindingGroups in use so I'm not really sure what it's talking about. I've narrowed it down to occurring with only the column below. I suspect it also has to do with virtualization. Any ideas?
Here is the DataGrid markup:
<DataGrid x:Name="dgStudentSNP"
              AutoGenerateColumns="False"

              Grid.Row="1" Margin="6,10"
              HorizontalAlignment="Stretch"
              HeadersVisibility="Column"
              CanUserSortColumns="True"
              CanUserAddRows="False"
              CanUserResizeColumns="True"
              CanUserDeleteRows="False"
              BorderThickness="1"
              SelectedValuePath="SNPEnrollmentID" VerticalScrollBarVisibility="Auto" VerticalAlignment="Top" Height="Auto" IsReadOnly="True">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Student Name" MinWidth="120">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock>
                                    <Hyperlink Click="GetStudentFamily" >
                                        <Run>
                                            <Run.Text >
                                                <MultiBinding StringFormat="{}{0} {1}">
                                                    <Binding Path="FirstName"/>
                                                    <Binding Path="LastName" />
                                                </MultiBinding>
                                            </Run.Text>
                                        </Run>
                                    </Hyperlink>
                            </TextBlock>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
              </DataGrid.Columns>
            </DataGrid>

Here is the stack trace for the exception:
Stack Trace :    at System.Windows.Data.BindingExpressionBase.JoinBindingGroup(BindingGroup bg, Boolean explicitJoin)
   at System.Windows.Data.BindingExpressionBase.RejoinBindingGroup(Boolean isReflective, DependencyObject contextElement)
   at System.Windows.Data.BindingExpression.OnDataContextChanged(DependencyObject contextElement)
   at System.Windows.Data.BindingExpression.HandlePropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
   at System.Windows.Data.BindingExpressionBase.OnPropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
   at System.Windows.Data.BindingExpression.OnPropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
   at System.Windows.Data.MultiBindingExpression.HandlePropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
   at System.Windows.Data.BindingExpressionBase.OnPropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
   at System.Windows.DependentList.InvalidateDependents(DependencyObject source, DependencyPropertyChangedEventArgs sourceArgs)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.TreeWalkHelper.OnInheritablePropertyChanged(DependencyObject d, InheritablePropertyChangeInfo info)
   at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d)
   at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d)
   at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren)
   at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d)
   at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d)
   at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d)
   at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren)
   at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren)
   at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d)
   at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d)
   at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe)
   at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d)
   at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren)
   at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d)
   at System.Windows.DescendentsWalker`1.StartWalk(DependencyObject startNode, Boolean skipStartNode)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
   at System.Windows.Controls.ContentPresenter.OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp)
   at System.Windows.Data.BindingExpressionBase.Invalidate(Boolean isASubPropertyChange)
   at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
   at System.Windows.Data.BindingExpression.Activate(Object item)
   at System.Windows.Data.BindingExpression.OnDataContextChanged(DependencyObject contextElement)
   at System.Windows.Data.BindingExpression.HandlePropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
   at System.Windows.Data.BindingExpressionBase.OnPropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
   at System.Windows.Data.BindingExpression.OnPropertyInvalidation(DependencyObject d, DependencyPropertyChangedEventArgs args)
   at System.Windows.DependentList.InvalidateDependents(DependencyObject source, DependencyPropertyChangedEventArgs sourceArgs)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
   at System.Windows.Controls.ItemContainerGenerator.LinkContainerToItem(DependencyObject container, Object item, Boolean isRecycled)
   at System.Windows.Controls.ItemContainerGenerator.OnItemReplaced(Object oldItem, Object newItem, Int32 index)
   at System.Windows.Controls.ItemContainerGenerator.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.IWeakEventListener.ReceiveWeakEvent(Type managerType, Object sender, EventArgs e)
   at System.Windows.WeakEventManager.DeliverEventToList(Object sender, EventArgs args, ListenerList list)
   at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args)
   at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
   at System.Windows.Controls.ItemCollection.System.Windows.IWeakEventListener.ReceiveWeakEvent(Type managerType, Object sender, EventArgs e)
   at System.Windows.WeakEventManager.DeliverEventToList(Object sender, EventArgs args, ListenerList list)
   at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args)
   at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
   at System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs args, Int32 adjustedOldIndex, Int32 adjustedNewIndex)
   at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args)
   at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   at System.Windows.Controls.MultipleCopiesCollection.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.MultipleCopiesCollection.set_CopiedItem(Object value)
   at System.Windows.Controls.Primitives.DataGridCellsPresenter.OnItemChanged(Object oldItem, Object newItem)
   at System.Windows.Controls.DataGridRow.OnItemChanged(Object oldItem, Object newItem)
   at System.Windows.Controls.DataGridRow.NotifyPropertyChanged(DependencyObject d, String propertyName, DependencyPropertyChangedEventArgs e, DataGridNotificationTarget target)
   at System.Windows.Controls.DataGridRow.OnNotifyRowPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.Controls.DataGridRow.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Controls.DataGridRow.PrepareRow(Object item, DataGrid owningDataGrid)
   at System.Windows.Controls.DataGrid.PrepareContainerForItemOverride(DependencyObject element, Object item)
   at System.Windows.Controls.ItemsControl.MS.Internal.Controls.IGeneratorHost.PrepareItemContainer(DependencyObject container, Object item)
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.PrepareItemContainer(DependencyObject container)
   at System.Windows.Controls.VirtualizingStackPanel.InsertContainer(Int32 childIndex, UIElement container, Boolean isRecycled)
   at System.Windows.Controls.VirtualizingStackPanel.AddContainerFromGenerator(Int32 childIndex, UIElement child, Boolean newlyRealized)
   at System.Windows.Controls.VirtualizingStackPanel.MeasureOverride(Size constraint)
   at System.Windows.Controls.Primitives.DataGridRowsPresenter.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
   at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
   at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at Oasis.App.Main()

A: Setting the BindingGroupName to null does indeed work. This is mysterious to me and I wish someone else who understood what was going on a little better would post an answer. But, in the documentation eran otzap posted above:
http://msdn.microsoft.com/en-us/library/system.windows.data.bindinggroup.aspx
It says the following:

You set the BindingGroup property on FrameworkElement or FrameworkContentElement. Child  elements inherit the BindingGroup from their parent elements, just as with any other inheritable property. A binding on a descendent element is added to a BindingGroup if one of the following situations occurs:

*

*The binding's source and the DataContext of the element that has the BindingGroup are the same object and the BindingGroupName property is not set.

*The BindingGroupName property of the binding is equal to the Name of the BindingGroup and they are not explicitly set to null.
In the example of the address, suppose that the DataContext of the Panel is set to the object of type Address. The binding for each TextBox is added to the BindingGroup of the panel.

It would appear that when you use a multibinding in a datagrid the BindingGroup does not match the BindingGroupName for the binding, and so when you try to update those binding errors ensue.
The solution is to explicitly set the BindingGroupName of the MultiBinding to null like
   <MultiBinding StringFormat="{}{0} {1}" BindingGroupName="{x:Null}">
      <Binding Path="FirstName"/>
      <Binding Path="LastName" />
   </MultiBinding>

I have no idea what effect this will have later down the line but it makes this specific exception go away.


text:
Q: Cisco Packet Tracer Dns enable using Router I have a question in Cisco Packet Tracer.
I have a Router and a Dns server and my Config from Dns is blocked. How can I start the DNS server using the Router?
ip dns server ... doesn't work
Thank you

A: Unfortunately Cisco Packet Tracer does not support command "ip dns server" hence you can not use Router like Dns server.
All supported commands you can see in Program_Root_Dir\help\default\index.html or push a question mark in the program.

A: First, you need to attach "WIC 1ENET" in Router to connect it with DNS server
Second, you need an IP address in DNS server For example (192.168.3.2)
Third, enter Gateway like this (192.168.3.1), and DNS server (192.168.3.2)
fourth, Enter the DNS server and go to Services and enter Name and address like this Figure, and then ADD.
Finally, Go to the end Host (PC), then Desktop and then IP Configuration, and Enter the DNS server (192.168.3.2).
I hope that's helpful for you to understand and make it work.

A: You need enable any routing protocol and add the network where is the DNS Server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android how to call the method 25 times per second? I am developing an application which is used to call take the screen shots from devices and saving in external sdcard.  i am able to take the screen shots only 5 per second .. if i exceeds the no of screen shots the mobile ui gets hangs.. i am unable to get the sequence. so please advice me.
First i am taking the frame-buffer as the raw file then converting this as the images.
i need to take to both processes concurrently and also should get atleast 25 frames per second. how should i call the method ?


text:
Q: How to check connection status for host url without using internet in Android? I want to check if the connection to a host url is successful or not, without using internet. My Android application will not use internet. The connection to host url is right now done with the help of VPN.
But in the future, the connection will get changed from VPN to something else, may be APN. And, users will be able to connect to host url with that connection. So, I should be able to check whether user is able to connect to the host url or not. if not, then I will have to stop user from using the application.
Let me know if it is possible to check the connection status without internet connection. And if yes, please give me the solution. I have tried different ways but all of them give me error when internet is not available.


text:
Q: CakePhP write Auth login/logout to debug log I am trying to log users attempts to log in and out, but I reached a dead end.
I am using the Auth Component in the AppController, where it sets all the $this->Auth->user data. If i log it here, it is written twice to the log and i don't know if the login was successful. If i log $this->log($this->Session->read('Auth'), 'debug'); in the login method of the UsersController, it is not yet set, so i don't get the data.
How can i get the Session data just after it's set or deleted? Any other way than extending the Auth Component?
Thank you


text:
Q: How to implement bidirectional relationship in Spring Spanner? In code, I tried with @Interleaved in 1-many relationship at non-owning side to get child list. Could anyone help with below questions:

*

*How to implement bidirectional relationship e.g. get parent from child for 1-1, 1-many relationship

*Regarding many-many relationship, what are best practices to implement it and how to implement bidirectional relationship for it.

Thank you very much.

A: Cloud Spanner currently doesn't offer a way to enforce foreign-key constraints between non-interleaved tables. You will have to enforce such constraints in your application logic. You could use DML statements in Cloud Spanner(that come with the ability to read-your-writes in a Cloud Spanner transaction) to enforce these constraints at insert time by inserting into your tables as follows:
INSERT INTO Referenced(key1,value1) VALUES ('Referenced','Value1');
INSERT INTO Referencing(key2, value2, key1)
SELECT 'Referencing', 'Value2', key1 FROM Referenced WHERE
key1 = 'Referenced';

Running the two statements in a read-write transaction will ensure that the PK-FK relationship between the Referenced and Referencing table is always maintained at insert time. You may have to similarly modify update requests/SQL update statements in your application logic to enforce the PK-FK constraint for updates.

A: For a 1-many relationship, when  using interleaved tables, then the child row's primary key already contains the primary key of its parent, so it is trivial to get the parent row.
CREATE TABLE parent (
    parent_key INT64 NOT NULL,
    ...
) PRIMARY KEY (parent_key);

CREATE TABLE child (
    parent_key INT64 NOT NULL,
    child_key INT64 NOT NULL,
    ...
) PRIMARY KEY (parent_key, child_key),
INTERLEAVE IN PARENT parent ON DELETE CASCADE;

If for some reason you do not have the key of the parent, and only the key of the child, then for efficiency you would need to create an index for the reverse lookup:
CREATE INDEX child_to_parent_index
ON child (
    child_key
);

and force use of that index when performing the query for the parent:
SELECT
    p.*
FROM
    parent as p
JOIN
    child@{FORCE_INDEX=child_by_id_index} AS c ON p.parent_key = c.parent_key
WHERE
    c.child_key = @CHILD_KEY_VALUE;

Many-many relationships would have to be implemented using a 'mapping' table linking table1-key to table2-key.
You will also need a top-level index to get efficient reverse-lookups, and use the FORCE_INDEX directive as above in your queries.
And as @adi mentioned, foreign key constraints would have to be enforced by the application.
CREATE TABLE table1 (
    table1_key INT64 NOT NULL,
    ...
) PRIMARY KEY (table1_key);

CREATE TABLE table2 (
    table2_key INT64 NOT NULL,
    ...
) PRIMARY KEY (table2_key);

CREATE TABLE table1_table2_map (
    table1_key INT64 NOT NULL,
    table2_key INT64 NOT NULL,
) PRIMARY KEY (table1_key, table2_key);

CREATE INDEX table2_table1_map_index
ON table1_table2_map (
    table2_key
) STORING (
    table1_key
);

Your application would be responsible for keeping the referential integrity of the mapping table - deleting the mapping rows when rows in table1 or table2 are deleted
If you want to use interleaved tables, then if your application needs to perform bi-directional lookups, you may have to create 2 mapping tables - as a child of each parent, so that finding the mappings from both directions are equally efficient.
CREATE TABLE table1 (
    table1_key INT64 NOT NULL,
    ...
) PRIMARY KEY (table1_key);

CREATE TABLE table2 (
    table2_key INT64 NOT NULL,
    ...
) PRIMARY KEY (table2_key);

CREATE TABLE table1_table2_map (
    table1_key INT64 NOT NULL,
    table2_key INT64 NOT NULL,
) PRIMARY KEY (table1_key, table2_key),
INTERLEAVE IN PARENT table1 ON DELETE CASCADE;

CREATE TABLE table2_table1_map (
    table2_key INT64 NOT NULL,
    table1_key INT64 NOT NULL,
) PRIMARY KEY (table2_key, table1_key),
INTERLEAVE IN PARENT table2 ON DELETE CASCADE;

Note that the application needs to keep both of these mapping tables up to date -- ie when deleting a row from table1, the application has to get the referenced table2_key values and delete the mappings from the table2_table1_map (and vice versa).


text:
Q: "git svn fetch" creates index.lock file then complains about it I'm migrating a large subversion repository, with history, to git. I started by cloning the svn repo using 'git svn clone' command. This crashed while cloning, however, I resumed the migration by executing 'git svn fetch'. The migration had been running successfully for a couple of days - occasionally it crashed and I had to delete the index.lock file as detailed here - fatal: Unable to create '/.git/index.lock': File exists. After deleting this file a couple of times it successfully continued until I ran into the same error:
    fatal: Unable to create '/path/index.lock': File exists.

If no other git process is currently running, this probably means a
git process crashed in this repository earlier. Make sure no other git
process is running and remove the file manually to continue.
read-tree f49b2a08d26076d9cb2828b9aba5fde30d46f73b: command returned error: 128

However, this time deleting the index.lock file did not work and 'git svn fetch' continues to complain. Here is what is happening:
I get the above error
I delete the index.lock file
I restart 'git svn fetch'
'git svn fetch' process recreates the index.lock file
'git svn fetch' errors again with the above error
So 'git svn fetch' appears to be in some bad loop where it's re-creating the index.lock file then then complains about it existing. So:
I've deleted the index.lock file.
I've ensured that the machine has enough disk space.
I've tried rebooting the machine in case there was an old git processing hanging around that was holding on to the lock file.
I've done a git gc and a git prune as advised here fatal: git-write-tree: error building trees
None of the above has worked and I'm new to git. I don't want to re-start the migration as it takes days to run. Can anyone suggest something else I could try?

A: Answering my own question just to tidy this up. Unfortunately I never got to the bottom of this problem and we had to set off a new migration (in fact we set off 3 migrations on different machines and the first one to finish took 2 weeks to run). If you're migrating a large repository (ours is a code and assets base of around 35 GB) expect it to take a long time and to encounter some frustrations. We frequently encountered the error above and I'm happy to say that deleting the index.lock file and continuing the migration with "git svn fetch" worked. We didn't again run into the problem above where the migration wouldn't continue.


text:
Q: Javascript add days, weeks or months to date of today I've got a piece of code that cleans the browsers local storage.
What I want is to delete some keys based on parameters set.
An example:

What this should be doing is to delete the localstorage on the first day of every month. Another example is when you fill in 5, 2, weeks. Then it should delete the localstorage every 5th day of every 2 weeks.
Now the main problem is adding the different periods to today's date in order to calculate the time when this needs to be done. I've been in over my head with this and tried some things (as you can see) but without results...
Anyone cares to help me out?
Thx!

Here's the code:
function cleanLocalStorage() {
  var today = makeDate(todayDate()),
    deleteoption = localStorage.getItem("historydeleteoption"),
    lasthistoryclean = makeDate(localStorage.getItem("lasthistoryclean"));

  if (deleteoption == "days") {
    for (key in localStorage) {
      if (makeDate(key) < today.subtractDays(getHistoryRetain())) // days to keep data excluding today
        delete localStorage[key];
    }
  } else if (deleteoption == "period") {
    var historyretain = localStorage.getItem("historyretain"),
      historyresetday = localStorage.getItem("historyresetday"),
      historyresetperiod = localStorage.getItem("historyresetperiod"),
      historyresetperiodunit = localStorage.getItem("historyresetperiodunit"),
      cleaningday = "";

    if (historyresetperiodunit == "days") { ?
      // ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
    } else if (historyresetperiodunit == "weeks") { ?
      //  ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
      var cleaningday = lasthistoryclean + (historyresetperiod * 7);
    } else if (historyresetperiodunit == "months") { ?
      // ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
      var cleaningday = new Date(lasthistoryclean.setMonth(lasthistoryclean.getMonth() + historyresetperiod));
    }
  }
  localStorage.setItem("lasthistoryclean", todayDate());
}

function todayDate() {
  var date = new Date();

  var dd = ('0' + date.getDate()).slice(-2),
    mm = ('0' + (date.getMonth() + 1)).slice(-2), //jan is 0
    yyyy = date.getFullYear();

  return dd + "-" + mm + "-" + yyyy;
}

function makeDate(date) {
  var parts = date.split("-");
  return new Date(parts[2], parts[1] - 1, parts[0]);
}

  <input type="radio" name="historydeleteoption" id="historydeleteoptiondays" value="days" onchange="greyOutHistoryDeleteOption()" checked="checked">
  Max days to keep history:
    <input type="number" name="historyretain" id="historyretain" value="30" min="0" max="999" style="width: 70px; margin: 2px 0;">

  <input type="radio" name="historydeleteoption" id="historydeleteoptionperiod" value="period" onchange="greyOutHistoryDeleteOption()">
  Reset history on day
    <input type="number" name="historyresetday" id="historyresetday" value="1" min="1" max="31" style="width: 70px; margin: 2px 0;"> of every
    <input type="number" name="historyresetperiod" id="historyresetperiod" value="4" min="1" style="width: 70px; margin: 2px 0;">
    <select name="historyresetperiodunit" id="historyresetperiodunit" onchange="maxValuesDeleteOption()" style="margin: 2px 0;">
      <option value="days">days</option>
      <option value="weeks">weeks</option>
      <option value="months">months</option>
    </select>

A: I created this compact function:
function DateAdd(dfrom,anz,sel){
    var df = (dfrom || dfrom === 0) ? (typeof dfrom == "string" ? dfrom.replace(/(\d{1,2})\.(\d{1,2})\./,'$2/$1/') : dfrom) : "";
    df = df instanceof Date ? new Date(df-0) : (df === "" ? new Date() : new Date(df));
    var pj = {y:[1,"FullYear"],m:[1,"Month"],w:[7,"Date"],d:[1,"Date"],h:[3600000],n:[60000],s:[1000],ms:[1]};
    var s=pj[sel] || [1];
    var s1 = s[1] || "Time";
    df["set"+s1](df["get"+s1]() + parseInt(anz||0,10) * s[0]);
    return df;
}

Negative numbers are also allowed for anz parameter.
These values are possible for the sel parameter:

*

*'y' - years

*'m' - months

*'w' - weeks

*'d' - days

*'h' - hours

*'n' - Minutes

*'s' - Seconds

*'ms' - Milliseconds

Examples of use
//Add 3 Days to current Date
var date = DateAdd(new Date, 3, 'd');

//2 weeks after 2019-03-01
var date = DateAdd('2019-03-01', 2, 'w');
//Fri Mar 15 2019

//6 month after 1.3.2019
var date = DateAdd('1.3.2019', 6, 'm');
//Sun Sep 01 2019


text:
Q: Creating an Outlook Add-in in Visual Studio 2013 from a Outlook VBA project (.OTM) I have a VBA Project in Outlook 2013 (VbaProject.OTM) that has several macros and currently works well. I would like to create a COM Add-in for Outlook in Visual Studio 2013 for this Project. What is the best/quickest way of getting this done? I have been searching through for information but most of them specify exporting the modules and importing it back in visual studio. Is it possible to do it on a project level? Also how do I add references that I had in Outlook 2013's VBA project to my visual studio 2013 project? Kindly let me know.
Cheers.

A: You'd need to manually convert all of your VBA code to VB.NET; I know of no existing converter.  The languages are very similar but still have a great of differences (especialily with variable declaration).
I'm not sure what kind of references you are using, but you can still set references to COM objects in Visual Studio.

A: As Eric mentioned, there is no tool for converting your VBA code into an add-in. Need to create an Outlook add-in from scratch.
You may find the Converting a VBA Macro to C# 4.0 blog post helpful.


text:
Q: Autocomplete jquery plugin does not work when data comes from database? I am using this plugin for textarea suggestion (auto completion). It is working fine as long as list is hardcoded. like this :-

var suggests = ["Action", "ActionScript", "Borland"];

But I need words list from the database. When i get list from database, plugin does not respond. Here is what I am doing:-
Plugin I am using:-

https://github.com/imankulov/asuggest/

Jquery:-
$(document).ready(function() {
        var suggests = getList();
        var $txt = $('#<%=txtArea.ClientID %>');
        $txt.asuggest(suggests);
    });

function getList() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ajaxService.asmx/autocompletelist",
        data: "{groupUid:'" + 4 + "', clientUid: '" + 8 + "'}",
        dataType: "json",
        success: function(data) {
            return (data.d);
        },
        error: function(result) {
            alert("No Match");
        }
    });
}

code behind:-
[WebMethod]
public List<string> autocompletelist(int groupUid, int clientUid)
{
        //call to database for the list.
          //code/

        List<string> result = new List<string>();
        result.Add("Action");
        result.Add("ActionScript");
        result.Add("Borland");
        return result;
}

Please suggest? Is it something to do with square brackets? How to get that in return from database?

A: An ajax success function is executed asynchronously (it doesn't get fired until a response is received), but you're trying to use its result in a synchronous fashion. So when you call $txt.asuggest(suggests);, nothing happens because suggests has not been populated yet. This is because the ajax request hasn't finished, but your code doesn't know that. The simplest way to fix this is to put the logic for the UI in the success method itself. That way your plugin wont be called until the suggests variable is guaranteed to be populated. Try this:
$(document).ready(function() {
    getList();
});

function getList() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ajaxService.asmx/autocompletelist",
        data: "{groupUid:'" + 4 + "', clientUid: '" + 8 + "'}",
        dataType: "json",
        success: function(data) {
            var $txt = $('#<%=txtArea.ClientID %>');
            $txt.asuggest(data);
        },
        error: function(result) {
            alert("No Match");
        }
    });
}

A: You can first do it like this alert(suggests),check whether the result was correct,then convert the result to array.
convert json to array:
var dataArray=eval(jsonStr);
for(var i in dataArray)
{
    //TODO
}


text:
Q: Move the line before the table along with the table if the line appears on the page preceding the table We have captions for tables in our Word documents that do not behave like captions and act as "Normal" word styles. These captions sometimes appear on the preceding page of the table.
There are hundreds of documents and may be a million instances of captions in those documents. The documents were imported from an old source system to a new source system using a script, which didn't do the job as expected.
I would like if such captions exist on the preceding page, they are removed from the page and shown before the table on the same page.
The logic that I want to use:

*

*Find a table

*Find the page number of the table

*Find the first instance of "Normal" paragraph style just before the table

*Find the page number of the "Normal" Paragraph style

*Only if the page number of the first instance of the "Normal" Paragraph style is less than the page number of the table by 1, then move the entire instance to the next page just before the table

*Do this for all tables.

So far I could only manage to write this code:
Dim tblNew As Table
Dim oPara As Paragraph
Dim oRng As Range
Dim PageNo As Integer
Dim PageNoCap As Integer

For Each tblNew In ActiveDocument.Tables
PageNo = tblNew.Range.Information(wdActiveEndPageNumber)

A: I would approach this by fixing the incorrect use of styles. The code below applies the Caption style to demonstrate the principle.
Using code to compensate for not using Word correctly in the first place is a bad idea, but if you have existing documents that you need to correct could be a useful temporary measure.
Sub ApplyStyleToTableCaptions()
    Dim tbl As Table
    Dim oRng As Range

    With ActiveDocument.Styles(wdStyleCaption).ParagraphFormat
        If Not .KeepWithNext Then .KeepWithNext = True
    End With
    For Each tbl In ActiveDocument.Tables
        Set oRng = tbl.Range
        oRng.Collapse wdCollapseStart
        oRng.Move wdParagraph, -1
        oRng.Paragraphs(1).Range.Style = wdStyleCaption
    Next tbl
End Sub


text:
Q: Casimir Effect. Where does the energy which pulls the plate come from? According to this video here on the Casimir Effect Wikipedia. Due to the greater pressure from the 'outside' of the plates these plates of metals get pushed towards each other.  When this pressure pushes one plate it does work on the plate and increases the plate's energy. However since the effect is demonstrated in a vacuum where does this energy come from?

A:
However since the effect is demonstrated in a vacuum where does this energy come from?

You are under a bit of a misapprehension here. The many different fields described by Quantum Field Theory exist everywhere throughout the universe, they are not limited by a vacuum.

In theoretical physics, quantum field theory (QFT) is the theoretical framework for constructing quantum mechanical models of subatomic particles in particle physics and quasiparticles in condensed matter physics. QFT treats particles as excited states of the underlying physical field, so these are called field quanta.
Although the Casimir effect can be expressed in terms of virtual particles interacting with the objects, it is best described and more easily calculated in terms of the zero-point energy of a quantized field in the intervening space between the objects. This force has been measured and is a striking example of an effect captured formally by second quantization.

Personally, my mental image of  it is that there are less excitations/modes of vibration inside the plates than outside, so there is a net force. It is  not that there is no field in the vacuum, it's that there are less degrees of freedom for the field inside the gap than outside it.
I apologise to all of those people now shouting at the screen,  who have gone (much) further in their studies of QFT than I have.  I would ask for a little leeway in this crude descrption, and hopefully a more sophisticated answer.  There are probably duplicates and better answers currently  on this site.

A: Think about how the plates get there in the first place. The energy of the vacuum state with the plates placed apart has higher energy than the vacuum state with the plates together (or with no plates at all). Therefore, putting the plates in their initial positions does work on the quantum fields comprising the vacuum. This work input can then be extracted again by releasing the plates and allowing them to be pushed together.
You can think of the placement of the plates as like a piston (plates) compressing a gas (quantum fields). Releasing the plates allows the vacuum to perform work on the plates, just like a compressed gas would perform work on a piston by expanding back to its equilibrium volume. Clearly you never get more energy out than you put in.


text:
Q: New to powershell and my foreach keeps failing. Trying to iterate over a list of cert files but it fails. Probably simple Problem:
When I import a cert individually, outside of a foreach, it prints the thumbprint as needed; however, I need to iterate through a list of .cer files on a fileshare so that I can run them against a local machine's currently installed certs. The moment I try to run the list of certs through my foreach, it fails.
Working code (individually)
<# Notice the explicite .cer file #>
$certGet = Get-ChildItem -Path \\fileserver\...\Certs\cert.cer

$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($certGet)
$cert.Thumbprint

I am trying to scale this working code out into a foreach to iterate over a list or .cer files. Below is my attempt thus far.
Failing code:
$certGetList = Get-ChildItem -Path \\fileserver\...\Certs

$certGetList | ForEach-Object {
    $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
    $cert.Import($_)
    $cert.Thumbprint
}

Error message
ERROR: Exception calling "Import" with "1" argument(s): "The system cannot find the file specified.
ERROR: "
list_thumbprints_test.ps1 (18, 2): ERROR: At Line: 18 char: 2
ERROR: +     $cert.Import($_)
ERROR: +     ~~~~~~~~~~~~~~~~
ERROR:     + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
ERROR:     + FullyQualifiedErrorId : CryptographicException
ERROR:

A: Of course... so simple.
Answer:
$cert.Import($certGetList + "\" + $_)

Somehow, it loses the origin of the object and tries to find the relative file locally, instead of on the network share. I needed to explicitly direct it to the network share for each iteration.


text:
Q: Inverse Matrix Question Determine whether there is an inverse and then determine what the inverse is if it exists:
\begin{bmatrix}a&b\\c&d\end{bmatrix}
Where $ad-bc\not= 0$.
I know how to do this for a normal matrix, but I don't understand how to do this for one with the variables.

A: Try to multiply your matrix by
$$\frac 1{ad-bc}\begin{pmatrix} d & -b \\ -c & a \end{pmatrix}$$
which is legit since $ad-bc\ne 0$.
What can you conclude?
One way of finding this particular matrix is using Gauss' reduction.

A: If a matrix has an inverse, we can find this inverse using the following method:(in this case, because $ad-bc \neq 0$, we certainly can find an inverse matrix, as you will notice throughout the work)
$(A|I_n) \equiv (I_n|A^{-1}) $
where $\equiv$ means that those 2 matrices are row equivalent. Thus, look for the row reduced echelon form of:
\begin{bmatrix}a&b&1&0\\c&d&0&1\end{bmatrix}.
What appears in the two last column will be the inverse you are looking for.

A: You need to solve this equation:
$$\begin{bmatrix}a&b\\c&d\end{bmatrix}\begin{bmatrix}a'&b'\\c'&d'\end{bmatrix}
=\begin{bmatrix}1&0\\0&1\end{bmatrix}.$$
After expansion, you get the system
$$\begin{cases}aa'+bc'=1,\\ca'+dc'=0,\\ab'+bd'=0,\\cb'+dd'=1.\end{cases}$$ which splits in two $2\times2$ subsystems.
Then by Cramer
$$\begin{cases}
a=\frac{\left|\begin{matrix}1&b\\0&d\end{matrix}\right|}{\left|\begin{matrix}a&b\\c&d\end{matrix}\right|},
b=\frac{\left|\begin{matrix}0&b\\1&d\end{matrix}\right|}{\left|\begin{matrix}a&b\\c&d\end{matrix}\right|},\\
c=\frac{\left|\begin{matrix}a&1\\c&0\end{matrix}\right|}{\left|\begin{matrix}a&b\\c&d\end{matrix}\right|},
d=\frac{\left|\begin{matrix}a&0\\c&1\end{matrix}\right|}{\left|\begin{matrix}a&b\\c&d\end{matrix}\right|},
\end{cases}$$
giving
$$\begin{bmatrix}\frac d{ad-bc}&-\frac b{ad-bc}\\-\frac c{ad-bc}&\frac a{ad-bc}\end{bmatrix}.$$

A: There are other answers. But I wanted to include this answer wherein we reduce the matrix to the identity and ensures the existence of the inverse.
Denote the given matrix by $A.$
1) $c=0$
If $c=0,$ then $a$ and $d$ both has to be non-zero, otherwise we would have $ad-bc=0.$
Row-reducing $\begin{bmatrix}a&b\\0&d\end{bmatrix}\to \begin{bmatrix}1&b/a\\0&1\end{bmatrix}\to \begin{bmatrix}1&0\\0&1\end{bmatrix}$
Thus $A$ is invertible.
2) $a=0$
If $a=0$ then $b$ and $c$ both has to be non-zero, otherwise we would have $ad-bc=0.$
Row-reducing $\begin{bmatrix}0&b\\c&d\end{bmatrix}\to\begin{bmatrix}0&1\\1&d/c\end{bmatrix}\to\begin{bmatrix}0&1\\1&0\end{bmatrix}\to\begin{bmatrix}1&0\\0&1\end{bmatrix}$
$A$ is invertible in this case too.
3) $a\ne 0, c\ne 0$
Row-reducing $\begin{bmatrix}a&b\\c&d\end{bmatrix}\to \begin{bmatrix}ac&bc\\ac&ad\end{bmatrix}\to\begin{bmatrix}ac&bc\\0&ad-bc\end{bmatrix}\to\begin{bmatrix}ac&bc\\0&1\end{bmatrix}\to\begin{bmatrix}ac&0\\0&1\end{bmatrix}\to\begin{bmatrix}1&0\\0&1\end{bmatrix}.$
Thus $A$ is invertible in all the cases and the inverse exists.
The explicit form of the inverse is given in one of the other answers to the question.


text:
Q: Hooking to Zapier using .Net WebHooks as RESThooks I am looking into creating a "Zap App" and am wondering if anyone has done so using the new .Net Webhooks. They seem to have the "pattern" requested by RESTHooks, the Subcription/Publish mechanism. Not a lot of examples of it working and I wanted to check before I spent days implementing it and find it is incompatible.
Actual code examples of hooking to Zapier would be great!

A: Took a bit of research, but I finally have the Zapier Rest Hooks working. Not as straight forward as I might have hoped (more likely I am a bit slow on the uptake). The customer support was excellent and friendly, so don't hesitate to email them your questions. Also once you get this working it is VERY powerful, though their normal webhook mechanism also works and does not require you to create a Zap App. At the time of this writing I have not pushed out the application, though it is working locally. This assumes you have started to create your own Zapier Application in the Developer Dashboard. It is pretty straightforward so I will not cover it here.
This explanation will only cover creating a single Trigger (though you create 1 more private one to support user Authentication, and I created another for a dynamic pulldown purposes) and only as a RESThook with Basic Auth. The basics are:
1. Create webhooks to allow Zapier to add, update and remove subscriptions to your Actions. By "subscribing" Zapier does not have to poll your webhook, rather when the subscribed action happens on your side, you respond to a URL that Zapier has given you during the subscription process.
2. Create a DB table that logs these subscriptions, storing the data that you need to be able to then Post a response back to a Zapier supplied URL when the action is triggered on your side.
3. When the action is triggered, recognize that and post the data you told zapier that you would be sending. Zapier is pretty clever and will map the data (JSON or XML) for you, so when wiring up to another app the user can map between the two.
So a few more details. This was done in C# on .Net, but I think the concepts should work just as well in any other language or platform.
First the RESTHooks. What follows is an example of the RESTHook methods. Please note that I spent days trying to figure out the Zapier scripting side, so I am not entirely happy with the naming conventions, but hopefully you will get the idea.
In this scenario there is the concept of a "form" which is a chunk of JSON holding data that I care about, a User and Account that user belongs to. All of them have a unique ID in the System. Finally the subscription itself has an id. When you are subscribing, a specific User in a specific Account is subscribing a specific Form to be sent to Zapier when a specific Trigger (a submission of that form) is accomplished.
RESTHooks:
First the RouteConfig which maps the path to the method to execute. You can see all the methods I implemented. Some of them are not used and just included for possible future use (like updating a subscription).
    // ZAPIER Webhooks
    routes.MapRoute(
       "User_Form_List",
       "api/zapier/user/formlist",
        new { controller = "Zapier", action = "RetrieveFormListForUser" },
        new { httpMethod = new HttpMethodConstraint("GET") }
        );
    routes.MapRoute(
       "Authenticate_Subscription",
       "api/zapier/authenticate",
        new { controller = "Zapier", action = "WebhookAuthenticate" },
        new { httpMethod = new HttpMethodConstraint("GET") }
        );
    routes.MapRoute(
        "Test_Subscription",
        "api/zapier/subscription/testdata",
        new { controller = "Zapier", action = "TestData" },
        new { httpMethod = new HttpMethodConstraint("GET") }
        );
    routes.MapRoute(
        "Create_Submission",
        "api/zapier/subscription/create",
        new { controller = "Zapier", action = "CreateSubscription" },
        new { httpMethod = new HttpMethodConstraint("GET") }
        );
    routes.MapRoute(
       "List_Subscriptions",
       "api/zapier/subscription",
       new { controller = "Zapier", action = "ListSubscriptions" },
       new { httpMethod = new HttpMethodConstraint("GET") }
       );
    routes.MapRoute(
       "Get_Subscriptions",
       "api/zapier/subscription/{id}",
       new { controller = "Zapier", action = "GetSubscription", id = 0 },
       new { httpMethod = new HttpMethodConstraint("GET") }
       );
    routes.MapRoute(
       "Update_Subscription",
       "api/zapier/subscription/{id}",
       new { controller = "Zapier", action = "UpdateSubscription", id = 0 },
       new { httpMethod = new HttpMethodConstraint("PUT") }
       );
    routes.MapRoute(
        "Delete_Subscription",
        "api/zapier/subscription/{id}",
        new { controller = "Zapier", action = "DeleteSubscription", id = 0 },
        new { httpMethod = new HttpMethodConstraint("DELETE") }
    );

The code corresponding to this is (Also I have pulled out the error handling to reduce the code size):
    public class ZapierController : BaseController //(this inherits from Controller)
    {
        private readonly IMyRepository _DBrepository;

        public ZapierController(IMyRepository repository, ...lots of other autowiring you don't need or care about)
            : base(logger)
        {
            _DBrepository = repository;
         }

        #region Zapier Subscriptions

        // api/zapier/subscription/create  : Creates a subscription
        [HttpGet]
        public ActionResult CreateSubscription()
        {
            ApiResult authresult = Authenticate();
            if (authresult.code != 201)
            {
                return JsonApiResult(authresult);
            }

            // Get the request parameters
            var reqParams = GetParameters();

            // Create the subscription so long as it does not already exist
            WebhookSubscription sub = new WebhookSubscription();
            // _currentUser and _currentAccount are set as part of the authenticate and stored in our base controller
            sub.AccountId = _currentAccount.Id;
            sub.UserId = _currentUser.UserId;
            sub.TargetURL = reqParams["target_url"];
            sub.EventType = reqParams["target_event"];
            sub.FormId = Int32.Parse(reqParams["form_id"]);
            sub.IsActive = true;

            ObjectResult workflowActionRecord = _DBrepository.createWebhookSubscription(sub);
            sub.Id = workflowActionRecord.objectId;

            // return the subscription back to Zapier in the result. Zapier will remember it
            var result = new ApiResult();
            result.data.id = workflowActionRecord.objectId;
            result.data.subscription = sub;
            result.code = 201;
            return JsonApiResult(result);
        }

        // api/zapier/authenticate  : used to test authentication
        [HttpGet]
        public ActionResult WebhookAuthenticate()
        {
            ApiResult authresult = Authenticate();

            var result = new ApiResult();
            result.code = 201;
            return JsonApiResult(result);
        }

        // api/zapier/user/formlist  : returns list of forms for this user
        [HttpGet]
        public ActionResult RetrieveFormListForUser()
        {
            ApiResult authresult = Authenticate();

            var result = new ApiResult();

            List<Form> forms = _DBRepository.FormListRetrieveByUser(_currentUser, false);

            JsonSerializer serializer = new JsonSerializer();
            serializer.Converters.Add(new JavaScriptDateTimeConverter());
            serializer.NullValueHandling = NullValueHandling.Ignore;

            // Again Zapier likes arrays returned
            JArray objarray = JArray.FromObject(forms);
            return JsonApiResultDynamic(objarray);
        }

        // api/zapier/subscription/testdata  : returns test data for zapier
        [HttpGet]
        public ActionResult TestData()
        {

            ApiResult authresult = Authenticate();

            var result = new ApiResult();

            JsonSerializer serializer = new JsonSerializer();
            serializer.Converters.Add(new JavaScriptDateTimeConverter());
            serializer.NullValueHandling = NullValueHandling.Ignore;

            // Get the request parameters
            var reqParams = GetParameters();
            int chosenFormId = -1;
            // We need the form Id to proceed
            if (reqParams != null && reqParams["form_id"] != null)
                chosenFormId = Int32.Parse(reqParams["form_id"]);
            else
                return  JsonApiResult(new ApiResult() { code = 403, error = "Form Id Not Found" });

            // Get the form by Form Id, and return the JSON...I have removed that code, but make sure the result is place in an Array
            var resultdata = new[] { myFinalFormJSON };

            JArray objarray = JArray.FromObject(resultdata);
            return JsonApiResultDynamic(objarray);
        }

        // api/zapier/subscription  : returns list of subscriptions by account
        [HttpGet]
        public ActionResult ListSubscriptions()
        {
            ApiResult authresult = Authenticate();

            // Get a list all subscriptions for the account
            List<WebhookSubscription> actionData = _DBrepository.accountWebhookSubscriptions(_currentAccount.Id);

            var result = new ApiResult();
            result.code = 201;
            result.data.subscriptions = actionData;
            return JsonApiResult(result);
        }

        // api/zapier/subscription/{id}  : Creates a subscription
        [HttpGet]
        public ActionResult GetSubscription(int id)
        {
            ApiResult authresult = Authenticate();

            // Get a list all subscriptions for the account
            WebhookSubscription actionData = _DBrepository.getWebhookSubscription(id);

            var result = new ApiResult();
            result.data.subscription = actionData; ;
            result.code = 201;
            return JsonApiResult(result);
        }

        // api/zapier/subscription/{id}  : updates a subscription
        [HttpPut]
        public ActionResult UpdateSubscription(int id)
        {
            ApiResult authresult = Authenticate();

            // get target url and eventy type from the body of request
            string jsonString = RequestBody();
            var json = CommonUtils.DecodeJson(jsonString);

            // Create the subscription so long as it does not already exist
            WebhookSubscription sub = _DBrepository.getWebhookSubscription(id);

            var result = new ApiResult();
            if (sub != null)
            {
                sub.TargetURL = json.target_url; ;
                sub.EventType = json.eventType;

                ObjectResult objResult = _DBrepository.updateWebhookSubscription(sub);
                result.code = 201;
            }

            return JsonApiResult(result);
        }

        // api/zapier/subscription/{id}  : deletes a subscription
        [HttpDelete]
        public ActionResult DeleteSubscription(int id)
        {
            ApiResult authresult = Authenticate();

            // Delete a subscription
            _DBrepository.deleteWebhookSubscription(id);

            var result = new ApiResult();
            result.code = 201;
            return JsonApiResult(result);
        }

        // We need to Basic Auth for each call to subscription
        public ApiResult Authenticate()
        {
            // get auth from basic authentication header
            var auth = this.BasicAuthHeaderValue();

            // parse credentials from auth
            var userCredentials = Encoding.UTF8.GetString(Convert.FromBase64String(auth));
            var parts = CommonUtils.SplitOnFirst(userCredentials, ":");
            var username = parts[0];
            var password = parts[1];

            // authenticate user against repository
            if (!_DBrepository.UserAuthenticate(username, password))
            {
                _logger.Info("Invalid Authentication: " + username);
                return new ApiResult() { code = 401, error = "invalid authentication" };
            }

            return new ApiResult() { code = 201, error = "successful authentication" };

        }
   }

The DB table that will hold the subscriptions looks like this. I will leave out the reading and writing side, since you might have different mechanism.
   Create.Table("WebhookSubscription")
        .WithColumn("Id").AsInt32().Identity().PrimaryKey().NotNullable()
        .WithColumn("AccountId").AsInt32().NotNullable()
        .WithColumn("UserId").AsInt32().NotNullable()
        .WithColumn("EventType").AsString(256).NotNullable()
        .WithColumn("TargetURL").AsString(1000).NotNullable()
        .WithColumn("IsActive").AsBoolean().NotNullable()
        .WithColumn("CreatedOn").AsDateTime().Nullable()
        .WithColumn("FormId").AsInt32().NotNullable().WithDefaultValue(0);
        .WithColumn("UpdatedAt").AsDateTime().Nullable();

Just to be clear, the meaning/use for the following columns:

*

*Id - Unique Subscription ID. Will be used to unsubscribe

*AccountId - Account Id for the user subscribing. If you wanted all of these to work on an Account level could just do that instead

*UserId - Id of user subscribing

*EventType - The type of event your Action is to respond to, such as "new_form_submission"

*TargetURL - Target URL that zapier gave you when subscribing. Will be where you post your JSON when Action initiated

*FormId - Id of the form the user wants an action for when submitted

So that is the code needed for subscription (obviously you can't just throw it up there and have it work - left out a good amount to save space)...
Trigger Code
Only code left is the actual Trigger code - the code you execute when the event being looked for is encountered in your code. So for example when the user submits a "form" we want to send that form JSON to Zapier. Now that we have all the other code set up, this part is pretty simple. First the code to detect we had a submission arrive that needs a Zapier response:
The actual code that looks to see if the form submission is registered/subscribed to Zapier:
public BusinessResult FormSubmitted(string jsonString)
{
    var json = CommonUtils.DecodeJson(jsonString);
    var account = _DBrepository.AccountRetrieveById(_currentUser.AccountId.Value); // Assumes user has bee authenticated

    // inject additional meta data into json and retrieve submission/alert settings
    var form = _DBformRepository.FormRetrieveById((int)json.formId);

    // Lookup Subscription Webhooks
    List<WebhookSubscription>  subscriptions = _DBrepository.accountWebhookSubscriptions(account.Id);
    if (subscriptions != null && subscriptions.Count > 0)
    {
        foreach (WebhookSubscription sub in subscriptions)
        {
            if (sub.EventType.Equals("new_form_submission") && sub.FormId == form.Id)
            {
                _webhookService.NewFormSubmission(sub, jsonString, form.Name, account.Name, account.Id);
            }
        }
    }
}

And Finally the code to post that response back to Zapier, who will parse the JSON and send it to the appropriate parties:
public class WebhookService : IWebhookService
{
    protected readonly IRepository _DBrepository;

    public WebhookService(IRepository repository)
    {
        _DBrepository = repository;
    }

    public void NewFormSubmission(string formResultJSON)
    {
        throw new NotImplementedException();
    }

    public void NewFormSubmission(WebhookSubscription subscription, string formResultJSON, string formName, string accountName, int accountId)
    {
        // Now post to webhook URL
        string response;
        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            // Needs to be an array sent to Zapier
            response = client.UploadString(subscription.TargetURL, "POST", "[" + formResultJSON + "]");
        }
    }
}

Ok, that should get you most of the way there. But the wiring of the code/webhooks into Zapier is where is gets a bit more difficult. The idea now is to wire code above into your Zapier application using Development Dashboard. You will have to start creating a Zapier application. There are 2 main triggers you need - The basic action you are trying to implement (in this case "New Form Submission") and the authenticate so Zapier can authenticate a user as they are creating a Zap (in this case "Test Auth"). I am using Basic Auth, but others are supported (OAuth, etc). Additionally I added a trigger that will return the list of Forms the user has access to. Since it is not required I will not show that implementation in the screen captures:

I will not show the wiring for the "Test Auth" since that went pretty smoothly (I'll add it if someone requests it - heaven knows if anyone will even read this). So here is the wiring, page by page for the "New Form Submission":
Page 1

Page 2
This is where I wire up the Form Listing, which provides a list of forms the user creating a Zap can select from. You probably can skip this (leave it empty) unless you have dynamic data you want to display. I have included it for completeness:

Page 3
Here you wire up the test data

Page 4
This page allows you to enter Sample Data. Skipping this since it it pretty straight forward.
Scripting API
So now you have wired up your first Zap Trigger! But wait, we are not done. To make the Subscription process work we need to add some script. This was the hardest part of the entire process and was not very intuitive. So on the original main screen, a bit down you will see Scripting API:

Now you have to have the script for the RESTHook subscription. I am not going to go into great detail since Zapier does have documentation on this, but it is good to know that Zapier does store data as part of the subscription. Also we will need to do one more wiring step after this...
var Zap = {
    pre_subscribe: function(bundle) {
        bundle.request.method = 'GET';
        bundle.request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        bundle.request.params = {
            target_url: bundle.subscription_url,
            target_event:bundle.event,
            form_id:bundle.trigger_fields.form_id
        };
        bundle.request.data = $.param({
            target_url: bundle.subscription_url,
            target_event:bundle.event,
            form_id:bundle.trigger_fields.form_id
        });
        return bundle.request;
    },
    post_subscribe: function(bundle) {
        // must return a json serializable object for use in pre_unsubscribe
        var data = JSON.parse(bundle.response.content);
        // we need this in order to build the {{webhook_id}}
        // in the rest hook unsubscribe url
        return {webhook_id: data.id};
    },
    pre_unsubscribe: function(bundle) {
        bundle.request.method = 'DELETE';
        bundle.request.data = null;
        return bundle.request;
    },
    new_form_submission_pre_poll: function(bundle) {
        bundle.request.method = 'GET';
        bundle.request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        bundle.request.params = bundle.trigger_fields;
        bundle.request.data = $.param({
            form_id:bundle.trigger_fields.form_id
        });
        return bundle.request;
    }
};

There is a bit to this...but look at the Zapier documentation and it should help. Or post questions here and I will try to answer them...this is getting larger than I expected!
Manage Trigger Settings
Finally, we need to finish up the wiring for the subscriptions...

We then set up the RESTHook methods we created a while back:

And that is it. Hopefully this will save someone some time and learning lessons!


text:
Q: Having problems with pymongo 3.0 (ServerSelectionTimeoutError) I'm having the following problem with PyMongo 3.0. Did anyone find out how to fix this problem?
from pymongo import MongoClient

# making a Connection with MongoClient
client = MongoClient()
# getting a Database
db = client.test_database
# getting a Collection
test = db['test-collection']
client['test-collection']
print client('test-collection')
---Database(MongoClient('localhost', 27017), u'test-collection')
# inserting a document
test.insert_one({"test": True})

This is the error:
  File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 113, in select_server
  server_selection_timeout))
  File "/usr/local/lib/python2.7/dist-packages/pymongo/topology.py", line 93, in select_servers
  self._error_message(selector))
  pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused

Edit 1:
I get the same error when I try to execute the MongoDB interactive shell:
# making a Connection with MongoClient
client = MongoClient()
client.database_names()

SOLVED:
I found the following error in /var/log/mongodb:
[initandlisten] exception in initAndListen: 15926 Insufficient free space for journals, terminating

It seems I have no enough free disk in my VM so my mongodb it wasn't running on my machine.
I finally I found the solution to this problem in the following post: Why getting error mongod dead but subsys locked and Insufficient free space for journal files on Linux?
It seems that the problem can be solved using smallfiles property in mongodb log file.

A: I believe that you are having this error because you don't have mongo db running on your machine at port 27017. It seems that PyMongo only tries to connect to the server on the insert command.
Verify if the Mongodb server is running on localhost in port 27017 or pass to the MongoClient constructor the correct address and por if different of localhost 27017


text:
Q: Point IP to site for testing before delegation? I'm migrating to a new server and would like to test before redelegating the domain over. I have some familiarity with setting up apache virtual hosts, but limited knowledge.
How can I go about setting this up? My server already has a domain delegated to the server, and the IP by default has been setup to point to that.
I've been told I can just add an entry to /etc/hosts/ which I haven't been able to understand what I can add in there to make this work.
Any pointers would be greatly appreciated!

A: Here is a more detailed tutorial on creating hosts file entries.
The short answer is to make an entry in the file (c:\windows\system32\drivers\etc\hosts) that follows the pattern of IP [tab] Host(s):
1.1.1.1        www.myserver.com    myserver.com
On a Mac or Linux desktop, this file is at /etc/hosts.
This should be done on the client machine from which you will test the new server. Once you have put it into production and your new DNS records have propagated, you can safely remove the entry.

A: The simplest solution, in my mind, would be to create a dns entry such as www-test.domain.com and point it to your new ip.
In httpd.conf, add
ServerAlias www-test.domain.com

to your virtualhost config.
reload named and httpd and point your browser to www-test.domain.com


text:
Q: How to compute memory displacement in assembly? I've been working on yasm assembly language and I generated a listing file that contains the following. I need help understanding how the memory displacement is computed in the first column. Thanks in advance.
1                                %line 1+1 memory.asm
2                                [section .data]
3 00000000 04000000              a dd 4
4 00000004 CDCC8C40              b dd 4.4
5 00000008 00000000<rept>        c times 10 dd 0
6 00000030 01000200              d dw 1, 2
7 00000034 FB                    e db 0xfb
8 00000035 68656C6C6F20776F72-   f db "hello world", 0
9 00000035 6C6400

A: Assembler is producing bytes (machine code), starting at some start address (here 0) and laying them next to each other. So first a dd 4 produces 4 bytes of data 04 00 00 00, thus memory at addresses 0, 1, 2 and 3 are filled up. Next free slot is at address 4. There goes b dd 4.4, again 4 bytes long. c times 10 dd 0 is 40 bytes long, so 8+40 = 48 (0x30) => next free slot.


text:
Q: I'm having trouble center-aligning a div So I have a header for a website like this:
http://i.stack.imgur.com/k4hjp.png
And I'm trying to align the navigation menu to the center. The navigation div is inside the center columnn (in black) and the CSS for it is:
.nav {
    text-align: center;
    margin: 0 auto;
    position: relative;
    top: 287px;
    width: 100%;
    height: 70px;
    z-index: 100;
}

At the moment, each button in the navigation is yet another div. If someone has suggestions about how to approach it without having so many divs I would appreciate it, but anyway the code for the buttons is:
.button {
    margin-left: 10px;
    float: left;
    position: relative;
    text-align: center;
    line-height: 40px;
    width: 135px;
    height: 40px;
    background: #aa0000;
    color: #fff;
    font-weight: bold;

}

I have even tried setting text-align in body to center, but it won't work. How can I center align this menu?

A: Right now it is the "float:left" on your divs that makes them stay left aligned. Replace that float with "display:inline-block;" and you are fine.
And, if you don't want to use those divs, you could try to go with a list.
A common practice for menus is something like this:

Menu item a

Menu item b

A: Styles:
.centerDiv {
            width: 60%;
            height:70px;
            margin: 0 auto;
            text-align: center;
            top: 287px;
            z-index: 100;
        }

        .buttonDiv {
            width: 10%;
            height:40px;
            background-color:#aa0000;
            float:left;
            margin-left: 10px;
            position: relative;
            text-align: center;
            line-height: 40px;
            color: #fff;
            font-weight: bold;
        }

Markup:

Button 1

Button 2

Button 3

Button 4

Button 5

Button 6

A: Sorry for the self-answer, but none of the answers solved the problem exactly. Apparently the nav container width being set to 100% prevented any centering. After setting it to a static value, I was able to align normally. Thanks everyone for the help!

A: Use  instead of divs you can make it look attractive like
a{
display:block;
background-color:red;
width:100px;
}

then use text-align:center it will align


text:
Q: Switch from nHibernate HiLo to GUID Is it possible to switch from HiLo to GUID.comb? As far as I can tell, the latter combines the advantage of HiLo, namely managing Ids client-side instead of needing a call to the DB for getting a new Id, with the advantage that it's impossible to run out of Ids.
Currently we are running into problems with HiLo generating Ids so big, that Int32 (this should have been Int64, but that's more of a WTF of my predecessor) isn't big enough. We can change to Int64, but this just means we will run into problem later rather than sooner.
As the Ids do not need to be meaningful, a switch to GUIDs seems logical. However, as I've never attempted such a switch, I was wondering whether anyone here could help me assessing the impact something like that could have.

A: Actually, switching to int64 is usually enough. Remember that you're adding 32 more bits, which multiplies the id space by +/- 2 billion. Are you sure that's not enough?
Regarding switching to Guid, it involves (assuming a live DB):

*

*Creating new pk / fk columns

*Filling the pk columns with new values

*Filling the fk columns based on the old ones

*Dropping current foreign and primary keys

*Dropping old pk / fk columns

*Creating new primary and foreign keys

*Changing the id property types and generators (this is the only step involving .net code)

Anyway, while GUID provides "unlimited" ids and it's easy to generate, it also has the disadvantage of being twice as big (128 bits) and slightly harder to manipulate by hand (i.e. you'll depend on copy&paste when debugging


text:
Q: Ubuntu 20.04 - Terminus font not working anymore I've been using the terminus font from the "xfonts-terminus" package with the default GNOME-terminal.
Now I upgraded to Ubuntu 20.04 and the font is gone in GNOME-terminal and the Gnome fonts app.
What on earth is going on? How do I get the font back?

A: Pango stopped supporting old x11 fonts between versions 1.43 and 1.44, breaking them for all gtk apps.

A: It looks like 20.04 now has more than one package for Terminus.

*

*xfonts-terminus - Installs the "Terminus" font. Only some applications seem to support it. (eg: Shows up in Konsole, but not Terminator.)

*fonts-terminus - Installs the "Terminus (TTF)" font. This seems to work everywhere.


text:
Q: FTP error, cannot access a server, but other can Yesterday i accessed the server of a friend, and all went good.
But today I'm getting this error message(on filezilla).
Status: Connecting to 37.187.32.6:21...
Status: Connection established, waiting for welcome message...
Status: Initializing TLS...
Error:  GnuTLS error -12: A TLS fatal alert has been received.
Error:  Could not connect to server
Status: Waiting to retry...
Status: Connecting to 37.187.32.6:21...
Status: Connection established, waiting for welcome message...
Response:   220 ProFTPD 1.3.4c Server (ProFTPD) [37.187.32.6]
Command:    AUTH TLS
Response:   234 AUTH TLS successful
Status: Initializing TLS...
Error:  GnuTLS error -12: A TLS fatal alert has been received.
Error:  Could not connect to server

And with FireFTP, I see this

And this is in the index.html file
Welcome to Parallels!

If you are seeing this message, the website for is not available at this time.
If you are the owner of this website, one of the following things may be occurring:

You have not put any content on your website.
Your provider has suspended this page.

Please login to https://:8443 to receive instructions on setting up your website
New to Parallels?

Parallels is a worldwide leader in virtualization and automation software that optimizes computing for consumers, businesses, and Cloud services providers across all major hardware, operating systems, and virtualization platforms.

For the Cloud, Parallels automation and virtualization software enables cloud services providers to rapidly and profitably deliver the widest range of cloud services that small businesses want and need. Our software includes key building blocks of cloud service delivery - self service control panels, billing, cloud service provisioning and virtualization. We enable the delivery of all types of services that small businesses need - shared web hosting and web applications, messaging and collaboration services, virtualized infrastructure services and thousands of other applications.

Our Automation products allow businesses to optimize their systems to maximize profit. Our Virtualization products allow personal computers to run several operating systems on one computer (like OSX and Windows) and for individual servers to function like many servers at once for creating cloud computing environments.

This website was created using our Parallels Panel product. We offer a full line of Billing, Sitebuilder and cloud computing tools. Please visit www.parallels.com to find out more information.
Test pages

Parallels Plesk Panel provides several test pages that you can use for checking the scripting features, testing database connections and mail sending. Click an icon to see test pages for different scripts:

FastCGI
Python
PHP
Perl
SSI

Consumer Products
Parallels® Desktop
for Mac
Parallels® Desktop for Mac The best solution for running Windows, Linux, or any of many other operating systems alongside OS X.
Parallels® Desktop for
Windows and Linux
Parallels® Desktop for Windows and Linux Simultaneously run multiple operating systems on your PC
Service Provider Products
Parallels® Automation
Parallels® Automation Hosting, SaaS, and cloud computing automation solution.
Parallels® Panel
Parallels® Panel The Best Control Panel Ever For Easy, Complete and        Profitable      Hosting

The strange thing is that my friend and others can access the server.
Has anyone faced this problem?

A: Go to File -> Site Manager -> Transfer Settings and choose active or passive mode. It should resolve your problem.


text:
Q: React Hooks trying to useState in array ref I'm trying to work with Hooks in react but i have a doubt about useState and References. My problem is because i want to create multiple references in my jsx but i dont know how use the usestate like a Array, well in the insert of the usestate data.
import React, { useState, useEffect } from "react";
import { Row, Col, Image, ListGroup, Container } from "react-bootstrap";
import AOS from "aos";
import "./css/App.css";
import "aos/dist/aos.css";
import Skills from "./Components/Skills";
import Work from "./Components/Work";

const App = () => {
  const [ref, setRef] = useState([]);

  useEffect(() => {
    AOS.init({
      duration: 2000
    });
  });

  function handleOnClick(event) {
    ref.scrollIntoView();
  }

  return (

      <Row>
        <Col className="menu text-center" lg={4}>

            <Image
              src={process.env.PUBLIC_URL + "/Images/picture.jpg"}
              roundedCircle
            />

Fulanito Detal

Software Engineer - Web Developer

            <Row>
              <Col lg={3}></Col>
              <Col lg={6} className="menu-text">
                <ListGroup>
                  <ListGroup.Item
                    onClick={event => handleOnClick(event)}
                    active
                  >
                    ABOUT
                  </ListGroup.Item>
                  <ListGroup.Item>WORK EXPERIENCE</ListGroup.Item>
                  <ListGroup.Item>EDUCATION</ListGroup.Item>
                  <ListGroup.Item>SKILLS</ListGroup.Item>
                  <ListGroup.Item>CONTACT</ListGroup.Item>
                </ListGroup>
              </Col>
              <Col lg={3}></Col>
            </Row>

        </Col>

        <Col className="info text-center" lg={8}>
          <Container>

 {
                setRef(ref);
              }}
            >
              <Work />

 {
                setRef(ref);
              }}
            >
              <Skills />

          </Container>
        </Col>
      </Row>

  );
};

export default App;

The ref works fine just with one. If clicked about redirect to skills, but i want to use state like array to work with all references but i'm stuck with this one. Thanks for any help!

A: Here is a simplified example of using the useRef hook:
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
  const work = React.useRef();
  const skills = React.useRef();

  return (

      <button onClick={() => work.current.scrollIntoView()}>
        WORK EXPERIENCE
      </button>
      <button onClick={() => skills.current.scrollIntoView()}>SKILLS</button>

        WORK SECTION

        SKILL SECTIONS

  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


text:
Q: WPF - Different SelectedValues in different GridViewColumns? I have 12 Properties and I want to bind each of them to one GridViewColumn in a ListView. They contain an ID (string) and look like the following:
        //DAR01
        public static readonly PropertyInfo<string> DAR01Property = RegisterProperty<string>(p => p.DAR01);
        /// <summary>
        ///Date type
        /// </summary>
        public string DAR01
        {
            get { return GetProperty( DAR01Property); }
            set { SetProperty(DAR01Property, value); }
        }

I also have a Key-Table in my database which contains a key and a description, which I already have in my Code-Behind:
public System.Collections.Generic.IEnumerable<AOK.NW.Beihilfe.Customizing.Schluessel> PlanungsdatenSchluessel
        {
            get
            {
                System.Collections.Generic.IEnumerable<AOK.NW.Beihilfe.Customizing.Schluessel> SchluessellistePlanungsdaten = Schluesselliste.GetSchluesselliste().Where<Schluessel>(x => x.Gruppe == "T548T");
                return SchluessellistePlanungsdaten;
            }
        }

Basically the easiest way to explain what I want are these following ComboBoxes, but in a GridView with multiple GridViewColumns which have different Bindings:
<ComboBox Grid.Row="2" Grid.Column="1" Width="Auto"
                      ItemsSource="{Binding Path=PlanungsdatenSchluessel}"
                      DisplayMemberPath="Beschreibung"
                      SelectedValuePath="Id"
                      SelectedValue="{Binding Path=CurrentDate.DAR01}"
                      IsEnabled="{Binding Path=IsBearbeiten}"/>

<ComboBox Grid.Row="3" Grid.Column="1" Width="Auto"
                  ItemsSource="{Binding Path=PlanungsdatenSchluessel}"
                  DisplayMemberPath="Beschreibung"
                  SelectedValuePath="Id"
                  SelectedValue="{Binding Path=CurrentDate.DAR02}"
                  IsEnabled="{Binding Path=IsBearbeiten}"/>

[...]

My GridViewColumns (goes up to DAR12):
<ListView Grid.Row="0"
                  ItemsSource="{Binding Path=Person.Planungsdaten}"
                  IsSynchronizedWithCurrentItem="True"
                  SelectedItem="{Binding SelectedItem}"
                  MaxHeight="580" Height="Auto"
                  Width="Auto"
                  ScrollViewer.CanContentScroll="True"
                  ScrollViewer.VerticalScrollBarVisibility="Auto"
                  ScrollViewer.HorizontalScrollBarVisibility="Auto">

<GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Path=DAR01}">
                                <GridViewColumnHeader Name="DAR01" Content="Datentyp 01"/>
                            </GridViewColumn>

    <GridViewColumn Width="Auto" DisplayMemberBinding="{Binding Path=DAR02}">
                            <GridViewColumnHeader Name="DAR02" Content="Datentyp 02"/>
                        </GridViewColumn>

</GridView>
            </ListView.View>
        </ListView>

Any ideas how I can achieve that? I am grateful for any tip!


text:
Q: How to get max number from array key matching a pattern I have an array
$_images['image[1]'] = image1.jpg
$_images['image[2]'] = image2.jpg
$_images['image[3]'] = image3.jpg
$_images['image[4]'] = image4.jpg

How do I find the max number/ count in the key is 4 which matches a pattern image[].
Appreciate any help.

A: I don't really understand what you're asking but if you mean
$_images[1] = 'image1.jpg';
$_images[2] = 'image2.jpg';
$_images[3] = 'image3.jpg';
$_images[4] = 'image4.jpg';

Then just do echo count($_images);
If you mean
$images[1] = 'image1.jpg';
$images[2] = 'image2.jpg';
$images[3] = 'image3.jpg';
$images[4] = 'image4.jpg';

$_images = array();
array_push($_images, $images); //array of arrays

then do
echo count($_images, COUNT_RECURSIVE) - 1; //keep in mind your parent array must only have 1 array inside it, or you have to do -x where x = number of your second-level arrays

If you mean something else, then you have to explain more...

A: Thanks to Marc B !
count(preg_grep('/images[([0-9]+)]/', $_images));


text:
Q: Creating a pseudo-module that creates submodules at runtime To support extensions in my Python project, I'm trying to create a pseudo-module that will serve "extension modules" as it's submodules. I'm having a problem treating the submodules as modules - it seems like I need to access them using from..import on the main pseudo-module and can't just access their full path.
Here is a minimal working example:
import sys
from types import ModuleType

class Foo(ModuleType):
    @property
    def bar(self):
        # Here I would actually find the location of `bar.py` and load it
        bar = ModuleType('foo.bar')
        sys.modules['foo.bar'] = bar
        return bar

sys.modules['foo'] = Foo('foo')

from foo import bar  # without this line the next line fails
import foo.bar

This works, but if I comment out the from foo import bar line, it'll fail with:
ImportError: No module named bar

on Python2, and on Python3 it'll fail with:
ModuleNotFoundError: No module named 'foo.bar'; 'foo' is not a package

If I add the fields to make it a package:
class Foo(ModuleType):
    __all__ = ('bar',)
    __package__ = 'foo'
    __path__ = []
    __file__ = __file__

It'll fail on:
ModuleNotFoundError: No module named 'foo.bar'

From what I understand, the problem is that I did not set sys.modules['foo.bar'] yet. But... to fill sys.modules I need to load the module first, and I don't want to do it unless the user of my project explicitly imports it.
Is there any way to make Python realize that when it sees import foo.bar it needs to load foo first(or I can just guarantee foo will already be loaded at that point) and take bar from it?

A: This post does NOT answer "This is how you do it."
If you want to know how to do this yourself look at PEP 302 or Idan Arye's solution.
This post instead presents a recipe that makes it easy to write.  The recipe is at the end of this answer.

The block of code below defines two classes intended for use: PseudoModule and PseudoPackage. The behaviour only differs from whether import foo.x should raise an error stating foo isn't a package or try to load x and make sure it's a module.  Several example uses are outlined below.
PseudoModule
PseudoModule can be used as a decorator to a function, it creates a new module object that when attributes are accessed for the first time it called the decorated function with the name of the attribute and the namespace of previously defined elements.
For example, this will make a module that assigns a new integer to each attribute accessed:
@PseudoModule
def access_tracker(attr, namespace):
    namespace["_count"] = namespace.get("_count", -1) + 1
    return namespace["_count"]

#PseudoModule will set `namespace[attr] = <return value>` for you
#this can be overriden by passing `remember_results=False` to the constructor

sys.modules["access_tracker"] = access_tracker

from access_tracker import zero, one, two, three

assert zero == 0 and one == 1 and two == 2 and three == 3

PseudoPackage
PseudoPackage is used the same way as PseudoModule however if the decorated function returns a module (or package) it will correct the name to be qualified as a subpackage and sys.modules is updated as needed. (the top level package still needs to be added to sys.modules manually)
Here is an example use of PseudoPackage:
spam_submodules = {"bacon"}
spam_attributes = {"eggs", "ham"}

@PseudoPackage
def spam(name, namespace):
    print("getting a component of spam:", name)
    if name in spam_submodules:
        @PseudoModule
        def submodule(attr, nested_namespace):
            print("getting a component of submodule {}: {}".format(name, attr))
            return attr #use the string of the attribute
        return submodule #PseudoPackage will rename the module to be spam.bacon for us
    elif name in spam_attributes:
        return "supported attribute"
    else:
        raise AttributeError("spam doesn't have any {!r}.".format(name))

sys.modules["spam"] = spam

import spam.bacon
#prints "getting a component of spam: bacon"

assert spam.bacon.something == "something"
#prints "getting a component of submodule bacon: something"

from spam import eggs
#prints "getting a component of spam: eggs"
assert eggs == "supported attribute"

import spam.ham #ham isn't a submodule, raises error!

The way PseudoPackage is setup also makes arbitrary depth packages very easy although this specific example doesn't accomplish much:
def make_abstract_package(qualname = ""):
    "makes a PseudoPackage that has arbitrary nesting of subpackages"
    def gen_func(attr, namespace):
        print("getting {!r} from package {!r}".format(attr, qualname))
        return make_abstract_package("{}.{}".format(qualname, attr))
    #can pass the name of the module as second argument if needed
    return PseudoPackage(gen_func, qualname)

sys.modules["foo"] = make_abstract_package("foo")

from foo.bar.baz import thing_I_want
##prints:
# getting 'bar' from package 'foo'
# getting 'baz' from package 'foo.bar'
# getting 'thing_I_want' from package 'foo.bar.baz'
print(thing_I_want)
#prints "<module 'foo.bar.baz.thing_I_want' from '<PseudoPackage>'>"

Few notes on implementation
As general guidelines:

*

*The function that computes attributes of the module should not import the module it's defining the attributes for

*If you want a package or module to be available for import, you need to put it in sys.modules yourself.

*PseudoPackage assumes each submodule is unique, don't reuse module objects.

It is also worth noting that sys.modules is only updated with submodules of PseudoPackages when an import statement that requires the name to be a module, for example if foo is a package already in sys.modules but foo.x has not been referenced yet then all these assertions will pass:
assert "foo.x" not in sys.modules and not hasattr(foo,"x")
import foo; foo.x #foo.x is computed but not added to sys.modules
assert "foo.x" not in sys.modules and hasattr(foo,"x")
from foo import x #x is retrieved from namespace but sys.modules is still not affected
assert "foo.x" not in sys.modules

import foo.x #if x is a module then "foo.x" is added to sys.modules
assert "foo.x" in sys.modules

as well in the above case if foo.x isn't a module then the statement import foo.x raises a ModuleNotFoundError.
Finally, while the problematic edge cases I have identified can be avoided by following the guidelines above, the docstring for _PseudoPackageLoader describes the implementation details responsible for unwanted behaviour for possible future modifications.

The recipe
import sys
from types import ModuleType
import importlib.abc #uses Loader and MetaPathFinder, more for inspection purposes then use

class RawPseudoModule(ModuleType):
    """
    see PseudoModule for documentation, this class is not intended for direct use.

    RawPseudoModule does not handle __path__ so the generating function of direct
    instances are expected to make and return an appropriate value for __path__

    *** if you do not know what an appropriate value for __path__ is
        then use PseudoModule instead ***
    """
    #using slots keeps these two variables out of the module dictionary
    __slots__ = ["__generating_func", "__remember_results"]
    def __init__(self, func, name=None, remember_results = True):
        name = name or func.__name__
        super(RawPseudoModule, self).__init__(name)
        self.__file__ = "<{0.__class__.__name__}>".format(self)
        self.__generating_func = func
        self.__remember_results = remember_results

    def __getattr__(self, attr):
        value = self.__generating_func(attr, vars(self))
        if self.__remember_results:
            setattr(self, attr, value)
        return value

class PseudoModule(RawPseudoModule):
    """
    A module that has attributes generated from a specified function

    The generating function passed to the constructor should have the signature:
       f(attr:str, namespace:dict) -> object:
          - attr is the name of the attribute accessed
          - namespace is the currently defined values in the module

    the function should return a value for the attribute or raise an AttributeError if it doesn't exist.

    by default the result is then saved to the namespace so you don't
    have to explicitly do "namespace[attr] = <value>" however this behaviour
    can be overridden by specifying "remember_results = False" in the constructor.

    If no name is specified in the constructor the function name will be
    used for the module name instead, this allows the class to be used as a decorator

    Note: the PseudoModule class is setup so that "import foo.bar"
          when foo is a PseudoModule will fail stating "'foo' is not a package".
         -  to allow importing submodules use PseudoPackage.
         -  to handle the internal __path__ manually use RawPseudoPackage.

    Note: the module is NOT added to sys.modules automatically.
    """
    def __getattr__(self, attr):
        #to not have submodules then __path__ must not exist
        if attr == "__path__":
            msg = "{0.__name__} is a PseudoModule, it is not a package so it doesn't have a __path__"
            #this error message would only be seen by people who explicitly access __path__
            raise AttributeError(msg.format(self))
        return super(PseudoModule, self).__getattr__(attr)

class PseudoPackage(RawPseudoModule):
    """
    A version of PseudoModule that sets itself up to allow importing subpackages

    When a submodule is imported from a PseudoPackage:
    - it is evaluated with the generating function.
    - the name of the submodule is overriden to be correctly qualified
    - and it is added to sys.modules to allow repeated imports.

    Note: the top level package still needs to be added to sys.modules manually

    Note: A RecursionError will be raised if the code that generates submodules
          attempts to import another submodule from the PseudoPackage.
    """
    #IMPLEMENTATION DETAIL: technically this doesn't deal with adding submodules to
    #  sys.modules, that is handled in _PseudoPackageLoader
    #  which explicitly checks for instances of PseudoPackage

    __path__ = [] #packages must have a __path__ to be recognized as packages.

    def __getattr__(self, attr):
        value = super(PseudoPackage, self).__getattr__(attr)
        if isinstance(value, ModuleType):
            #I'm just going to say if it's a module then the name must be in this format.
            value.__name__ = self.__name__ + "." + attr
        return value

class _PseudoPackageLoader(importlib.abc.Loader, importlib.abc.MetaPathFinder):
    """
    Singleton finder and loader for pseudo packages

    When ever a subpackage of a PseudoPackage (that is already in sys.modules) is imported
    this will handle loading it and adding the subpackage to sys.modules

    Note that although PEP 302 states the finder should not depend on the parent
    being loaded in sys.modules, this is implemented under the understanding that
    the user of PseudoPackage will add their module to sys.modules manually themselves
    so this will work only when the parent is present in sys.modules

    Also PEP 302 indicates the module should be added to sys.modules first in case
    it is imported during it's execution, however this is impossible due to the
    nature of how the module actually gets loaded.
    So for heaven's sake don't try to import a pseudo package or a module that uses
    a pseudo package from within the code that generates it.

    I have only tested this when the sub module is either PseudoModule or PseudoPackage
    and it was created new from the generating function, ideally there would be a way
    to allow the generating function to return an unexecuted module and this would
    properly handle executing it but I don't know how to deal with that.
    """
    def find_module(self, fullname, path):
        #this will only support loading if the parent package is a PseudoPackage
        base,_,_ = fullname.rpartition(".")
        if isinstance(sys.modules.get(base), PseudoPackage):
            return self
        #I found that `if path is PseudoPackage.__path__` worked the same way for all the cases I tested
        #however since load_module will fail if the base part isn't in sys.modules
        # it seems safer to just check for that.

    def load_module(self, fullname):
        if fullname in sys.modules:
            return sys.modules[fullname]
        base,_,sub = fullname.rpartition(".")
        parent = sys.modules[base]
        try:
            submodule = getattr(parent, sub)
        except AttributeError:
            #when we just access `foo.x` it raises an AttributeError
            #but `import foo.x` should instead raise an ImportError
            raise ImportError("cannot import name {!r}".format(sub))

        if not isinstance(submodule, ModuleType):
            #match the format of error raised when the submodule isn't a module
            #example: `import sys.path` raises the same format of error.
            raise ModuleNotFoundError("No module named {}".format(fullname))
        #fill all the fields as described in PEP 302 except __name__
        submodule.__loader__ = self
        submodule.__package__ = base
        submodule.__file__ = getattr(submodule, "__file__", "<submodule of PseudoPackage>")
        #if there was a way to do this before the module was made that'd be nice
        sys.modules[fullname] = submodule
        #if we needed to execute the body of an unloaded module it'd be done here.
        return submodule

#add the loader to sys.meta_path so it will handle our pseudo packages
sys.meta_path.append(_PseudoPackageLoader())

A: Thanks to the link @TadhgMcDonald-Jensen provided I managed to solve it:
import sys
from types import ModuleType

class FooImporter(object):
    module = ModuleType('foo')
    module.__path__ = [module.__name__]

    def find_module(self, fullname, path):
        if fullname == self.module.__name__:
            return self
        if path == [self.module.__name__]:
            return self

    def load_module(self, fullname):
        if fullname == self.module.__name__:
            return sys.modules.setdefault(fullname, self.module)
        assert fullname.startswith(self.module.__name__ + '.')
        try:
            return sys.modules[fullname]
        except KeyError:
            submodule = ModuleType(fullname)

            name = fullname[len(self.module.__name__) + 1:]
            setattr(self.module, name, submodule)

            sys.modules[fullname] = submodule

            return submodule

sys.meta_path.append(FooImporter())

from foo import bar

@TadhgMcDonald-Jensen - please make an answer so that I can approve it.