text:
Q: calling methods if previous call success I my c# program I have to perform 5 steps(tasks) sequentially. basically these five should execute one after the other only the previous task performed is success. Currently I have done it in following style. But this is not very good code  style to follow.
var isSuccess=false;
isSuccess=a.method1();

if(isSuccess)
    isSuccess=a.method2();

if(isSuccess)
    isSuccess=a.method3();

if(isSuccess)
    isSuccess=a.method4();

if(isSuccess)
    isSuccess=a.method5();

How can I re factor this code. What is the best way I can follow?

A: C#/.NET process conditions left to right and would stop at the first false if they were "ANDed" together, e.g.
bool success = A() && B() && C();

should stop at B() if it returned false. Thus the following code will only output "In A" and "In B", but not "In C", because as soon as B() returns false, it stops.
using System;

public class App
{
  public static void Main()
  {
    bool success = A() && B() && C();
  }

  static bool A()
  {
    Console.WriteLine("In A");
    return true;
  }

  static bool B()
  {
    Console.WriteLine("In B");
    return false;
  }

  static bool C()
  {
    Console.WriteLine("In C");
    return true;
  }
}

Output:
In A
In B

A: I would actually let it stay as it is, since this way it's easily readable and understandeable by anyone. But if you use the same pattern in a lot of places and all the method have the same signature here's an (overengineered and probably twisted) idea:
public class SequentialExecutor
{
    private Func<bool>[] functions;

    public SequentialExecutor(params Func<bool>[] functions)
    {
        this.functions = functions;
    }

    public bool Execute()
    {
        foreach (var func in functions)
        {
            bool isSuccess = func();
            if (!isSuccess)
            {
                return false;
            }
        }

        return true;
    }
}

You can use it like this:
var executor = new SequentialExecutor(a.method1, a.method2, a.method3, a.method1, a.method4);
bool isSuccess = executor.Execute();

P.S. NOT TESTED

A: This is the sort of situation where throwing an exception on failure may be neater. If that's your API, you can then do:
try {
    a.method1();
    a.method2();
    a.method3();
    a.method4();
    a.method5();
} catch (UnsatisifedException e) {
    // Some sort of recovery logic here...
}


text:
Q: Dealing with change requests from clients for an old system that only take 5 minutes to implement
Possible Duplicate:
How should I charge for programming things which take two minutes to fix?

On some systems I created, every now and then I get tiny change requests from clients that are very easy for me to do, but the client can not do it themselves.
For example:

*

*Hey, we made a new logo, could you please upload it to our website?

*Can you check how many users we had this month?

Most of them basically just requires me to log on to the FTP server and upload a file which takes 2 minutes max. Sometimes even answering the email or writing the bill takes longer!
How do I charge the client for these changes? I could easily do it for free, because at the moment I don't get them frequently at all, maybe once per month. If the initial cost of the system is big it would seem like a nice gesture to the client to give and take a bit. What I'm afraid of is that they will become more and more frequent and then the client will get used to getting these changes for free. Also where do I draw the line for what to give away, 2 minutes? 5 minutes? 15 minutes? I want to be consistent in the pricing so it doesn't seem like I charge whatever I feel for at the moment.
Some ideas:

*

*Charge per started hour/half hour/quarter, that is, 1 minute counts as 1 hour, 61 minutes as 2 hours (at least for the first hour).

*Accumulate small changes into a pool of time. Instead of sending out bills for 2 minutes each they add up to a sum at the end of every 3 months or something.

*Only charge if they want the fix NOW. Otherwise say they'll get it once I have time, within the next weeks.

*Be an ass and pretend it's a big fix.

A: There's no one right answer for this. However, you have to make it clear that these things take your time and so have to be paid for in some way. Where the cut off between something that's trivial for you to do and something that will take a significant amount of time is only something that you can really decide.
However, taking your examples as a starting point it might be better for you to build admin functions into your websites so that users can do these things for themselves. This means that they won't have to bother you and you can concentrate on creating new sites and new functionality.
It could be argued that the first (uploading a new logo) should have been in the site in the first place - but that's splitting hairs - tell them that you are going add this functionality at some point but it will cost them a small one-off amount. Otherwise you'll have to charge them each time they want these things doing.
Adding functionality for the second (analytics) sounds like it's a change in requirements so should be charged as a new development - or again you you'll have to charge for each request.
If you've done these things for free in the past then you'll need to tread more carefully, but if you introduce the idea that your time cost money they should understand. Also if you bring in a couple of changes at the same time (e.g. the ability to upload a new logo) then they should see the benefit of this approach.

A: My girlfriend has a hair dresser who insists that she comes back for free 5 minute bang trims whenever her bangs grow too long (much more often than a full hair cut).  She loves her hair dresser, recommends him to friends, and tips him well whenever she needs her bangs trimmed.
Perhaps you can exploit this model.

A: Neogitiate a maintenance/support contract or make them buy time-contingents. It's as simple as that.
Have statistics on the average amount of time you spend per month and then hand them a simple maintenance contract. That's fair.
If they don't want a contract or don't want to buy time-contingents, then charge them every once in a while for a minor task when some time has been accumluated.
However, I also agree with giving them some freebies if you have been paid generously for development. I also give our customers a small freebie every now and then to improve the relationship.

A: The trouble with "5 minute" jobs is there is really no such thing.
By the time you get the request, open it, read it, think about it, log in, do stuff, check it.... doing ANYTHING in 5 minutes is really not going to happen.
15 minutes, perhaps.
The there is the effect on you of context switch time - the down time caused to get your mental gears changed over.
And then there is opportunity cost - the $ you are not earning by doing this stuff for free.
Put that all together, and this is costing you money. Each "5 minute" job request is probably worth around 15 to 30 minutes of real genuine chargeable time, in thinking about it, actually doing it, and the time taken off other more useful (and probably better paying) jobs.
So - charge 1/2 hour for every task as a minimum, and probably go in 15 minute increments from there.
A support agreement is a good thing to have but you still need a means of judging how to cost that agreement. The above should be a suitable basis whether you invoice each task, or you debit the outstanding amount of "support time" for a client. Do less, and you are being less than honest with yourself.

A: Two things:

*

*Every application should have a section for super users who can manage it. This section is usually called management or admin, and users with enough privilege can log into it and upload the new logo or see the online users or anything of this sort. Your application probably doesn't have this section. You can make a contract to build this section, or:

*You can add up all these minutes till the sum gets big enough to become chargeable (for example, 2 hours).

But please, don't work for free, not because what you earn from an hour of work is a noticeable amount, but because this behavior causes customers to think that providing free support service is just a must in development field.

A: Always remember that while it might take you 5 minutes, it took a long time for you to learn to do it in 5 minutes.
If you're doing a load of them maybe accumulate them and send an itemised invoice when it amounts to more than a couple of hours.

A: Price is defined roughly by

*

*What your customer will pay for a thing or service

*Who can provide that service at a given price

So, charge what it's worth to the customer.  If you gouge them, then you risk that they may take future business elsewhere at contract renegotiation time, but you have a strong advantage of being the current service provider / incumbent.  Don't underestimate how strong this is- finding a new supplier is usually a complicated process that most businesses avoid if they can.  They can't switch companies as easy, so they'll be willing to pay more.  Don't think for a second that if they could get the same service you provide for less money with a seamless transition that they wouldn't drop you!
The point is: just because something takes you 5 minutes does not mean it's worth a pittance.  That's called profit (and sole-valuation based on hours worked is called communism).
In your particular case I'd charge monthly for metrics (want a metric? pay for a month of service that gets you X many of Y kind of reports either on demand or on a schedule).  For the site upgrade/logo swap I'd charge that as a discrete activity since a smart company isn't going to change its brand logo very often.

A: These "5 minute changes" often involve more work than one would think. OK, changing a logo is easy, but are you sure there aren't more versions of that logo lurking around the application? What if the size they give you isn't right? What if they change their mind 4 hours later? All this stuff adds up. It can come back and bite you hard no matter how well you know your application.
If they need a change, clients should be willing to pay for it. By giving it out for free or for a very low cost, it could encourage these clients to not value your time as much as they should. Future RFQ's might get sloppy if they think that they they can just hit you up for nickel and dime changes as needed. In the end it hurts everyone involved.
Another way to think about is that the time you actually spending making a change is worth something. However, so is the ability to make it at a moment's notice at the whim of the client. I can't imagine even the most trivial change being worth less than 1-2 hours of your time. If something is so trivial it is not worth "pocket change" from a company's point of view, it probably isn't worth doing anyway (and yes, "pocket change" is a few hundred bucks).

A: I would do occasional tiny changes for free, but make it very clear that the free maintenance is only because the changes they are asking for are tiny and infrequent, and that if they need bigger or more frequent changes then you will have to start charging a maintenance fee.

A: A lot has to do with how much of an interuption this is and what is their expectation for the timing of this change. Any level of urgency on their part or increased frequency needs to be settled.
Be upfront about charging. If they can't wait for the new logo because they want to show the site to an investor in half an hour, they should pay. If not, what is the point in picking up the phone when they call? If they don't expect you to have other clients, they need to pay you to be on call full time.
Also, try to make the billing simple on yourself. Ask them to buy a block of 5 or 10 requests. Offer a discount for them to pay up front. You don't want to keep tracking every single bill and payment for this little stuff.
This can also be a part of negotiating a large contract.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does my WiFi Network have a huge Subnet mask? I'm currently learning about IP and Routers, and have recently learned about Subnet Masks and their purposes. When I checked my own IPs (with ipconfig), I noticed an oddity:
My Ethernet Subnet mask is 255.255.255.0, which I suppose is rather normal (although it leaves space for surprisingly many devices), but much more concerning is my Wireless LAN Subnet Mask, standing at 255.255.0.0, which would be a ridiculous amount of possible devices in my network - which is just a FritzBox in my family home.
Is there any explanation to the size of this Subnet Mask, could it may be that I am misunderstanding the concept of Subnet Masks with WiFi or is this something I should change?
Any information is greatly appreciated :)

A: Ok so 255.255.0.0 is the maximum amount of devices that can be used so probably the first two octets of all devices must be the same on the network for it to configuire itself as this. Alas your network does not believe itself to be running at full capacity but believes it has the ability to run at full capacity which is true right? (hopefully as it is new) Therefore you certainly have a set up calibration problem which is no worry and really an unnecessary issue that really at the end of the day has no problem unless you wanted to run some thing of the sort of  a mass AI learning system of independent integrated workstations on your home LAN (which again, i wouldnt expect)
A bit of extra clarification (perhaps unnecessary)but because you asked you asked for as much information :) ... the AI would only be a problem because it would always want to reach the max device number you have allocated when running and incrementing learning. The AI always overspills the max you have set but of course as it is set as the largest possible max on your system (at 255) it has no overspill capabilities at all and would cause a queue.


text:
Q: Django making recursive calls on relationship I have the following model on Django 1.6.5
class Location(models.Model):
    parent = models.ForeignKey('Location', blank=True, null=True)
    name = models.CharField(max_length=50)

    class Meta:
        db_table = 'locations'
        ordering = ('parent__name', 'name')

    def __unicode__(self, ):
        if self.parent!= None:
            return self.name + " (" + self.parent.name +  ")"
        else:
            return self.name

And I'm listing these locations in a dropdown, so I want to show the name + (parent.name if available)
Any idea hwo to do this without having to do thousands of calls?

A: Finally I did this:
In the forms.py I created a method:
def get_locations_with_parents():
    location_list = [(0,'Select One ...')]
    locations = Position.objects.raw('select l.id, l.name, p.name as parent from locations l left join locations p on l.parent_id = p.id order by parent, l.name')
    for l in locations:
        if l.parent:
            location = (int(l.id), l.name + " (" + l.parent + ")")
        else:
            location = (int(l.id), l.name)

        location_list.append(location)

    return tuple(location_list)

and then in the form I use
    locations = forms.ChoiceField(choices=get_locations_with_parents(), validators=[validate_empty])
It does the trick and it doesn't do 2000 queries to the DB anymore. There are some validators and clean and so... but does not really relevant to the solution.

A: I may be misunderstanding your question, but I think I have a similar situation. In the dropdown you want the object to be labelled with the name of the location. If there is a parent for that location, you would like to show the name of that parent as well within parentheses following the location name.
You can accomplish this by overriding the __init__ method of your ModelForm:
def __init__(self, *args, **kwargs):
    def new_label_from_instance(self, obj):
        try:
            #see if there is a parent or not
            p = obj.parent
        except:
            #no parent; use the location's default label
            rep = obj.description
            return rep
        #if we find a location's parent, p=parent label and d=location label
        d = obj.description
        rep = "%s (%s)" % (d, p)
        return rep

    super(PublisherCreateTSCForm, self).__init__(*args, **kwargs)
    funcType = type(self.fields['location'].label_from_instance)
    self.fields['location'].label_from_instance = funcType(new_label_from_instance, self.fields['location'], forms.models.ChoiceField)

You should know the consequences of doing this before you do it. Check out this old question:
Django CheckboxSelectMultiple override 'choices' from ModelForm
And the docs related to label_from_instance here (bottom of the linked section): https://docs.djangoproject.com/en/1.7/ref/forms/fields/#modelchoicefield


text:
Q: Find spectrum of integral operator in L2 Please help me find the spectrum of operator $A$, I do not speak English well. In Russian forums I did not find the answer.
Find spectrum of integral operator in $L_2$($R$):
$$ (Ax)(t) = \int\limits_{-\infty}^{+\infty} \dfrac{x(s)ds}{1+(t-s)^2}\ $$
This is Fredholm integral operator (first type)
$$K(t,s) = \dfrac{1}{1+(t-s)^2}$$
Eigenvalues are found from the condition $Ax=\lambda x$
The spectrum will consist of $0$ and its own conceptions


text:
Q: How to find a string, delete corresponding node and append two nodes using xmlstarlet I have a file called FILE.XML
It looks like this
      <File>${IB}/OP/views/ACCOUNT.xml</File>
      <File>${IB}/OP/views/EMPLOYEES.xml</File
      <File>${IB}/OP/views/STATUS.xml</File>

I need to use xmlstarlet to look at FILE.XML and determine if there's a match for ACCOUNT.xml. If there is, append two additional lines beneath it. Including the tags and the full path as seen below.
<File>${IB}/OP/views/ACCOUNT_MAIN.xml</File>
<File>${IB}/OP/views/ACCOUNT_SECONDARY.xml</File>

Then delete ACCOUNT.xml line
<File>${IB}/OP/views/ACCOUNT.xml</File>

So I came up with a way to delete the line but not sure how to append the new ones before or after I delete.
Here's my delete command.
xmlstarlet ed -L -d '//rules/File[contains(text(),"{IB}/OP/view/ACCOUNT.xml")]' ${HOME}/file.xml

The final result in FILE.xml should look like this
      <File>${IB}/OP/views/ACCOUNT_MAIN.xml</File>
      <File>${IB}/OP/views/ACCOUNT_SECONDARY.xml</File>
      <File>${IB}/OP/views/EMPLOYEES.xml</File
      <File>${IB}/OP/views/STATUS.xml</File>

A: Given this input,
<rules>
  <File>${IB}/OP/views/ACCOUNT.xml</File>
  <File>${IB}/OP/views/EMPLOYEES.xml</File>
  <File>${IB}/OP/views/STATUS.xml</File>
</rules>

this should do what you're after:
# shellcheck shell=sh disable=SC2016
xmlstarlet edit \
  --var T '//rules/File[contains(text(),"${IB}/OP/views/ACCOUNT.xml")]' \
  -a '$T' -t elem -n 'File' -v '${IB}/OP/views/ACCOUNT_SECONDARY.xml' \
  -a '$T' -t elem -n 'File' -v '${IB}/OP/views/ACCOUNT_MAIN.xml' \
  -d '$T' \
file.xml

--var defines a named variable, see examples in
xmlstarlet.txt. If the T variable
matches nothing then input is not modified.

A: Input
<root>
  <File>${IB}/OP/views/ACCOUNT_MAIN.xml</File>
  <File>${IB}/OP/views/ACCOUNT_SECONDARY.xml</File>
  <File>${IB}/OP/views/EMPLOYEES.xml</File
  <File>${IB}/OP/views/STATUS.xml</File>
</root>

What I would do:
xmlstarlet ed -L \
  -a '//File[contains(., "ACCOUNT.xml")]' -t elem -n File \
  -v '${IB}/OP/views/ACCOUNT_SECONDARY.xml' \
  -a '//File[contains(., "ACCOUNT.xml")]' -t elem -n File \
  -v '${IB}/OP/views/ACCOUNT_MAIN.xml' \
  -d '//File[contains(., "ACCOUNT.xml")]' file.xml

Output
<?xml version="1.0"?>
<root>
  <File>${IB}/OP/views/ACCOUNT_MAIN.xml</File>
  <File>${IB}/OP/views/ACCOUNT_SECONDARY.xml</File>
  <File>${IB}/OP/views/EMPLOYEES.xml</File>
  <File>${IB}/OP/views/STATUS.xml</File>
</root>


text:
Q: Error in Import App pools from windows server 2016 to windows server 2012 I am trying to export using appcmd from a windows server 2016 (IIS 10) to a windows server 2012 R2(IIS 8.5). I am getting an error hresult:8007000B command execution failed data is invalid. Due to some reasons I can not use webDeploy tool here. Any suggestion please

A: You can try the solution below to solve this question:

*

*Run appcmd as administrator.

*Try to enable 32-bit application in application pool advanced setting.

*Ensure you have synced the config file.


text:
Q: How i can give all privilages for a user to all databases in my shared hosting I have a user and 10 databases in my cpanel and i want grant this user to all databases in my host using sql command.
I used this command :
grant all privileges on *.* to 'myacc_myuser'@localhost identified by 'mypass' with grant option;

But it give me this error :
#1045 - Access denied for user 'myacc'@'localhost'

How i can resolve this problem ?
Thanks.


text: Q: "command not found" ошибка git bash при попытке коммита и прохождения тестов на Windows У меня есть несколько прекоммитных тестов. При попытке коммита возникает эта ошибка. Я пыталась прописать путь ("C:\Program Files\nodejs\node.exe") в переменных среды в настройках системы Windows и также создала файл .bashrc в папке пользователя и прописала путь там. Но ничего из этого не помогло, есть ли какие-то способы решить эту проблему?


text:
Q: css3 rotation 3d on chrome and firefox (First of all I'm sorry for my english!)
I'm developing a site that uses 3D rotation (link), there is no problems on Safari but on Chrome (19.0.1084.46) and Firefox (12.0) it doesn't work correctly.
On Firefox if you switch several times between "porftolio" and "profile", the face with profile disappears.
On chrome the face "profilo" appears when the rotation is already playing.
Can you help me?

A: You can try to change or delete :
#profilo .pad {
padding-left: 30px;}


text:
Q: WPF DataGrid Dynamic width cell highlighting I have an application that's using the WPF Data Grid. That grid presents a set of test results. If the result of a test is out side the min and max allowed values I want to highlight that cell in red. I currently have it working, but am not quite happy with the highlighting.
Here's what it looks like currently:

Here's the desired look (via some image twiddling):

Notice the highlighting in the first example consumes the entire cell width. I'm hoping for the desired example where it only consumes as much space as the widest result with a little margin on both sides. Keep in mind, a result in any one cell could range between 0 and 1920K from one sample to the next. This is an edge case, but I want the highlighted area to grow and shrink as a result.
Just FYI, these results are updated on a configurable timer that triggers anywhere between 10 ms and 10 seconds depending on the user configuration.
Below is the code that generates the first example (sorry for the large amount of code). The interesting bits are DataGridCellStyle, ResultCellStyle and CellTemplate
The XAML
<Window x:Class="StackOverflow_HighlightCell.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:StackOverflow_HighlightCell"
    mc:Ignorable="d"
    Loaded="Window_Loaded"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <Style TargetType="DataGridColumnHeader">
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="HorizontalContentAlignment" Value="Center" />
    </Style>

    <ControlTemplate x:Key="CellTemplate" TargetType="{x:Type DataGridCell}">
        <Border Background="{TemplateBinding Background}">
            <ContentPresenter Margin="12,0,0,0" />
        </Border>
    </ControlTemplate>

    <Style x:Key="DataGridCellStyle" TargetType="DataGridCell">
        <Setter Property="Background" Value="#707070" />
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="HorizontalContentAlignment" Value="Left" />
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Foreground" Value="#CCCCCC" />
            </Trigger>
        </Style.Triggers>
    </Style>

    <Style x:Key="ResultCellStyle" TargetType="DataGridCell"
           BasedOn="{StaticResource DataGridCellStyle}">
        <Setter Property="Template" Value="{StaticResource CellTemplate}" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsResultOutOfBounds,
                                           StringFormat={}{0:0.00}}"
                                           Value="True">
                <Setter Property="Background" Value="Red" />
                <Setter Property="Foreground" Value="White" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

    <Style TargetType="DataGrid" BasedOn="{x:Null}">
        <Setter Property="RowBackground" Value="#707070" />
        <Setter Property="AutoGenerateColumns" Value="False" />
        <Setter Property="IsReadOnly" Value="True" />
        <Setter Property="Background" Value="#666666" />
        <Setter Property="GridLinesVisibility" Value="None" />
        <Setter Property="BorderBrush" Value="Transparent" />
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="CanUserSortColumns" Value="False" />
        <Setter Property="HeadersVisibility" Value="Column" />
        <Setter Property="HorizontalAlignment" Value="Stretch" />
        <Setter Property="Foreground" Value="#CCCCCC" />
        <Setter Property="RowDetailsVisibilityMode" Value="Collapsed" />

        <Setter Property="CellStyle" Value="{StaticResource DataGridCellStyle}" />
    </Style>

    <!-- A left justified DataGridTextColumn -->
    <Style x:Key="ElementLeftJustified">
        <Setter Property="TextBlock.HorizontalAlignment" Value="Left" />
        <Setter Property="TextBlock.Margin" Value="15,0,5,0" />
    </Style>

    <!-- A right justified DataGridTextColumn -->
    <Style x:Key="ElementRightJustified">
        <Setter Property="TextBlock.HorizontalAlignment" Value="Right" />
        <Setter Property="TextBlock.Margin" Value="0,0,5,0" />
    </Style>

</Window.Resources>

<Grid Background="#FF666666">
    <Border Margin="20" >
        <DataGrid x:Name="_testSummaryGrid"
              ItemsSource="{Binding TestResults}">

            <DataGrid.Columns>
                <DataGridTextColumn
                    MinWidth="75" Header="Test"
                    Binding="{Binding TestName}"
                    ElementStyle="{StaticResource ElementLeftJustified}" />

                <DataGridTextColumn
                    MinWidth="75" Header="Min"
                    Binding="{Binding Min, StringFormat={}{0:0.00}}"
                    ElementStyle="{StaticResource ElementRightJustified}" />

                <DataGridTextColumn
                    MinWidth="75" Header="Result"
                    Binding="{Binding Result, StringFormat={}{0:0.00}}"
                    ElementStyle="{StaticResource ElementRightJustified}"
                    CellStyle="{StaticResource ResultCellStyle}" />

                <DataGridTextColumn
                    MinWidth="75" Header="Max"
                    Binding="{Binding Max, StringFormat={}{0:0.00}}"
                    ElementStyle="{StaticResource ElementRightJustified}" />
            </DataGrid.Columns>
        </DataGrid>
    </Border>

</Grid>
</Window>

The View Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace StackOverflow_HighlightCell
{
    public class ResultsViewModel : ViewModelBase
    {
        public ResultsViewModel()
        {
            TestResults = new ObservableCollection<TestResult>
            {
            { new TestResult { TestGroup = "Circle",TestName = "Radius",
                               Min = 100, Max = 153, Result = 150} },
            { new TestResult { TestGroup = "Circle", TestName = "Min Radius",
                               Min = 0, Max = 90, Result = 97.59 } },
            // And so on ...
            };
        }

        public ObservableCollection<TestResult> TestResults { get; set; }

    }

    public class TestResult : ViewModelBase
    {
        public string TestGroup { get; set; }
        public string TestName { get; set; }
        public double Result { get; set; }
        public double Min { get; set; }
        public double Max { get; set; }
        public bool IsResultOutOfBounds { get { return !(Result >= Min && Result <= Max); } }

    }

    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void FirePropertyChanged(string property)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
        }
    }
}

A: I think this should do what you want:
<ControlTemplate x:Key="ResultCellTemplate" TargetType="{x:Type DataGridCell}">
    <Border Background="{TemplateBinding Background}">
        <Grid
            Margin="12,0,0,0"
            HorizontalAlignment="Right"
            >
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" SharedSizeGroup="Result" />
            </Grid.ColumnDefinitions>
            <Border Grid.Column="0" x:Name="ContentPresenterBorder">
                <ContentPresenter
                    />
            </Border>
        </Grid>
    </Border>

    <ControlTemplate.Triggers>
        <!--
        That stringformat you had will have been ignored because the target
        type isn't string.
        -->
        <DataTrigger Binding="{Binding IsResultOutOfBounds}" Value="True">
            <Setter TargetName="ContentPresenterBorder" Property="Background" Value="Red" />
            <Setter TargetName="ContentPresenterBorder" Property="TextElement.Foreground" Value="White" />
        </DataTrigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

<Style x:Key="ResultCellStyle" TargetType="DataGridCell"
    BasedOn="{StaticResource DataGridCellStyle}">
    <Setter Property="Template" Value="{StaticResource ResultCellTemplate}" />
</Style>

...but don't forget to set Grid.IsSharedSizeScope="True" on the DataGrid. That works with SharedSizeGroup="Result" on the ColumnDefinition to ensure that any grid column named "Result" anywhere within the DataGrid will be dynamically sized to the same width.
<DataGrid
    x:Name="_testSummaryGrid"
    ItemsSource="{Binding TestResults}"
    Grid.IsSharedSizeScope="True"
    >

Excellent example by the way. Would've been better trimmed down to just two DataGrid columns, but I pasted it in, pressed F5, and it worked. And the important part wasn't hard to find.


text:
Q: apticron EMAIL setting format for multiple recipients? What is the format for multiple emails in /etc/apticron/apticron.conf?
Should it be
EMAIL="user1@example.com" "user2@example.com"

or
EMAIL="user1@example.com user2@example.com"

A: EMAIL="user1@example.com user2@example.com" is the correct format. I have tested it out and can confirm that it works.


text:
Q: GWT ,Vaadin,SmartGwt,ExtGwt ?---from Swing I start to migrate an old Swing app to web interface:
Alternatives I want :
       Gwt, Vaadin,Smart Gwt, Ext Gwt
The profile of the app is a custom ERP.
Big question is which ?
Why GWT do not have rich components like Vaadin ,SmartGwt and ExtGwt has ?
DO you know any GWT component library ?
Thanks.

A: Well, I don't think there is a definite answer for this one. I started about 2 years ago with all this web-dev maze and I have theses conclusions:

*

*GWT: This framework is really all about abstracting you from the "real" web development. The framework has evolved a lot since I use it. It has gotten better and they are continually introducing interesting new concepts and options for you to build your app. They leave a hole lot of freedom to the dev. This can be a good thing since it can be nice to choose components you already know. Say you know JQuery, they have GQuery, you know Hibernate you can use it, Spring you can use it. But, to much freedom is kind of daunting for GWT beginners since it's hard to plug all the components to get an enterprise application. Is it that hard? Not really you get used to it's concepts and start liking it. As far as Widget goes, they do not offer as many eye candy stuff as Vaadin, gxt or Smart but I like to stick with the bases.

*Smart: I used SmartGWT for enterprise level projets and it does the job. It has many great components that will get you where you want. It is a huge framework though and it gets complex when something doesn't work as you expected. But, you could be happy with it. It gets a bit hard to use layouts sometimes.

*GXT: Really nice. They offer a lot of great widgets, yes. They offer good support, yes. You have to pay :( yes. Unless you are an Open source project, you will have to pay fees to use it. The baseline is, I abandoned it until they release the version 3.0. Why? They are syncing with GWT roadmap. They will be using the same event handling and UI binders. I'm waiting for this to ease my dev. time. Sometimes you also want to mix (which might not be the greatest idea) but the event model being different from the GWT one is pretty crappy.
Bottom line, I sticking with GWT for now. They will continue enhancing it and the support community is great! But you won't get a savvy UI which you could get with any of the frameworks.
good luck


text:
Q: CASE Statement between dates For my EntryDate column I've been trying to successfully separate my data by month and into specific names '2013_04','2013_05' etc, so I can later group my data by it also. This code has thus far been unsuccessful, how can it be changed to work?
CASE
WHEN EntryDate BETWEEN '2013-04-01' AND '2013-04-30' THEN '2013_04'
WHEN EntryDate BETWEEN '2013-05-01' AND '2013-05-31' THEN '2013_05'
WHEN EntryDate BETWEEN '2013-06-01' AND '2013-06-30' THEN '2013_06'
END

Thank you.

A: You can use DATE_FORMAT function:
DATE_FORMAT(EntryDate, '%Y_%m')

http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date-format

A: I would use the year() and month() functions, just because this is common across databases:
CONCAT_WS('_', YEAR(EntryDate), MONTH(EntryDate))

However, DATE_FORMAT() is also a good solution.

A: DATE_FORMAT() is the best option, but you could use a various number if string functions and CONVERT


text:
Q: unused expression Newbie here.  In the following code:
+ (NSString *)descriptionOfProgram:(id)program
{
    NSMutableArray *mutableCopyOfProgram = [program mutableCopy];
    NSString *descr = @"";
    for (int i=0; i<mutableCopyOfProgram.count; i++)
    {
        descr = [descr stringByAppendingString:(@"%@",[mutableCopyOfProgram objectAtIndex:i])];
    }
    return descr;
}

I keep getting an "expression result unused" warning on the code in the loop.  But how can that be, when in the next line I return the expression result?

A: The warning you get is because you should use stringByAppendingFormat: method instead of stringByAppendingString:. Anyway, I would recommend using NSMutableString for building a string. Also, it's better to use [mutableCopyOfProgram count] instead of mutableCopyOfProgram.count. The following code should work for you:
+ (NSString *)descriptionOfProgram:(id)program
{
    NSMutableArray *mutableCopyOfProgram = [program mutableCopy];
    NSMutableString *descr = [[NSMutableString alloc] init];
    for (int i=0; i < [mutableCopyOfProgram count]; i++)
    {
        [descr appendFormat:@"%@", [mutableCopyOfProgram objectAtIndex:i]];
    }
    return descr;
}

A: use stringByAppendingFormat: instead of stringByAppendingString:
I don't think [mutableCopyOfProgram objectAtIndex:i] is used when you use stringByAppendingString: so that would be what's unused.
a format is something like @"%@", @"a string" while a string is just @"a string", so if you're going to use a format, make sure you use the proper method.

A: You have a few stray parenthesis () and also should be using stringByAppendingFormat:
+ (NSString *)descriptionOfProgram:(id)program
{
    NSMutableArray *mutableCopyOfProgram = [program mutableCopy];
    NSString *descr = @"";
    for (int i=0; i<mutableCopyOfProgram.count; i++)
    {
        descr = [descr stringByAppendingFormat:@"%@", [mutableCopyOfProgram objectAtIndex:i]];
    }
    return descr;
}


text:
Q: Why public certificates are stored in a keystore? If certificates are public anyways, why are they stored in a password-protected keystore?
Is this a must, or a means to relate the public key to the private key?

A: There a few reasons for that:
First, in terms of implementation it is indeed a means to relate a private key to a public key. If a private key if compromised, the whole certificate is compromised.
Second,
the knowledge of "who we trust" is valuable.
Third,
a random user shouldn't be able to add new certificates to the trust store.


text:
Q: What does "error: invalid types 'float [10001][float]' for array subscript" mean? I am trying to put some real numbers in a vector. Please help me because I don't know what the problem is.
Here is my code:
#include <iostream>
using namespace std;
float i, n, v[10001];
int k;
int main()
{
    cin >> n;
    for(i = 1; i <= n; i++)
        cin >> v[i];
    for(i = 2; i <= n - 1; i++)
        if(v[i] >= v[1] && v[i] <= v[n])
            k++;
    cout << k;
    return 0;
}

A: You cannot address an array with a float:
cin>>v[i];

with
float i;

i being a floating point number, it wouldn't point to an exact spot in the array. You need:
 int i,n;
 float v[10001];


text:
Q: Add a "convert-comment-to-answer" button
Possible Duplicate:
Mark a comment as answer to a question

I find that in many cases a comment I've made turns out to be the answer to the question. I suggest adding a "convert-comment-to-answer" button.

A: If it is a comment, it is too short for an answer.
You can easily click the edit link next to your comment, copy to an answer and improve/flesh out before posting, then deleting the comment.

A: Most of the times, comment doesn't fit as an answer, because comments are too short.
Sometimes it would be useful, though
However, I do not think this would ever become status-completed, because it's too simple to just copy your comment and put it as an answer instead


text:
Q: Python opencv // strange results on .EXR image I'm starting to use opencv and I'm getting strange result when I'm reading my .exr file.
I just want to get values of some pixels to start but that doesn't seems to work.
Is there an issue with EXR, or is it something else ?
Here is my basic code :
import cv2

imgSource = '*path to my image*'
logo = cv2.imread(imgSource)

print logo[10,13]
print logo[13,16]

The output I get is this :
[2 2 2]
[2 2 2]

This is not the intended values, and the 2 regions should give different things


text:
Q: Symfony2 asset_version being added twice My config.yml looks like so
framework:
    templating:
        engines: ['twig']
        assets_version: 2

And my twig template has this
{% block stylesheets %}
    {% stylesheets  output='css/compiled/main.css'
    '@AppBundle/Resources/public/css/bootstrap.min.css'
    '@AppBundle/Resources/public/css/main.css'
    %}

    <link rel="stylesheet" type="text/css" media="screen" href="{{ asset(asset_url) }}" />
    {% endstylesheets %}
{% endblock %}

This works but the output has the version param twice.

/css/compiled/main.css?v=2?v=2

I have no idea why this is happening and I am not overriding the assets_version_format either. I even searched my whole project for it just in case.
This only occurs though in my production env, dev is fine and works correctly with just one query param.

A: It should be:
<link rel="stylesheet" type="text/css" media="screen" href="{{ asset_url }}" />

(do not put asset_url within an asset() function)


text:
Q: How do I retrieve * literal using read command? I have a script that receives input from the user. One of the possible values I want to retrieve is  the literal *. It seems the shell is intercepting it and executing so that I'm getting a list of all the file names.
while   read -p "Enter operand: " operandTwo
        echo "Argument: $operandTwo"
        echo "Argument: $(echo $operandTwo)"
        [ $operandTwo != X ]
        echo "Result: $?"
do...

This is the output:
Argument: *
Argument: File1 File2 File3
./script: line 20: [: too many arguments
Result: 2

Is the comparison being made here between File1 File2 File3 and X? How do I make a comparison between * and X instead?


text:
Q: Как реализовать обмен ip-адресами в c# Есть программа для работы с БД в локальной сети среди нескольких компьютеров(5-7).
Один из компьютеров - воображаемый сервер на котором хранится БД.
Как реализовать функцию рассылки всем программам на других компьютерах этого ip-адреса, для подключения к БД.
Или нужен другой подход?
A: То что вы описали больше всего похоже на Р2Р-облако - когда один из компов объявляет себя раздающим услугу, а все остальные подключающиеся к сети юзают эту его услугу и рассказывают окружающим)
Здача интересная, но гемморойная и на 5-10 компов - не нужная.
А в случае с вами - БД вероятнее всего находится на одном компе, и никуда с него не девается. Поэтому стоит просто положить конфиг-файл на каждый клиент, чтоб они знали, где искать свой сервер.
A: Для ваших задач должен подойти udp. Вот пример про UDP в С#.

Видится такое решение. Клиент, посылает udp сообщение "кто нынче сервак?" и нынешний сервер ответит тоже udp сообщением, мол, "я, мой ip такой".


text:
Q: pgadmin4 inside a Docker container doesn't login when i tried to login in pgadmin4 with this credentials
i get this error
Unable to connect to server:
connection to server at "db" (172.18.0.3), port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?

A: You should change the hostname in your server registration page to localhost. This is because container name is only accessible from other containers within the same docker user defined network.


text:
Q: Difference between daemon and child thread? As per my knowledge daemon thread is a thread that runs in background(low priority thread) and also a child thread runs in the background when the parent thread runs foreground so where does the difference lie between a child and a daemon thread?
It's in case of java and can you explain referring to other languages too.

A: Java does not use the term child thread.
A thread is either a daemon-thread or a non-daemon-thread.
A non-daemon-thread must be stopped manually and keeps the VM running as long as the thread is running.
A daemon-thread cannot keep the VM running. When the VM stops all daemon-threads will stop running.
You can group threads together with a ThreadGroup. Groups can itself be grouped together that means that you can have a parent and a child ThreadGroups.
The priority of a thread has nothing to do with the explained concepts of threads. Any thread can have any priority.
For other languages/OS I cannot tell how the concepts are there.

A: Daemons (or Demons) and parent | child threading concepts are orthogonal to each other.  In other words, the basis of your question is wrong.  Likewise, priorities can be assigned to processes and threads, but priority is orthogonal to the definition of a demon, parent thread, or child thread status.
An application is a program that has been written and becomes a process when it is executed.  An application is made up of a process and zero, one, or more threads.  The Wikipedia entry on Threads does a good job of explaining the difference between a process and a thread.

*

*processes are typically independent, while threads exist as subsets of a process

*processes carry considerably more state information than threads, whereas multiple threads within a process share process state as well as memory and other resources

*processes have separate address spaces, whereas threads share their address space

*processes interact only through system-provided inter-process communication mechanisms

*context switching between threads in the same process is typically faster than context switching between processes.

A couple of notes -

*

*threads may or may not share the same address space, it is OS dependent.

*take the comment about context switching with a grain of salt - this will be OS and chipset dependent.

"Process" and "thread" are sometimes used interchangeably in conversations.  It's common to call the process the "parent thread" even though this isn't technically correct since it's a process.  Any thread spawning additional threads would be considered parent threads as well.
A daemon is a background process or application, generally without any interactive elements but that's not a hard requirement.  A demon can have any priority assigned to it, not just low priority.  In addition to the process, a daemon may have some child threads associated with it.
All of these terms are independent of the programming language used to write the application.  Some languages provide better support for threads than other languages do.


text:
Q: Compile ERROR: The method error(String, Object, Object) in the type Logger is not applicable for the arguments I inherited a project that is not in Maven & has no documentation on dependency set up.  I'm getting A LOT of errors related to slf4j.
For example, the  _logger.error() call in the following code generates this compile error: "The method error(String, Object, Object) in the type Logger is not applicable for the arguments".
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//lines ommitted

Logger _logger;

//lines ommitted
    _logger.error("getValueList|Error|valueId|{}|date|{}| current|{}|", _valueId, _date,_current);

What slf4j jars do I need to include in my class path to avoid this?  Note, I already have all of slf4j 1.7.5 in my classpath & most logging statements compile fine, but others do not.  I'm not sure how to fix this.
UPDATE - added  extra code for clarity

A: SOLVED:  I accidently included slf4j-api-1.6.6.jar in the classpath.  That was being linked instead of slf4j-api-1.7.5.jar.  Once I removed slf4j-api-1.6.6.jar the slf44 compile errors went away.
thanks for your help.

A: Just refer to this link http://www.slf4j.org/apidocs/org/slf4j/Logger.html
As per the doc, there is no way to include 3 arguments in the logger.error method the way your code is doing.
The only way to involve more than two Objects for logging is by putting those objects in an array and passing it as parameter to the logger.error method
Refer to
void error(String format,
           Object... arguments)
method on the page


text:
Q: XML response of a fetch http-request access denied Im trying to fetch (get) content from a site.
When I manually enter the Url in my browser (HTTP-Request) I get the Response as a XML in my browser.
But when I try to fetch the exact same url in my code like this:
       const response = await fetch(url);
        const myResult = await response.text();
        console.log(myResult);

I get this printed out:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>

<title>403 - Forbidden: Access is denied.</title>

Server Error

<fieldset>

403 - Forbidden: Access is denied.

You do not have permission to view this directory or page using the credentials that you supplied.

 </fieldset>

So I get access denied when fetching in my code, but when I manually access the url, everything is showing correctly.
What is the reason for this and how can I fix it?


text:
Q: Could not load file or assembly 'JavaScript.Net.dll' or one of its dependencies All,
I am getting this error:

System.IO.FileNotFoundException: Could not load file or assembly
  JavaScript.Net.dll or one of its dependencies.

From:
https://github.com/JavascriptNet/Javascript.Net  , get test source.
Run:
win7,x64 ; vc++ 2008 to vc++ 2015, run error computer with net45.2,  run success computer with most all net (it is a development computer).
Problem:
Use fuslogvw.exe to get the msg, but I can't get the problem.
Best wishes.


text:
Q: Find the position of a specific number that appear first in the list [python] So I want to find a number that appears more than once in the list. I want the position of the first one.
Example: Say I want 3
     s = [1,2,3,4,5,3,9,8]  => s[2] appears first

A: def first_dup( seq ):
    # keep track of the positions
    seen = {}
    for pos,item in enumerate(seq):
        if item in seen:
            # saw it before, so its a duplicate
            return seen[item]
        else:
            # first time we see it, store the pos
            seen[item] = pos

A: A little bit ambiguous question.
If you just want to find index of first occurrence of specific element, you should use list.index() method:
index = s.index(3)

But if you

want to find a number that appears
  more than once in the list

in general (without element value given), seems you can

*

*either do simple O(N^2) search in array (check all elements of the list for each element, till duplication is found)

*or do sort, find duplicated element in sorted list and then find index of duplicated element in the original array with list.index() method - this will take O(N*log(N)) because of sort.

A: Unless I'm misunderstanding your question, this should do the trick:
s = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3]
for i in range(len(s)):
    if s.count(s[i]) > 1:
        return i

This should give you the index of the first occurrence of the first element that appears multiple times in the list
If this is not what you're after, please leave a comment and I'll edit the code.

A: The function below returns the index of the first appearance of a duplicate
def find_first_duplicate(num_list):
        track_list =[]
        index = 0
        for e in num_list:
            if(e not in track_list):
                track_list += [e]
            else: ## found!
                return index
            index += 1

A: This is another way of doing it..
If present, it will return the first index..
If there are no duplicates available, it will raise IndexError.
[s.index(_) for _ in s if s.count(_) > 1][0]

A: Yet another way of doing it:
from operator import countOf

def multindex(seq):
    """ find index of first value occurring more than once
        in a sequence, else raise ValueError if there aren't any
    """
    for i,v in enumerate(seq):
        if countOf(seq, v) > 1:
            return i
    else:
        raise ValueError

print 's[{}] is first value in the list occurring more than once'.format(multindex(s))
# s[2] is first value in the list occurring more than once

A: s.index(3)

will return 2, as you desire.
index will raise ValueError if the specified item is not in the list.


text:
Q: microcontroller slew rate I have to control some device which require minimum 40mV/uS as slew rate for ENABLE input. My mcu runs at 3.3V so the rise and fall should be faster than 82.5uS. This is correct? Does it matter the actual speed of MCU?

A: Yes, that's correct.  If you're comparing to datasheet rise time maybe it would be slightly better to use 2.6V for the calculation, as the rise times are spec'd at 10% - 90% voltage instead of the full 3.3V swing.
But it hardly matters here.  Any microcontroller should have faster edges than that.  You normally would only get in trouble with slowly rising lines, e.g. an RC delay circuit, or open-collector outputs, or if the enable input is shared with a lot of capacitance for some reason.  A microcontroller with its push-pull outputs should give a really nice signal.


text:
Q: Angular $http POST changes date format Following situation:
I have a form with an input[date] field. I transform the values by following code:
$scope.entity.date = $filter('date')($scope.entity.date, 'yyyy-MM-dd');

This correctly formats the date to e.g. 2015-10-27
When I submit the entity using $http.post angular seems to recognize this as date and reformats it to 2015-09-30T23:00:00.000Z. I am in Germany and we have GMT+1. So angular converts the date to GMT.
Is there any way to disable this behaviour?
Edit:
HTML-Code:
<form ng-submit="submit()">
  <input type="date" ng-model="entity.date" />
</form>

JS-Code:
$scope.submit = function() {
  $scope.entity.date = $filter('date')($scope.entity.date, 'yyyy-MM-dd');

  // when debugging this is the point where $scope.entity.date is 2015-10-27
  // so it is the format and date I expect

  $http({
    data: $scope.entity,
    method: POST,
    url: '/resource'
  })
    .success(function(data) {
      // do some stuff
    });

  // when looking into network traffic the request was sent with
  // 2015-09-30T23:00:00.000Z as value for $scope.entity.date
};

A: You're changing the model value on post. Since your input type is a date, it's getting changed back. This is not a good idea, since the actual form element will change values only after you post.
Any time you need to manipulate your object before saving it's a pretty idea to create a copy of the object. That way it'll behave the way you expect.
var entity = angular.copy($scope.entity);

Then post the local copy and you should be good.
 $http({
    data: entity,
    method: POST,
    url: '/resource'
  })


text:
Q: Orbit of the Earth - numerical methods leapfrog edit:
I get these plots now from earths orbit. However, total energy looks not right. Should it not be oscillating between 0?
Thanks again!

I am attempting this numerical methods homework exercise part b).
Orbit of the Earth
My goal is to modify my code from part a) so it returns kinetic and potential energy of earths orbit but I get this error:
(8.12).py:31: RuntimeWarning: overflow encountered in multiply
  z_vec[i+1,:]=z_vec[i,:] + h*f(z_half_step, t_vec[i])

My code for finding kinetic and potential energy of earths orbit is obviously wrong. My problem is that I don't know how to modify my code in a) to find potential and kinetic energy.
This is my code for a:
import matplotlib.pyplot as plt
import numpy as np
import scipy.integrate as spi

"""a"""

G = 6.6738*10**-11
M = 1.9891*10**30
h = 3600
y = 1.4710*10**11
vx = 3.0287*10**4

def LeapFrog(f, t_start, t_stop, z0, h):

    t_vec = np.arange(t_start, t_stop, h)
    n = len(t_vec)
    d = len(z0)
    z_vec = np.zeros((n, d))
    z_vec[0,:] = z0
    z_half_step=z_vec[0 , :] + (1/2)*h*f(z0,t_vec[0])

    for i in range(0, n - 1):
        z_vec[i+1,:]=z_vec[i,:] + h*f(z_half_step, t_vec[i])
        z_half_step += h*f(z_vec[i+1,:], t_vec[i])

    return t_vec, z_vec,

def f(z,t):   #dz/dt

    x=z[0]
    y=z[1]
    vx=z[2]
    vy=z[3]
    r=np.sqrt(x**2+y**2)

    dz=np.zeros(4)

    dz[0]=vx
    dz[1]=vy
    dz[2]=-G*M*x/r**3
    dz[3]=-G*M*y/r**3

    return dz

t_start = 0
t_stop = 24*365*h*5 #5 years
z0 = np.array([0,y,vx,0])
t_vec, z_vec = LeapFrog(f, t_start, t_stop, z0, h)

figure, ax = plt.subplots()

plt.title("Orbit of the Earth")
plt.plot(0,0,'yo', label = 'Sun positon')
plt.plot(z_vec[:,0],z_vec[:,1], 'g', markersize=1, label='Earth trajectory')
ax.set_aspect('equal')

ax.set(xlim=(-1.55*10**11, 1.55*10**11), ylim = (-1.55*10**11, 1.55*10**11))
a_circle = plt.Circle((0, 0), 1.4710*10**11, fill=False,color='r')
ax.add_artist(a_circle)
ax.set_aspect('equal')

legend = plt.legend(['Sun position','Earths 5-year trajectory','Perfect circle'],loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()

"""

We can see that the trajectory of the earth for 5 years is very slightly non-circular.

"""

For part b) I modified "dz2" and "dz[3]". Obviously it didn't work:
"""b"""

    m = 5.9722*10**24
    def f(z,t):   #dz/dt

        x=z[0]
        y=z[1]
        vx=z[2]
        vy=z[3]
        r=np.sqrt(x**2+y**2)

        dz=np.zeros(4)

        dz[0]=vx
        dz[1]=vy
        dz[2]=-G*M*m/r
        dz[3]=0.5*m*y**2

        return dz

    t_start = 0
    t_stop = 24*365*h*5 #5 years
    z0 = np.array([0,y,vx,0])
    LeapFrog(f, t_start, t_stop, z0, h)

Thanks

A: There should be no integration in part b), you use the result from part a) to compute the energies at each point.
    x,y,vx,vy = z_vec.T
    r = np.hypot(x,y)
    E_kin = 0.5*m*(vx**2+vy**2)
    E_pot = -G*M*m/r
    E = E_kin+E_pot
    plt.plot(t,E)


text:
Q: Can we ad-hoc distribute MAC App? I am very new in Mac app development. I noticed there is not much information how MAC apps are developed and distributed. I have basic questions.
Can we distribute/sell the Mac app build for (Mac app-store) directly to the customers?
Or can we use Mac App development tools to make App which we can distribute without app store?

A: I think that you can distribute applications for MacOSX (non iOS) without app store.

A: You can build and distribute your Mac application however you want.
If (and only if) you want to distribute through the App Store you need to pay Apple a cut for it, pay for a developer account, and follow the App Store rules, but you can still also distribute the application in any way you want beside that; the Mac App Store distribution deal isn't exclusive.

A: You can distribute Mac Apps without the Mac Store. However, if your app wants to use iCloud, you need to distribute it via the Mac App Store (or deliver an AdHoc distribution to hardware-registered Macs, limited to 100 developer machines per year). Only applications downloaded through the Mac App Store are allowed to access their iCloud container.
Also: you need to be a registered Mac App developer and sign your app if you wish that gatekeeper automatically opens your app (since Mountain Lion 10.8.). Otherwise users have to disable gatekeeper, change its settings or (first) launch the app via the context menu > open.


text:
Q: Given 3 elements, return the number of the element with a given class Given some HTML like this:
foo
bar
baz

What JavaScript will return the number of the element with the active class? For instance, if these were returned by an array like in: [].slice.call(document.getElementsByTagName('a'));, I would like to return the number 1, representing the second element in the array.
Here is what I have tried, it just keeps returning 1 and 2:
var tagCount = 0;
var tagArray = [].slice.call(document.getElementsByTagName('a'));
for (var a = 0; a < tagArray.length; a++) {
    while (tagArray.className[a] !== "active") {
        tagCount = tagCount + 1;
    }
}

I do not need all a tags, just those inside of another element.

A: You can use Array.prototype.indexOf.call, combined with querySelector and querySelectorAll:

var i = [].indexOf.call(document.querySelectorAll('a'), document.querySelector('a.active'));
console.log(i);
foo
bar
baz


text:
Q: Is it possible to write polymorphic Postgres functions using RECORD parameters? I want to write a PL/pgSQL function that can take records of different types, check the type of record provided, then do something with the record. Example:
CREATE FUNCTION polymorphic_input(arg_rec RECORD) RETURNS TEXT LANGUAGE plpgsql AS
$plpgsql$
BEGIN
  IF pg_typeof(arg_rec)::text = 'information_schema.tables' THEN
    RETURN (arg_rec::information_schema.tables).table_name;
  ELSIF pg_typeof(arg_rec)::text = 'information_schema.columns' THEN
    RETURN (arg_rec::information_schema.columns).column_name;
  ELSE
    RETURN 'unknown';
  END IF;
END;
$plpgsql$;

When you call the function with a row from the information_schema.tables table, it should return the name of the table and it does so when you call it like this:
-- this returns table name "pg_type"
SELECT polymorphic_input((SELECT t FROM information_schema.tables t WHERE table_name = 'pg_type' LIMIT 1));

When you call the function with a row from the information_schema.columns table, it should return the name of the column and it does so when you call it like this:
-- this returns column name "objsubid"
SELECT polymorphic_input((SELECT t FROM information_schema.columns t WHERE t.column_name = 'objsubid' LIMIT 1));

The problem is you CAN'T call the function twice in a row with different row types. For example, if you call it with a row from information_schema.columns it works, then when you call it with a row form information_schema.tables, you get an error like this:

type of parameter 1 (information_schema.tables) does not match that when preparing the plan (information_schema.columns)

The words "when preparing the plan" gave me a hint that Postgres is caching the plans, so I figured running DISCARD PLANS; before each call to the function would work, and indeed it does when you run this entire query:
DISCARD PLANS; SELECT polymorphic_input((SELECT t FROM information_schema.tables t WHERE table_name = 'pg_type' LIMIT 1));
DISCARD PLANS; SELECT polymorphic_input((SELECT t FROM information_schema.columns t WHERE t.column_name = 'objsubid' LIMIT 1));

Running DISCARD PLANS; seems like the nuclear option and would no doubt affect performance in a real-world scenario. After some experimentation, I saw that using the pg_typeof function is what forces the plans to be cached. We can rewrite the function to avoid pg_typeof by adding a parameter that specifies what record type to expect:
CREATE FUNCTION polymorphic_input2(arg_rec RECORD, arg_type text) RETURNS TEXT LANGUAGE plpgsql AS
$plpgsql$
BEGIN
  IF arg_type = 'tables' THEN
    RETURN (arg_rec::information_schema.tables).table_name;
  ELSIF arg_type = 'columns' THEN
    RETURN (arg_rec::information_schema.columns).column_name;
  ELSE
    RETURN 'unknown';
  END IF;
END;
$plpgsql$;

You can then call polymorphic_input2 multiple times in a row with different row types without error as follows:
-- no need for DISCARD PLANS here...these calls work fine.
SELECT polymorphic_input2((SELECT t FROM information_schema.tables t WHERE table_name = 'pg_type' LIMIT 1), 'tables');
SELECT polymorphic_input2((SELECT t FROM information_schema.columns t WHERE t.column_name = 'objsubid' LIMIT 1), 'columns');

The problem with polymorphic_input2 is that you have to manually give it a hint as to the type of the record to expect. My question: is it possible to implement a polymorphic function that can figure out the type of record passed to it, without the cached plan errors?
The docs mention the plan_cache_mode setting:

Prepared statements (either explicitly prepared or implicitly generated, for example by PL/pgSQL) can be executed using custom or generic plans. Custom plans are made afresh for each execution using its specific set of parameter values, while generic plans do not rely on the parameter values and can be re-used across executions....The allowed values are auto (the default), force_custom_plan and force_generic_plan...

I tried removing the error by running SET plan_cache_mode = force_custom_plan; but that didn't help (which is probably a bug because the docs imply it should force a custom plan in each call, but Postgres is still caching the plan and causing errors). Only DISCARD PLANS worked.
The docs on plan caching seem to recognize this issue and say:

The mutable nature of record variables presents another problem in this connection. When fields of a record variable are used in expressions or statements, the data types of the fields must not change from one call of the function to the next, since each expression will be analyzed using the data type that is present when the expression is first reached. EXECUTE can be used to get around this problem when necessary.

...and a little further down the docs indicate this shouldn't be happening:

Likewise, functions having polymorphic argument types have a separate statement cache for each combination of actual argument types they have been invoked for, so that data type differences do not cause unexpected failures.

This is further confirmed by the docs EXECUTE which say:

Also, there is no plan caching for commands executed via EXECUTE. Instead, the command is always planned each time the statement is run. Thus the command string can be dynamically created within the function to perform actions on different tables and columns.

So I tried another variant that tries to run pg_typeof via EXECUTE:
CREATE FUNCTION polymorphic_input3(arg_rec RECORD) RETURNS TEXT LANGUAGE plpgsql AS
$plpgsql$
DECLARE
  rec_type text;
BEGIN
  EXECUTE 'SELECT pg_typeof($1)' INTO rec_type USING arg_rec;
  IF rec_type = 'information_schema.tables' THEN
    RETURN (arg_rec::information_schema.tables).table_name;
  ELSIF rec_type = 'information_schema.columns' THEN
    RETURN (arg_rec::information_schema.columns).column_name;
  ELSE
    RETURN 'unknown';
  END IF;
END;
$plpgsql$;

...but that still produces the same error as the variant which calls pg_typeof directly.
My question once again: is it possible (in Postgres 14) to implement a polymorphic function that can figure out the type of record passed to it, without the cached plan errors?


text:
Q: Why does using Random() to setX() and setY() Certain devices make the view disappear? Not sure if this has been answered. I did definitley search as hard as I could, because I feel like someone else would have had this issue. Basically I am using random along with setX and setY to move a view around randomly onClick. This works perfectly on my device and I went ahead and released the app. Although my brother uses a different device and said that as soon as he clicks the button, the view disappears from the screen.
My guess, obviously, is that the setX and setY just moved it off the screen. Anyone know how to make the view move only within the parent layout? I also need to keep my current random method in tact as it is integral to the game.
Here is my code for the button movement:
Random r = new Random();
int buttonHeight;
int buttonWidth;
buttonHeight = btnCount.getHeight();
buttonWidth = btnCount.getWidth();
int xLeft = r.nextInt(480 - buttonHeight);
int yUp = r.nextInt(800 - buttonHeight);
int xRight = r.nextInt(480 + buttonHeight);
int yDown = r.nextInt(800 + buttonHeight);

btnCount.setX(xLeft);
btnCount.setX(xRight);
btnCount.setX(yUp);
btnCount.setX(xDown);

Any ideas?
Backwards Compatibility
I do see a lot of how to questions about this, but if you want to help out 2 for 1 question here, any ideas on how to do the same method above for pre-API 11? If not that's cool I can just look up the other questions and methods after this gets fixed.

A: I found that finding the width and height on the current layout, no matter the device, and then dividing those values by 3, then taking the value divided by 3 and creating an int variable which is then used along with buttonHeight and buttonWidth works great on all devices to keep the button within screen. I understand this is probably not an ideal fix, but it is a quick one. I am still open to other suggestions.
Thanks!

A: Save the main device height and width somewhere and do simple maths like:
maindeviceHeight - randomscaleheight
newDeviceHeight - ?

You should do the same for width.


text:
Q: How to make the browser download .csv file from a node / express application In my node /express app I have the following server-side file download function:
app.get('/download_playcards_export', function(req, res){

            var file = fs.createReadStream('/Users/eugene/Documents/dev/node/DataManager/PlayCards.csv');
            var stat = fs.statSync('/Users/eugene/Documents/dev/node/DataManager/PlayCards.csv');
            res.setHeader('Content-Length', stat.size);
            res.setHeader('Content-Type', 'text/csv');
            res.setHeader('Content-Disposition', 'attachment; filename=PlayCards.csv');
            file.pipe(res);
        }
    );

I can see the contents of my .csv file on the browser console:
$scope.exportPlaycardsData = function(){

                        $http.get('/download_playcards_export').success(function(response) {
                            console.log('success downloading playcards export  ' + response);
                        });
            }

But I am unable to make the browser just DOWNLOAD this file.
What can I do to fix this?


text:
Q: How to identify transfer functions in a time series regression forecasting model? I am trying to build a time series regression forecasting model for an outcome variable, in dollar amount, in terms of other predictors/input variables and autocorrelated errors.  This kind of model is also called dynamic regression model.  I need to learn how to identify transfer functions for each predictor and would love to hear from you about ways to do just that.

A: The classic approach, described in Box, Jenkins & Reinsell (4th ed, 2008) involves looking at the cross-correlation function and the various auto-correlation functions, and making a lot of subjective decisions about the orders and lags for the various terms. The approach works ok for a single predictor, but is not really suitable for multiple predictors.
An alternative approach, described in Pankratz (1991), involves fitting lagged regressions with AR errors and determining the appropriate rational lag structure from the fitted coefficients (also a relatively subjective process). Then refitting the entire model with the supposed lag structures and extracting the residuals. The order of the ARMA error process is determined from these residuals (using AIC for example). Then the final model is re-estimated. This approach works well for multiple predictors, and is considerably simpler to apply than the classic approach.
I wish I could say there was this neat automated procedure that did it all for you, but I can't. At least not yet.

A: Originally the idea of examining pre-whitened cross-correlations was suggested by Box and Jenkins. In 1981, Liu and Hanssens published( L.-M. Liu and D.M. Hanssens (1982). "Identification of Multiple-Input Transfer Function Models." Communications in Statistics A 11: 297-314.) a paper that suggested a common filter approach that would effectively deal with multiple inputs whose pre-whitened series exhibit cross-correlative structure. They even created a 2 input model data set to demonstrate their solution.
After we programmed that approach and then compared it to the Box-Jenkins pre-whitening approach iteratively implemented by us we decided to not to use either the Pankratz approach or the Liu-Hanssens approach.We would be glad to share the Liu-Hansens test data with you if you wish me to post it to the list.


text:
Q: C++ variadic template type filtering transformation Problem.
I am new to template metaprogramming and am unsure of how to implement
a type filtering transformation on a tuple where a type is produced when provided
with a filtering description. I believe the following code snippet demonstrates
the behaviour I want.
enum : int {
  INCLUDE,
  EXCLUDE
};

template <int filter_val, class T>
struct filter {
};

int
main() {

  struct A {};
  struct B {};
  struct C {};

  typedef std::tuple<filter<INCLUDE, A>,
                     filter<EXCLUDE, B>,
                     filter<INCLUDE, C>> filters;

  typedef filter_all<filters>::type filtered;

  static_assert(std::is_same<filtered,
                             std::tuple<A, C>
                            >::value,
                ":(");

  return 0;
}

What I've tried
To my knowledge, you cannot unpack more than 1 independent variadic templates so the way I thought about approaching the problem is to maintain two tuples during the recursive template specialization process where one of them represents where we are in the recursion while the other represents the so-far included T's.
template <template <class ...> class, class ...Unfiltered_Ts>
struct filter_all {
private:
  template <class Unfiltered_Ts_Tuple, class Included_Ts_Tuple>
  struct filter_all_impl;

  // CASE 1: Include T in the result
  template <
    template <int, class> class, int filter_val, class T, class ...Unfiltered_Ts_impl, // Unfiltered input
    template <class ...> class, class ...Included_Ts                                   // Result so far
  >
  struct filter_all_impl<std::tuple<filter<INCLUDE, T>,
                                    Unfiltered_Ts_impl...>,
                         std::tuple<Included_Ts...>> {
    typedef typename
      filter_all_impl<std::tuple<Unfiltered_Ts_impl...>,
                      std::tuple<Included_Ts..., T> // Append T to result
                     >::type type;
  };

  // CASE 2: Don't include T in the result
  template <
    template <int, class> class, int filter_val, class T, class ...Unfiltered_Ts_impl, // Unfiltered input
    template <class ...> class, class ...Included_Ts                                   // Result so far
  >
  struct filter_all_impl<std::tuple<filter<EXCLUDE, T>,
                                    Unfiltered_Ts_impl...>,
                         std::tuple<Included_Ts...>
                        > {
    typedef typename
      filter_all_impl<std::tuple<Unfiltered_Ts_impl...>,
                      std::tuple<Included_Ts...> // Don't append T to result
                     >::type type;
  };

  // CASE 3: Filtering finished - set the final type as the included T's
  template <
    template <int, class> class, int filter_val, class T, class ...Unfiltered_Ts_impl,
    template <class ...> class, class ...Included_Ts
  >
  struct filter_all_impl<<>, // empty
                         std::tuple<Included_Ts...>
                        > {
    // Final step, set type as a tuple of all included Ts
    typedef std::tuple<Included_Ts...> type;
  };
public:
  typedef typename filter_all_impl<
    std::tuple<Unfiltered_Ts...>, // Initially contains all unfiltered Ts
    std::tuple<>                  // Initially empty filtered Ts which eventually becomes the return type
  >::type type;
};

I hope there is a simpler way to do this transformation but this is what I have arrived at so far but it's far from compiling and complains about the template specializations not being valid. Any guidance is appreciated.

A: Firstly, define a pick<T> helper that returns an empty tuple for excluded items, and a tuple containing the item otherwise:
template <typename>
struct pick;

template <typename T>
struct pick<filter<INCLUDE, T>> { using type = std::tuple<T>; };

template <typename T>
struct pick<filter<EXCLUDE, T>> { using type = std::tuple<>; };

Then, implement your filtering logic in terms of std::tuple_cat:
template <typename>
struct filter_all;

template <typename... Ts>
struct filter_all<std::tuple<Ts...>>
{
    using type = decltype(std::tuple_cat(typename pick<Ts>::type{}...));
};

Done!
live example on wandbox.org

If you can modify the implementation of filter to expose a constexpr bool, it can be even simpler:
template <int filter_val, class T>
struct filter
{
    static constexpr bool pick = filter_val == INCLUDE;
    using type = T;
};

template <typename T>
struct filter_all;

template <typename... Ts>
struct filter_all<std::tuple<Ts...>>
{
    using type = decltype(std::tuple_cat(
        std::conditional_t<Ts::pick,
            std::tuple<typename Ts::type>, std::tuple<>>{}...
    ));
};

live example on wandbox.org


text:
Q: Python v2 convert scientific notation from string to float - values are changing I'm using Python 2.7.11 and I have a text file with x,y,z values that represent values from a raster (lon, lat, value).
I'm trying to import this file into a numpy array so I can continue processing it with an existing set of python code, however I'm getting issues when converting from string to scientific notation.
x,y,z = [], [], []
f = open(xyz_file, 'r')

for l in f:
    row = l.split()
    x.append(row[0])
    y.append(row[1])
    z.append(row[2])

This results in the z list containing strings in scientific notation:
['8.23984e+05',
 '3.85186e-34',
 '2.31061e+06',
 '0.00000e+00',
 '9.86076e-32',
 '0.00000e+00', etc.

The min-max values on this list are:
-1.00000e+00
nan

If I create the array, I get an error:
A = np.array((x, y, z), dtype=float)

ValueError                                Traceback (most recent call last)
<ipython-input-7-3e00a73369e4> in <module>()
----> 1 A = np.array((x, y, z))

ValueError: setting an array element with a sequence

I thought there may be a problem with the scientific notation being strings, so I converted them:
z3 = []
rows = len(z)
for i in range(0, rows):
    val = float(z[i])
    z3.append(val)

The min-max values on this list are now, which are different from above:
-3.40281e+38
3.40282e+38

I checked if removing the 'nan' values would help and initially the min-max values were:
z2 = [x for x in z if str(x) != 'nan']

-1.00000e+00
9.99999e-34

When I then convert this list to float, I get the same wrong min-max values:
z4 = []
rows2 = len(z2)
for i in range(0, rows2):
    val = float(z2[i])
    z4.append(val)

-3.40281e+38
3.40282e+38

Can anyone explain why the values are changing when I convert from string to float?


text:
Q: Different representations of one resource When i have a resource, let's say customers/3 which returns the customer object and i want to return this object with different fields, or some other changes (for example let's say i need to have include in customer object also his latest purchase (for the sake of speed i dont want to do 2 different queries)).
As i see it my options are:

*

*customers/3/with-latest-purchase

*customers/3?display=with-latest-purchase
In the first option there is distinct URI for the new representation, but is this REALLY needed? Also how do i tell the client that this URI exist?
In the second option there is GET parameter telling the server what kind of representation to return. The URI parameters can be explained through OPTIONS method and it is easier to tell client where to look for the data as all the representations are all in one place.
So my question is which of these is better (more RESTful) and/or is there some better way to do this that i do not know about?

A: I think what is best is to define atomic, indivisible service objects, e.g. customer and customer-latest-purchase, nice, clean, simple.  Then if the client wants a customer with his latest purchases, they invoke both service calls, instead of jamming it all in one with funky parameters.
Different representations of an object is OK in Java through interfaces but I think it is a bad idea for REST because it compromises its simplicity.

A: There is a misconception that making query parameters look like file paths is more RESTful. The query portion of the address is included when determining a distinct URI so the second option is fine.
Is there much of a performance hit in including the latest purchase data in all customer GET requests? If not, the simplest thing would be to do that so there would neither be weird URL params or double requests. If getting the latest order is a significant hardship (which it probably shouldn't be) there is nothing wrong with adding a flag in the query string to include it.


text:
Q: Discussion Board - categories I ran into a situation where user created a discussion board with "categories" and they have views created to display the respective categories. So far so good. BUT seems like when a user responds to a discussion (on a flat view[/flat.aspx page]) it does not pick the "category". So when people go to any particular view it shows the discussion and the number of replies (see below). Once you click the discussion to see the replies - it's empty. With a bit of digging (editing the reply) I noticed "reply" does not store the Category information - hence being filtered out.
If I create a new view without any Filter, replies can be seen. Is this behaviour normal? if so what's the point of creating "categories"? I see people create Categories quite often. Here is an example of adding Categories to a discussion board. 2nd one here.
Any feedback would be greatly appreciated!


text:
Q: I have a table in excel 2007 and i want to get a chart I have a table in excel 2007 and i want to get a chart.
Here is my code:
Range("A2:P15").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'list'!$A$2:$P$15")
ActiveChart.ChartType = xlLineStacked
ActiveChart.SetSourceData

The beginning of the table is "A2" but the end is not the same every time.
I can't find a solution so please help me.
Thank you ;)

A: If you want to select all of the cells in a sheet from a specific start point (set to A2 in my code below) then I usually use a LastRow and LastCol function for this. There are lots of different ways to get the last row / column, I have included what I normally use.
I have also added to your code and put this inside a procedure named Main. This loops through each sheet in the workbook and gets the range as described above and then goes into the code that you posted. As I do not have the data in your sheets I have not been able to test the code for the charts itself:
Sub main()
    Const cStartCell As String = "A2"
    Dim vLastRow As Long, vLastCol As String
    Dim vRange As Range
    Dim vSheet As Worksheet

    For Each vSheet In Application.ActiveWorkbook.Sheets
        vLastRow = LastRow(vSheet.Name)
        vLastCol = LastCol(vSheet.Name)
        Set vRange = vSheet.Range(cStartCell & ":" & vLastCol & vLastRow)
        Debug.Print "Sheet " & vSheet.Name & ", vRange set to address range: " & vRange.Address()

        vSheet.Shapes.AddChart.Select
        ActiveChart.SetSourceData Source:=Range(vRange)
        ActiveChart.ChartType = xlLineStacked
        ActiveChart.SetSourceData (vRange)
    Next vSheet
End Sub

Function LastRow(pSheet As String)
On Error GoTo LastRow_err

    LastRow = Sheets(pSheet).UsedRange.Rows.Count

LastRow_exit:
    Exit Function

LastRow_err:
    Debug.Print "Error in LastRow function", vbCrLf, "Err no: ", _
                Err.Number, vbCrLf, "Err Description: ", Err.Description

End Function

Function LastCol(pSheet As String)
On Error GoTo LastCol_err

    LastCol = ColNoToLetter(Sheets(pSheet).UsedRange.Columns.Count)

LastCol_exit:
    Exit Function

LastCol_err:
    Debug.Print "Error in LastCol function", vbCrLf, "Err no: ", _
                Err.Number, vbCrLf, "Err Description: ", Err.Description

End Function

Function ColNoToLetter(pColNo As Integer)
On Error GoTo ColNoToLetter_err
' Goes from currently active cell and finds the next available row

    ' Local constants / variables
    Const cProcName = "ColNoToLetter"
    Dim vNumberOne As Integer
    Dim vNumberTwo As Integer
    Dim vLetterOne As String
    Dim vLetterTwo As String

    vNumberOne = 0
    vNumberTwo = 0
    vLetterOne = Empty
    vLetterTwo = Empty

    vNumberOne = Int((pColNo - 1) / 26)
    vNumberTwo = pColNo - (vNumberOne * 26)
    vLetterTwo = Chr(vNumberTwo + 64)

    If vNumberOne >= 1 Then
        vLetterOne = Chr(vNumberOne + 64)
    End If

    ColNoToLetter = vLetterOne & vLetterTwo

ColNoToLetter_exit:
    Exit Function

ColNoToLetter_err:
    Debug.Print "Error in ColNoToLetter function", vbCrLf, "Err no: ", _
                Err.Number, vbCrLf, "Err Description: ", Err.Description
    Resume Next

End Function

Let me know if you have any questions about how the code works etc.


text:
Q: Can I Use ASP.NET Wizard Control to Insert Data into Multiple Tables? I have an ASP.NET 3.5 webforms project written in VB that involves a multi-table SQL Server insert.  That is, I want the customer to input all their contact information, order details etc. into one control (thinking wizard control).  Then, I want to call a stored procedure that does the insert into the respective database tables.
I'm familiar and comfortable with the ASP.NET wizard control.  However, all the examples I've seen in my searches pertain to inserting data into one table.
Questions:
1.  Given a typical order process - customer information, order information, order details - should a wizard control be used to insert data into multiple database tables?  If not, what controls/workflow do you suggest?
2.  I've set primary keys and indexes on my order details, orders and customers tables.  Is there special stored procedure syntax to use to ensure that referential integrity is maintained through the insert process?
Thanks,
Sid

A: Referential integrity doesn't depend on "stored procedure syntax", it depends on how you have the keys/constraints/etc. defined on the database objects themselves. That's really the beauty of referential integrity. It doesn't matter how the insert/update is occurring (i.e. via stored procedure, call from a C#/JAVA program, etc.), the referential integrity will ensure that the integrity of the data is preserved.
To preserve proper parent child relationships between your tables, what you want to use are foreign keys. For example, a foreign key for an order to order_details table might be from order_details->order_num to it's parent table (order->order_num). This relationship would ensure that no order record can be deleted if it has associated order_detail records.
As far as the best way to do the updates (via wizard, etc.) I think the main thing is to stick with stored procedures as much as possible. The high level mechanism you use (a wizard in your example) isn't as important, but by using a stored procedure you encapsulate the database logic in the proper place, and plus, it can be reused later by other applications if need be.


text:
Q: Find duplicate rows in 2 fields? Can you teach me how to find duplicate or same values in different rows?
SELECT * FROM `geoname`

Now I need to compare these rows for duplicates:
WHERE `feature code` = 'ADM1'

WHERE `feature code` = 'ADM2'

UPDATE.
Column NAME contains names that can be duplicates. I wanna find ones?

A: To get a count of the occurrences of these two feature codes you can try conditional aggregation:
SELECT SUM(CASE WHEN `feature code` = 'ADM1' THEN 1 ELSE 0 END) AS adm1count,
       SUM(CASE WHEN `feature code` = 'ADM2' THEN 1 ELSE 0 END) AS adm2count
FROM yourTable

Update: If you want to find out which names occur in duplicate then you can try:
SELECT NAME
FROM yourTable
GROUP BY NAME
HAVING COUNT(*) > 1

A: SELECT geo.*,count(*) as Duplicate_Count
   FROM dbo.geoname AS geo
   having count(*) > 1
   group by geo.*
WHERE `feature code` = 'ADM1' OR `feature code` = 'ADM2'

This Query will return record with its duplicate count,how many times duplication occurred.


text:
Q: Flutter Android sdk is missing command line tools I added the steps provided by docs.
I also added Android SDK to the environmental variable but it's still remaining an issue.
I also tried these steps but it didn't work.

Also asked on https://github.com/flutter/flutter/issues/19805

A: Please try adding
G:\sdk\tools and G:\sdk\platform-tools to the PATH environment variable.

A: For MAC:
AndroidStudio -> Preferences -> Appearance & Behavior -> System Settings ->
Android SDK

*

*choose the SDK Tools Segment

*Check the Android SDK Command-line tool (latest)

A: See if it is configured this way in "Project Structure"

It worked for me

A: It is little confusing.
ANDROID_HOME location is not C:\Program Files\Android\Android Studio
ANDROID_HOME location is     C:\Users\username\AppData\Local
restart command prompt or Power Shell
re-check flutter doctor

A: I was using Windows 10 and I encounter this issue. I had tried ANDROID_HOME to my path but it was not working because I was forget to add tools and build-tools in path variable.
try this Open Edit the system Environment Setting(Search in Windows search).

*

*Click on Environments Variable -> Create New variable -> Variable
Name ANDROID_HOME and path your SDK path.

*Double Tap on PATH or Edit it Add platform-tools,build-tools,tools (All folders are in Your SDK path)

Reopen Terminal and type Flutter Doctor
Done

A: Open Android studio, then go to appearance and behavior > system settings > android sdk. Then choose SDK Tools instead of the standard SDK Platforms guide. Then choose Android SDK Command-line tools (latest).


text:
Q: Make bootstrap columns fill screen width in grid Here is a link to some bootstrap code
In the demo you can see the cells resize and stack nicely (use full screen for best effect).
However, the cells don't fill up the entire screen width!!
How do I have an identical setup, only the cells always cover the entirety of the screen horizontally??

A: Replace main wrapper class from container to container-fluid and it will fill to width:100%

A: Just remove the container div tag or add container-fluid instead of container

Box 1

Box 2

Box 3

Box 4

Box 5

Box 6

Box 7

Box 8

Box 9

Box 10

Box 11

Box 12


text:
Q: How do I check if a time is between 9am yesterday and 9 am today in Ruby? I'm very new to Ruby and I don't understand the answer to How can i check whether the current time in between tonight 9pm and 9am(tomorrow) in Ruby on Rails.
I have a time and I want to see if it is between 9am the day before and 9am today - how do I do that?
I've tried using that answer, but I'm not sure if I did it correctly-
updated_at = #some time that I access

if (0..8).cover? updated_at.hour
  a = updated_at - 1.day
else
  a = updated_at
end

start = Time.new updated_at.year, updated_at.month, updated_at.day, 9, 0, 0
b = a + 1.day
stop = Time.new b.year, b.month, b.day, 9, 0, 0

puts (start..stop).cover? updated_at

A: This will determine if the current time is in between 9pm and 9am:
time = Time.now
time.hour > 20 or time.hour < 9

For example:
time = Time.now
#=> 2016-08-01 20:23:32 +0000
time.hour > 20 or time.hour < 9
#=> false

A: yesterday_at_nine = Time.parse('9:00') - 1.day
today_at_nine = Time.parse('9:00')
now = Time.now

(yesterday_at_nine..today_at_nine).cover? now


text:
Q: Service and activity communication I am making a IM client for android and i want to know how to do the communication between a Service and Activity.
I have a Service that establish the connection to gtalk, gets the contacts, listens for the incoming messages... , and i have the activity that is the UI of my application.
In the activity i create the service and bind the activity to it. I have an aidl interface to communicate between service and the activity with this methods:
  String[] getContacts();
    String[] getPressence();
    int setConnection(int type);
    void logOut();

So far so good, i can make the connection to gtalk, i can get the contacts and the status, but now i want to do a function in the activity that listens when the service gets a message and updates the UI...
For this i made another aidl file with the metod void receivedMessage(String message);
and whenever the service gets a message, i call that method, in the activity i display the message passed in the message String and i get an NullPointer exception.
Do i have to get the message in a handler or by some sync or async methods ? I am beginner in android and now i learn the services part so please help me .
Thank you very much!

A: I solved the problem, i only had to reference the listener from the activity, in order to the service to use the listener.


text:
Q: keyHolder.getKey() return null Why code from "Spring in action 5" don't work (keyHolder.getKey() return null, but entity is saved in DB)?
private long savePizzaInfo(Pizza pizza) {
    pizza.setCreatedAt(new Date());
    PreparedStatementCreator psc =
            new PreparedStatementCreatorFactory(
                    "insert into PIZZA (name, createdAt) values (?, ?)",
                    Types.VARCHAR, Types.TIMESTAMP
            ).newPreparedStatementCreator(
                    Arrays.asList(
                            pizza.getName(),
                            new Timestamp(pizza.getCreatedAt().getTime())));
    KeyHolder keyHolder = new GeneratedKeyHolder();
    template.update(psc, keyHolder);
    return keyHolder.getKey().longValue();
}

My DB Table:
CREATE TABLE PIZZA
(
ID bigint DEFAULT (NEXT VALUE FOR
PUBLIC.SYSTEM_SEQUENCE_12CA966F_4FFD_469C_BA69_80BB93916EF3) AUTO_INCREMENT
PRIMARY KEY NOT NULL,
NAME varchar(50) NOT NULL,
CREATEDAT timestamp NOT NULL
);
CREATE UNIQUE INDEX PRIMARY_KEY_4 ON PIZZA (ID);

A: You need to specify your prepared statement
notice the Statement.RETURN_GENERATED_KEYS in the code bellow
you need something like this
final PreparedStatementCreator psc = new PreparedStatementCreator() {
      @Override
      public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException {
        final PreparedStatement ps = connection.prepareStatement("INSERT INTO `names` (`name`) VALUES (?)",
            Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, name);
        return ps;
      }
    };

A: You have to instruct PreparedStatementCreatorFactory instance to return the generated keys:
PreparedStatementCreatorFactory preparedStatementCreatorFactory = new PreparedStatementCreatorFactory(
         "insert into PIZZA (name, createdAt) values (?, ?)",
         Types.VARCHAR, Types.TIMESTAMP
 );

// By default, returnGeneratedKeys = false so change it to true
preparedStatementCreatorFactory.setReturnGeneratedKeys(true);

 PreparedStatementCreator psc =
         preparedStatementCreatorFactory.newPreparedStatementCreator(
                    Arrays.asList(
                            pizza.getName(),
                            new Timestamp(pizza.getCreatedAt().getTime())));

A: Why not use SimpleJdbcInsert instead?
dbcInsert = new SimpleJdbcInsert(jdbcTemplate);
        jdbcInsert.withTableName("TABLE_NAME").usingGeneratedKeyColumns(
                "Primary_key");
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("Column_NAME1", bean.getval1());
        parameters.put("Column_NAME2", bean.getval2());
        // execute insert
        Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(
                parameters));
           // convert Number to Int using ((Number) key).intValue()
            return ((Number) key).intValue();


text:
Q: Who is "quiet" when there is no comma? A stanza from Leslie Norris' poem The Tiger:

He stalks in his vivid stripes
The few steps of his cage,
On pads of velvet quiet,
In his quiet rage.

Who does the quiet belong to-- the velvet or the tiger?


text:
Q: Limit user to perform an action a certain number of times in a day I am using Rails 3.1.0 with Devise 2.1.0. I would like to limit the number of times a user can perform an action in a day. The main purpose of this limitation is to prevent spam.
I see many questions similar to this one but was wondering if there is a specific way to accomplish what I am trying to do through Devise.
For the actions that create model instances, the number of times an action has been performed in a day is easy to keep track of. However, at least one action that I would like to restrict does not create a model instance, so I'm not sure what to do about it.
I was also wondering if this is a legitimate/effective way of preventing spam (in addition to requiring users to register and sign in to perform the actions).

A: Personally, I find these sorts of systems to be over-complications. Unless spam is an existing, provable problem I'm not sure adding in a system that's likely to be rather extensive is a good use of time and energy.
Alternatives to this would be requiring registration through a third-party service (say Facebook) and using either captchas or exciting and new negative captchas.
That said, if you want to do this, I think the best place to keep track of it would be in an ephemeral data store. Redis would be really good for this since you can use queues. In the actions that you want to restrict, add a timestamp to the queue, and before you allow the user to perform said action, check the number of elements in the queue, purging ones that are too old while you do so.
That's sort of pseudo-codey, but should at least help you get started.


text:
Q: Auto startup and shutdown of VMs in Hyper-V I want to be able to automate startup and shutdown of a Windows XP VM running under Hyper-V on Windows 2008.
The VM should only be available during office hours.  Its a standard Windows XP (SP3) installation.  So the VM should startup at 8am and shutdown at 6pm (regardless of any running applications) according to a schedule that I can easily configure.
I've looked at a batch job under the VM itself to shutdown,
(something like at 18:00 every M,T,W,Th,F shutdown /l/y/c)
but I can't work out how to get it to start up again - possibly something under Hyper-V could be used?
And it would be nice to control both startup and shutdown from the same place

A: You can use Hyper-v PowerShell library from Codeplex to create your own PowerShell script to save (suspend) and start guest machines within the required time with scheduled task.


text:
Q: .delegate() not binding to anchor elements tag I'm trying to use the delegate function and not succeeding, here is my html…

This is generated for me by SharePoint, there's a lot more in the table which may be a factor to my problem, please see here for the full listing. The html for the table (id onetidDoclibViewTbl0) is generated after the page has loaded; via an ajax call.
My attempt at using the delegate function...
$('#onetidDoclibViewTbl0').delegate('tr td.ms-vb-icon a', 'click', function(event)  {
    alert('document anchor clicked');
});

I even tried this which didn't work either
$('body').delegate('a', 'click', function() {
    alert('this really should work?');
});

A: Most of your links have an onclick attribute that has a return false;. This prevents the event from bubbling up the DOM, which the delegate method relies on to function correctly.

A: You're right... that really should work. I took your code and put it in a jsFiddle. That seems to be working fine. Perhaps it is related to the version of jQuery you are using? delegate was added relatively recently...
Also, the body element would need to exist at the point at which the code is run. You are probably best off doing as hunter suggested and wrapping it in a document ready callback.