text:
Q: WPF Combobox allow clicking on items outside Default behavior of WPF Combobox is when it expanded and the user clicks anywhere outside of it then it collapses.
Is it possible to make such Combobox that won't deactivate other controls when expanded? So I can click on anything outside of it and it would be collapsed/expanded only if I press exactly on the small button with a triangle on the right-hand side?

A: You can achieve a such behaviour without overriding template of ComboBox using Expander and ListView. For example:
<Expander>
   <ListView>
      <ListViewItem Content="1"/>
      <ListViewItem Content="2"/>
      <ListViewItem Content="3"/>
      <ListViewItem Content="4"/>
      <ListViewItem Content="5"/>
   </ListView>
</Expander>

Update:
Style of ComboBox where ItemsPresenter is closed only if you click at the right triangle:
<Style x:Key="ComboBoxFocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="4,4,21,4" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <LinearGradientBrush x:Key="ButtonNormalBackground" EndPoint="0,1" StartPoint="0,0">
        <GradientStop Color="#F3F3F3" Offset="0"/>
        <GradientStop Color="#EBEBEB" Offset="0.5"/>
        <GradientStop Color="#DDDDDD" Offset="0.5"/>
        <GradientStop Color="#CDCDCD" Offset="1"/>
    </LinearGradientBrush>
    <SolidColorBrush x:Key="ButtonNormalBorder" Color="#FF707070"/>
    <Geometry x:Key="DownArrowGeometry">M 0 0 L 3.5 4 L 7 0 Z</Geometry>
    <Style x:Key="ComboBoxReadonlyToggleButton" TargetType="{x:Type ToggleButton}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="IsTabStop" Value="false"/>
        <Setter Property="Focusable" Value="false"/>
        <Setter Property="ClickMode" Value="Press"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" SnapsToDevicePixels="true">
                        <Grid HorizontalAlignment="Right" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                            <Path x:Name="Arrow" Data="{StaticResource DownArrowGeometry}" Fill="Black" HorizontalAlignment="Center" Margin="3,1,0,0" VerticalAlignment="Center"/>
                        </Grid>
                    </Themes:ButtonChrome>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="true">
                            <Setter Property="RenderPressed" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Fill" TargetName="Arrow" Value="#AFAFAF"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <LinearGradientBrush x:Key="TextBoxBorder" EndPoint="0,20" MappingMode="Absolute" StartPoint="0,0">
        <GradientStop Color="#ABADB3" Offset="0.05"/>
        <GradientStop Color="#E2E3EA" Offset="0.07"/>
        <GradientStop Color="#E3E9EF" Offset="1"/>
    </LinearGradientBrush>
    <Style x:Key="ComboBoxEditableTextBox" TargetType="{x:Type TextBox}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="AllowDrop" Value="true"/>
        <Setter Property="MinWidth" Value="0"/>
        <Setter Property="MinHeight" Value="0"/>
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <ScrollViewer x:Name="PART_ContentHost" Background="Transparent" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="ComboBoxToggleButton" TargetType="{x:Type ToggleButton}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="IsTabStop" Value="false"/>
        <Setter Property="Focusable" Value="false"/>
        <Setter Property="ClickMode" Value="Press"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ToggleButton}">
                    <Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RoundCorners="false" SnapsToDevicePixels="true" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                        <Path x:Name="Arrow" Data="{StaticResource DownArrowGeometry}" Fill="Black" HorizontalAlignment="Center" Margin="0,1,0,0" VerticalAlignment="Center"/>
                    </Themes:ButtonChrome>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsChecked" Value="true">
                            <Setter Property="RenderPressed" TargetName="Chrome" Value="true"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Fill" TargetName="Arrow" Value="#AFAFAF"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="ComboBoxStyle1" TargetType="{x:Type ComboBox}">
        <Setter Property="FocusVisualStyle" Value="{StaticResource ComboBoxFocusVisual}"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/>
        <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
        <Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
        <Setter Property="Padding" Value="4,3"/>
        <Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
        <Setter Property="ScrollViewer.PanningMode" Value="Both"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ComboBox}">
                    <Grid x:Name="MainGrid" SnapsToDevicePixels="true">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Width="0"/>
                        </Grid.ColumnDefinitions>
                        <!--<Popup x:Name="PART_Popup" StaysOpen="True" AllowsTransparency="true" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" Margin="1" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">-->
                        <Popup x:Name="PART_Popup" IsOpen="{Binding IsChecked, ElementName=toggleButton, Mode=TwoWay}" StaysOpen="True" AllowsTransparency="true" Grid.ColumnSpan="2" Margin="1" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">
                        <Themes:SystemDropShadowChrome x:Name="Shdw" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=MainGrid}">
                                <!--<Border x:Name="DropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="25" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">-->
                                    <Border x:Name="DropDownBorder" BorderBrush="Green" BorderThickness="5" Background="Red">
                                    <ScrollViewer x:Name="DropDownScrollViewer">
                                        <Grid RenderOptions.ClearTypeHint="Enabled">
                                            <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                                <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=DropDownBorder}" Height="{Binding ActualHeight, ElementName=DropDownBorder}" Width="{Binding ActualWidth, ElementName=DropDownBorder}"/>
                                            </Canvas>
                                            <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>

                                        </Grid>
                                    </ScrollViewer>
                                </Border>
                            </Themes:SystemDropShadowChrome>
                        </Popup>
                        <!--<ToggleButton Name="toggleButton" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ComboBoxReadonlyToggleButton}"/>-->
                        <ToggleButton Name="toggleButton" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" Style="{StaticResource ComboBoxReadonlyToggleButton}"/>
                        <ContentPresenter ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" Content="{TemplateBinding SelectionBoxItem}" ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" IsHitTestVisible="false" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="true">
                            <Setter Property="Margin" TargetName="Shdw" Value="0,0,5,5"/>
                            <Setter Property="Color" TargetName="Shdw" Value="#71000000"/>
                        </Trigger>
                        <Trigger Property="HasItems" Value="false">
                            <Setter Property="Height" TargetName="DropDownBorder" Value="95"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                            <Setter Property="Background" Value="#FFF4F4F4"/>
                        </Trigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsGrouping" Value="true"/>
                                <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="false"/>
                            </MultiTrigger.Conditions>
                            <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
                        </MultiTrigger>
                        <Trigger Property="ScrollViewer.CanContentScroll" SourceName="DropDownScrollViewer" Value="false">
                            <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}"/>
                            <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsEditable" Value="true">
                <Setter Property="BorderBrush" Value="{StaticResource TextBoxBorder}"/>
                <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
                <Setter Property="IsTabStop" Value="false"/>
                <Setter Property="Padding" Value="3"/>
                <Setter Property="Template" Value="{StaticResource ComboBoxEditableTemplate}"/>
            </Trigger>
        </Style.Triggers>
    </Style>

Example of using style is:
<ComboBox Style="{DynamicResource ComboBoxStyle1}" >
   <ComboBoxItem Content="1"/>
   <ComboBoxItem Content="2"/>
   <ComboBoxItem Content="3"/>
</ComboBox>


text:
Q: Unable to form the required regex in C I am trying to write a regex which can search a string and return true if it matches with the regex and false otherwise.
Check should ensure string is wildcard domain name of a website.
Example:

*

**.cool.dude is valid

**.cool is not valid

*abc.cool.dude is not valid
So I had written something which like this
\\*\\.[.*]\\.[.*]

However, this is also allowing a *.. string as valid string because * means 0 or infinite occurrences.
I am looking for something which ensures that at-least 1 occurrence of the string happens.
Example:
*.a.b -> valid but *.. -> invalid
how to change the regex to support this?
I have already tried doing something like this:
\\*\\.([.*]{1,})\\.([.*]{1,}) -> doesnt work

\\*\\.([.+])\\.(.+) -> doesnt work

^\\*\\.[a-zA-Z]+\\.[a-zA-Z]+ -> doesnt work

I have tried a bunch of other options as well and have failed to find a solution. Would be great if someone can provide some input.
PS. Looking for a solution which works in C.

A: [.*] does not mean "0 or more occurrences" of anything. It means "a single character, either a (literal) . or a (literal) [*]". […] defines a character class, which matches exactly one character from the specified set. Brackets are not even remotely the same as parentheses.
So if you wanted to express "zero or more of any character except newline", you could just write .*. That's what .* means. And if you wanted "one or more" instead of "zero or more", you could change the * to a plus, as long as you remember that regex.h regexes should always be compiled with the REG_EXTENDED flag. Without that flag, + is just an ordinary character. (And there are a lot of other inconveniences.)
But that's probably not really what you want. My guess is that you want something like:
^[*]([.][A-Za-z0-9_]+){2,}$

although you'll have to correct the character class to specify the precise set of characters you think are legitimate.
Again, don't forget the crucial REG_EXTENDED flag when you call regcomp.
Some notes:

*

*The {2,} requires at least two components after the *, so that *.cool doesn't match.

*The ^ and $ at the beginning and end of the regex "anchor" the match to the entire input. That stops the pattern matching just a part of the input, but it might not be exactly what you want, either.

*Finally, I deliberately used a single-character character class to force [*] and [.] to be ordinary characters. I find that a lot more readable than falling timber (\\) and it avoids having to think about the combination of string escaping and regex-escaping.
For more information, I highly recommend reading man regcomp and man 7 regex. A good introduction to regexes might be useful, as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Selenium Can't get value of null I am trying to fill data in an input box using selenium. The tag is inside an iframe and I am able to asses the element in Chrome Inspect Element.

Change from top to Iframe => by2Frame (Contacts)

I tried to switch to iframe:
browser.switch_to.frame(browser.find_element_by_xpath('//*[@id="by2Frame"]'))
Then I tried this:
script2 = """ var a = document.getElementById("addname").value = '%s';
             var b = document.getElementById("addmob").value = '%s';
             console.log(a.id)
             console.log(b.id)

                """ % (names,numbers)

browser.execute_script(script2)

But this gives me can't get value of null. I also tried using xpath but this also gives me an error Unable to locate element.
I can easily set the value by using chrome console and changing from top to iframe in Execution Context Selector (can be seen at the top bar). Then why is selenium unable to locate my element


text:
Q: System.ComponentModel.Win32Exception when executing F# Nunit unit test code with Mono I'm trying to use F# unittest on Mono. I use Mac OS X. I downloaded and copied NUNit frameworks.
I have the following environments
nunitFramework=.../bin/mono/NUnit.2.6.4/nunit.framework.dll
console=.../bin/mono/NUnit.2.6.4/nunit-console.exe
fsUnit=.../bin/mono/NUnit.2.6.4/FsUnit.NUnit.dll

This is F# code:
namespace HelloWorld.Core
module Hello = let SayHello name = "Hello"

This is the unittest for it.
module HelloWorld.Tests.Hello
open HelloWorld.Core.Hello
open NUnit.Framework
open FsUnit

[<Test>]
let shouldSayHello () = Assert.AreEqual("Hello World!", SayHello "World")

I compile the code and unittest:
fsharpc --target:library HelloWorld.fs
fsharpc --target:library -r:HelloWorld.dll -r:$nunitFramework -r:$fsUnit HelloWorldTest.fs

I run the test: mono $console HelloWorldTest.dll to get the error messages.
ProcessModel: Default    DomainUsage: Single
Execution Runtime: mono-3.5
Unhandled Exception:
System.ComponentModel.Win32Exception: ApplicationName='mono', CommandLine='--runtime=v4.0.30319 "/Users/smcho/Dropbox/smcho/bin/mono/NUnit.2.6.4/nunit-agent.exe" cc695a32-96df-4346-bfda-e5547d7acc87 tcp://127.0.0.1:58755/TestAgency', CurrentDirectory='', Native error= Cannot find the specified file
  at System.Diagnostics.Process.Start_noshell (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
  at System.Diagnostics.Process.Start_common (System.Diagnostics.ProcessStartInfo startInfo, System.Diagnostics.Process process) [0x00000] in <filename unknown>:0
  at System.Diagnostics.Process.Start () [0x00000] in <filename unknown>:0
  at (wrapper remoting-invoke-with-check) System.Diagnostics.Process:Start ()
  at NUnit.Util.TestAgency.LaunchAgentProcess (NUnit.Core.RuntimeFramework targetRuntime) [0x00000] in <filename unknown>:0
  at NUnit.Util.TestAgency.CreateRemoteAgent (NUnit.Core.RuntimeFramework framework, Int32 waitTime) [0x00000] in <filename unknown>:0
  at NUnit.Util.TestAgency.GetAgent (NUnit.Core.RuntimeFramework framework, Int32 waitTime) [0x00000] in <filename unknown>:0
  at (wrapper remoting-invoke-with-check) NUnit.Util.TestAgency:GetAgent (NUnit.Core.RuntimeFramework,int)
  at NUnit.Util.ProcessRunner.Load (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0
  at NUnit.ConsoleRunner.ConsoleUi.Execute (NUnit.ConsoleRunner.ConsoleOptions options) [0x00000] in <filename unknown>:0
  at NUnit.ConsoleRunner.Runner.Main (System.String[] args) [0x00000] in <filename unknown>:0

What might be wrong?

A: I needed multiple changes for solving the issue:
Revised F# test code
I needed to use TestFixture.
module HelloWorld.Tests.Hello

open HelloWorld.Core.Hello
open NUnit.Framework
//open FsUnit

[<TestFixture>]
type TestClass() =
    [<Test>]
    member tc.When2IsAddedTo2Expect4() =
        Assert.AreEqual(4, 2+2)

    [<Test>]
    member tc.shouldSayHello () =
        Assert.AreEqual("Hello", SayHello "World")

Execute mono provided unit-console
I had to execute the unit-console that is symbolically linked to /usr/bin/nunit-console@ -> /Library/Frameworks/Mono.framework/Commands/nunit-console
No need to use external dlls
I didn't have to use FsUnit.NUnit or unit.framework that I downloaded from NUNit website.
fsharpc --target:library HelloWorld.fs
fsharpc --target:library -r:HelloWorld.dll -r:nunit.framework HelloWorldTest.fs
nunit-console HelloWorldTest.dll

After the changes, everything seems to be working fine:
F# Compiler for F# 3.1 (Open Source Edition)
Freely distributed under the Apache 2.0 Open Source License
F# Compiler for F# 3.1 (Open Source Edition)
Freely distributed under the Apache 2.0 Open Source License
NUnit version 2.4.8
Copyright (C) 2002-2007 Charlie Poole.

Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.

Copyright (C) 2000-2002 Philip Craig.

All Rights Reserved.

Runtime Environment -
   OS Version: Unix 14.3.0.0
  CLR Version: 2.0.50727.1433 ( 3.12.0 ((detached/a813491 Tue Dec 16 12:19:26 EST 2014) )

..
Tests run: 2, Failures: 0, Not run: 0, Time: 0.034 seconds

References

*

*http://sector0.dk/?p=33

*http://www.nunit.org/index.php?p=consoleCommandLine&r=2.2.5

A: I'd like to add an updated answer to your question where your original answer helped lead me to a revised approach that is for Mono, NUnit, and F# in 2019 on macOS.
This answer applies to Mono 5.18.1.3, NUnit framework 3.12.0, and F# 4.1. There are many benefits to being able to use the latest versions including greater stability, availability of features, and integration with other contemporary tools (like IDE-based test runners).
A few differences in my answer are noted below.

*

*[<TestFixture>] is deprecated now along with NUnit 2.6.4.

*The version of nunit-console.exe bundled with Mono is also deprecated.

*Debugging has been enabled for my build where I've included a selection of system libraries.

Additionally, the error you reported for the console runner of Native error= Cannot find the specified file is due to mono not being accessible from your PATH. This happened to me when I first attempted to use an NUnit.ConsoleRunner downloaded by NuGet where I resolved it with:
$ export PATH=$PATH:/Library/Frameworks/Mono.framework/Commands/

Source code
Following your original idea, I create a module to test in Module.fs:
namespace com.example.fs.hello.testing

module Hello
    = let SayHello = "Hello"

Then add a test in Test.fs with:
namespace com.example.fs.hello.testing

open Hello
open NUnit.Framework

type Test() =
    [<Test>]
    member x.TestCase() = Assert.AreEqual("Hello", SayHello)

Building
Finally, I add the commands to build everything to a custom location:
#/bin/sh
PROJECT_ROOT=($PWD)
DESTINATION=obj/CUSTOM
fsharpc -o:$DESTINATION/hello-world-testing.dll \
-g \
--debug:portable \
--noframework \
--define:DEBUG \
-r:$PROJECT_ROOT/packages/FSharp.Core.4.6.2/lib/net45/FSharp.Core.dll \
-r:/Library/Frameworks/Mono.framework/Versions/5.18.1/lib/mono/4.5.1-api/mscorlib.dll \
-r:$PROJECT_ROOT/packages/NUnit.3.12.0/lib/net45/nunit.framework.dll \
-r:/Library/Frameworks/Mono.framework/Versions/5.18.1/lib/mono/4.5.1-api/System.Core.dll \
-r:/Library/Frameworks/Mono.framework/Versions/5.18.1/lib/mono/4.5.1-api/System.dll \
--target:library \
Module.fs \
Test.fs
cp $PROJECT_ROOT/packages/NUnit.3.12.0/lib/net45/nunit.framework.dll $DESTINATION

Console runner command-line testing
After a successful build, I change to the output directory. For demonstration only, I install the console runner into the current working directory and run the runner on the DLL.
$ cd obj/CUSTOM
$ nuget install NUnit.ConsoleRunner
$ mono NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe hello-world-testing.dll

Results
If all is correct, the command-line testing ends up producing the following output.
NUnit Console Runner 3.10.0 (.NET 2.0)
Copyright (c) 2019 Charlie Poole, Rob Prouse
Tuesday, June 18, 2019 06:49:41Z

Runtime Environment
   OS Version: MacOSX 18.6.0.0
  CLR Version: 4.0.30319.42000

Test Files
    hello-world-testing.dll

Run Settings
    DisposeRunners: True
    WorkDirectory: hello-world-fs-testing/obj/CUSTOM
    ImageRuntimeVersion: 4.0.30319
    ImageRequiresX86: False
    ImageRequiresDefaultAppDomainAssemblyResolver: False
    NumberOfTestWorkers: 12

Test Run Summary
  Overall result: Passed
  Test Count: 1, Passed: 1, Failed: 0, Warnings: 0, Inconclusive: 0, Skipped: 0
  Start time: 2019-06-18 06:49:41Z
    End time: 2019-06-18 06:49:43Z
    Duration: 1.137 seconds

Results (nunit3) saved as TestResult.xml


text:
Q: Angular-ui ui-router - using multiple nested views I am trying out the nested views feature of ui-router plugin, but faced the issue I don't know how to solve.
The code that shows the problem can be found at http://jsfiddle.net/3c9h7/1/ :
  var app = angular.module('myApp', ['ui.router']);

  app.config(function($stateProvider) {
    return $stateProvider.state('root', {
      template: "

"
    }).state('root.step1', {
      url: '',
      views: {
        'viewA': {
          template: '
View A
'
        }
      }
    }).state('root.step1.step2', {
      url: '/step2',
      views: {
        'viewB': {
          template: '
View B
'
        }
      }
    });
  });

  app.controller('MainCtrl', [
    '$scope', '$state', function($scope, $state) {
      $state.transitionTo('root.step1.step2');
    }
  ]);

So, the code activates "root.step1.step2" state by using $state.go method(https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stategoto--toparams--options)
According to ui-router documentation:

When the application is in a particular state—when a state is
  "active"—all of its ancestor states are implicitly active as well.

So, I expect that "root.step1" and "root" will be active and it works as expected, but "viewB" is not filled with the template as you can see in jsfiddle sample : the top viewA(root.step1) is OK, but the middle viewB(root.step1.step2) is empty.
What I am doing wrong?

A: The documentation says:

Child states will load their templates into their parent's ui-view.

So there should be a ui-view='viewB' inside the viewA template, since the parent state of root.step1.step2 is root.step1. Or the viewB should be one of the views of root.step1, and there should be no root.step1.step2.


text:
Q: Class not found exception at org.apache.cordova.facebook.Connect I am using the same code at
https://github.com/jimzim/phonegap-facebook-android-sample/blob/master/platforms/android/assets/www/index.html
In Config.xml, i have added below codes
      <feature name="org.apache.cordova.facebook.Connect"><param name="android-package" value="org.apache.cordova.facebook.ConnectPlugin" />

 </feature>

What i have did wrong?
Please help me
Thanks


text:
Q: ireport with hibernate, Could not instantiate dialect class I am working with hibernate and iReport, configure the classpath well, but I get this error Could not instantiate dialect class, esoty working with SQLServer.
this is the dialect
<property name="dialect"> org.hibernate.dialect.SQLServerDialect </property>

Thanks for your time.

A: This problem occurs when you have two different versions of hibernate being used in your project and the ireport classpath. Make sure that both your project and ireport classpath points to same version of hibernate.


text: Q: Prove that there are infinitely many primes p with p ≢ ±1 mod 8. I understand how to prove this in the case of p is congruent to 1(mod 8) but am stuck on what to pick as a prime that is not included in a list {p1,...,pk} and can be shown to not be congruent to 1(mod 8).


text:
Q: Received Facebook error response of type OAuthException: (#200) The user hasn't authorized the application to perform this action I want to post some message to fb wall using java code. but while posting got this error: "com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#200) The user hasn't authorized the application to perform this action"
FacebookType publishMessageResponse =facebookClient.publish("me/feed", FacebookType.class,Parameter.with("message", postText));


text:
Q: Help with the ffmpeg I can read now the last line from the FFmpeg procees executed in a cmd window.
with this source using Scripting host model object reference.
Private Sub Command1_Click()
    Dim oExec       As WshExec
    Dim sRow        As String

    With New WshShell
        Set oExec = .Exec("ffmpeg.exe")
    End With
    Do While oExec.Status = WshRunning
        sRow = oExec.StdOut.ReadLine
    Loop
End Sub

This line is like this. it's the last line in the cmd window (in the botom).
frame= 2816 fps=667 q=11.0 Lsize= 13036kB time=187.66 bitrate= 569.1kbits/s

I cut the part of Time to bulid a progress bar in my vb 6.0 app.  But in the cmd process exist a value 13 lines up this value its called Total duration.  But i cant read this line , somebody haves a code or any idea to read this line ubicated 13 lines up from the last line of the cmd window from ffmpeg...

A: I've done this myself in Java.  I think the problem is that the status update lines (like you quote above with the time= substring) is terminated with a CR (Carriage Return) and not a LF (Line Feed).  My gut says that ReadLine is looking for a full CRLF.  So, to do this, you will need to:

*

*understand the difference between CR, LF and CRLF, and what ASCII code each is

*read in the output stream character by character, building up a CR-terminated line, and then parse it for the time= and Durration= tokens

It would help both you and us if you had debugging print statements in your code, and showed us the output.


text:
Q: I know that $G$ is finitely generated free group with generating set $S$, $G=\langle S\rangle $. Is $G$, free with base $S$? Let $G$ be a group.
Then, $G$ is free iff there exists $X\subset G$ such that for any group $H$ and a function $f\in H^X$, there exists a unique $\phi\in Hom(G,H)$ such that $\phi\upharpoonright X=f$. It can be shown that if $G$ is a group and $X\subseteq G$, then $G$ is free with base $X$ if and only if every $g\in G$ can be uniquely written in the form $g=x_1 x_2\ldots x_n$ where $0\leq n$, $x_i\in X\cup X^{-1}$ for all $1\leq i\leq n$ and $x_{i+1}\neq x_i$ for all $1\leq i\leq n-1$.
Question. I know that $G$ is finitely generated free group with generating set $S$, $G=\langle S\rangle$. Is $G$, free with base $S$? ($S$ is symetric)


text:
Q: R CMD check note: Non-standard files/directories found at top level (PNG file) When I run R CMD check via devtools::check(), I get the following NOTE:
Non-standard files/directories found at top level:
  'README-unnamed-chunk-3-1.png' 'README-unnamed-chunk-4-1.png'
This is a file generated by knitting the README.rmd file. How can I address this note? The source for the package is here.


text:
Q: WPF MVVM binding positions of two UserControls, when one gets moved, the other reacts I am trying to build a diagram with nodes, pins and wires.
Lets pretend i only care about the wires and pins for now.
Wire
<Path Stroke="Red" StrokeThickness="2" >
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="### HERE I NEED TO BIND TO PIN POSITION ###">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                <BezierSegment Point1="100 100"
                                               Point2="100 50"
                                               Point3="300 200"/>
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>

Take a look at the PathFigure's StartPoint, its a Point value which tells the Wire where to start from.
Now the pin is much simpler, its basically a Thumb(which allows easy dragging and dropping on the Canvas)
<UserControl x:Class="WireMvvm.Pin"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WireMvvm"
         mc:Ignorable="d"
         d:DesignHeight="10" d:DesignWidth="10">
<Thumb Background="Red">
</Thumb>

What i dont know how to do is to apply the MVVM pattern in this occasion and as the Pin moves, the StartPoint from the Wire should have the same location as the Pin, i for sure know how to do this normally with events and lots of code behind and don't think its bad at all but i like to explore more ways.
I also need to be able to serialize the diagram and add pins/wires at runtime(but thats not my question, just extra information because im not sure how MVVM works with runtime dynamic stuff)
Should i have models for the wire and pin separately, then viewmodels for both too? Im seriously lost, and tried watching lots of videos but i still struggle to apply this with my idea.

A: I would recommend using an items control with a canvas inside of it. That way you can bind properties you mention and use data templates for your items.
    <ScrollViewer x:Name="CanvasScroller" Grid.Column="1" HorizontalScrollBarVisibility="Auto">
    <ItemsControl Name="ItemsContainer"
                  ItemsSource="{Binding ElementName=self, Path=CanvasBoardViewModel.BoardItems}"
                  AllowDrop="True">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas x:Name="_canvas" IsItemsHost="True" Background="White" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Canvas.Left" Value="{Binding CurrentLocation.X}"/>
                <Setter Property="Canvas.Top" Value="{Binding CurrentLocation.Y}"/>
                <Setter Property="Width" Value="{Binding Width}" />
                <Setter Property="Height" Value="{Binding Height}"/>
            </Style>
        </ItemsControl.ItemContainerStyle>

    </ItemsControl>
</ScrollViewer>

Your Data Templates could be something like this
<DataTemplate DataType="{x:Type local:CanvasBoardItem}">
        <Grid>
            <Rectangle>

            </Rectangle>
            <Thumb></Thumb>
            <Thumb></Thumb>
            <Thumb></Thumb>
        </Grid>
 </DataTemplate>

Your View Model would be something along these line
public class ViewModel
{
    public ObservableCollection<CanvasBoardItem> BoardItems { get; private set; }

    public ICommand SerializeDataCommand { get; }

    public ViewModel()
    {
        //Set up command here
        //Set up board items here
    }
}

Canvas board item contains all of the stuff you want to bind to in the items template like height, width, connections and so on


text:
Q: How to do random addition I created a maths quiz as follow:
import random
score=0
ask="Y"
while ask=="Y":
    num1=random.randint(1,20)
    num2=random.randint(1,20)
    answer=int(input(str(num1)+"+"+str(num2)+":"))
    correctanswer=num1+num2
    if(correctanswer==answer):
        print("well done")
        score=score+10
    else:
        print("Oh no....")
    ask=input("Want another one? (Y/N)")
print("your score is: ", score)

The problem is it is not stopping after 3 wrong tries. What should I add to the program to do so.

A: import random
score=0
ask="Y"
errors = 0
max_tries = 3
while ask == "Y":
    num1=random.randint(1,20)
    num2=random.randint(1,20)
    answer=int(input(str(num1)+"+"+str(num2)+":"))
    correctanswer=num1+num2
    if(correctanswer==answer):
        print("well done")
        score=score+10
    else:
        errors += 1
        print("Oh no....")
    if errors >= max_tries:
        break
    ask = input("Want another one? (Y/N)")
print("your score is: ", score)

A: Add wrong_tries_counter, explenations are in comments.
Note that we check if reached limit only when failing, to spare redundant checks.
import random
score=0
ask="Y"
# Initialize counter with zero
wrong_tries_counter     = 0
WRONG_TRIES_LIMIT       = 3
while ask=="Y":
    num1=random.randint(1,20)
    num2=random.randint(1,20)
    answer=int(input(str(num1)+"+"+str(num2)+":"))
    correctanswer=num1+num2
    if(correctanswer==answer):
        print("well done")
        score=score+10
    else:
        print("Oh no....")
        # Update wrong tries, when faild
        wrong_tries_counter += 1
        # Break if reached wrong tries limit
        if WRONG_TRIES_LIMIT == wrong_tries_counter:
            break
    ask=input("Want another one? (Y/N)")
print("your score is: ", score)

A: Add break at this part of your code:
import random
score=0
ask="Y"
wrongs=0
while ask=="Y":
    num1=random.randint(1,20)
    num2=random.randint(1,20)
    answer=int(input(str(num1)+"+"+str(num2)+":"))
    correctanswer=num1+num2
    if(correctanswer==answer):
        print("well done")
        score=score+10
    else:
        print("Oh no....")
        wrongs+=1
        if wrongs==3:
            break
    ask=input("Want another one? (Y/N)")
print("your score is: ", score)


text:
Q: SSL Apache с переадресацией Использую такую конфигурацию для переадресации сайта с виртуальной машины с ип 1.1.1.1 через сервер с апачем.
rewriteengine on
rewritecond %{REMOTE_ADDR} ^1\.1\.1\.1$
rewriterule ^(.*)$ http://site.ru/$1 [L,R=301]

Установлены mod_rewrite, mod_proxy, mod_proxy_http.
Нужно все тоже самое, но чтоб работало через https.
Какие модули добавить и что изменить в конфигурации?

A: вы привели конфигурацию для первого из предложенных вариантов, когда браузеру возвращается http-ответ 301, в соответствии с которым браузер должен сделать переход на предложенный url.
в такой ситуации никаких дополнительных модулей в apache подключать не нужно, надо всего лишь изменить строку http на https (в третьей приведённой вами строке).


text:
Q: Codeblocks succeeded in compiling, but gcc failes, Why? I'm using ubuntu 18.
I'v installed codeblocks ide and bare gnu gcc compiler (command line) both
gcc version 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
code blocks 16.01
I wrote a very simple code to create and print a string variable
Code blocks(with inbuilt gnu gcc compiler) succeeded in compiling. But bare gcc compiler failes
I've tried by including iostream and stdio also
#include <string>
using namespace std;

int main() {
    string a = "I am learning C++";
    printf("%s",a.c_str());
    return 0;
}

codeblocks compiles it successfully and gives the output without raising an error. As well as sololearn online compiler also
I am learning C++
I got into the folder where the cpp file is and gave following command
gcc string_var.cpp -o string_var.out
Bt the bare gcc compiler gives some long stuff of compiler errors which i can't understand
/tmp/ccen8bfp.o: In function `main':
string_var.cpp:(.text+0x20): undefined reference to `std::allocator<char>::allocator()'
string_var.cpp:(.text+0x37): undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)'
string_var.cpp:(.text+0x43): undefined reference to `std::allocator<char>::~allocator()'
string_var.cpp:(.text+0x4f): undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::c_str() const'
string_var.cpp:(.text+0x74): undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()'
string_var.cpp:(.text+0x96): undefined reference to `std::allocator<char>::~allocator()'
string_var.cpp:(.text+0xb0): undefined reference to `std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()'
/tmp/ccen8bfp.o:(.data.rel.local.DW.ref.__gxx_personality_v0[DW.ref.__gxx_personality_v0]+0x0): undefined reference to `__gxx_personality_v0'

collect2: error: ld returned 1 exit status

A: The GNU Compiler Collection (GCC) can be used to compile many different languages. Some of those languages are common enough that they can use the same front-end program.
C and C++ are two such languages, and both can be compiled with the gcc front-end program. However, the gcc program by default is for C code, and because of that don't use some flags needed to build C++ programs. One such missing thing is that gcc doesn't link with the C++ standard library.
You can solve this by explicitly linking with the library:
gcc string_var.cpp -o string_var.out -lstdc++

Or, even simpler, use the front-end program for C++, g++:
g++ string_var.cpp -o string_var.out

A: gcc string_var.cpp -o string_var.out

gcc is a C compiler. You want to compile C++ code:
g++ string_var.cpp -o string_var.out

It just so happens that either gcc or g++ works insofar as compiling the actual code, the compiler understand that .cpp files contain C++ code, and proceeds accordingly.
However, when it times to linking the resulting object module, gcc does not provide the runtime C++ library to the linker (it still thinks it's just a C compiler, and has never heard of C++), resulting in your link failure.


text:
Q: Time complexity of Dijkstra's algorithm Searching through various sources, I have seen contradictory information on the worst case time complexity for the Dijkstra algorithm using binary heap (the graph being represented as adjacency list).
According to wikipedia https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Running_time

With a self-balancing binary search tree or binary heap, the algorithm requires Θ((E+V) logV) time in the worst case

where E - number of edges, V - number of vertices.
I see no reason why it can't be done in O(V + E logV).
In case E >= V, the complexity reduces to O(E logV) anyway. Otherwise, we have O(E) vertices connected to the start vertex (the algorithm will perform one iteration for each of them). On each iteration we select a vertex and remove it from the heap in O(logV) time. We also need O(logV) time for each update of the minimal distance to a connected vertex. The number of these updates is bound by the number of edges E so in total we need O(E logV) for the updates.
In total we need O(V) to initalize distances to each vertex, O(E logV) for removing vertices from the heap and O(E logV) for updating the heap when shortest distance changes. We get final complexity O(V + E logV).
Am I wrong or is wikipedia wrong?

A: Dijkstra's algorithm only finds vertices that are connected to the source vertex.  The number of these is guaranteed to be <= E, since each such vertex requires an edge to connect it.  The body of Dijkstra's algorithm therefore requires only O(E log V) time.
The version given on the wikipedia page, however, performs an initialization step that adds each vertex to the priority queue, whether it's connected or not.  This takes O(V log V) time, so the total is O((V+E) log V).
You imagine an implementation that only initializes distances, without adding them to the priority queue immediately.  That is also possible, and as you say it results in O(V + E log V) time.
Some implementations require only constant time initialization, and can run in O(E log V) total

A: Their code adds all vertices to the queue at first, and goes until the queue becomes empty, thus performing $|V|$ extractions (and $|E|$ updates). Of course, it can be optimized - for example, if we minimal known distance in the queue is $\infty$, we can stop. But without this extra check, algorithm can run longer than $O(|V| + |E|\log |V|)$.
Also, depending on implementation, initialization step can also require $O(|V|\log |V|)$ time - for example, if we use self-balancing tree, each insert operation will require $O(\log|V|)$ time.


text:
Q: How to create lines crossing through cursor position in JavaScript I would like to find a way to create two perpendicular lines, crossing at the cursor position and spanning across the entire canvas. Since I'll be presenting some complex and rather chaotic fully-meshed diagrams to the user, I want to give them a way to quickly find the cursor.
What is the best way to achieve this in JavaScript?
My Problem is: I'm still new to JavaScript and the endless libraries that are available for this kind of stuff so I really have no clue what's best to use. I found a similar question for QT GraphicsView here and was wondering whether there might be a library or script out there that can achieve the same.
Thank you in advance.


text:
Q: Odeint - How to solve the problem "local variable '' referenced before assignment I am facing a problem to solve a set of differential equations using odeint. The problem is that the variables that My variables are interdependent. The part of the code that is returning me the error is:
def G(solution,time):
θ1_d, ϕ1_d, θ2_d, ϕ2_d, q_d = solution[0], solution[1], solution[2],solution[3], solution[4]
θ1, ϕ1, θ2, ϕ2, q = solution[5], solution[6], solution[7],solution[8], solution[9]

C_VL = 1/2 * q * C_L0
u = sqrt(1/(2*pi*St) * (1/(2*pi*St) - 2*l*θ1_d - h*θ2_d) + l**2 * (-2*θ1*ϕ1*θ1_d*ϕ1_d + θ1_d**2 + ϕ1_d**2) + l*h*(-θ1*ϕ1*θ1_d*ϕ2_d - θ2*ϕ2*θ2_d*ϕ1_d + θ1_d*θ2_d + ϕ1_d*ϕ2_d) + (h**2/4)*(-2*θ2*ϕ2*θ2_d*ϕ2_d + θ2_d**2 + ϕ2_d**2))
C_VX = (C_VL*2*pi*St*(l*ϕ1_d + (h/2)*ϕ2_d) + C_DM*(1 -2*pi*St*(l*θ1_d + (h/2)*θ2_d)))*u  + α*C_VL**2*(1 - 2*pi*St*(l*θ1_d + (h/2)*θ2_d))*abs(1 - 2*pi*St*(l*θ1_d + (h/2)*θ2_d))
C_VY = (C_VL*(1 -2*pi*St*(l*θ1_d + (h/2)*θ2_d)) - C_DM*2*pi*St*(l*ϕ1_d + (h/2)*ϕ2_d))*u

θ1_dd = -h*θ2_dd/(2*l) - 2*ζ1*Ω1*θ1_d - ζ1*Ω1*h*θ2_d/l - Ω1**2*θ1
ϕ1_dd = -h*ϕ2_dd/(2*l) - 2*ζ1*Ω1*ϕ1_d - ζ1*Ω1*h*ϕ2_d/l - Ω1**2*ϕ1
θ2_dd = 3*C_VX/(4*pi**3*St**2*h*(m_r + C_a)) - 3*l*θ1_dd/(2*h) - 3*ζ2*Ω2*θ2_d/2 - 3*ζ2*Ω2*l*θ1_d/h +Ω2**2*θ2
ϕ2_dd = 3*C_VY/(4*pi**3*St**2*h*(m_r + C_a)) - 3*l*ϕ1_dd/(2*h) - 3*ζ2*Ω2*ϕ2_d/2 - 3*ζ2*Ω2*l*ϕ1_d/h +Ω2**2*ϕ2
q_dd = A*(l*ϕ1_dd + (h/2)*ϕ2_dd) - ε*(q**2 - 1)*q_d - q + κ*(l*θ1_dd + (h/2)*θ2_dd)*q

return np.array([θ1_dd, ϕ1_dd, θ2_dd, ϕ2_dd, q_dd, θ1_d, ϕ1_d, θ2_d, ϕ2_d, q_d])

solution=odeint(G,solution0,time)

The problem is that θ1_dd is a function of θ2_dd that is defined latter, and θ2_dd is a function of θ1_dd. So I cannot simply invert the order of the equations to solve that problem.
The error message is: UnboundLocalError: local variable 'θ2_dd' referenced before assignment
Any suggestion of how to solve that problem?


text:
Q: How to access web method path from the url obtained from AWS elastic beanstalk I have deployed my Springboot web application on AWS Elastic Beanstalk tomcat server. When i enter the url i am able to see the "Hello World' screen however i am unable to access the other web method paths by simply concatenating '\path' on the end.
How am i able to access my web method paths via the url provided by AWS?

A: i was not able to access this because i had not added a WebApplicationInitialiser to the main class.
@ComponentScan
@EnableAutoConfiguration
@SpringBootApplication
public class Application  extends SpringBootServletInitializer
implements WebApplicationInitializer {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
  return builder.sources(Application.class);
  }
}


text:
Q: Twilio, connect PLAY to conference Is it possible to Play in a Conference between 2 people by adding a new call to that conference which Plays. Will there be an inherent "lag" when that call joins because of the minimum 2 way network trip that happens. Is it possible to cut that down to 1 way by pushing TwiML to Twilio instead of having Twilio pull it down?

A: Twilio evangelist here.
There isn't a way to have Twilio store the TwiML, but there are strategies that can help reduce the lag.
One of the biggest things you can do when using the <Play> verb is to make sure that you are returning proper caching headers for both your TwiML and the audio file you are planing.  Twilio is a well-behaved HTTP client and will honor those headers.

*

*https://www.twilio.com/docs/api/twiml/your_response

*https://www.twilio.com/docs/api/twiml/play#hints

*https://www.twilio.com/help/faq/voice/how-can-i-change-the-cache-behavior-of-audio-files
Hope that helps


text:
Q: Hive User Impersonation for Sentry I was reading on that for while using sentry you must disable hive user impersonation.
Is it necessary to disable to impersonation? If Yes is there any other way to impersonate hive user with sentry enabled?

A: Impersonation and Sentry are two different ways to provide authorization in Hive. First one is based on "POSIX-like" hdfs file system permissions, while Sentry is role-based authorization module + SentryService.
There is no way to use Sentry with impersonation enabled in Hive. It could be a security issue. User/application with granted access to any entity (database, table) stored in hive metadata store could have access to any directory/file on hdfs that doesn't "belong" to him.
According to Cloudera the impersonation is not a recommended way to implement authorization in HiveServer2 (HiveServer2 Impersonation).


text:
Q: Compact operators are orthogonally equivalent to a diagonal matrix? On Brezis's Functional Analysis, the last question of Problem 44 (near the end of the book) reads (modified to include context)

Assume that the Hilbert space $H$ is separable and $T\in\mathcal K(H)$ (but $T$ doesn't necessarily satisfy the following condition: there exists an isometry $J\colon\ker T\to\ker T^*$), the set of compact operators on $H$. Prove that there exist two orthogonal bases $(e_n)$ and $(f_n)$ of $H$ such that
  $$Tu=\sum_{n=1}^\infty\alpha_n(u,e_n)f_n$$
  where $(\alpha_n)$ is a sequence of nonnegative real numbers and $\alpha_n\to0$ as $n\to\infty$.

Since one should assume the operator to be partial isometric instead of orthogonal/unitary, as the wiki page pointed out. Even if the operator is compact, I think it's still necessary since we can compose the one-sided shift with a compact operator corresponding to a diagonal matrix.
So I think this question is in fact false, but I doubt that I got stuck somewhere, since Brezis stressed in the parenthesis that the condition about existence of isometry isn't necessary. I want your help to clarify my misunderstandings. Thanks!


text:
Q: Integer check in PHP I'm writing an odds converter in PHP and came across this code for converting decimal odds to fractional ones
function dec2frac($dec) {
    $decBase = --$dec;
    $div = 1;
    do {
        $div++;
        $dec = $decBase * $div;
    } while (intval($dec) != $dec);
    if ($dec % $div == 0) {
        $dec = $dec / $div;
        $div = $div / $div;
    }
    return $dec.'/'.$div;
}

When I tested the code, it would sometimes succeed in the calculations and sometime try to load the page for some time without success so I figured that it got stuck in the loop somehow. I set the time limit to 1 second and an echo in the loop, which confirmed my suspicion. I added these two echoes to the loop so I could see what went wrong.
echo "$dec $div
";
echo var_dump(intval($dec) == $dec)." $dec is int
";

Example printout when it fails, using decimal = 1.6
1.2 2
bool(false) 1.2 is int
1.8 3
bool(false) 1.8 is int
2.4 4
bool(false) 2.4 is int
3 5
bool(false) 3 is int  //should break here and return 3/5
3.6 6
bool(false) 3.6 is int
4.2 7
bool(false) 4.2 is int
Example printout when it succeeds, using decimal = 1.8
1.6 2
bool(false) 1.6 is int
2.4 3
bool(false) 2.4 is int
3.2 4
bool(false) 3.2 is int
4 5
bool(true) 4 is int
Why doesn't it recognize the integers sometimes? How can I fix it so it exits the loop when an integer is found?

A: It looks like a floating precision rounding error. intval($dec) and $dec appear to be equal, but actually aren't. The difference is negligible but strict equalness fails.
On my 64bit system, with a precision of 1E-15 the function works, with a precision of 1E-16 it loops.
In general, strict comparison of two floating point numbers is to be avoided. Two floats are to be considered "equal" if their difference is less than a threshold. There are ways of calculating this threshold (google for "determining machine precision"), for it is not the same everywhere.
Since in my PHP.INI I have the default value
; The number of significant digits displayed in floating point numbers.
; http://php.net/precision
precision = 14

then the two numbers are shown equal even if one is 3 and the other 3.0000000000044, and the caltrop goes unnoticed.
With precision = 18, $dec is shown not to be what you'd expect:
1.20000000000000018
1.80000000000000027
2.40000000000000036
3.00000000000000044

Try:
function dec2frac($dec) {
    $decBase = --$dec;
    $div = 1;
    do {
        $div++;
        $dec = $decBase * $div;
    } while (abs(intval($dec) - $dec) > 1e-15);
    if (($dec % $div) == 0) {
        $dec = $dec / $div;
        $div = $div / $div;
    }
    return $dec.'/'.$div;
}


text:
Q: When is a vector field the curl of another vector field? Under what conditions does a given vector field $\bf X$ on some open subset $U \subseteq \mathbb{R}^3$ satisfy ${\bf X} = \text{curl } {\bf Y}$ for some vector field $\bf Y$ on $U$?

A: If the second de Rham cohomology $H^2(U)$ of the underlying set $U$ is trivial (which is true, e.g., for all contractible sets $U$), then a necessary and sufficient condition is that $$\text{div } {\bf X} = 0,$$ which follows more or less from the definition of cohomology and the relationship between the $\text{curl}$ and $\text{div}$ operators and the exterior derivative operator.
If $H^2(U)$ is not trivial, then $\text{div } {\bf X} = 0$ is a necessary but not a sufficient condition.

A: Given $\mathbf{X}=(X_1,X_2,X_3)$, a vector field $\mathbf{Y}=(Y_1,Y_2,Y_3)$ such that $\mathbf{X}=\text{curl }\mathbf{Y}$ will satisfy:
$$\begin{cases}
X_1&=\dfrac{\partial Y_3}{\partial y}-\dfrac{\partial Y_2}{\partial z}\\
X_2&=\dfrac{\partial Y_1}{\partial z}-\dfrac{\partial Y_3}{\partial x}\\
X_3&=\dfrac{\partial Y_2}{\partial x}-\dfrac{\partial Y_1}{\partial y}
\end {cases}$$

A: The condition $\text{div }{\bf X} = 0$ is obviously necessary. If the domain is star-shaped, is also sufficient and there is an explicit formula. Supposing wlog that that the domain is star-shaped respect to the origin:
$${\bf Y}({\bf r}) = \int_0^1{\bf X}(t{\bf r})\times t{\bf r}\,dt.$$
See http://www.maths.tcd.ie/~houghton/231/Notes/LN/231.I.6.pdf or http://www.maths.tcd.ie/~houghton/231/Notes/ChrisFord/vp.ps


text:
Q: Display HTML file in uiwebview from SQLite database? I have a project that I am working on that requires me to be able to display an HTML file stored in a SQLite database in a uiwebview. I know how to display a local file stored in the main bundle, but I just can't figure out how to get these files stored in the SQLite database to display in the uiwebview. If anyone can help me it would be greatly appreciated. Sample project or tutorial is great! Thanks in advance!
ADDED INFO
I thought I would attach this link to help in understanding what I'm trying to do. http://www.google.com/url?sa=t&source=web&cd=1&ved=0CCYQFjAA&url=http%3A%2F%2Fdblog.com.au%2Fiphone-development-tutorials%2Fiphone-sdk-tutorial-reading-data-from-a-sqlite-database%2F&rct=j&q=sqlite%20animals%20tutorial%20iphone&ei=41eIT-79L9H-2QW50tXaCQ&usg=AFQjCNGqongc81oHHa3WGFTctkBIiduCvA in the linked tutorial I have dropped the image view since I don't need it for my purposes, and I have replaced the data in the database to be the contents of an html file. In the tutorial it displays the text in a textview and I want to change it to display in a uiwebview. I want this to keep formatting and a few other reasons. Thanks to those who have posted. If anyone can help me get this it would be great!! Thanks in advance!

A: webView loadHTMLString:baseURL: (I assume it is just stored as a string....if you have any images, you will need to set your base directory accordingly)

A:   [WebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

this code displays "test.html" which is located in the project folder

A: Got it by using
NSString *html = [animal description];
[self.animalView.animalDesciption loadHTMLString:html baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

when the ViewController that contains the webview is pushed into the display.


text:
Q: Finite extensions of $\mathbb{Q}_p$ as completions of number fields with some valuation over a prime ideal In my first post, I asked if $\mathbb{Q}_p$ is the completion of $\mathbb{Q}$ over some valuation of an prime ideal (and it seems to be true, according to an answer). Now I am asking if this can be generalized for finite extensions of $\mathbb{Q}_p$.
To put it in other words: Let $K$ be a finite extension of $\mathbb{Q}_p$. Question: Is there a valuation $v$ of some prime ideal in $\mathcal{O}_k$ on a global field $k$ (i.e. a finite extension of $\mathbb{Q}$) such that the completion $k_v$ of $k$ over $v$ is equal to $K$?

A: Yes.  Let $K$ be a finite extension of $\mathbb Q_p$.  We want to show that there is a finite extension $F$ of $\mathbb Q$, and a prime ideal $\mathfrak p$ in the ring of integers $\mathcal O_F$ of $F$, such that $K$ is the completion of $F$ with respect to the $\mathfrak p$-adic valuation on $F$.
Krasner's lemma tells us that there is an irreducible polynomial $g(t)$ (irreducible in the ring $\mathbb Q_p[t]$, that is) with rational coefficients, and a root $\beta$ of $g(t)$, such that $K = \mathbb Q_p(\beta)$.  Then $g(t)$ is also irreducible in the ring $\mathbb Q[t]$, so if we set $F = \mathbb Q(\beta)$, then $[F : \mathbb Q] = [K : \mathbb Q_p] = \operatorname{deg} g$.
Now let $| - |$ be the unique extension of the $p$-adic absolute value to $K$.  Restrict $|-|$ to an absolute value on $F$.  A version of Ostrowski's theorem for number fields states that this absolute value is either archimedean, or arises from a prime ideal $\mathfrak p$ in the ring of integers $\mathcal O_F$ of $F$.  Specifically, there is a real number $0 < \rho < 1$ and a prime ideal $\mathfrak p$ such that
$$|x| = \rho^{\operatorname{ord}_{\mathfrak p}(x)}.$$
Obviously this absolute value is not archimedean on $F$ (its restriction to the $p$-adic absolute value on $\mathbb Q$ isn't, after all).
Anyway, the completion of $F$ with respect to $\mathfrak p$ is the same as the metric space completion of $F$ with respect to $|-|$.  Finally, just as the metric space completion of $\mathbb Q$ with respect to $|-|$ gets you $\mathbb Q_p$, so does the metric space completion of $F = \mathbb Q(\beta)$ with respect to $|-|$ get you $\mathbb Q_p(\beta) = K$.


text:
Q: How to modify Get-ADGroupMember to run for multiple groups from csv, to replace nested groups with members of the said groups Hi Im trying to write a script to replace nested groups with members of said group. I found one from https://community.spiceworks.com/topic/1816091-ad-powershell-replace-nested-groups-with-members-of-said-group
and modified as follows. Where #Parent_1 is an AD distribution group.
$TargetGroup= '#Parent_1'
ForEach ($Member in Get-ADGroupMember -Identity $TargetGroup) {
    if ($Member.objectclass -eq 'group') {

        ForEach ($SubMember in Get-ADGroupMember -Identity $Member -Recursive ) {
        Add-ADGroupMember -Identity $TargetGroup -Members $SubMember.SamAccountName

        }
    Remove-ADGroupMember -Identity $TargetGroup -Members $Member -Confirm:$false

    }
}

It works perfectly fine for a single group that is "#Parent_1" when used as $TargetGroup.
But I wish to run it more than one for $TargetGroup using a CSV as follows.
Instead of using $TargetGroup= '#Parent_1', I wish to have $TargetGroup =Import-Csv -Path .\xx.csv
With the following CSV.

But it won't run, just by replacing that. It just gives errors.

Did several modifications, yet casting different different errors time to time, could not make it. Not sure we need another for each loop.
Can anyone please help ? Any help would be appreciated.

PS answer for my question | Final working code
foreach($TargetGroup in Import-Csv -Path .\xx.csv)
{

    ForEach ($Member in Get-ADGroupMember -Identity $TargetGroup.samaccountname)
    {
        if ($Member.objectclass -eq 'group')
        {
            ForEach ($SubMember in Get-ADGroupMember -Identity $Member -Recursive)
            {
                Add-ADGroupMember -Identity $TargetGroup.samaccountname -Members $SubMember.SamAccountName
            }
            Remove-ADGroupMember -Identity $TargetGroup.samaccountname -Members $Member -Confirm:$false
        }
    }
}

A: You just need to loop one $TargetGroup at a time
foreach($TargetGroup in Import-Csv -Path .\xx.csv)
{
    ForEach ($Member in Get-ADGroupMember -Identity $TargetGroup)
    {
        if ($Member.objectclass -eq 'group')
        {
            ForEach ($SubMember in Get-ADGroupMember -Identity $Member -Recursive)
            {
                Add-ADGroupMember -Identity $TargetGroup -Members $SubMember.SamAccountName
            }
            Remove-ADGroupMember -Identity $TargetGroup -Members $Member -Confirm:$false
        }
    }
}

A: @Doug thanks.. $TargetGroup should be $TargetGroup.samaccountname for internal loops in this way.. and its works! perfect.
foreach($TargetGroup in Import-Csv -Path .\xx.csv)
{

    ForEach ($Member in Get-ADGroupMember -Identity $TargetGroup.samaccountname)
    {
        if ($Member.objectclass -eq 'group')
        {
            ForEach ($SubMember in Get-ADGroupMember -Identity $Member -Recursive)
            {
                Add-ADGroupMember -Identity $TargetGroup.samaccountname -Members $SubMember.SamAccountName
            }
            Remove-ADGroupMember -Identity $TargetGroup.samaccountname -Members $Member -Confirm:$false
        }
    }
}


text:
Q: Android/PhoneGap/SQLite app: this 'Create Virtual Table' command works on emulator, fails on device I have an app, using the Lite4Cordova plug-in. It's populating a virtual SQLite FS4 table from some documents on first run of the app. It runs correctly on an emulated device, but fails on a real device with an SQL error.
To open the DB, I do this:
        var db;
        var shortName = 'linienDB';
        var version = '1.0';
        var displayName = 'linienDB';
        var maxSize = 65535;

        db = window.sqlitePlugin.openDatabase({name: shortName, version: version, displayName: displayName, maxSize: maxSize});
        alert("OpenDB is " + db)

The alert gives me "OpenDB is [object Object]" on both emulator and real device.
The create table code is this:
      db.transaction(function(tx){
           tx.executeSql( 'CREATE VIRTUAL TABLE IF NOT EXISTS guidelines USING FTS4 (category, id, chapter, header, content)',[],defaultNullHandler,defaultErrorHandler);
      },defaultErrorHandler);

On an emulated device, this runs OK. The DB gets created & populated correctly, & I am able to run queries against it. But on my real device, the defaultErrorHandler is triggered on db.transaction,  and I get alert "Error Processing SQL: undefined". The error on the console is this:
12-18 17:39:08.948: V/executeSqlBatch(4375): SQLitePlugin.executeSql[Batch](): Error=near "NOT": syntax error: , while compiling: CREATE VIRTUAL TABLE IF NOT EXISTS guidelines USING FTS4 (category, id, chapter, header, content)

If I switch back to the standard WebSQL DB open, like this:
db = openDatabase(shortName, version, displayName, maxSize);

then the OpenDB alert is OpenDB is [object Database], and the load sequence completes- but of course the table isn't built because creating an FS4 virtual table is an SQLite command, not a WebDB command.

UPDATE:
Following the error from LogCat that there was an error near "Not", I removed the "IF NOT EXISTS" from the Create Table statement, and just have:
db.transaction(function(tx){
                    tx.executeSql( 'CREATE VIRTUAL TABLE guidelines USING FTS4 (category, id, chapter, header, content)',[],defaultNullHandler,defaultErrorHandler);
                },defaultErrorHandler);

Which now works perfectly on the device. It's annoying not to be able to use IF NOT EXISTS syntax, but thumbs up to Android SDK for the useful error, anyway.


text:
Q: Display 'Today' instead of date I am using angular and moment.js to display dates in my app. If the user chooses a date other than today I want the format to be '12:00 PM Sat 21st Nov' which I have working when the user clicks a day from my calendar with amDateFormat
the following:
$scope.setDate = function(day){
    var myDate = day.date;
    $scope.date = moment($scope.date).set(
    {
        'year': myDate.year(),
        'month': myDate.month(),
        'date': myDate.date()
    }).toDate();
}

 {{ date | amDateFormat:'h:mm A ddd Do MMM'}}

If the date chosen is today how do I display the date to be '12:00 PM Today' instead?

A: I am not familiar with angular. However you can use moment calendar for today date.
From the doc you can tweak the calendar like this:
moment.locale('en', {
    calendar : {
        sameDay : 'LT [Today]'
    }
});

And then call moment().calendar();
Here is a snippet with an alternative way of doing it assuming you are using a version that is at least 2.10.5:

    var divTime = $('#time');
    var time = moment().calendar(null, {
      sameDay: 'LT [Today]'
    });
    divTime.text(time);


text:
Q: Calendar overlay error message
I have a calendar overlay with several team calendars on it. I noticed there is a message on top of the calendar stating "List does not exist. The page you selected contains a list that does not exist. It may have been deleted by another user [*****] <- this ID changes every time i reload the page. I went through every team calendar thinking it was a permissions issue, I can access every single team calendar with no issue. What i'm I missing? Any suggestions?
Thanks

A: I removed the calendar overlays and re-added them. It's working now. Thanks


text:
Q: Selmer Group versus Selmer Variety For an abelian variety $A$, the $p$-adic Selmer group is defined to be the subset of $H^1(G_k,H_1^{et}(A;\mathbb{Q}_{p}))$ whose restriction to $G_{k_v}$ is in the image of $A(k_v)$ for all places $v$ of $k$.
Minhyong Kim's paper states on its third page (p.91) that his Selmer varieties generalize $\mathbb{Q}_p$ Selmer groups of elliptic curves. As I understand it, his Selmer variety would refer to the subset of $H^1(G_k,H_1^{et}(A;\mathbb{Q}_{p}))$ that is unramified for $v \nmid p$ and crystalline at $v \mid p$ (assuming the abelian variety has good reduction there).
Is it clear that these two definitions are equivalent? Why is this true?

A: You should read the Bloch--Kato paper in the Grothendieck Festschrift. This was, I believe, the first paper to consider Selmer groups of Galois representations defined by local conditions coming from p-adic Hodge theory (e.g. crystalline at p).
The definition you quote from Kim is exactly the Bloch--Kato definition of the Selmer group; and Bloch and Kato prove in their paper that in the case of abelian varieties their definition recovers the classical Selmer group.


text:
Q: Spinner dropdown list doesn't show http://i.stack.imgur.com/HGsTw.jpg
This is the error I get and the app just crashes and shows nothing!.
PS:When I moved those last 4 lines of code from the OnCreate method to the beginning of the OnItemSelected method I get no errors and this layout (http://i.stack.imgur.com/1DiLI.jpg) shows but no dropdown lists (I expect a list of colors when I click the arrow button next to background).
Here is my code:
public class SetLayout extends Activity implements OnItemSelectedListener {
TextView o_markertv, x_markertv, bcktv, gridtv;
String[] colors ={"Red", "Green", "Blue", "Black", "White"};
Spinner spinner1, spinner2, spinner3, spinner4;
LinearLayout bck;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setlayout);
    bck= (LinearLayout) findViewById(R.id.bck);

    o_markertv= (TextView) findViewById(R.id.o_markertv);
    x_markertv= (TextView) findViewById(R.id.x_markertv);
    bcktv= (TextView) findViewById(R.id.bcktv);
    gridtv= (TextView) findViewById(R.id.gridtv);
    spinner1 = (Spinner) findViewById(R.id.spinner1);
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    spinner3 = (Spinner) findViewById(R.id.spinner3);
    spinner4 = (Spinner) findViewById(R.id.spinner4);
    //Button BtnSubmit = (Button) findViewById(R.id.btnSubmit);

    ArrayAdapter<String> adapter=new ArrayAdapter<String> (SetLayout.this,android.R.layout.simple_spinner_item,colors);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter);
    spinner1.setOnItemSelectedListener(this);
}

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
        long arg3) {

    int position= spinner1.getSelectedItemPosition();
    switch(position){ //red, green blue black white
    case 0:
        bck.setBackgroundColor(color.red);
        break;
    case 1:
        bck.setBackgroundColor(color.green);
        break;
    case 2:
        bck.setBackgroundColor(color.blue);
        break;
    case 3:
        bck.setBackgroundColor(color.black);
        break;
    case 4:
        bck.setBackgroundColor(color.white);
        break;

    }
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

}


text:
Q: Laravel Search engine using whereIN How Do I use the whereIn clause for a search engine that I am trying to create. I have two inputs one for where the user types in what they are looking for and the other for the city,state or zip code.When I do search for what I'm looking for and the city it shows results,when I look for the state it shows results and when I look for the zip code it shows results, but when I type the city and state it doesn't show results. Can someone help me with this Please? This is like my fourth time that I posted on Stack overflow and still nothing seems to be functioning as I expected. Here is my code
     $userinput=$request->input('mywhat');

    $userinputt=$request->input('mywhere');

    $str = trim(preg_replace('/\s+/',' ', $userinput));

    $strr = trim(preg_replace('/\s+/',' ', $userinputt));

    $this->validate($request,array(
       $strr=>'nullable',
    ));

    $pro=Profile::Where('what','Like','%'.$str.'%')->Where(function ($query) use($strr, $userinputt) {
    $query->Where('city', 'LIKE', '%'.$strr.'%');

})->orWhere('what','Like','%'.$str.'%')->Where(function ($query) use($strr, $userinputt) {
    $query->Where('state', 'LIKE', '%'.$strr.'%');

})->orWhere('what','Like','%'.$str.'%')->Where(function ($query) use($strr, $userinputt) {
    $query->Where('zipcode', 'LIKE', '%'.$strr.'%');

// })->orWhere('what','Like','%'.$str.'%')->Where(function ($query) use($strr, $userinputt) {
     //   $query->Where('city', 'LIKE', '%'.$strr.'%');
})->orWhere('what','Like','%'.$str.'%')
   ->Where('city', 'LIKE', '%'.$strr.'%')
   ->Where( function ($query) use ($strr,$userinputt) {
        $query->Where('state',  'LIKE', '%'.$strr.'%');
        $query->orWhere('zipcode', 'LIKE', '%'.$strr.'%');
   })->inRandomOrder()->paginate(5);

    return view('layouts.reveal')->with('pro',$pro);

A: See where this gets you (you'll need to change the Model and variables to fit your code, of course):
$query = Model::where('search', 'like', '%' . $search . '%')
    ->when($city, function ($query) use ($city) {
        return $query->whereCity($city);
    })
    ->when($state, function ($query) use ($state) {
        return $query->whereState($state);
    })
    ->when($zip, function ($query) use ($zip) {
        return $query->whereZip($zip);
    })
    ->get();


text:
Q: ASP.NET MVC3 Development Practices for Disconnected Active Directory I'm starting a new MVC 3 application at the same time I'm transitioning to a more disconnected development environment where I will only occasionally be connected to the corporate network to do deployments.
I have normally used the [Authorize(Roles = @"xxx,yyy")] attributes to handle basic group authentication, but of course when I'm disconnected doing development, this will not work.
Does anyone have any suggestions or best practices for this kind of situation?

A: Any time you need to do development against a resource that you may not have full (or any) access to, you should consider a mocking framework. Moq and Rhino Mocks are just two of the more popular frameworks for this purpose.
The idea is to create an interface that your code will use so that you can swap in the actual AD provider or the mocking framework depending upon which environment you're working with.


text:
Q: Rspec and Declarative Authorization: Rules in dummy app doesn't work with testing I'm trying to integration-test a gem that uses authlogic and declarative authorization.
To check a custom controller in my dummy-app I created a new spec/dummy/config/authorization_rule.rb file:
authorization do
role :admin do
    has_permission_on :admin_events, :to => [:manage]
end
end

When I fire up a server in test environment (rails s -e test) everything works as expected.
But when I run my tests with capybara (doesn't matter if using rack_test, selenium or webkit) the custom rules aren't loaded, my test-user is not authorized to access the controller.
Declarative Authorization's built in test-helper without_access_control does work with rack_test, but not with js=true.
Any ideas? As this is "declarative" I can't add permissions on the fly (runtime). Or is it possible anyhow?
Thanks for any ideas!


text:
Q: can not call method from the main class? i am trying to make a web browser and here is my code
CODE:
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.applet.*;

public class browserPannel extends JFrame{

    public static void main(String[] arg)
    {
        JFrame browser = new JFrame("A Nun In A Weelchair");
        browser.setSize(1000,700);
        browser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        browser.setLocationRelativeTo(null);
        browser.pack();
        browser.setVisible(true);

        JPanel header = new JPanel();
        header.setBackground(Color.lightGray);
        header.setVisible(true);

        final JEditorPane htmlc = new JEditorPane();
        htmlc.setBackground(Color.red);
        htmlc.setEditable(true);
        htmlc.setContentType("text/html");
        htmlc.setVisible(true);

        final JTextField url = new JTextField(20);

        url.setSize(890,30);
        url.setVisible(true);

        url.addActionListener(
            new ActionListener()
            {
                public void actionPerformed(ActionEvent event)
                {
                    loadHtml(htmlc, url, event.getActionCommand());
                    System.out.println("action performed");
                }
            }
            );

        JButton send = new JButton("Send");
        send.setSize(75,30);
        send.setVisible(true);

        header.add(url, BorderLayout.SOUTH);
        header.add(send);
        browser.getContentPane().add(header, BorderLayout.NORTH);
        browser.getContentPane().add(new JScrollPane(htmlc));
    }

    private void loadHtml(JEditorPane htmlc, JTextField url, String link)
    {
        try{
            htmlc.setPage(link);
            url.setText(link);
        }catch(Exception e){
            System.out.println("ops sorry could not fined Virgine Mobile");
            e.printStackTrace();
        }
    }

}

and here is my error message:
browserPannel.java:38: error: non-static method loadHtml(JEditorPane,JTextField,
String) cannot be referenced from a static context
                                        loadHtml(htmlc, url, event.getActionComm
and());
                                        ^
1 error

as you can tell it is getting errors from the loadHtml which is defined in a method at the buttom of my code, now if i remove the loadHtml, then it displays the println("action Performed");, but only when i refer the loadHtml it says that it that the non static method can not be preformed in a static method.

A: Correct. You need an instance of your class browserPannel to invoke that method,
browserPannel bp = new browserPannel();
bp.loadHtml(htmlc, url, event.getActionCommand());

or you can make
private void loadHtml(JEditorPane htmlc, JTextField url, String link)

static, like
private static void loadHtml(JEditorPane htmlc, JTextField url, String link)

Edit
Also, Java camel case conventions would name your class BrowserPanel (and I suggest you follow that convention).

A: As you have called the "loadHtml" from main method you will have to do either of the below:-
1) use object of browserPannel class to call loadHtml or
2) you will need the loadHtml method to be static
remember the rule static and within the same class can be directly called from main method
cheers!


text:
Q: How to loop by specific step I have a nested loop data=
[[1,43,344,546],[2,34,45,565]....[10,1,1,1],

[1,15,111,151],[2,152,28,19]....[10,2,2,2],

[1,21,45,1647],[2,288,65,90]....[10,3,3,3]
                      .....]

so basically, all the inside lists can be grouped by 10lists with the first element always starting from 1 to 10. taking the every 10th list as a key, so I want to calculate a newlist by subtracting every list's number by the 10th list accordingly, for example
[[1,43-1,344-2,546-3],   [2,34-1,45-2,565-3]....   [10,1,2,3],

[1,15-21,111-22,151-23],[2,152-21,28-22,19-23]....[10,21,22,23],

[1,21-31,45-32,1647-33],[2,288-31,65-32,90-33]....[10,31,32,33]

.....]

My code seems don't work, can someone plz help with this? thanks
line = 0
    while line <= (len(data) - 10):
          for i in range(line, line + 10):
               temp = data[i]
               if temp[0] == 10: #find the every 10 th keys and store them to x, y, z
               x = temp[1]
               y = temp[2]
               z = temp[3]
               break

          for sublist in data:
             sublist[1] = sublist[1] - x# assign new elements to original list data
             sublist[2] = sublist[2] - y
             sublist[3] = sublist[3] - z
line += 10
return data

A: This is one way to do what you want
from pprint import pprint

def next_mul(n):
    "returns next multiple of 10 greater than n"
    return n + (10 - n % 10)

# sample data
data = [[i for i in range(4)] for i in range(20)]

for i in range(len(data)):
    if i % 10 == 0:
        continue
    data[i-1][1:] = [k-l for k,l in zip(data[next_mul(i)-1][1:], data[i-1][1:])]

pprint(data)

Output (originally every sublist of data was just [0, 1, 2, 3]):
[[0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 1, 2, 3],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 0, 0, 0],
 [0, 1, 2, 3]]

Hope this helps. Please let me know if there are any questions/concerns!


text:
Q: php - how to extract a particular word from url removing question mark HTTP://localhost/website/?search=hello+world

This is the URL and I just want to extract hello world from it
Right now i am using this code:
if(isset($_GET['q'])) {
   $url = $_GET['q'];
   $x = rtrim($url,'/');
   $x = explode('/',$url);
   print_r($x);
   echo($url);
}

But this does not show anything after the question mark. Is there anything wrong with this code or the .htaccess file.
I have also included the .htaccess file with code:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9-+/]+)$ index.php?q=$1
RewriteRule ^([a-zA-Z0-9-+/]+)/$ index.php?q=$1

A: Use php inbuilt function parse_url()
http://php.net/manual/en/function.parse-url.php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

results
Array
(
   [scheme] => http
   [host] => hostname
   [user] => username
   [pass] => password
   [path] => /path
   [query] => arg=value
   [fragment] => anchor
)

A: You can use parse_url and parse_str function:
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

A: I think parse_ur() is your friend!
$url = 'HTTP://localhost/website/?search=hello+world';
$parsed = parse_url($url);
echo $parsed['query'] ; // search=hello+world

A: Your htaccess rule is wrong..
It must be
RewriteEngine On
RewriteRule ^([a-zA-Z0-9-+/]+)$ index.php?search=$1
RewriteRule ^([a-zA-Z0-9-+/]+)/$ index.php?search=$1

and the code should be
if(isset($_GET['search'])) {
$url = $_GET['search'];
$x = rtrim($url,'/');
$x = explode('/',$url);
print_r($x);
echo($url);


text:
Q: Wait for AFNetworking operation for login I have an app that needs to use AFNetworking and I'm having an issue with the operations being asynchronous. I know there are a lot of similar questions here, but I have not found the answer to my issue yet.
The app calls a login method in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
That method looks like this:
- (void)loginWithUsername:(NSString *)username password:(NSString *)password {
    url = [NSURL URLWithString:@"Users/Login/" relativeToURL:baseURL];
    NSDictionary *parameters = @{UsernameParameter: username, PasswordParameter: password};
    [requestManager GET:url.absoluteString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        user = [[User alloc] initWithServerResponse:responseObject];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(error.description);
    }];
}

The response contains a couple of authorization tokens that are necessary for all other calls to the remote API. The problem is that the other operations are being executed before the login response is received and the success or failure blocks are executed. As a result, the app is crashing (or does nothing if I check for a nil user) when it tries to make another call to the API. What is the best way to ensure that the login response is received before proceeding?
Thank you.

A: do the another calling of remote api after user's login call  (in the block).
e.g.
NSDictionary *parameters = @{UsernameParameter: username, PasswordParameter: password};
[requestManager GET:url.absoluteString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    user = [[User alloc] initWithServerResponse:responseObject];
    ///insert another remote api here.

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(error.description);

   ///warnning for error.
}];


text:
Q: EventHandler to Reactive Extensions where event handler is transient lifestyle I need to bridge my messaging framework so that when an event occurs (TimeAggregate which contains a members called Reading and Stream) I can pass into Reactive Extensions and do fancy things:
public class TestHandler : ITopicNotificationHandler<TimeAggregate>
{
    public TestHandler(/* singleton variables are injected here */)
    {
    }

    public async Task Handle(TimeAggregate notification, string topic, CancellationToken cancellationToken)
    {
        // notification contains TimeAggregate.Reading (which is a decimal)
        // and TimeAggregate.Stream (which is a string, i.e. Office1, OfficeA etc)
        // I want to perform an average on TimeAggregate.Reading but split by TimeAggregate.Reading
    }
}

How would I go about linking the two (the event handler and Reactive Extension) and splitting so each Reading name is averaged independently (a dictionary of average observable of sorts) per TimeAggregate.Stream key?
Lifetime details
Also there is a technical aspect where each time the event handler (TestHandler) is called it is build from scratch, the lifetime of TestHandler is transient.
I can get around this by making a static registration manager (which the IoC injects into the TestHandler constructor, or we literally reference as static within).

A: One approach is to inject a service that has singleton lifetime that can be called in the event handler. It can use a Subject to generate an observable and expose / utilize an observable of running average messages:
public class MonitoringService : IMonitoringService
{
    private Subject<TimeAggregate> _subject;

    // Calculate tuples of (key, average)
    public IObservable<(string, decimal)> Averages => _subject
        // Group by key
        .GroupBy(s => s.Group)
        .SelectMany(g => g
            .Select(g => g.Reading)
            // Collect element count and running total
            .Scan((elements: 0, total: (decimal)0), (agg, v) => (agg.elements + 1, agg.total + v))
            // Calculate running average
            .Select(t => t.total / t.elements)
            // Associate key and average for SelectMany
            .Select(average => (g.Key, average)));

    public MonitoringService()
    {
        _subject = new Subject<TimeAggregate>();
    }
    public void PostNotification(TimeAggregate notification)
    {
        _subject.OnNext(notification);
    }
}

Which can then be used like this:
var monitoringService = new MonitoringService();
var handler = new TestHandler(monitoringService);

var dict = new Dictionary<string, decimal>();
monitoringService.Averages.Subscribe<(string group, decimal average)>(t =>
{
    // Do something with running average. In this case populate a dictionary
    dict[t.group] = t.average;
});

Note: if you want to start calculating averages before an observer is attached, you may want to look into Connectables (Publish etc.) and you would want to avoid using a get only generating property like this and instead assign it once in the constructor. But remember that this approach will only push updates to averages, so if a message isn't chatty the average message will be delayed.
e.g.
public class MonitoringService : IMonitoringService
{
    private Subject<TimeAggregate> _subject;

    // Calculate tuples of (key, average)
    public IObservable<(string, decimal)> Averages { get; }

    public MonitoringService()
    {
        _subject = new Subject<TimeAggregate>();
        Averages = _subject
        // Group by key
        .GroupBy(s => s.Group)
        .SelectMany(g => g
            .Select(g => g.Reading)
            // Collect element count and running total
            .Scan((elements: 0, total: (decimal)0), (agg, v) => (agg.elements + 1, agg.total + v))
            // Calculate running average
            .Select(t => t.total / t.elements)
            // Associate key and average for SelectMany
            .Select(average => (g.Key, average)))
        .Publish()
        // Connect immediately
        .AutoConnect(0);
    }
    public void PostNotification(TimeAggregate notification)
    {
        _subject.OnNext(notification);
    }
}

Full example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        public static async Task Main()
        {
            var monitoringService = new MonitoringService();
            var handler = new TestHandler(monitoringService);

            var dict = new Dictionary<string, decimal>();
            monitoringService.Averages.Subscribe<(string group, decimal average)>(t =>
            {
                // Do something with running average. In this case populate a dictionary
                dict[t.group] = t.average;
            });

            await handler.Handle(new TimeAggregate
            {
                Group = "Test1",
                Reading = 100
            }, "Test", CancellationToken.None);

            await handler.Handle(new TimeAggregate
            {
                Group = "Test1",
                Reading = 200
            }, "Test", CancellationToken.None);

            await handler.Handle(new TimeAggregate
            {
                Group = "Test2",
                Reading = 200
            }, "Test", CancellationToken.None);

            await handler.Handle(new TimeAggregate
            {
                Group = "Test2",
                Reading = 300
            }, "Test", CancellationToken.None);
        }
    }

    public class MonitoringService : IMonitoringService
    {
        private Subject<TimeAggregate> _subject;

        // Calculate tuples of (key, average)
        public IObservable<(string, decimal)> Averages => _subject
            // Group by key
            .GroupBy(s => s.Group)
            .SelectMany(g => g
                .Select(g => g.Reading)
                // Collect element count and running total
                .Scan((elements: 0, total: (decimal)0), (agg, v) => (agg.elements + 1, agg.total + v))
                // Calculate running average
                .Select(t => t.total / t.elements)
                // Associate key and average for SelectMany
                .Select(average => (g.Key, average)));

        public MonitoringService()
        {
            _subject = new Subject<TimeAggregate>();
        }
        public void PostNotification(TimeAggregate notification)
        {
            _subject.OnNext(notification);
        }
    }

    public class TestHandler : ITopicNotificationHandler<TimeAggregate>
    {
        private readonly IMonitoringService _monitoringService;

        public TestHandler(IMonitoringService monitoringService)
        {
            _monitoringService = monitoringService;
        }

        public Task Handle(TimeAggregate notification, string topic, CancellationToken cancellationToken)
        {
            _monitoringService.PostNotification(notification);
            return Task.CompletedTask;
        }
    }

    public interface IMonitoringService
    {
        void PostNotification(TimeAggregate notification);
        IObservable<(string group, decimal average)> Averages { get; }
    }

    public class TimeAggregate
    {
        public string Group { get; set; }
        public decimal Reading { get; set; }
    }

    public interface ITopicNotificationHandler<T>
    {
    }
}


text:
Q: Know what directives are allowed on apache server I'm trying to create a collabtive server.
For this, collabtive specify : Apache Web Server >= 2.0 compiled with mod_rewrite module and with the following directives allowed: DirectoryIndex, Deny, Allow, Options, Order, AddHandler, RewriteEngine, RewriteBase, RewriteCond and RewriteRule.
How can I know if these directives are allowed ? Do I need to change apache config to make it works ?
Thank you for you help

A: Apache functionality is organised into a series of modules.  Each module may be enabled (or disabled) in your Apache configuration files, to permit you to restrict and/or extend the capabilities you wish your server to have.  Some modules are enabled by default in a new Apache installation.
Modules can be enabled (in httpd.conf) with the LoadModule directive e.g. for mod_rewrite, the module is enabled with:
LoadModule rewrite_module modules/mod_rewrite.so

There is an index of all of the available directives for the current Apache release available here.  There is an index of all of the available modules for the current release available here.
For the specific directives you have asked about:

*

*RewriteEngine, RewriteBase, RewriteCond and RewriteRule are provided by mod_rewrite.  If you have that module enabled, then you will have those directives available.

*Deny, Allow and Order are access control directives that are deprecated for versions of Apache after v2.2.  For Apache v2.4+, you should use Require instead.  Examples of the new syntax are available here.  You will usually need to enable mod_authz_core and mod_authz_host to make common Require options available.

*AddHandler is provided by mod_mime.

*DirectoryIndex is provided by mod_dir.

*Options is part of Apache's core functionality and is always available.


text:
Q: How addr2line can locate the source file and the line of code? addr2line translates addresses into file names and line numbers. I am still beginner in debugging, and have some questions about addr2line.

*

*If am debugging a certain .so (binary) file, how the tool can locate
its source code file (from where can get it!), what if the source doesn't exist?

*What is the relation between the address in a binary and the line
number in its source, so addr2line can do this kind of mapping?

A: In general, addr2line works best on ELF executables or shared libraries with debug information. That debug information is emitted by the compiler when you pass -g (or -g2, etc...) to GCC. It notably provides a mapping between source code location (name of source file, line number, column number) and functions, variable names, call stack frame organization, etc etc... The debug information is today in DWARF format (and is also processed by the gdb debugger, the libbacktrace library, etc etc...). Notice that the debug information contains source file paths (not the source file itself).
In practice, you can (and often should) pass the -g (or -g2) debugging option to GCC even with optimization flags like -O2. In that case, the debug information is slightly less precise but still practically usable. In some cases, stack frames may disappear (inlined function calls, tail call optimizations, ....).
You could use the strip(1) utility to remove debug information (and other symbol tables, etc) from some ELF executable.


text:
Q: Interpolation of iterated logarithms $$\text{Let }\log^2(x)=\log(\log(x)),\\ \text{ then }f(y,x)=\log^{\lfloor1+y\rfloor}\left(\log(x)/\log((1-x^{1/x}(y-\lfloor y\rfloor))+(y-\lfloor y\rfloor))\right)$$
gives an interpolation between $\log^{\lfloor y\rfloor}(x)\text{ and }\log^{\lceil  y\rceil}(x).$
log[y_, x_] := N[NestList[Log,Log[x]/Log[(1-FractionalPart[y]) x^(1/x)+
FractionalPart[y] E], Floor[y + 1]][[Floor[y + 1]]]]

As mike4ty4 says in his answer here,

there isn't a unique way to interpolate the values of tetration at integer "height"

and presumably the same goes for logarithmic interpolation. Is there a generally accepted standard method for interpolating log functions? I looked at the answer to this question, but I am not any clearer on this particular issue.


text:
Q: number distribution with AWK the script is given a list of 100 values from 0 to 100, which distributes them by tens, displays the number of digits
10 number example:
4 2 22 1 2 2 3 33 84 84
cat numbets.txt|awk -f script.awk
0-9 : 5
10-19 : 0
20-29 : 1
30-39 : 1
40-49 : 0
50-59 : 0
60-69 : 0
70-79 : 0
80-89 : 2
90-99 : 0
100 : 0

How can I implement it with awk? Unfortunately, I've run out of ideas

A:
Unfortunately, I've run out of ideas

You might to get desired result using integer division and using array of counters, consider following example, let file.txt content be
4 2 22 1 2 2 3 33 84 84

then
awk 'BEGIN{RS="[[:space:]]"}{arr[int($1/10)]+=1}END{for(i=0;i<=10;i+=1){printf "%d0-%d9 : %d\n",i,i,arr[i]+0}}' file.txt

gives output
00-09 : 6
10-19 : 0
20-29 : 1
30-39 : 1
40-49 : 0
50-59 : 0
60-69 : 0
70-79 : 0
80-89 : 2
90-99 : 0
100-109 : 0

Explanation: I inform GNU AWK that row separator is one or more whitespaces, this way each number is treated as single row. For each row I compute result of integer division by zero int($1/10) and then increase value under that key in array arr. After all lines are processed I use for loop to iterate over 0 to 10 (inclusive) and use printf to output formatted text, which contain current value (twice) and corresponding value from array arr.
(tested in gawk 4.2.1)