text:
Q: WPF- How to place the Expander icon at the center of its header? Please take a look at the code below:
<Window x:Class="WpfTest.Test2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Test2" Height="300" Width="400">
    <Grid>
        <DockPanel LastChildFill="true">
            <Expander DockPanel.Dock="Left" Header="" Background="#E2FFD6"
                      HorizontalAlignment="Left" VerticalAlignment="Stretch"
                      ExpandDirection="Left" IsExpanded="True" Height="Auto">
                <StackPanel>
                    <Button Content=" open some tabs and show a messagebox "/>
                    <Button Content="do something else"/>
                </StackPanel>
            </Expander>
            <TabControl HorizontalAlignment="Stretch">
                <!-- some tabs here -->
            </TabControl>
        </DockPanel>
    </Grid>
</Window>

which results in this:

As you see in the picture, this doesn't look nice and I want to move the expander icon to the center of the header. How can I do this? I tried changing the HeaderTemplate, but it didn't affect the icon placement.

A: This behaviour is hard-coded in the Template. When we edit a copy:

Rightclick your element in the designer window (not in the Xaml-Code),
  then "Edit Template..." and "Edit a Copy..."

We find the relevant code in the ExpanderLeftHeaderStyle
<Style x:Key="ExpanderLeftHeaderStyle" TargetType="{x:Type ToggleButton}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ToggleButton}">
                <Border Padding="{TemplateBinding Padding}">
                    <Grid Background="Transparent" SnapsToDevicePixels="False">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="19"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Grid>
                            <Grid.LayoutTransform>
                                ...
                            </Grid.LayoutTransform>
                            <Ellipse x:Name="circle" Fill="{StaticResource Expander.Static.Circle.Fill}" HorizontalAlignment="Center" Height="19" Stroke="{StaticResource Expander.Static.Circle.Stroke}" VerticalAlignment="Center" Width="19"/>
                            <Path x:Name="arrow" Data="M 1,1.5 L 4.5,5 L 8,1.5" HorizontalAlignment="Center" SnapsToDevicePixels="false" Stroke="{StaticResource Expander.Static.Arrow.Stroke}" StrokeThickness="2" VerticalAlignment="Center"/>
                        </Grid>
                        <ContentPresenter HorizontalAlignment="Center" Margin="0,4,0,0" Grid.Row="1" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Top"/>
                    </Grid>
                </Border>
                <ControlTemplate.Triggers>
                    ...
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The RowDefinitions determine the location of the Icon (= the inner Grid), so we need to change them and the Row assignments for the inner Grid and ContentPresenter accordingly:
<Border Padding="{TemplateBinding Padding}">
    <Grid Background="Transparent" SnapsToDevicePixels="False">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="19"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="1">
            <Grid.LayoutTransform>
                ...
            </Grid.LayoutTransform>
            <Ellipse x:Name="circle" Fill="{StaticResource Expander.Static.Circle.Fill}" HorizontalAlignment="Center" Height="19" Stroke="{StaticResource Expander.Static.Circle.Stroke}" VerticalAlignment="Center" Width="19"/>
            <Path x:Name="arrow" Data="M 1,1.5 L 4.5,5 L 8,1.5" HorizontalAlignment="Center" SnapsToDevicePixels="false" Stroke="{StaticResource Expander.Static.Arrow.Stroke}" StrokeThickness="2" VerticalAlignment="Center"/>
        </Grid>
        <ContentPresenter Grid.Row="2" HorizontalAlignment="Center" Margin="0,4,0,0" RecognizesAccessKey="True" SnapsToDevicePixels="True" VerticalAlignment="Top"/>
    </Grid>
</Border>


text:
Q: Redemption RDOSearches not visible on Session.Stores.DefaultStore I have an Outlook Addin that perform really big scanning and often cause Outlook crash. I made a lot of searches and find out I should use Redemption instead.
I have download Redemption 5.17, I am trying to make a search folder in Outlook to start with. I follow the doc here
set Session = CreateObject("Redemption.RDOSession")
Session.Logon
set Searches = Session.Stores.DefaultStore.Searches
for each Search in Searches
    Debug.Print "-------------"
    Debug.Print Search.Name
    Debug.Print Search.SearchCriteria.AsSQL
next

I code this with VS2017 C#. I could not find the properties Searches on Session.Stores.DefaultStore
Anyone could help me on how to make a search folder that copy an existing
SearchCriteria from another search folder.

A: Firstly, in an addin there is no reason to use RDOSession.Logon - you already have an Outlook session: set RDOSession.MAPIOBJECT property to Application.Session.MAPIOBJECT from OOM.
Secondly, Searches property is exposed by the RDOStore2 interface (see http://www.dimastr.com/redemption/rdosearches.htm) - just cast your RDOStore object to RDOStore2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tensor product and injective maps during a class we met a map $\Phi : \mathbb{Z}^n\to \mathbb{Z}^n$. We saw that $\Phi\otimes 1_\mathbb{Q}$ was an isomorphism and then the Professor said that it implied that $\Phi$ was injective. Unfortunately, I am not sure about the reason for this and I wanted to ask you if you may help me to understand it. I have doubts because I was studying on my own commutative algebra and saw that I may have two modules $M'\subset M$, $N$ and an inclusion $i: M'\to M$, but $i\otimes 1: M'\otimes N\to M\otimes N$ may not be not injective ($M'=2\mathbb{Z}$, $M=\mathbb{Z}$, $N=\mathbb{Z}/2\mathbb{Z}$ and consider the element $2\otimes x=0 \in \mathbb{Z}\otimes \mathbb{Z}/2\mathbb{Z}$, $\neq 0 \in 2\mathbb{Z}\otimes \mathbb{Z}/2\mathbb{Z}$). So I understood that tensor product should be considered carefully in both direction: $\Phi\otimes 1_\mathbb{Q}$ injective => $\Phi$ injective; $\Phi$ injective => $\Phi\otimes 1_\mathbb{Q}$ injective. I was wondering whether there is an object that measure the problem in both direction. I thank you in advance if you may help with the first part of this question, the second or both. Thanks for the attention.

A: Hint: the fundamental fact here is that $\mathbb{Z}^n$ is free.
The canonical map $\def\Z{\mathbb{Z}}\def\Q{\mathbb{Q}}\Z\to\Q$ is injective and you can identify $\Q$ with $\Z\otimes\Q$. But the tensor product commutes with direct sums, so $\Z^n\to\Z^n\otimes\Q$ is injective too.
It's just a check seeing that the diagram
$$
\begin{array}{c}
\Z^n & \xrightarrow{\Phi} & \Z^n \\
\downarrow && \downarrow \\
\Z^n\otimes\Q & \xrightarrow{\Phi_{\Q}} & \Z^n\otimes\Q
\end{array}
$$
is commutative.
There are other cases in which tensoring by $\Q$ reflects monomophisms (it always preserves them because $\Q$ is torsion-free, hence flat), but at a first stage a direct proof using freeness of $\Z^n$ seems better.

A: Use the commutative diagram
$\begin{array}{c} \mathbb{Z}^n & \xrightarrow{\Phi} & \mathbb{Z}^m \\ \downarrow && \downarrow \\ \mathbb{Q}^n & \xrightarrow{\Phi_{\mathbb{Q}}} & \mathbb{Q}^m. \end{array}$
Since $\Phi_{\mathbb{Q}}$ is an injective and $\mathbb{Z}^n \to \mathbb{Q}^n$ is injective, it follows that $\Phi$ is injective.

A: Write down the short exact sequence
$$ 0 \to \ker \Phi \to \Bbb{Z} \to \Bbb{Z} \to \operatorname{coker} \Phi \to 0.$$
The functor $-\otimes_{\Bbb{Z}} \Bbb{Q}$ is exact since $\Bbb{Q}$ is a flat $\Bbb{Z}$-module. Thus if  the tensored map is injective this means that $(\ker \Phi) \otimes_{\Bbb{Z}} \Bbb{Q} = 0$. Now $\ker \Phi$ is a submodule of a free module over a PID and hence is finitely generated. This means $\ker \Phi = T \oplus F$, torsion part plus a free part of finite rank. The torsion part has to be zero as $\Bbb{Z}^n$ is torsion free. So $\ker \Phi \cong \Bbb{Z}^k$ for some $0 \leq k \leq n$. But now
$$0 = \ker \Phi \otimes_{\Bbb{Z}}\Bbb{Q} = (\Bbb{Z}^k) \otimes_{\Bbb{Z}} \Bbb{Q} = \Bbb{Q}^k  $$
which implies that $k= 0$, i.e. $\ker \Phi = 0$.


text:
Q: Running a while loop and retrieving row names from dataset on R What I'm trying to do right now is to get, from the mtcars dataset on R, the car names that are that have an hp column value of less than 200.  The thing is that I want the car names and I don't want to go back and rematch all the numbers with the corresponding car names.  How might I go about doing that?  Here's what I have so far:
> carvector<-mtcars["hp"]
> while (i<=32)
+ i<-i+1
if (mtcars[i,1]<200)
p<-mtcars[i,1]

Its not quite working and I guess I'm closer to storing the values than the names of the cars.  How can I make sure the names are not lost?  How do I dispose of the values I don't want?


text:
Q: Extracting epoch from two different days yields same result If I run this query on my database
SELECT EXTRACT('epoch' FROM age('2021-01-01'::date, '2019-12-01'::date))

The result is 34149600.
But then if I try with 2019-12-02 (one day more)
SELECT EXTRACT('epoch' FROM age('2021-01-01'::date, '2019-12-02'::date))

The result is exactly the same 34149600!
As if the seconds passed from 02 december 2019  to 01 january 2021 are the same as the seconds passed from 01 december 2019 to 01 january 2021.
Why is this? I've already tried the above code with timezones on 00:00:00+00 timezone for all dates (for 1st january 2021, 1st december 2019 and 2nd december 2021), and it gives the same result
Obviously, I would have expected the epoch to be different, around 3600*24 of difference (seconds in a day).

A: The similar results come from the age() function which returns an interval with years, months, days. In such an interval, 1 month = 30 days, so their conversions in seconds are similar.
You will get the expected result with
SELECT extract(epoch from  ('2021-01-01'::timestamp - '2019-12-01'::timestamp)) => 34300800.000000
SELECT extract(epoch from  ('2021-01-01'::timestamp - '2019-12-02'::timestamp)) => 34214400.000000


text:
Q: Menu Inflater doesn't render items outside menu xml I am trying to create menu according to https://guides.codepath.com/android/Using-the-App-Toolbar
Menu items are shown perfectly only in menu_main.xml. I cant see items in toolbar_main.xml or activity_main.xml... According to other solutions posted on stack, I didn't solve my problem. Everything is done according to these docs at codepath and should work.

What should be done to see menu in main activity, or this is normal behavior?

A: Turns out that's normal behavior. Strange not to see render in root coming from web :D


text:
Q: PHP - Checking if a timedate has past $from = time();
$to = strtotime($row['clock']);
if($to<$from){
    echo("Time has past.");
}

I am just trying to check if the time has past with a simple IF statement.
Currently the if statement is always true, no matter the datetime.
$row['clock'] = 2013-10-31 00:04:00

A: This works fine here. Make sure $row['clock'] contains what you think it does.
$from = time();
$to = strtotime('2013-11-01 00:00:00');
if($to<$from){
    echo("Time has past.");
}

echos nothing on my machine, while:
$from = time();
$to = strtotime('2013-10-01 00:00:00');
if($to<$from){
    echo("Time has past.");
}

echos "Time has past.".
Barring that, check that your server's time is correctly set.


text:
Q: Understanding lm Multiple R when fit is a horizontal line I have been using R and the lm function to do linear regression and report R2.
y  = c(1,2,3,4)
x  = c(1,2,3,4)
f  = lm(y~x)
r2 = summary(f)$r.squared

However, someone gave me this case-
y = c(1,1,1,1,1)
x = c(75,33,50,33,50)

Excel reports an intercept of 1, coefficient of 0 and Multiple R and r2 of 1.
R reports an intercept of 1, coefficient of 01e-17 and Multiple R-squared of 0.3392
Not being a statistician, I'm not understanding where lm() gets that number for Multiple R-squared from. Could someone help me out with an explanation?
If I change the data to
y = c(1,1,1,1,1)
x = c(1,1,1,1,1)

Excel still gives y = 1 + 0 * x  r2 = 1
whereas lm() reports the slope as NA and does not report a Multiple R-squared.
While this seems like a unique case, I'm still being told my program that calls lm() does not work because it fails these tests and Excel gives the 'expected' answer.
Thanks

A: I thought I would summarize the very helpful, but long series of comments related to my original question which I will restate as: what is the appropriate value of r2 when y does not vary, i.e., the y data can be exactly fit to the equation y = c?
a. Excel reports an r2 of 1. Which is what my users want, since the data is fit exactly.
b. The r2 value should reflect the fraction of variation accounted for by the model as compared with that accounted for by the null hypothesis, i.e., the mean. The equation is
R2 = 1 - SSR/SST

where SSR is the sum of the squared distances between the actual and model (predicted) values and SST is the sum of the squared distances between the actual and mean values.
When the data exactly fits a horizontal line, there is no deviation from the mean. So asking what proportion of the deviation is accounted for by the model is actually meaningless. From the equation, one is dividing 0 by 0.
The values reported by R are thus likely to be nothing more than round-off error in values that are effectively zero.
I should therefore check for this condition and not report an R2 rather than either report the number coming from R (lm) or report the value that Excel would give (1).


text:
Q: essential range of a function Suppose $\phi$ is an invertible function in $L^\infty(T)$ where $T$ is the unit circle such that the essential range of $\phi$, $R(\phi)$ is contained in the open right half-plane.  Show there exist an $\epsilon>0$ such that $\epsilon R(\phi)\subset \{z\in\mathbb{C}:|z-1|<1\}$.
This is part of a proof.  I cannot see why it is true.  I know $R(\phi)$ is compact and does not contain 0 as $\phi$ is invertible.
For this, we have $R(\phi)=\{\lambda\in\mathbb{C}:\mu(\{x\in X:|f(x)-\lambda|<\epsilon\})>0 \ \forall \epsilon>0\}$.  Here $\mu$ is the Lebesgue measure and $X$ is the unit circle.

A: The essential range is compact, and the sets of the form $\varepsilon^{-1}\{z\in\mathbb{C}\colon\lvert z-1\rvert<1\}$ with $\varepsilon>0$ is an open cover (of the open right half plane, and hence of $R(\phi)$). So $R(\phi)$ is contained in a finite union of these sets, and therefore in one of them since these sets are nested.


text:
Q: Removing String from Powershell variable I am trying to return simply the active username to use later in a script, however I am currently hung up on having my variable populate only the username, excluding the domain.
Function Get-Username() {
$username = Get-WMIObject -class Win32_ComputerSystem | select username

return $username
}

Function Delimit-Username() {
$newUserName = $username -replace 'DOMAIN\',''

Write-Host $newUserName
}

Get-Username
Delimit-Username

A: The domain is delimited from the user by a \, hence you can use the -split operator and access the second element to get the username without the domain.
('DOMAIN\User' -split '\\')[1]

You can also access the environment variable username ($env:username)

A: The USERNAME is also in the environment.
$Env:USERNAME


text:
Q: Construct a connectionString at runtime from the url for ASP.Net MVC Identity 2 I'm working on a multi-tenant web application using ASP.Net C# MVC 5. For reasons not relevant to this question, I want a separate database for each tenant, including the Identity 2.0 part. Also, I do not want to use the tenant name as hostname before my domain (i.e. http://tenant.myapp.com).
One obvious solution that's generally easy to implement is to have the tenant name in the MVC route configuration:
namespace MyApp
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{tenant}/{controller}/{action}/{id}",
                defaults: new { tenant = "Demo", controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

This works fine, but the approach seems to have one drawback. I was hoping to construct a connectionString at runtime, using the tenant from the RouteData.Values and passing that string to my ApplicationDbContext.
I suspect that, during initialization, the Identity framework is initialized as a singleton. From the template MVC code you get the following Startup partial.
public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        ...
    }
}

The remark states that a single instance is created "per request", but this code looks to be hit only once when the app initializes, not per request. What I was hoping to do, is do something like this, passing the tenant into the constructor of ApplicationDbContext.
public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        // Get the tenant from the routeData
        string tenant = "YourCompany"; // Switch to something different from the default set during route configuration, for testing purposes.
        if (HttpContext.Current.Request.RequestContext.RouteData.Values["tenant"] != null) tenant = HttpContext.Current.Request.RequestContext.RouteData.Values["tenant"].ToString();

        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(() => ApplicationDbContext.Create(tenant));
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        ...
    }
}

But, alas, the HttpContext.Current.Request.RequestContext has no RouteData.Values since we're initiliazing when the code hits and there is no request. This code always results in a connectionString with 'YourCompany' as tenant.

A: I have developed several years ago exactly the same scenario...
Startup & RouteConfig are executed normally in global.asax/Application_Start, only once per iis-site start.
Try to create and set your DbContext in global.asax/Application_BeginRequest.
And some other hint: perhaps you should have only one DbContext per HttpRequest, by holding it in HttpContext.Current.Items["dbcontext"] for use in child actions or similiar.
Let me know if you succeed or need more hints
Frank


text:
Q: OR in Expectation How can I do an OR operation when specifying my expectations ? The arguments can either be 10 or 11.
public void testGetRandom() {
    context.checking(new Expectations() {{
        oneOf (myrandom).isSpecific(10)  **OR** oneOf (myrandom).isSpecific(11);
    }});

    context.assertIsSatisfied();
}

A: you want to use argument matches - last one
example (untested):
oneOf (myrandom).isSpecific(with(anyOf(10,11)));


text:
Q: Maximum of IO(Int) list I have the following sample code
let x = [return 1::IO(Int), return 2::IO(Int)]

So x is a list of IO(Int)s.
maximum is a function which returns the maximum of a list, if the things in the list are Ords.
How do I "map" maximum to run on this list of IO(Int)s?

A: The key point here is that you cannot compare IO actions, only the values
that result from those actions. To perform the comparison, you have to perform
those actions to get back a list of the results. Fortunately, there is
a function that does just that: sequence :: (Monad m) => [m a] -> m [a].
This takes a list of actions and performs them in order to produce an action
that gives a list of results.
To compute the maximum, you would do something like
x = [return 1::IO(Int), return 2::IO(Int)]
...
biggest = maximum `fmap` sequence x :: IO [Int]

A: First sequence the array into IO [Int] and then run maximum on it using liftM:
liftM maximum (sequence yourList) :: IO Int


text:
Q: Inheriting child-specific method from parent I don't know if this is at all possible, but I was thinking of something in Java:
If I have an abstract parent class, I can do this:
public ParentClass add(ParentClass a, ParentClass b);

If ParentClass then has a child and I want to override this method, the child class will still have a ParentClass add(ParentClass, ParentClass) method.
Is there a way to make the parent function derive itself to each child?
I don't know if I'm wording it right, but something like this:
// ParentClass.java
public ParentClass add(ParentClass a, ParentClass b);

// Foo.java
@Override // or an equivalent
public Foo add(Foo a, Foo b) {}

// Bar.java
@Override
public Bar add(Bar a, Bar b) {}

Notice how each child doesn't have a ParentClass add(...) function, but rather one for each of their own types instead?
Obviously I can just make these myself, but I want to be able to create overridable ones in parents. I've never seen this in practice before, so I doubt its existence. I just want to clarify with someone with a higher Java knowledge than me. Thanks.
In theory, which I guess no language has ever done, something like this:
public child add(child a, child b);
// where *child* is the type of the child inheriting the method

A: In Java covariance of parameters of a method is not allowed.
This inherited method : public ParentClass add(ParentClass a, ParentClass b);
is legal for all children as it will allow to specify any subclass of ParentClass as parameters.
It is more flexible.
Now, if you don't want this flexibility and you want to force a specific type for parameters in the inherited method, you should use a generics abstract class.
public abstract class ParentClass <T extends ParentClass <?>>{
    public abstract ParentClass<?> add(T a, T b);
}

And in child class you could write :
public class ChildClass extends ParentClass <ChildClass>{
    public ParentClass<?> add(ChildClass a, ChildClass b){
       ....
   }
}

A: Something like this could work with Generics:
public abstract class ParentClass<T extends ParentClass> {
    public abstract T add(T a, T b);
}

class Foo extends ParentClass<Foo> {
    @Override
    public Foo add(Foo a, Foo b) {
        return null;
    }
}

class Bar extends ParentClass<Bar> {
    @Override
    public Bar add(Bar a, Bar b) {
        return null;
    }
}


text:
Q: How to I show the featured image in paragraph two or three? This code helps me place the featured image after paragraph one. How would I use it to place the same image in another paragraph, say paragraph two or three?
// Adds $img content after after first paragraph (!.e. after first `</p>` tag)
add_filter('the_content', function($content)
    {
       $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
       $img = '';
       $content = preg_replace('#(
.*?
)#','$1' .$img, $content, 1);
       return $content;
    });


text:
Q: ATI HD5700 with HDMI, DVA and VGA & 3 displays I have a ATI HD5700 graphics card with HDMI (could be DisplayPort too?), DVI and VGA outputs and I want to use three monitors. Currently I have one monitor working with HDMI and other one working with DVI but if I plug the third monitor to VGA, it does not work without first disabling one of the two other monitors in the ATI Catalyst Center.
How can I get the three monitors working together?

A: You cannot use three monitors at the same time with that card (and every other card I know of with an HDMI port).  The HDMI port uses the same circuitry as one of the DVI ports.  Two monitors at once is the most you can do with that card, one DVI connection and one HDMI connection or two DVI connections.

A: acctually you can you can have 2 through DVI and another throught Display Port i have a 5700 and thats what im running now with no problems

A: Your computer has a internal Intel video card. This Is what you are saying along the ATI radeon 5700 let me guess two DVI one HDMI no vga on that card but it is on your computer  along your audio outputs and usb Esata ports that's called sli two video card's.
But they will not work together that's because you don't have windows 7 or it is disabled and in the motherboard under the bios setting's, It is a time consuming process and step's. 3 monitor's will work. The operating system has to understand as well as the bios together.
So press f12 for boot setting's if you want to install windows 7. I don't care if it's downloaded from p2p sites. Drivers has to be installed use windows update manually download them or www.Intel.com or www.AMD.com this may very to depending on your computer's hardware I recommend windows update for drivers.
But first there should be options under f2 in your bios, Make sure before your drivers are installed it is disabled the dual video or sli it will names every bios work's different and can be updated use the ATI only during installation.
Use windows update to find drivers than restart press f2 than search around under advanced or display for enabled and disabled features enable it's auto or disabled auto mean sli can work use auto or enable press f10 save configuration  and restart install the Intel driver restart i take it still not working right 2 last steps restart press f2 disable press f10 save configuration and restart press f2 auto or enable what ever you see will work save configuration and restart boot type your pass word or log in basically right any where on your desktop click screen resolution all 3 should be there.
If it worked good it's tricky but what just did is trick the binary code to make it work. But sorry the ati does not have vga it has dvi to vga converter adapter you intel uses vga and should have a plastic cap with circle and a line this mean do not use but can be used it's called sli. ati it's self can not run but two monitors enabling sli is a hassle

A: In Ubuntu it works perfectly.
I have the same HD 5700 and the same problem in Windows but after testing in Ubuntu all works perfectly. Use Ubuntu and if you need windows 7 just use VMWare to have it inside of Ubuntu.


text:
Q: What are the partial derivatives and Jacobian for this function? How do you calculate the partial derivatives/Jacobian for a function of this sort using chain rule?
$$z=z(x,y)=f(3xy,\sin (xy))$$ where $f$ is a differentiable function from $\mathbb R^2$ to $\mathbb R$.


text:
Q: Profiling Python via C-api (How to ? ) I have used the Python's C-API to call some Python code in my c code and now I want to profile my python code for bottlenecks. I came across the PyEval_SetProfile API and am not sure how to use it. Do I need to write my own profiling function?
I will be very thankful if you can provide an example or point me to an example.

A: If you only need to know the amount of time spent in the Python code, and not (for example), where in the Python code the most time is spent, then the Python profiling tools are not what you want.  I would write some simple C code that sampled the time before and after the Python interpreter invocation, and use that.  Or, C-level profiling tools to measure the Python interpreter as a C function call.
If you need to profile within the Python code, I wouldn't recommend writing your own profile function.  All it does is provide you with raw data, you'd still have to aggregate and analyze it.  Instead, write a Python wrapper around your Python code that invokes the cProfile module to capture data that you can then examine.


text:
Q: Log4j - File is created every time I run my program, but I only want it to create a file when the log level is Errror and up upon experimenting with Log4j, I have two Appenders that I want to do different things with.
I have one that is supposed to log ERROR Levels and up to a file and another that is supposed to log everything no matter the level to the console.
The console Appender seems to work, but the error Appender continues to create a new file every time I start my program even if I am not logging any errors. I have tried setting Threshold to ERROR in the error Appender, but the file is still created every run of the program just with nothing in it.
My problem: I would like the Error Appender to not create a new file until an error is logged. Right now, a new error file is being created even if no error messages has been logged.
I am using log4j version 1.2.17 if that makes a difference.
Here is my code. Help is much appreciated!
Java:
public final class Sandbox {

    private static final Logger logger = Logger.getLogger(Sandbox.class);
    private static Sandbox instance;

    public Sandbox() {
        Thread.setDefaultUncaughtExceptionHandler(new ErrorFileLogger());
        instance = this;
        System.setProperty("file.date.format", Util.getDate("yyyy-MM-dd_HH-mm-ss"));
        DOMConfigurator.configure("log4j.xml");
//      PropertyConfigurator.configure("log4j.properties");
        logger.info("Creating " + Info.NAME + " " + Info.VERSION + " by " + Info.AUTHOR);
    }
}

public class ErrorFileLogger implements Thread.UncaughtExceptionHandler {

    private static Logger logger;
    private static final String s = System.lineSeparator();

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        logError(this.getClass(), t, e);
    }

    /**
     * Should be called when an uncaught exception is thrown or a caught exception is thrown.
     * @param c: The class where the error is coming from.
     * @param t: The thread the error occurred on.
     * @param e: The throwable, or actual error itself.
     */
    public static void logError(Class<?> c, Thread t, Throwable e) {
        logger = Logger.getLogger(c);
        logger.error(s + "---------- Sandbox Error Report ----------" + s + s + Util.getDate("dd/MM/yyyy HH:mm:ss")
                + s + s +"Uh oh, I'm going down. Save your self!" + s + s
                + "Details about the crash is listed below" + s
                + "---------------------------------------" + s + s +
                t.getName(), e);
    }
}

xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <!-- Error -->
    <appender name="ErrorFile"
         class="org.apache.log4j.RollingFileAppender">
        <param name="Threshold" value="error"/>
        <param name="file" value="./logs/error_report_${file.date.format}.log" />
        <param name="Append" value="false" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{HH:mm:ss}] [%p] [%c{1}]: %m%n" />
        </layout>
        <filter class="org.apache.log4j.varia.LevelMatchFilter">
            <param name="LevelToMatch" value="error"/>
            <param name="AcceptOnMatch" value="true"/>
        </filter>
        <filter class="org.apache.log4j.varia.DenyAllFilter"/>
    </appender>

    <!-- Console -->
    <appender name="Console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%p] [%c{1}]: %m%n" />
        </layout>

    </appender>

    <root>
        <appender-ref ref="ErrorFile"/>
        <appender-ref ref="Console"/>
    </root>

    </log4j:configuration>

Also, if anyone could explain what the root is and its importance that would be great!
Thanks so much,
Andy608

A: creating new error log file is a normal behavior.You have to add RollingPolicy into the log configuration.You can configure time frequency(create new log file for every hour) or log file size basis (create new one after exceeding 100MB).
Please check sample config xml from github


text:
Q: IBM Rational Business Developer for EGL programs, issue with generation output directory My organization uses IBM Rational Business Developer (RBD) to write EGL program for an IBM mainframe system.  The Network folder where out output generation directory is located for the program generations has been moved.  The issue is where within RBD or external to the product do you specify the folder where the output generation directory is located.  We are unable to locate this and it should be easy to change once we know where it is located.  Anyone familiar with this?

A: It is specified in the build options inside the build descriptor file(*.eglbld). The option name is something like genProject or genLocation


text:
Q: What is a clean way to represent a bind in a uml diagram? I would like to represent the following code using a UML diagram:
#include <iostream>
#include <boost/bind.hpp>

using namespace std;

class A {
 public:
  void bar() {std::cout << "A::bar()" << std::endl;}
};

// FUNC should be callable with arguments (int, A*)
template <typename FUNC>
class B {
 public:
  B(FUNC func, int data) : func_(func), data_(data){}
  void operator()(A* ap){func_(data_, ap);}
  FUNC func_;
  int data_;
};

// object generator uses argument deduction to construct B
template <typename FUNC>
B<FUNC> makeB(FUNC func, int data) {
  return B<FUNC>(func, data);
}

struct F {
  static void apply(int a, int b, A* ap){
    std::cout << "a+b = " << a + b << std::endl;
    ap->bar();
  }
};

int main() {
  A* a = new A;
  auto b = makeB(boost::bind(F::apply, 10, _1, _2), 20);
  b(a);
}

Here is my first attempt. I think there is some room for improvement:

*

*Should I capture pointers to F and A in the bind attributes or represent them serparately? Currently I'm showing both. I think the syntax for the F::apply attribute is also wrong.

*What is the best way to write the signature template for the bind class?

*Is there a better way to use decltype in B's template parameter? currently it looks a bit clumsy.
The purpose is to communicate how bind works to people who may not be familiar with it and perhaps convey a little about how bind works internally. The diagram should be as simple as possible so any hacks that are intuitive and not misleading are okay, it doesn't have to conform precisely to the UML standard.
update: This version fixes the type of bind's internal function pointer.


text:
Q: передать контекст в шаблон без api есть views которая парсит данные и возвращает их в шаблон контекстом, как мне отдать на фронт эти данные используя reactjs для frontend, без api? возможно ли это?

A: В джанговском шаблоне написать что-то вроде
<script>
   window.yourData = {...}
</script>

И на стороне фронта с этой переменной уже можно будет работать, не важно реакт там будет или нет.
Только желательно обернуть ваш скрипт в специальный тег, чтобы шаблонизатор воспринимал содержимое буквально, без изменений. По аналогии с тегом literal в smarty.


text:
Q: Scrollorama code causing sections of wordpress admin not to work I've added some animation script to be used with the scrollorama plugin but it's causing parts of the wordpress admin not to function ie media button wont work, the error I get is TypeError: targetBlock is undefined in the scrollorama.js
$.scrollorama/scrollorama.animate()
 jquery.scrollorama.js:285
<anonymous>
 custom.js:100
m.Callbacks/j()
 load-scripts.php:2
m.Callbacks/k.fireWith()
 load-scripts.php:2
.ready()
 load-scripts.php:2
J()

and also this in my custom.js file:
var scrollorama = $.scrollorama({ blocks:'.scrollblock' });

   for(var i=1;i<7;i++){

                    var title = "#bubbles"+i;

                    switch(i){

                    case 1:
                    scrollorama.animate('.bubbles.a',{ duration: 2000, property:'top', start:1050, end:-windowh});
    break;

                    }

                }

Everything is working fine on the frontend but have just come across this issue, when I remove my custom.js file the admin works fine so I know it's this file that is the issue

A: solved the issue: I didn't properly enque my scripts in the functions.php
I had:
wp_enqueue_script( 'scrollorama', get_template_directory_uri() . '/js/jquery.scrollorama.js', array( 'jquery' ));

and it needed to be
add_action('wp_enqueue_scripts', 'load_javascript_files');
function load_javascript_files() {

wp_enqueue_script( 'scrollorama', get_template_directory_uri() . '/js/jquery.scrollorama.js', array( 'jquery' ));

}


text:
Q: Unchallengingly accept - easily or without dispute? [...] Unchallengingly, we accept that the rose is beautiful, though it must be said that roses in the wild can make some garden varieties look almost vulgar.(Cambridge English, Objective Proficiency)
What does 'unchallengingly' mean in this case? Do we easily accept that the rose is beautiful (since the adjective 'unchallenging' means easy), or rather do we not challenge this fact?
Thank you!

A: Something is unchallenged  when it is:

*

*accepted without asking questions or criticizing:
We can't allow her comments to go unchallenged.

Cambridge Dictionary

*

*The idea is that you passively accept the idea  that the rose is beautiful despite the fact  roses in the wild can be remarkably more beautiful.

A: Unchallengingly in the sentence meant undoubtingly or unquestionably. Without a doubt, we accept the rose is beautiful. Without questioning, we accept the rose is beautiful.


text:
Q: Many to Many initializing relationship as default in Def New In Rails 4.0 I have a many to many relationship of game, game_item (the look up table) and item. How do I initialize a default relationship to existing Items when creating a new Game?
game.rb:
class Game < ActiveRecord::Base
  has_many :game_items
  has_many :items, :through => :game_items
  accepts_nested_attributes_for :game_items
end

game_item.rb:
class GameItem < ActiveRecord::Base
  belongs_to :game
  belongs_to :item
  accepts_nested_attributes_for :item
end

item.rb:
class Item < ActiveRecord::Base
  has_many :game_items
  has_many :games, :through =>  :game_items
end

The items already exist in the database and do not need to be created but will need to be updated. When creating a new Game object I want to associate several Items with it.
games_controller.rb:
  # GET /games/new
  def new
    @game = Game.new
    @game.items = Item.all(:order => 'RANDOM()', :limit => 3)
  end

This seems to work as I view them in the games/new.html.erb with this code:
<p>
  <% @game.items.each do |item| %>
      <%= item.name %>
  <%end %>
</p>

The problem is when saving the game, via the GameController#create method, the relationship does not save into the look up table game_items.
 # POST /games
  # POST /games.json
  def create
    @game = Game.new(game_params)

    respond_to do |format|
      if @game.save
        format.html { redirect_to @game, notice: 'Game was successfully created.' }
        format.json { render action: 'show', status: :created, location: @game }
      else
        format.html { render action: 'new' }
        format.json { render json: @game.errors, status: :unprocessable_entity }
      end
    end
  end

I believe it is the strong parameters which are not allowing the relationship to be saved although
  # Never trust parameters from the scary internet, only allow the white list through.
    def game_params
      #params.require(:game).permit( :correct, :incorrect,  :timed_out,  item_attributes: [:id, :name])[] )
      params.require(:game).permit( :correct, :incorrect,  :timed_out, :item_ids => [])

     end

I know that I can build the relationship again in the create with
  # POST /games
  # POST /games.json
  def create
    @game = Game.new(game_params)
    @game.items = Item.all(:order => 'RANDOM()', :limit => 3)
  ...

but since the items are random, I need to save the items that were presented to the user when they first initiated the game object with the new method.
How can I save the game_item relationship?
Edit:
Solution as suggested by @phoet. Use a hidden field to pass the array.
<% @game.items.each do |item| %>
    <%= f.hidden_field :item_ids, :multiple => true, :value => item.id %>
<% end %>

A: you use a hidden field with the name item_ids[] and assign the item array to it.


text:
Q: How can i convert entity relations from corenlp to ontology? I want to create an ontology for news dataset. My task is to convert entity relations from corenlp to ontology.
I have extracted relations using Stanford corenlp.
for k in range(0,50):
    text = df['event_summary'][k]
    print('sentence:'+text+ '\n')
    output = nlp.annotate(text, properties={"annotators":"tokenize,ssplit,pos,depparse,natlog,openie",
                            "outputFormat": "json",
                             "openie.triple.strict":"true",
                             "openie.max_entailments_per_clause":"1"})
    result = [output["sentences"][0]["openie"] for item in output]
    for i in result:
        for rel in i:
            relationSent=rel['subject'],rel['relation'],rel['object']
            print(relationSent )
            print('\n')
            df['Entity Relation'][k]= relationSent

My output looks like this:
sentence:U.S. fast-food restaurant chain Chick-fil-A warns that a security > breach may have leaked credit card details of 9

('security breach', 'leaked', 'credit card details of 9')

sentence:The Palestine Authority signs a treaty to join and participate in the International Criminal Court. (Wall Street Journal)

sentence:The Eurasian Economic Union between Russia

sentence:Vietnam's new marriage law goes into effect

('Vietnam', 'has', 'new marriage law')

Now I want to convert these relations to ontology.

A: One of the main questions you need to answer when building an ontology is "What inferences will you like from the ontology?". From the information you provided, I cannot answer that question. Hence the reason why it is not that easy to tell you how to build an ontology for the given sentences.
What seems more realistic to me is to place these sentences in an RDF triple store. Since RDF data is stored as <subject, predicate, object>, it matches the retrieved sentences very well. I.e., ('Vietnam', 'has', 'new marriage law') will become <Vietnam, has, new_marriage_law>. The advantage of doing this is that you can query the RDF data with SPARQL.


text:
Q: Replace the misspelled words I have a city column of 25000 rows with lot of misspelled cities in a data frame. The sample looks like below
Vishakapatnam, a.p
Vishakapatnam URBAN
Vishakapatnam Distt.
Vishakapatnam
Vishakapatnam
vghjfg"
vgfsgsvsw
Vellore
Vellore
VELLORE
VELLORE
New deklhi
New Dehli
new dehli
NEW DEHI
xxxx

zz
a
1234
5644
3

The data contains city with different spelling, numeric, spaces and some random alphabets. I want change the misspelled cities into one name and remove spaces, alphabets with no meaning and numeric. I am trying to do with grep as mentioned in some of the answers here but it is so tedious. Also, I tried with TM package but I could not achieve this. Could some one please share any method which we can do this more efficiently.


text:
Q: relativity of the timestamp to the time zone I wonder if, when you call something like that

time();

it returns the timestamp relatively to your time zone setting or to UTC ?
For example, when syncing two agents, that must be important to take care of it, doesn't it ?

A: In python e.g. time.time

[r]eturns the time as a floating point number expressed in seconds since the epoch, in UTC.

A: You are absolutely right that the time needs to be adjusted for users at different locations.

*

*First, you need to be able to know
what timezone each agent is in, which you cannot really guess, but ask the client to include the info in the request.

*Then, depending on the language you
are using, you can either call some
function with the timezone offset as
the parameter to get the adjusted time, or calculate the
time yourself by adding
60*60*1000*offset milliseconds to the
UTC time.


text:
Q: How to simplify my jquery IF statement on multiple options <select>
  <option value="2">option 1</option>
  <option value="5">option 2</option>
  <option value="6">option 3</option>
  <option value="9">option 4</option>
  <option value="20">option 5</option>
  <option value="21">option 6</option>
  <option value="22">option 7</option>
  <option value="80">option 8</option>
  <option value="91">option 9</option>
  <option value="145">option 10</option>
  <option value="66">option 11</option>
  <option value="70">option 12</option>
  <option value="99">option 13</option>
</select>

I have a long select list which longer than above, I wonder how to simplify my following jquery statement as the options I would like to target individually is pretty long and redundant.
      $('select option').each(function(){

        $option =  $(this).val();

        if (($option == 5 || $option == 9 || $option == 22 || $option = 80 .....)){
           $(this).addClass('myclass');
        };

     });

A: You can use $.inArray()
var ar = [5,9,22,80];
if(jQuery.inArray($option ,ar ) != -1){
    $(this).addClass('myclass');
};

You can also narrow down the selector and directly addClass using:
$("select option[value='" + ar.join("'],[value='") + "']").addClass("myclass");

Working Demo


text:
Q: How to define a Tensor with the symmetries like Riemann tensor? I want to define a tensor that has the first two symmetries of Riemann tensor or maybe the last two. The symmetries of Riemann tensor are:
1) $ R_{\alpha\beta\gamma\lambda}=R_{\gamma\lambda\alpha\beta}$ 2)$R_{\alpha\beta\gamma\lambda}=-R_{\alpha\beta\lambda\gamma}$ and $R_{\alpha\beta\gamma\lambda}=-R_{\alpha\beta\lambda\gamma}$ 3)$R_{\alpha \beta \gamma \lambda} +R_{\alpha\lambda\beta\gamma} + R_{\alpha\gamma\lambda \beta }=0$ Could you help me to learn to define a tensor with mixed symmetries?

A: The skew symmetries and the interchange symmetry can be implemented easily by specifying them as symmetry generators in SymmetrizedArray:
rt=SymmetrizedArray[pos_:>Subscript["R",Row[pos]],{4,4,4,4},{
   {{2,1,3,4},-1},(* Skew symmetry in first two slots *)
   {{1,2,4,3},-1},(* Skew symmetry in last two slots *)
   {{3,4,1,2},1}(* Interchange symmetry between first and last pair of slots*)
}]
SymmetrizedArrayRules[%]
Length[%]

returns

This seems to work fine: one can check the symmetries by looking at the components and the number of components is also correct: if I recall my General Relativity lectures correctly the Riemann tensor has 21 independent components in four dimensions (20 when including the first (algebraic) Bianchi identity $R_{\alpha \beta \gamma \lambda} +R_{\alpha\lambda\beta\gamma} + R_{\alpha\gamma\lambda \beta }=0$).
The first (algebraic) Bianchi identity can not be implemented easily in terms of symmetry generators but one could manually select a number of components ($\frac{1}{24} d (d-1) (d-2) (d-3)$ where $d$ is the dimension of the tensor (slots)) to be expressed in terms of two other components. Depending on your dimension $d$ this might make sense or not. In $d<3$ the identity gives no additional symmetry, in $d=4$ just one, and so it only looks profitable for larger $d$.


text:
Q: How to apply JQuery DataTables to Gridview for large data(>1000) in asp.net c#? I'm applying Jquery DataTables to gridview and it is working fine but for only less than 1000 rows and for large data, first gridview will load then Jquery Datatables will apply, during jquery datatables rendering page become unresponsive and looks ugly.
How I can apply Jquery datatables to Gridview which has large data.

            <asp:GridView runat="server" ID="gvDetails" AutoGenerateColumns="false" CssClass="table table-bordered  display compact">
                <HeaderStyle BackColor="#8b6f4e" ForeColor="White" />
                <Columns>
                    <asp:BoundField HeaderText="ID" DataField="ID" />
                    <asp:BoundField HeaderText="Name" DataField="Name" />
                    <asp:BoundField HeaderText="City" DataField="City" />
                    <asp:BoundField HeaderText="State" DataField="State" />
                    <asp:BoundField HeaderText="Country" DataField="Country" />
                    <asp:BoundField HeaderText="BankAc" DataField="BankAc" />
                    <asp:BoundField HeaderText="Aadhar" DataField="Aadhar" />
                    <asp:BoundField HeaderText="PhoneNo" DataField="PhoneNo" />
                    <asp:BoundField HeaderText="EmailID" DataField="EmailID" />
                </Columns>
            </asp:GridView>

I'm applying Jquery Datatable to gridvie like below
function bindDataTable() {
        table = $('#<%= gvDetails.ClientID%>').prepend($("

")
          .append($("#<%= gvDetails.ClientID%>").find("tr:first")))
     .DataTable({
            responsive: true,
            stateSave: true
        })
    }

is there any other way to apply?

Note: JQuery DataTables should render fast for large data without
waiting for Gridview to load first.

Please help if anybody already did this!!

A: How long is it taking for the GridView to load the data? It might be better to Ajax load it, or load it per page (called "server-side processing" in DataTables). Please see the FAQ.


text:
Q: Confusion about coordinates, frames & child nodes in SpriteKit on iOS? I'm still playing around with learning SpriteKit in iOS & have been doing lots of reading & lots of experimenting.  I'm confused by something else I've found* regarding coordinates, frames & child nodes.
Consider this snippet of code, in which I'm trying to draw a green box around my spaceship sprite for debugging purposes:
func addSpaceship()
{
    let spaceship = SKSpriteNode.init(imageNamed: "rocketship.png")
    spaceship.name = "spaceship"

    // VERSION 1
    spaceship.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))

    let debugFrame = SKShapeNode(rect: spaceship.frame)

    debugFrame.strokeColor = SKColor.greenColor()
    spaceship.addChild(debugFrame)

    // VERSION 2
   //       spaceship.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))

    spaceship.setScale(0.50)

    self.addChild(spaceship)
}

If I add the set the spaceship sprite with the line marked "VERSION 1" above, I get this:

which is clearly wrong.  But if I comment out the line marked "VERSION 1" above, and instead use the line marked "VERSION 2", I get what I want:

Notice that the actual code for the lines marked Version 1 & Version 2 is identical:
spaceship.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
So why does it matter when I set the position of the spaceship sprite?
To my way of thinking, the position of the spaceship sprite is irrelevant to the placement of the the debugFrame, because the debugFrame is a child of the spaceship sprite & thus, it's coordinates should be relative to the spaceship sprite's frame - right?
Thanks
WM
*This is somewhat related to a question I asked yesterday:
In SpriteKit on iOS, scaling a textured sprite produces an incorrect frame?
but a) I understand that one now, and b) this is a different enough that it deserves its own question.
UPDATE:
Hmmm - thanks, guys for the ideas below, but I still don't get it & maybe this will help.
I modified my code to print out the relavant positions & frames:
func addSpaceship()
{
    let spaceship = SKSpriteNode.init(imageNamed: "rocketship.png")
    spaceship.name = "spaceship"
    println("Spaceship0 Pos \(spaceship.position) Frame = \(spaceship.frame)")

    // VERSION 1 (WRONG)
    spaceship.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
    println("Spaceship1 Pos \(spaceship.position) Frame = \(spaceship.frame)")

    let debugFrame = SKShapeNode(rect: spaceship.frame)
    println("DEBUG Pos \(debugFrame.position) Frame = \(debugFrame.frame)")

    debugFrame.strokeColor = SKColor.greenColor()
    spaceship.addChild(debugFrame)

    // VERSION 2 (RIGHT)
//      spaceship.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
//      println("Spaceship2 Pos \(spaceship.position) Frame = \(spaceship.frame)")

    spaceship.setScale(0.50)

    self.addChild(spaceship)
}

Then, I ran it both ways got these results.  Since I understand Version 2, let's start there.
Running with the "VERSION 2 (RIGHT)" code, I got:
Spaceship0 Pos (0.0,0.0) Frame = (-159.0,-300.0,318.0,600.0)
DEBUG Pos (0.0,0.0) Frame = (-159.5,-300.5,319.0,601.0)
Spaceship2 Pos (384.0,512.0) Frame = (225.0,212.0,318.0,600.0)

The spaceship node starts, by default, with its position at the bottom left of the screen (Spaceship0). Its frame is also expressed in terms of its anchor point (center) being set in the bottom left of the screen, hence the negative numbers for the origin of its frame rect.
The debug frame is then created with its position set to 0, 0 by default & its frame set to be the same as the spaceship's.
The code (Spaceship2) then moves the spaceship node to a position in the view's coordinates (384.0,512.0), and its frame's origin is moved by adding the new position to the old origin (i.e. 384 + -159 = 225).
All is well.
Unfortunately, I still don't get Version 1.
When I run with the "VERSION 1 (WRONG)," code, I get
Spaceship0 Pos (0.0,0.0) Frame = (-159.0,-300.0,318.0,600.0)
Spaceship1 Pos (384.0,512.0) Frame = (225.0,212.0,318.0,600.0)
DEBUG Pos (0.0,0.0) Frame = (0.0,0.0,543.5,812.5)

As above, the spaceship node starts, by default, with its position at the bottom left of the screen (Spaceship0). Its frame is also expressed in terms of its anchor point (center) being set in the bottom left of the screen, hence the negative numbers for the origin of its frame rect.
The code (Spaceship1) then moves the spaceship node to a position in the view's coordinates (384.0,512.0), and its frame's origin is moved by adding the new position to the old origin (i.e. 384 + -159 = 225).
The debug frame is then created with its position set to 0, 0 by default & its frame set to have a strange width (543.5) & a strange height (812.5).   Since I'm initializing the debugFrame.frame with spaceship.frame (i think that's what the default initializer does), I would expect the new debugFrame.frame to be the same as the spaceship's frame - but it isn't! The debug frame width & height values apparently come from adding the actual width & height to the origin of the spaceship node frame (543.5 = 225 + 318.5).  But if that is the case, why is t's frame rect origin still 0, 0 & not the same adding (225.0 + 0 = 225.0)???
I don't get it.

A: You are creating the shape node using the sprite's frame, which is in scene coordinates. Because the shape will be a child of the sprite, you should create the node in the sprite's coordinates. For example, if you create the SKShapeNode with spaceship's size
let debugFrame = SKShapeNode(rectOfSize: spaceship.size)

instead of using the spaceship's frame, debugFrame will be centered on the spaceship regardless of when you set the ship's position. Also, debugFrame will scale/move appropriately with the ship.

A: In response to your 'I don't get it'.
Your code is ok but has a logical problem. The 'frame' is counted relative to the parent coordinates. Please realize that the parent of the spaceship and the parent of the debug window are different in your code.
Two ways to resolve your problem:

*

*Add a zero offset for the debug window and use the spaceship as the parent.
The advantage of this is that the debug window will move, scale with the spaceship:

let rectDebug = CGRectMake( 0, 0, spaceship.frame.size.width, spaceship.frame.size.height)
let debugFrame = SKShapeNode(rect:rectDebug)
spaceship.addChild(debugFrame)

*Add the debug window with the spaceship 'frame' coordinates to the parent of the spaceship (which is 'self'). The disadvantage of this, is that you have to move, scale the debug window yourself in the code, since it will not be attached to the spaceship.:

let debugFrame = SKShapeNode(rect:spaceship.frame)
self.addChild(debugFrame)

Both solutions are widely used. You should chose whichever is better for you in your case.
Three other problems might come up:
1.There might be code errors in my code, I just typed these into the web window directly without xcode syntax checking.
2.The anchor points of the two objects could be different. So you might need alignment in your code for this.
3.The zPosition of the objects should also be taken into consideration, so these objects will not be hidden under some other objects.
In response to the problem you are trying to solve, perhaps showPhysics would help:
    skView.showsFPS = YES;
    skView.showsNodeCount = YES;
    skView.showsPhysics = YES;

A: This is almost the same problem as in the other question you mentioned. frame is a property that contains a position and a size. Both of them are subject to scaling of their ancestor node. Read section "A Node Applies Many of Its Properties to Its Descendants" in https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Nodes/Nodes.html#//apple_ref/doc/uid/TP40013043-CH3-SW13
Again : never apply scaling to a node, never move a node before having fully constructed its hierarchy, except if you want some special or weird effect.


text:
Q: Twitter bootstrap a href popover not working I have the following html
pop

and the javascript code:
$(function () {
    $('#example').popover();
});

and I have included the below Js files:
src="jquery.min.js"
src="bootstrap.js"
src="Tooltip.js"
src="Popover.js"

but when I click the link nothing happens but it seems to be reloading the page.
FYI, this button popover code works fine but the a href popover is not working:
<button popover="Some text" popover-trigger="mouseenter" class="btn btn-default">Scope</button>

Any help would be appreciated.

A: Try this, not too sure what you're attempting but this is a working pop!
http://jsfiddle.net/AlexHighHigh/weuWk/1785/
HTML
pop

JS
$("#example").popover({ title: 'This is the body of pop'});


text:
Q: Subring of complex numbers field Let $R = \left\{ a + b \frac{1+ i \sqrt{3} }{2}: a,b \in \mathbb{Z} \right\}$ .

*

*Show that $R$ is subring of complex numbers field.

*Designate all invertible elements of ring $R$ .

In first I must show that for any $z_1,z_2 \in R$ : $z_1-z_2 \in R$, $z_1 \cdot z_2 \in R$ ?
I have no idea for 2. I will grateful for yours help.

A: Hint for 2): The usual way to do this is using the field norm, which is defined by
$$N:R\to R,\quad \alpha\mapsto \alpha\overline{\alpha}$$
where $\overline{\alpha}$ is the usual complex conjugate of $\alpha$ (since $R\subset\mathbb C$).

*

*Check, that $N$ is multiplicative, that is $N(\alpha\beta)=N(\alpha)N(\beta)$ for all $\alpha,\beta\in R$

*Simplify $\alpha\overline{\alpha}$ in terms of $a,b$ where $\alpha=a+b\frac{1+\sqrt-3}{2}$.

*Deduce from 2), that $N(\alpha)\in\mathbb N_0$ for all $\alpha\in R$.

*Use 1) and 3) to prove, that  $\alpha\in R$ is invertible, iff $N(\alpha)=1$.

*Use 2) and 5) to find all invertible elements.

Result for 2):

 $N\left(a+b\frac{1+\sqrt-3}{2}\right)=a^2+ab+b^2$

A: Let

$$\frac{1+ i \sqrt{3} }{2}=-\omega \implies \omega^2=-\omega $$

where $\omega$ is the root of the unity $x^3-1=0$. Now, let $z_1 = (a+b\omega),\,z_2=(c+d\omega)\in R$, then we have

$$ (a+b\omega)(c+d\omega)=ad\omega+bc\omega-bd\omega+ac= ac+\left( ad+bc-bd \right) \omega=g+h\omega \in R, $$

where $ g=ac, h= ad+bc-bd \in \mathbb{Z}$.


text:
Q: MVC3 Controller per Entiry or Controller per group of entities? May be a stoopid question:
I have a number of reference tables in an application database, which I want to be updated from my MVC3 site.
I can create a "ReferenceController" which has CRUD methods for each of these tables
or
I can create a "EntityController" which has CRUD methods JUST for this one reference table (entity).
Not sure if there is a sensible pattern to follow for this?

EDIT:
If I do create a controller per Aggregate, then how do you name the methods on the controller?
e.g.
ReferenceController.CreateBusiness();
MyApplication/Reference/CreateBusiness
?

I have multiple, totally unrelated "reference" entities, would that mean a controller with a very large number of methods in there?
e.g. List, Create, Read, Update, Delete + confirmations?
Can you make controller methods Generic and have Create(T ...) ?

A: I would do something like this:
A Generic Crud Repository like:
class CrudRepo<TEntity> where T : class{
  void All();
  void Add(TEntity entity);
  void Edit(TEntity entity);
  void Delete(TEntity entity);
}

Then A generic Crud Controller like
class CrudController<TEntity> where T : class{
    CrudRepository<TEntity> Repository;

    [HttpPost]
    ActionResult Add(TEntity entity){
      Repository.Add(entity);
    }

    // Similer for other actions
}

And for specific type of entities, just extend CrudController like:
class StudentController : CrudController<Student>

Edit 1:
If you have really TOOOO many entities, there are ways to eliminate the need of inheriting the CrudController for each entity. You may want to write your custom ControllerFactory for that.

A: You should have a repository per aggregate root. Same stands for controllers.

A: Two things come to mind:

*

*Use something like WEB API so you don't have to recreate boilerplate code for every entity.

*Only create CRUD-like controllers for top-level entities, i.e. what's the point of creating a controller for something that isn't changeable to any clients.


text:
Q: Do we have any asp vbs complete for vim? I see a lot of complete for gvim such as php, c , css, but I can't find any complete form aspvbs

A: Are you talking about auto completion? Do you know about ctags? (http://ctags.sourceforge.net/).
Anyway, here's an OK solution. Well actually i haven't tested it too much yet but it seems to work fairly well. Assuming you are using ctags, add
--langmap=Asp:*.vbs

to your ~/.ctags file and it will tell ctags to generate tags for your *.vbs files (as Asp, whatever that is =D). I'm don't know much about asp / vbs and their relationship (not sure i want to, hehe), so once again I'm telling you I don't know how well this works. Perhaps someone can fill in on this?
I guess even better... Add your own language (and share with me) : )
http://ctags.sourceforge.net/EXTENDING.html

A: I don't use Vim much, but 5 seconds of googling turned up this: http://www.vim.org/scripts/script.php?script_id=993 - is that what you're looking for, or something different?


text:
Q: Why Sympy.solve does not provide every solution to the equation? I have tried to solve 100n^2 -2^n = 0 by using sympy.solve(). Sympy.solve() found only two positive solutions while the equation (100n^2-2^n) has actually three solutions (one negative, two positives). I'm curious why sympy.solve() is unable to find every solution to the equation. Below is my code. Any insight please?
import sympy as sy

n = sy.Symbol('n')
sol = sy.solve(100 * (n ** 2) - (2 ** n), dict =True)
print(sol)

Result: [{n: -2*LambertW(-log(2)/20)/log(2)}, {n: -2*LambertW(-log(2)/20, -1)/log(2)}]


text:
Q: javascript + mocha: probably a closure issue with functions declared inside a for loop To learn javascript, I implement and test classic algorithms with it.
Here is my attempt at implementing binary search and tests for it:
var assert = require('assert')

function binsearch (xs, v) {
  if (xs === undefined || xs.length === 0) { return null }

  var lo = 0
  var hi = xs.length - 1

  while (lo <= hi) {
    var i = (lo + hi) / 2 | 0

    if (xs[i] === v) {
      return i
    } else if (v < xs[i]) {
      hi = i - 1
    } else if (v > xs[i]) {
      lo = i + 1
    }
  }

  return null
}

var check_bsearch = function (bsearch, xs, x, i) {
  it(bsearch.name + ' [' + xs + '] ' + x + ' ' + i, function () {
    assert.equal(bsearch(xs, x), i)
  })
}

describe('Test binsearch', function () {
  describe('on a sorted array', function() {
    var xs = []

    for (var i = 0; i < 2; ++i) {
      xs[i] = 2 * i

      for (var j = 0; j <= i; ++j) {
        check_bsearch(binsearch, xs, 2 * j, j)
        check_bsearch(binsearch, xs, 2 * j + 1, null)

        check_bsearch(binsearch, xs, -1, null)
        check_bsearch(binsearch, xs, -2, null)

        check_bsearch(binsearch, xs, 2 * i + 1, null)
        check_bsearch(binsearch, xs, 2 * i + 2, null)
      }
    }
  })
})

In order to reproduce what I am about to say, copy the code above into some bsearch.js file, install mocha.js with something like sudo npm install -g mocha and finally run the file: mocha bsearch.js
One test should be failing: the one with xs = [0], x = 2 and expected result of null. If you recreate this test separately though, it will pass.
I am suspecting that this is a closure issue. You might have noticed that I am already using a helper function check_bsearch to get the expected closure environment. However, I am clearly missing something. How do I fix the tests?

A: Arrays are passed by reference. What happens is that as you loop you modify the xs array you pass to your functions, and by the time the tests actually run, they all get the same value. You should copy the array so that each test gets a snapshot of its value at the time it was called. It can be as simple as:
var check_bsearch = function (bsearch, xs, x, i) {
    xs = xs.slice(); // Make a private copy of xs.


text:
Q: This stream does not support seek operations. HttpWebResponse I'm making a program which downloads files over http.
I've got it downloading, however I want to be able to pause the downloads, close the program and resume them again at a later date.
I know the location i'm downloading them from supports this.
I'm downloading the file through HttpWebResponse and reading the response into a Stream using GetResponseStream.
When i close the app and restart it, I'm stuck as to how resume the download. I've tried doing a seek on the stream but it states its not supported.
What would be the best way to do this?

A: If the server supports this you have to send the Range Http header with your request using the AddRange method:
request.AddRange(1024);

This will instruct the server to start sending the file after the 1st kilobyte. Then just read the response stream as normal.
To test if a server supports resuming you can send a HEAD request and test if it sends the Accept-Ranges: bytes header.

A: How about an HTTPRangeStream class?
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Ionic.Kewl
{
    public class HTTPRangeStream : Stream
    {
        private string url;
        private long length;
        private long position;
        private long totalBytesRead;
        private int totalReads;

        public HTTPRangeStream(string URL)
        {
            url = URL;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            HttpWebResponse result = (HttpWebResponse)request.GetResponse();
            length = result.ContentLength;
        }

        public long TotalBytesRead    { get { return totalBytesRead; } }
        public long TotalReads        { get { return totalReads; } }
        public override bool CanRead  { get { return true; } }
        public override bool CanSeek  { get { return true; } }
        public override bool CanWrite { get { return false; } }
        public override long Length   { get { return length; } }

        public override bool CanTimeout
        {
            get
            {
                return base.CanTimeout;
            }
        }

        public override long Position
        {
            get
            {
                return position;
            }
            set
            {
                if (value < 0) throw new ArgumentException();
                position = value;
            }
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            switch (origin)
            {
                case SeekOrigin.Begin:
                    position = offset;
                    break;
                case SeekOrigin.Current:
                    position += offset;
                    break;
                case SeekOrigin.End:
                    position = Length + offset;
                    break;
                default:
                    break;
            }
            return Position;
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.AddRange(Convert.ToInt32(position), Convert.ToInt32(position) + count);
            HttpWebResponse result = (HttpWebResponse)request.GetResponse();
            using (Stream stream = result.GetResponseStream())
            {
                stream.Read(buffer, offset, count);
                stream.Close();
            }
            totalBytesRead += count;
            totalReads++;
            Position += count;
            return count;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new NotSupportedException();
        }

        public override void SetLength(long value)
        {
            throw new NotSupportedException();
        }
        public override void Flush()
        {
            throw new NotSupportedException();
        }

    }
}

A: Your solution is fine, but it will only work for the cases where the server sends a Content-Length header. This header will not be present in dynamically generated content.
Also, this solution is send a request for each Read. If the content changes on the server between the requests, then you will get inconsistent results.
I would improve upon this, by storing the data locally - either on  disk or in memory. Then, you can seek into it all you want. There wont be any problem of inconsistency, and  you need only one HttpWebRequest to download it.


text:
Q: systemd intrinsic dhcp server gives leases on old subnet when local IP changes Test Host/desktop: Linux dystantest 4.2.0-42-generic #49~14.04.1-Ubuntu SMP Wed Jun 29 20:22:11 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
RNDIS Device/Gadget: Linux colibri-imx6 3.14.52-v2.6b2+g7c83cef #1 SMP Wed Jun 29 15:57:37 CEST 2016 armv7l GNU/Linux
Let's say I have a system of multiple embedded boxes with 6 identical RNDIS usb gadget devices in each.
The default /etc/systemd/network/rndis.network file looks like this:

[Match]
Type=gadget
[Network]
Address=192.168.11.1/24
DHCPServer=yes

So, we're basically just turning on the dhcpd and hardcoding the boot address to 11.1. I can't find a dhcpd process anywhere, and my vendor tells me it's an intrinsic part of systemd - no /etc/dhcpd.conf, no other config files I can find except the ones that belong to systemd.
The main problem is, I can't have N x 6 devices all hardcoded to 11.1. So my embedded app on these devices changes the IP to something like 192.168."serialnum"."channelnum".
So far, so good. Only problem is that if I release/renew on my ubuntu system, it still always gets an IP of 192.168.11.X, not 192.168."serialnum".X
So, clearly the intrinsic dhcpd is still picking up the subnet from the initial configuration file, not from the actual IP of the interface used at whatever time a new lease is requested from a client.
I can't find any docs anywhere on changing this. I know regular servers are supposed to keep their IP from bootup, but this is an embedded device, so it has to behave differently and have a "semi"-dynamic IP on the dhcp server system. The [DHCPServer] section of the systemd docs does not specify anything that would make it dynamic, nor any dhcpd.service file which would alow me to restart the dhcp server, in order to make it use the new subnet.
I could put the dhcp server on the ubuntu machine instead of the embedded gadget machine, but that's going to create a support ~nightmare~ for my win32 customers, so that's a non-starter.
I could pay one of our techs to manually set up the IP in the rndis.network file on every single channel of every system we make, but that also seems silly when I have a server all set here if I can just make it follow whatever the current subnet is when giving out new leases.


text:
Q: Where are Google chrome passwords stored in windows? I know that Google Chrome stores the login data at LocalAppData\Google\Chrome\User Data\Default\Login Data but this doesn't shows the password, password value shows as the single special character.
I want to read the password value from the database.
I want to make an utility which can store the users sign on data in a backup file for user.

A: Chrome passwords are stored in sqllite database but passwords are encrypted using  CryptProtectData, which is a Windows API function for encrypting data. Data encrypted with this function is pretty solid. It can only be decrypted on the same machine and by the same user that encrypted it in the first place.
If you want to decrypt password you must do it using same machine which encryption done.
There is a app called ChromePasswordDump, which can decrypt passwords using that application, that can be easily Googled.

A: Thank you very much to all of you, I got the ans. one can decrypt the chrome passwords by using windows API CryptUnprotectData.


text:
Q: Switch to SSL using a relative URL I would like to create a relative link that switches the current protocol from http to https. The last place I worked had something set up on the server so that you could make that happen, but I don't remember much about it and I never knew how it worked.
The rationale for this is that I wouldn't need to hardcode server names in files that need to move in between production and development environments.
Is there a way for this to work in IIS 6.0?

Edit:
I am using .NET, but the "link" I'm creating will not be dynamically generated. If you really want the nitty gritty details, I am using a redirect macro in Umbraco that requires a URL to be passed in.

A: Here's a simple solution in VB.NET:
Imports System.Web.HttpContext

Public Shared Sub SetSSL(Optional ByVal bEnable As Boolean = False)
  If bEnable Then
    If Not Current.Request.IsSecureConnection Then
      Dim strHTTPS As String = "https://www.mysite.com"
      Current.Response.Clear()
      Current.Response.Status = "301 Moved Permanently"
      Current.Response.AddHeader("Location", strHTTPS & Current.Request.RawUrl)
      Current.Response.End()
    End If
  Else
    If Current.Request.IsSecureConnection Then
      Dim strHTTP As String = "http://www.mysite.com"
      Current.Response.Clear()
      Current.Response.Status = "301 Moved Permanently"
      Current.Response.AddHeader("Location", strHTTP & Current.Request.RawUrl)
      Current.Response.End()
    End If
  End If
End Sub

Usage:
'Enable SSL
SetSSL(True)

'Disable SSL
SetSSL(False)

You could add this to the Page_Load of each of your pages.  Or you could do something like I did and create a list of folders or pages that you want secured in your global.asax and set the SSL accordingly in the Application_BeginRequest method.  And this will work with relative links and the HTTP or HTTPS status of a page will always be what you tell it to be in the code.
I have this code in place on several websites.  But as an example, if you go to https://www.techinsurance.com you'll notice it automatically redirects to http because the home page doesn't need to be secured.  And the reverse will happen if you try to hit a page that needs to be secured such as http://www.techinsurance.com/quote/login.aspx
You may notice that I'm using 301 (permanent) redirects.  The side benefit here is that search engines will update their index based on a 301 redirect code.

A: Which language/framework are you using?
You should be able to create your own function in which you pass in the relative page and you deduce from the HttpRequest object and the Server object (again depending on the language or framework) what the host and URL are and then just simply redirect to that URL but with https as a prefix.

A: Here is a good CodeProject article on doing this by specifying certain directories and files that you want to use SSL. It will automatically switch these to and from https based on your needs.
I've use this for a project, and it works really well.

A: This is the same answer I gave here:
Yes you can. I recommend this free open source DLL that lets you designate which pages and folders need SSL and which don't:
http://www.codeproject.com/KB/web-security/WebPageSecurity_v2.aspx
So you can setup a page to be secure in your web.config like this:
<secureWebPages encryptedUri="www.example.com" unencryptedUri="www.example.com" mode="RemoteOnly" >
    <files>
      <add path="/MustBeSecure.aspx" secure="Secure" />
    </files>
</secureWebPages>

A: We ended up buying ISAPI Rewrite to perform redirects at the web server level for certain URLs. That's not quite the answer I was looking for when I asked the question, but it's what works for us.


text:
Q: PHP Closing Tag: =?> I've just seen this comment on php.net, which contains the following snippet of code:
</head>
<?= ob_flush(); =?>
<body>

I've not seen the =?> used before (I'm fine with the <?=, that's obvious) and when I put it in a test file it gave a syntax error. So, is this just a typo, or is there any situation where this is syntactically valid?

A: Typo.
There is a lot of junk in php.net comments.
As of recently, it's now possible to vote on comments on php.net.

A: I'm pretty sure that's one of the thousands of php.net's comments typos.


text:
Q: Cannot get injection to work in Azure Function when a service has other dependencies I have a service CompanyService
This service is dependent on 2 other services - ICompanyRepository and IDataCacheService
public class CompanyService : ICompanyService
{
    private readonly ICompanyRepository _companyRepository;
    private IDataCacheService _dataCacheService;

    public CompanyService(ICompanyRepository companyRepository, IDataCacheService dataCacheService)
    {
        _companyRepository = companyRepository;
        _dataCacheService = dataCacheService;
    }
}

This services themselves have no dependencies
Now I need to make this available via the built in injection within my Azure Function
so in Startup.cs, I modified Configure to add the new services
public override void Configure(IFunctionsHostBuilder builder)
{
    var cosmosDbConnectionString = new CosmosDBConnectionString(Environment.GetEnvironmentVariable("CosmosDBConnection"));
    builder.Services.AddSingleton<IDocumentClient>(s =>
       new DocumentClient(cosmosDbConnectionString.ServiceEndpoint, cosmosDbConnectionString.AuthKey));

    var companyRepository = new CompanyRepository();
    builder.Services.AddSingleton<ICompanyRepository>(companyRepository);

    var dataCacheService = new DataCacheService();
    builder.Services.AddSingleton<IDataCacheService>(dataCacheService);

    var companyService = new CompanyService(companyRepository, dataCacheService);

    builder.Services.AddSingleton<ICompanyService>(companyService);
}

This compiles and runs through fine
However, when I add ICompanyService as a parameter of my function I get the error

Cannot bind parameter 'companyService' to type ICompanyService

My method is below
public class Companies
{
    private const string OperationName = "OPERATION";

    [FunctionName(OperationName)]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "myroute/")]HttpRequest req,
        ICompanyService companyService,
        ILogger log)
    {
       //logic here
    }
}

This is the same way as other function run methods within my project
What have I done wrong?
This also doesn't work with the standard AddSingleton syntax
builder.Services.AddSingleton<ICompanyService, CompanyService>();

Paul

A: Given the shown configuration, the registration can be simplified to
public override void Configure(IFunctionsHostBuilder builder) {
    var services = builder.Services;
    var cosmosDbConnectionString = new CosmosDBConnectionString(Environment.GetEnvironmentVariable("CosmosDBConnection"));
    services.AddSingleton<IDocumentClient>(s =>
       new DocumentClient(cosmosDbConnectionString.ServiceEndpoint, cosmosDbConnectionString.AuthKey));

    services.AddSingleton<ICompanyRepository, CompanyRepository>();
    services.AddSingleton<IDataCacheService, DataCacheService>();
    services.AddSingleton<ICompanyService, CompanyService>();
}

All that is left is to make sure to explicitly inject the required service into the function instance via constructor injection.
public class Companies {
    private const string OperationName = "OPERATION";
    private readonly ICompanyService companyService;

    public Companies(ICompanyService companyService) {
        this.companyService = companyService;
    }

    [FunctionName(OperationName)]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "myroute/")]HttpRequest req,
        ILogger log) {
       //logic here
    }
}

Reference Use dependency injection in .NET Azure Functions


text:
Q: Show div on Submit button This question might have been asked many times, I have been having difficulty in applying approach which are given on different websites.
I have a JSP page which contains a search field
 ---------------------
|                     |   Type a Character to Search from the Database
|                     |
 ---------------------

             =============
            |   Submit    |
             =============

When the user types in a character and clicks on the Submit button, I am calling a different JSP "xyz.jsp" like

    <%@include file="searchResult.jsp"%>

My requirement is When the page gets loaded, it should display only the search text box and a submit button. When he/she click on the submit button, the div which is including another jsp should get called and displayed.
Note
I need to retain the value entered by the user in the search text field on the click on submit button.
Code for search page

    <aui:form action="......" method="post" name="searchForm" id="searchFormId">

        <aui:input id='name' name="name" label="Student Name" type="text"       value=""   size="50"/>

    </aui:form>

A: You can do something like this

A: it doesn't matter if its in jsp or php or asp. the method is the same. you should use java script. when the page initially loads you should already have the div just hidden. when the user clicks the submit button. load the result into the div and change the display to true. I hope this helps.


text:
Q: Remember-me not working in Spring MVC in spring-security, how can I check why cookie is not getting created I created remember-me in spring-security and also button in front end, but cookie is not getting created.
my spring security.xml
<logout success-handler-ref="logoutSuccessHandler" />
<remember-me key="_spring_security_remember_me"
user-service-ref="userDetailsService" />


text:
Q: Multiple Segues to the same destination I have a series of view controllers. One called home, followed by 10 others theat you navigate through in sequence, ie; home -> 1 -> 2 -> 3 and so on.
All view controllers have a 'home' button which takes you back to the first 'home' view controller. Is there an efficient way of doing this rather than create a 10 separate segues from each VC back to 'home' VC?
Keep in mind that I want memory usage to be as efficient as possible without creating an instance of the same view controller again and again as I navigate back and forth.
Any help is greatly appreciated.

A: Thanks to everyone who commented. Based on those comments the best course of action in this instance was as follows:
Embed Home View Controller in a Navigation controller and add the following method into Home View Controller:
@IBAction func unwindToViewController(_ sender: UIStoryboardSegue) {}

Then in all storyboards with a home button, Control-drag to its respective View Controllers "exit" icon in the top bar, then select the 'unwindToViewController' method created earlier.
That will remove all VC's in the stack when navigating back to the root VC.


text:
Q: How to preserve the error message that is thrown during a 500 internal exception using restTemplate I want to know what is best practice to preserve error messages when calling several micro services that is chained: I have an angular front end that calls a back end rest service which calls another rest service which calls another 3rd party service.
The 3rd party service is somewhat unreliable. And I want the response from that service to be propagated to my front end.
So to make it easier for the sake of demo'ing the problem.
I have a control class in downstream project (separate micro-service/application)
@RestController
@RequestMapping("/my-down-stream-service")
public class MyController {

    @RequestMapping(value = "my-method")
    public MyCustomResponse method1() {
       //Some complex logic that catch exceptions and propogates a nice little message
       throw new RuntimeException("This is my exception that indicates what the response is to my 3rd party service");
    }
}

On the other micro-service calling the service above I have a restTemplate making the call to the above service
public MyResponse doIt() {
    try {
       restTemplate.postForEntity("MyUrl…", req, MyResponse.class);
    } catch (final HttpStatusCodeException ex) {
        //If I add a break point and inspect the exception here
    }
}

I can see it is a 500 internal exception that gets send to the front end.
If I go and get the ex.getResponseBodyAsString() I get back a JSON map with the actual detail of the exception.
{
    "timestamp": "2020-05-06T22:17:08.401+0200",
    "status": 500,
    "error": "Internal Server Error",
    "exception": "java.lang.RuntimeException",
    "message": "This is my exception that indicates what the response is to my 3rd party service",
    "path": "…"
}

And I can convert this into a map and get the message portion and construct a new exception and throw that
new ObjectMapper().readValue(ex.getResponseBodyAsString(), HashMap.class).get("message")

But this seems like a lot of work that needs to be implemented where ever I need this.
Is there a better way of doing this?
I also tried creating my own HttpStatus - Like a 550 with my "Own custom message". But you cannot set the message for the HttpStatus code dynamically aka at Runtime. Not even sure if this is the correct venture or path to go down.
My solution in the end based on Amit's suggestion
I finally ended up creating a custom class that extends springs ResponseEntityExceptionHandler. If this is on the class path of your springboot app it will intercept the exception before returning it from the controller. I also created my own exception. Reason being this way if I want my functionality to trigger I fire my own exception and everyone else can still follow the normal way. It can be changed at any time.
Also on the client side I had to cast the exception's getBody() JSON to my exception. But I didn't knew if it was my exception to start of with. So I also added some HTTP header. And on the client side I check if that header is present then I know the body is my exception and I could comfortable convert the JSON to my exception.
@ControllerAdvice
public class MyRestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = {MyCustomException.class})
    protected ResponseEntity<Object> handleConflict(final MyCustomException ex, final HttpServletResponse response) {
        if (!response.containsHeader("MYTAG")) {
            response.addHeader("EX_TYPE", "MYTAG");
        }

        //here you can go wild as to what type of or just the normal 500
        //return ResponseEntity.status(ex.getHttpStatus()).body(ex); // 500 internal exception
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex);
    }

}

A: If I were you, I would like to create a controller advice to handle all kind of exceptions. Then I would like to create a ErrorMessage class which will have custom errorCode, errorMessage fields as per requirements. From this controller advice, for any kind of exceptions occurred in application, it will create an instance of ErrorMessage with details like errorCode and errorMessage and wrap into ResponseEntity object (with HTTP status) and return to the other microservices.
At consumer end check the response status and act accordingly.

A: I think the answer you are looking for is creating an implementation of ExceptionMapper. The interface is designed to handle java exceptions that map to Response.
In your case, if the 3rd part throws an exception which is handled by the ExceptionMapper implementation you can access the error message and return that in the response.
public class ServiceExceptionMapper implements ExceptionMapper<ServiceException>
{
    /**
     * {@inheritDoc}
     */
    @Override
    public Response toResponse(ServiceException exception)
    {
        //grab the message from the exception and return it in the response
    }


text:
Q: Magento 2.3.4 Plugin Sitemap not working I've had a plugin working on 2.2.2 version but it's not working on 2.3.4. Its seem that collectSitemapItems() method is not firing even in native magento WHen I print_r('Die');die;
public function collectSitemapItems()
    {
        print_r('Not firing');die;
        /** @var $helper \Magento\Sitemap\Helper\Data */
    ...

But it's printing under protected method _initSitemapItems()
/**
     * Initialize sitemap
     *
     * @return void
     */
    protected function _initSitemapItems()
    {
     print_r('Working Here');die;
    ...

My plugin have afterCollectSitemapItems() Method:
public function afterCollectSitemapItems(
        Sitemap $subject
    )
    {
        print_r('Not firing here either');die;

My Plugin di.xml:
 <type  name="Magento\Sitemap\Model\Sitemap">
   <plugin name="vendor-sitemap" sortOrder="1"  disabled="false" type="Vendor\Module\Plugin\Sitemap\Plugin"/>
 </type>

Any ideas why this isn't working anymore?

A: I've found out that my plugin is firing ok after printing in __constructor bu method afterCollectSitemapItems not any more. So using public method generateXml like so:
public function __construct(
        \Magento\Sitemap\Helper\Data $helper
        ) {
            $this->helper = $helper;
    }
    public function beforeGenerateXml(
        \Magento\Sitemap\Model\Sitemap $subject
        )
    {
        $storeId = $subject->getStoreId();
        $newRecords = [];
        $object = new \Magento\Framework\DataObject();
        $object->setId(['test_id']);
        $object->setUrl('test-url');
        $object->setUpdatedAt('2020-04-17 14:24:38');
        $newRecords['test_id'] = $object;
        $subject->addSitemapItem(new  \Magento\Framework\DataObject(
            ['changefreq' => $this->helper->getPageChangefreq($storeId),
             'priority' => $this->helper->getPagePriority($storeId),
             'collection' => $newRecords,]
         ));
    }

}

Worked, Sorted!
Note/Tip: only before method works on generateXml and also when generating always open xml in incognito mode as is caches in chrome browser.

A: Try this below and add your die as well
   public function __construct(
        \Magento\Sitemap\Helper\Data $helper
        ) {
            $this->helper = $helper;
    }
    public function afterCollectSitemapItems(
        \Magento\Sitemap\Model\Sitemap $subject
        )
    {

        die('Not firing here either');
        $storeId = $subject->getStoreId();
        $newRecords = [];
        $object = new \Magento\Framework\DataObject();
        $object->setId(['test_id']);
        $object->setUrl('test-url');
        $object->setUpdatedAt('2020-04-17 14:24:38');

        $newRecords['test_id'] = $object;

        $subject->addSitemapItem(new  \Magento\Framework\DataObject(
            [

                'changefreq' => $this->helper->getPageChangefreq($storeId),
                'priority' => $this->helper->getPagePriority($storeId),
                'collection' => $newRecords,
            ]
         ));
    }

}


text:
Q: Merging 2 Text Files in C# Firstly, i'd just like to mention that I've only started learning C# a few days ago so my knowledge of it is limited.
I'm trying to create a program that will parse text files for certain phrases input by the user and then output them into a new text document.
At the moment, i have it the program searching the original input file and gathering the selected text input by the user, coping those lines out, creating new text files and then merging them together and also deleting them afterwards.
I'm guessing that this is not the most efficient way of creating this but i just created it and had it work in a logical manor for me to understand as a novice.
The code is as follows;
private void TextInput1()
    {
        using (StreamReader fileOpen = new StreamReader(txtInput.Text))
        {
            using (StreamWriter fileWrite = new StreamWriter(@"*DIRECTORY*\FIRSTFILE.txt"))
            {
                string file;
                while ((file = fileOpen.ReadLine()) != null)
                {
                    if (file.Contains(txtFind.Text))
                    {
                            fileWrite.Write(file + "\r\n");
                    }
                }
            }
        }
    }

    private void TextInput2()
    {
        using (StreamReader fileOpen = new StreamReader(txtInput.Text))
        {
            using (StreamWriter fileWrite = new StreamWriter(@"*DIRECTORY*\SECONDFILE.txt"))
            {
                string file;
                while ((file = fileOpen.ReadLine()) != null)
                {
                    if (file.Contains(txtFind2.Text))
                    {
                        fileWrite.Write("\r\n" + file);
                    }
                }
            }
        }
    }

    private static void Combination()
    {
        ArrayList fileArray = new ArrayList();

        using (StreamWriter writer = File.CreateText(@"*DIRECTORY*\FINALOUTPUT.txt"))
        {

            using (StreamReader reader = File.OpenText(@"*DIRECTORY*\FIRSTFILE.txt"))
            {
                writer.Write(reader.ReadToEnd());
            }

            using (StreamReader reader = File.OpenText(@"*DIRECTORY*\SECONDFILE.txt"))
            {
                writer.Write(reader.ReadToEnd());
            }
        }

    }

    private static void Delete()
    {
        if (File.Exists(@"*DIRECTORY*\FIRSTFILE.txt"))
            {
                File.Delete(@"*DIRECTORY*\FIRSTFILE.txt");
            }

        if (File.Exists(@"*DIRECTORY*\SECONDFILE.txt"))
            {
                 File.Delete(@"*DIRECTORY*\SECONDFILE.txt");
            }

    }

The output file that is being created is simply outputting the first text input followed by the second. I am wondering if it is possible to be able to merge them into 1 file, 1 line at a time as it is a consecutive file meaning have the information from Input 1 followed 2 is needed rather than all of 1 then all of 2.
Thanks, Neil.

A: try this method. You can receive three paths. File 1, File 2 and File output.
public void MergeFiles(string pathFile1, string pathFile2, string pathResult)
{
    File.WriteAllText(pathResult, File.ReadAllText(pathFile1) + File.ReadAllText(pathFile2));
}

If the pathResult file exists, the WriteAllText method will overwrite it. Remember to include System.IO namespace.
Important: It is not recommended for large files! Use another options available on this thread.

A: To combine the two files content in an one merged file line by line you could substitute your Combination() code with this
string[] file1 = File.ReadAllLines("*DIRECTORY*\FIRSTFILE.txt");
string[] file2 = File.ReadAllLines("*DIRECTORY*\SECONDFILE.txt");

using (StreamWriter writer = File.CreateText(@"*DIRECTORY*\FINALOUTPUT.txt"))
{
    int lineNum = 0;
    while(lineNum < file1.Length || lineNum < file2.Length)
    {
        if(lineNum < file1.Length)
            writer.WriteLine(file1[lineNum]);
        if(lineNum < file2.Length)
            writer.WriteLine(file2[lineNum]);
        lineNum++;
    }
}

This assumes that the two files don't contains the same number of lines.

A: If your input files are quite large and you run out of memory, you could also try wrapping the two readers like this:
        using (StreamWriter writer = File.CreateText(@"*DIRECTORY*\FINALOUTPUT.txt"))
        {
            using (StreamReader reader1 = File.OpenText(@"*DIRECTORY*\FIRSTFILE.txt"))
            {
                using (StreamReader reader2 = File.OpenText(@"*DIRECTORY*\SECONDFILE.txt"))
                {
                    string line1 = null;
                    string line2 = null;
                    while ((line1 = reader1.ReadLine()) != null)
                    {
                        writer.WriteLine(line1);
                        line2 = reader2.ReadLine();
                        if(line2 != null)
                        {
                            writer.WriteLine(line2);
                        }
                    }
                }
            }
        }

Still, you have to have an idea how many lines you have in your input files, but I think it gives you the general idea to proceed.

A: Using a FileInfo extension you could merge one or more files by doing the following:
public static class FileInfoExtensions
{
  public static void MergeFiles(this FileInfo fi, string strOutputPath , params string[] filesToMerge)
  {
    var fiLines = File.ReadAllLines(fi.FullName).ToList();
    fiLines.AddRange(filesToMerge.SelectMany(file => File.ReadAllLines(file)));
    File.WriteAllLines(strOutputPath, fiLines.ToArray());
  }
}

Usage
  FileInfo fi = new FileInfo("input");
  fi.MergeFiles("output", "File2", "File3");

A: I appreciate this question is almost old enough to (up)vote (itself), but for an extensible approach:
const string FileMergeDivider = "\n\n";

public void MergeFiles(string outputPath, params string[] inputPaths)
{
    if (!inputPaths.Any())
        throw new ArgumentException(nameof(inputPaths) + " required");

    if (inputPaths.Any(string.IsNullOrWhiteSpace) || !inputPaths.All(File.Exists))
        throw new ArgumentNullException(nameof(inputPaths), "contains invalid path(s)");

    File.WriteAllText(outputPath, string.Join(FileMergeDivider, inputPaths.Select(File.ReadAllText)));
}