text:
Q: Interpreting tail events and their "dependence" on finite r.v.'s Let $X_1,X_2...$ be random variables defined on the same sample space. Let $$\mathcal{F}_n = \sigma(X_n,X_{n+1}...), \mathcal{F} = \bigcap_n\mathcal{F_n}$$ where the latter is the tail $\sigma$-field.

I am trying to understand what we mean when we say that a tail event $A \in \mathcal{F}$ does not depend on any finite set $\{X_1...X_n\}$. From a previous answer, this is my "intuitive" understanding:
If $A \in \mathcal{F}$, then for all $n \in \mathbb{N}$, $A \in \mathcal{F_n}$. But since $\mathcal{F_n} \subset \mathcal{F_1}$, we see that "omitting" the first $n-1$ $X_i$'s does not affect our event being in $\mathcal{F}$. Thus, if we think about the $\sigma$-fields as "current knowledge" about our space, we see that this "current knowledge" is not "dependent" on $X_1 ... X_{n-1}$.
However, I am not sure how this can be made rigorous. In particular,
(i) is the term "dependent" being used here comparable to how we speak of independence of events and random variables? What is the mathematical definition of dependent here? Or is just "dependent" in an intuitive sense?
(ii) What justifies seeing the $\sigma$-field as our "current knowledge" about the space? I know that $\sigma(X_n,X_{n+1}...)$ is the collection of sets $[\omega \in \Omega : X(\omega) \in B]$, where $X = (X_n,X_{n+1}...)$ and $B$ is a Borel set in $\mathbb{R^{\mathbb{N}}} $. I suppose this is linked to the view of a $\sigma-$field as a set of events, but what do we mean by "current knowledge"
(iii) Finally, how can I view (i) and (ii) together? In math, what does it mean for our current knowledge -the $\sigma$-field $\sigma(X)$ - to not "depend" on $X_1...X_n$?

If it helps for you to explain, I suppose a helpful and simple example to think might be the event $\{\omega \in \Omega: \sum X_i(\omega) < \infty\}$  - I understand why this does not "depend" on the value that finitely many $X_i$ take from an analysis perspective, but now I am trying to understand it from this probability theory perspective.

A: One way of conceptualising events that foreground the "information" heuristic is thinking of a sample space $\Omega$ as all possible outcomes of a random experiment, and an event $A$ as a yes/no question about a realised outcome $\omega \in \Omega$.
Informallly, the question would be "is $\omega \in A$?"
A $\sigma$-algebra $\mathcal{F}$ can then be thought of as a set of yes/no questions about $\omega$ that we know the answer to assuming that we can synthesise a countable number of answers.
You can reconcile the $\sigma$-algebra axioms with this this intuitive description.
In this way, $\sigma(X_n)$ is the set of yes/no questions that we can answer about $\omega$ if we only know the value of $X_n(\omega)$.
Now, random processes $(X_1, X_2, \dotsc)$ are linearly structured.
That is, we usually think of observing a process not all at once, but at a specific time $n$, at which point we can observe "past" values $(X_1, \dotsc, X_n)$ but not "future" values $(X_{n+1}, X_{n+2}, \dotsc)$.
In this way, the $\sigma$-algebra $\mathcal{F}_n = \sigma(X_1, \dotsc, X_n)$ is the set of yes/no questions that can be answered if we know the values of the process $X$ up to time $n$.
But this is exactly what we would want in a definition of "current knowledge about $X$ at time $n$."
In this framework, phrases like "$\mathcal{F}_n$ doesn't depend on $X_{n+1}$" mean that the value of $X_{n+1}$ never influences the answer to any question in $\mathcal{F}_n$.
This has nothing to do with statistical dependence, as its perfectly possible (and  is the case in most non-trivial examples) that $X_{n+1}$ is not statistically independent of $\mathcal{F}_n$ - it's just that the word "depends" is unfortunately overloaded in statistics.
In the case of the tail $\sigma$-algebra, $\mathcal{F}$ is "the set of questions about the process $X$ whose answers are not influenced by any finite set of values $(X_1, \dotsc, X_n)$".
Another way of thinking about $\mathcal{F}$ is that it is the set of questions that we would be able to answer if we knew all of $X$, but can never answer by stepping forward linearly in time and observing the current information $\mathcal{F}_n$ at each time point $n$.

A: I think @Damian Pavlyshyn's answer is quite good already, but maybe I can rephrase things a little and add some more examples to help. Like Damian said, $\Omega$ can be thought of as all the outcomes of a certain experiment you're doing. For example, $\Omega$ is the set of all points on a dartboard, and the experiment you are performing is throwing a dart at the dartboard. Then, every $\omega\in \Omega$ can be identified with one trial of the experiment, namely the trial in which you get the outcome $\omega\in \Omega$.
Then, a random variable $X: \Omega \to \mathbb R$ can be thought of as some instrument that can measure the outcome of your experiment. For example, the dartboard could have rings of scores, like $100$ points for the center, $90$ points for close to the center, etc. and $X(\omega)$ could be this score. The $\sigma$-algebra $\mathscr B$ (normally Borel sets of course) on $\mathbb R$ represents all the questions you can ask about the measurement you receive from $X$. For example if $\mathscr B$ is $\{\varnothing, (-\infty, 0), [0,\infty), \mathbb R\}$, maybe you can think of this as the user-interface of the instrument $X$ is really bad and can only gives very coarse readings.
(Normally for the Borel sets $\mathscr B$, basically any question you can ask about the reading $X$ gives you is valid --- though you can't ask cursed questions like "is $X(\omega)$ in some Vitali set", for technical reasons. In fact actually if you abandon the Axiom of Choice you don't need to worry about these technicalities, and in fact are allowed to ask "any question".)
Then the pullback $\sigma$-algebra on $\Omega$, namely $\sigma(X)$, is just pulling back all questions "is $X(\omega) \in B$" to "did $X$ measure the outcome of the trial $\omega$ of the experiment to be in $B$". In other words, using $X$ to measure some facet of the outcomes of your experiment, you gained some information on the outcome of each trial of your experiment, and $\sigma(X)$ represents exactly all this information you've gained. For example, you know know the answer to "did this particular trial $\omega_0$ result in $X$ measuring at least $>90$ points", or "which trials of the experiment resulted in $X$ measuring $0$ points".
Now thinking about a random process, pretend like you are again running an experiment, with $\omega\in \Omega$ denoting each trial. Every day, you find a new instrument $X_i$ to measure your experiment with. So the first day, you now know the answers corresponding to $\sigma(X_1)$, and on the second day, you now know the answers corresponding to $\sigma(X_1,X_2)$, and so on. For example, by day 3, you know the answer to "which trials of the experiment result in all three measurements having $>90$ points", which corresponds to the set $\{\omega\in \Omega: X_1(\omega),X_2(\omega),X_3(\omega)\} \in \sigma(X_1,X_2,X_3)$. And then the probability $P(\{\omega\in \Omega: (X_1,X_2,X_3)(\omega) \in (B_1,B_2,B_3)\})$ is exactly the answer to "what fraction of the trials of my experiments resulted in measurements $X_i$ landing in $B_i$, for $i=1,2,3$" (the measure-theoretic approach to probability is indeed a "frequentist" approach).
In contrast, $\{\omega\in \Omega : X_4(\omega)=100\}$ is not $\sigma(X_1,X_2,X_3)$-measurable, because we literally have not measured $X_4$ yet, i.e. that information is not accessible from the day 3 information $\sigma(X_1,X_2,X_3)$, unless of course $X_4$ is completely determined by the results of $X_1,X_2,X_3$, i.e. $X_4=f(X_1,X_2,X_3)$ for some (measurable) function $f: \mathbb R^3 \to \mathbb R$.
So we see that $\mathscr F_N:=\mathscr F_{\leq N}:=\sigma(X_1,\ldots, X_N)$ is all the information we now know about all the trials of our experiment by day $N$. Similarly, $\mathscr F_{> N}:=\sigma(X_{N+1},\ldots)$ is all the information we know about the trials of our experiment if we only know the results of days $N+1, N+2$, through infinity. But we really only like using the words "current knowledge" to talk about "forward-time" processes like $\mathscr F_1,\mathscr F_2,\ldots$, since that matches our intuition of "learning new information as time passes".
Finally, we are ready to talk about the tail $\sigma$-algebra $\mathscr F:= \bigcap_{n=1}^\infty \mathscr F_n$. The key idea is this: the complete information you get by looking "with a birds-eye-view" at the totality of your experiment, namely $\sigma(X_1,X_2,\ldots, )$ (i.e. the information/questions you could answer if you knew $X_i(\omega)$ for every trial $\omega\in \Omega$ and every measurement $i\in \mathbb N^+$), is DIFFERENT from union of the information you learn at each finite day, namely $\bigcup_{n=1}^\infty \sigma(X_1,\ldots, X_n)$! For example, only knowing the union of all information from each finite day, you can never be sure that the sequence $\{X_i(\omega)\}_{i=1}^\infty$ converges (for given fixed $\omega\in \Omega$). But you WOULD know this information if you had the total/complete information $\sigma(X_1,X_2,\ldots, )$. The tail $\sigma$-algebra is exactly the difference $\sigma(X_1,X_2,\ldots, ) \smallsetminus \bigcup_{n=1}^\infty \sigma(X_1,\ldots, X_n)$, i.e. all information/questions you could answer if you knew the totality of EVERY measurement/trial altogether, but that you would not know on any given day $n$.
Another way of phrasing this: in this form of the original intersection definition, $S \in \mathscr F \iff S \in \mathscr F_{>n}$ for every $n\in \mathbb N^+$, so we see that $\mathscr F$ is all the information I am sure I can learn about any given trial $\omega\in \Omega$ of your experiment, if I were to ask you a question, and require that you tell me all the readings $X_i(\omega)$ except perhaps finitely many (that you are free to choose to not tell me for whatever reason, where this choice can depend on what question I ask).
That's all the theory. Now for some examples: above I said $S:=\{\omega\in \Omega: \lim_{n\to\infty} X_n(\omega) \text{ exists}\}$ is in the tail $\sigma$-algebra $\scr F$ (verify that this makes sense with respect to both interpretations of $\scr F$ above). More explicitly, observe that for any $n\in \mathbb N^+$,  $S = \{\omega\in \Omega: \text{the limit of } X_{n+1}(\omega), X_{n+2}(\omega), \ldots \text{ exists}\}$, where the RHS is clearly in $\scr F_{>n}$. Similarly for $S:=\{\omega\in \Omega: \lim_{n\to\infty} X_n(\omega) \text{ exists and equals }a\}$ for $a\in \mathbb R$, or $\{\omega\in \Omega: \lim_{n\to\infty} X_n(\omega) \text{ exists and lies in }B\}$ for Borel $B \in \scr B$.
On the other hand, defining $S_n:= X_1 + \ldots + X_n$,  $S:=\{\omega\in \Omega: \lim_{n\to\infty} S_n(\omega) \text{ exists}\}$ is in the tail $\sigma$-algebra for the same reason, BUT  $S:=\{\omega\in \Omega: \lim_{n\to\infty} S_n(\omega) \text{ exists and equals }a\}$ for $a\in \mathbb R$, or $\{\omega\in \Omega: \lim_{n\to\infty} S_n(\omega) \text{ exists and lies in }B\}$ for Borel $B \in \scr B$ are NOT in the tail $\sigma$-algebra, since the precise value of $X_1(\omega)$ has a huge impact on the ultimate value of the limit $\lim_{n\to\infty} S_n(\omega)$. In other words, if you only tell me the readings $X_2(\omega_0), X_3(\omega_0),\ldots$, I'll be able to tell if $\lim_{n\to\infty} S_n(\omega_0)$ converges, but I won't be able to know what exactly it converges to!
Finally, $S:=\{\omega\in \Omega: \lim_{n\to\infty} \frac{S_n}{n}(\omega) \text{ exists}\}$ or $\{\omega\in \Omega: \lim_{n\to\infty} \frac{S_n}{n}(\omega) \text{ exists and equals }a\}$ for $a\in \mathbb R$, or $\{\omega\in \Omega: \lim_{n\to\infty} \frac{S_n}{n}(\omega) \text{ exists and lies in }B\}$ for Borel $B \in \scr B$ are all in the tail $\sigma$-algebra. Exercise for the reader :)
Remark: this last example is VERY important, since it is crucially used in (some) proofs of the strong law of large numbers (SLLN).

A: Here's something that might help with intuition for (iii). The tail $\sigma$-field is characterized by a saturation property. An event $A\in \mathcal F$ is tail measurable if and only if for each $\omega\in A$, another element $\tilde\omega$ of the sample space lies in $A$ if and only if $X_n(\omega)=X_n(\tilde\omega)$ for all sufficiently large $n$ (i.e. for all $n\ge n_0(\omega,\tilde\omega)$).


text:
Q: Application bar-style of automatic icon coloring elsewhere in WP7? When I add an icon button to the application bar the system takes care of displaying the icon in white if the dark theme is in use and displaying the icon in black if the light theme is in use.  Can I use this automatic coloring elsewhere in my application?  I would like to take an icon image from the SDK directory and use it on a normal button, and it would be great if I could get the system to display either white or black depending on the theme.  For now I'm doing it manually using a converter but if there's a way to automatically do it that would be cleaner.  Does anyone know of a way?

A: <Button Background="{StaticResource PhoneContrastBackgroundBrush}" >
   <Button.OpacityMask>
      <ImageBrush ImageSource="/Images/icon.png"/>
   </Button.OpacityMask>
</Button>

icon.png must be white
[EDIT]
OR (Draw a circle around them) using SDK image (appbar.basecircle.rest.png)
<Style x:Key="FlatStyle" TargetType="Button">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/>
            <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
            <Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/>
            <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/>
            <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
            <Setter Property="Padding" Value="10,3,10,5"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Grid Background="Transparent">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="MouseOver"/>
                                    <VisualState x:Name="Pressed">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneBackgroundBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">
                                <Grid>
                                    <Canvas Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
                                        <Rectangle Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Fill="{StaticResource PhoneForegroundBrush}">
                                            <Rectangle.OpacityMask>
                                                <ImageBrush ImageSource="/appbar.basecircle.rest.png"/>
                                            </Rectangle.OpacityMask>
                                        </Rectangle>
                                        <Rectangle Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Fill="{StaticResource PhoneForegroundBrush}" OpacityMask="{TemplateBinding BorderBrush}"/>
                                    </Canvas>
                                    <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                </Grid>

                            </Border>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

Usage:
<Button Style="{StaticResource FlatStyle}" BorderThickness="0" Width="48" Height="48">
                <Button.BorderBrush>
                    <ImageBrush ImageSource="/appbar.favs.rest.png"/>
                </Button.BorderBrush>
            </Button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: In dotnet mvc 5, how to inject a service into a view? In dotnet core mvc,i can inject a service into a view by using @inject directive,but how to do this in dotnet mvc 5.It seems that there is no @inject directive in mvc 5.

A: ASP.NET MVC 5 doesn't have @inject
This keyword only exists in ASP.NET Core.
Work-around using @model
However you can still inject a dependency in the controller and from the controller pass it to the model. @model and @Model can be used freely in the razor page/view.
MyController.cs:
public class MyController : Controller
{
    public MyController(IMyDependency dependency)
    {
        _dependency = dependency;
    }

    public ActionResult Index()
    {
        View(new ViewModel
        {
            Dependency = _dependency
        });
    }
}

Razor.cshtml:
@model ViewModel

@if (Model.Dependency.CanView)
{
    <!-- Put the code here -->
}

It also means you can put a IServiceProvider in the model and resolve directly in the view. However, in terms of separation of concerns, it's not the ideal.


text:
Q: fragment reloading after exiting the activity in android I have been working on an application where i have a fragment which communicates with an activity.
In that communication i have applied shared element transition and so far it works however the problem arises when i exit the activity and return to fragment after two seconds the fragments starts reloading i tried searching for a possible solution but couldnt find the reason for that so i was hoping if someone could help me out here.
Update: As i Have used shared element transition for animation and i noticed that without transition on back press the fragment isn't recreated and it works fine however with animation it is recreated again after few seconds.
Here is my fragment code
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_feed, container, false);
        getActivity().getWindow().setExitTransition(null);
        setRetainInstance(true);
        toolbar = (Toolbar)view.findViewById(R.id.toolbar);
        // ((MainActivity)getActivity()).setSupportActionBar(toolbar);
        feed_recycler_view = (RecyclerView)view.findViewById(R.id.feed_recycler_view);
        //ViewCompat.setNestedScrollingEnabled(feed_recycler_view, false  );
        CustomTextView customTextView = (CustomTextView)toolbar.findViewById(R.id.toolbar_title);

        feed_layout_manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
        feed_recycler_view.setLayoutManager(feed_layout_manager);
        //feed_recycler_view.setNestedScrollingEnabled(false);
        feed_recycler_view.setHasFixedSize(true);
        feed_adapter = new FeedAdapter(FeedUtils.generateFeeds(getContext()),this);
        feed_recycler_view.setAdapter(feed_adapter);
        return view;
    }

    public static FeedFragment newInstance() {
        FeedFragment fragment = new FeedFragment();
        return fragment;
    }

    public static void applyFont(CustomTextView tv, Activity context) {
        tv.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Quicksand-Medium.ttf"));
    }
    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onFeedItemClick(int pos, Feed_Data_Provider feedDataProvider, AppCompatImageView shareImageView) {
        Intent intent = new Intent(getContext(), ChatActivity.class);
        intent.putExtra(EXTRA_FEED_ITEM, feedDataProvider);
        intent.putExtra(EXTRA_FEED_IMAGE_TRANSITION_NAME, ViewCompat.getTransitionName(shareImageView));

        ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(
                getActivity(),
                shareImageView,
                ViewCompat.getTransitionName(shareImageView));

        startActivity(intent, options.toBundle());
    }
}

And here is the activity class
public class ChatActivity extends AppCompatActivity {
        AppCompatImageView chat_image;
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        getWindow().setEnterTransition(null);
        Bundle extras = getIntent().getExtras();
        Feed_Data_Provider feedItem = extras.getParcelable(FeedFragment.EXTRA_FEED_ITEM);
        chat_image = (AppCompatImageView)findViewById(R.id.chat_image);
        postponeEnterTransition();
        int imageUrl =feedItem.getClub_image();
        supportPostponeEnterTransition();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            String imageTransitionName = extras.getString(FeedFragment.EXTRA_FEED_IMAGE_TRANSITION_NAME);
            if (imageTransitionName != null) {
                chat_image.setTransitionName(imageTransitionName);
            }
        }
        Glide.with(this)
                .load(imageUrl)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        supportStartPostponedEnterTransition();
                        return false;

                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        supportStartPostponedEnterTransition();
                        return false;
                    }
                })
                .into(chat_image);

    }

}


text:
Q: Why does my modal keeps popping up even if there is no input errors? I am currently using HTML/CSS/JS and Materialize CSS for a webpage. The problem I am having is getting the Materialize CSS modal to show up at appropriate times such as when an user made an error. In my current case, it is a modal that pop ups to tell the user that they need to make a valid input.
My page works when I enter valid inputs from the beginning until I test it with an empty input. The modal will show up for an empty input, but after that, the modal keeps popping up even when I enter a valid input, which means my other functions will not also run.
Here is my current HTML:

   <form class="input-field col s12 m4 offset-m4" id="form">
       <input type="text" class="autocomplete white-text" id="pokemon-input">
       Pokemon
       <button data-target="modal1" class="btn modal-trigger" type="submit">Submit</button>
   </form>

Modal Header

A bunch of text

           Agree

Here is my current JavaScript:

var pokemonInput = $("#pokemon-input");
var formEl = $("#form");

formEl.submit(function (event) {
    event.preventDefault();
    var search = pokemonInput.val().split(" ")[0].trim().toLowerCase()
    console.log(search);
    console.log(typeof search);

    if (search !== "") {
      getPokemon(search);
    } else {
      $("#modal1").modal();
    }
  });

I tried using an if and else statement, and also the switch statements, but both have the same problem.
Feels like it is more of a JS problem, but maybe it could be a HTML problem too. I don't think it has anything to do with my other JS functions since those functions still work .
I basically expect the modal to show up only whenever there is an invalid input. Furthermore, the modal should not show up every time I give a valid input.


text:
Q: How do get a strongly typed single value using LINQ I am using LINQ to interact with data in a DataSet in a C#.NET program. The data is imported into the data set from an XML file so that is where it gets it's schema. I want to be able to grab a single row from the table and then access the specific columns of that row in a strongly-typed manner (with intelli-sense). I think I am close on the syntax but I can't quite get it. Here's what I have so far...
// RunnerDataTable contains columns named FirstName, LastName, etc.
   var OneRunner = RunnerDataTable().Single( p => p.Field<string>("FirstName") == "Jordan");
   MessageBox.Show(OneRunner.LastName);  // This doesn't work

This example does work but I would like to do it without the foreach loop...
var SomeRunners= from f in RunnerDataTable.AsEnumerable()
                                where f.Field<string>("FirstName") == "Jordan"
                                select new { FirstName = f.Field<string>("FirstName"), LastName = f.Field<string>("LastName")};
foreach (var o in SomeRunners)
{
    MessageBox.Show(o.FirstName + " " + o.LastName);
}

Any ideas?

A: var OneRunner = (from f in RunnerDataTable.AsEnumerable()
                 where f.Field<string>("FirstName") == "Jordan"
                 select new { FirstName = f.Field<string>("FirstName"),
                              LastName = f.Field<string>("LastName")}
                 ).SingleOrDefault();

Wrap in parens and add SingleOrDefault()

A: If I get your question correctly, then:
var OneRunner = (
  from f in RunnerDataTable.AsEnumerable()
  where f.Field<string>("FirstName") == "Jordan"
  select new
    {
       FirstName = f.Field<string>("FirstName"),
       LastName = f.Field<string>("LastName")
    }
 ).Single();


text:
Q: Postgresql stored procedure execution error in VBA I am trying to execute a Postgresql stored procedure in Excel VBA, but I am getting the following error:

duplicatefilechecksp is procedure(); error while executing the query.

Can someone assist me to fix the issue?
PFB code :
Dim conSQL          As New ADODB.Connection
Dim cmd             As New ADODB.Command
Dim Rs              As New ADODB.Recordset
Dim strErrDescSP    As String               ' Set Error Description of SP

With cmd
    .ActiveConnection = mod_General.RecturnMSSQLCon
    .CommandType = adCmdStoredProc
    .CommandText = "duplicatefilechecksp_test"
    .Execute
End With

A: In Postgres the driver was written this way because in the past, PostgreSQL did not support procedures.
To workaround this problem and execute it as a procedure, can set CommandType to adCmdText, and set CommandText to "CALL duplicatefilechecksp(?, ?, ?)", with one question mark per parameter.


text:
Q: AttributeError: 'module' object has no attribute 'DMatrix I tried all possible solution, but still getting this error, already installed all dependent libraries.
import numpy as np
import pandas as pd

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder

from tqdm import tqdm
import xgboost as xgb

d_train = xgb.DMatrix(X_train, label=y_train)
AttributeError: 'module' object has no attribute 'DMatrix'

A: You can force upgrade of XGBoost with:
python -m pip install xgboost --user --upgrade pip

This fixed it for me.


text:
Q: how to get a string for a class property name in dart? i want to do use the model's properties such as:
Animal.id as a param to a function or use some extension method to be able to "id". similarly, i'd like to use Animal.title in that way to get "title" as a returned value. how could i do this with my class to get a string for any given property name?
  int _id;
  String _title;

  Animal(this._id, this._title);

  int get id => _id;
  String get title => _title;
}

the usage case is being able to query without having autocomplete on my model's property names in a string for sql querying:
List<Map> results = await db.query("Animal",
        columns: Set. ["id", "title"],
        where:  'id = ?',
        whereArgs: [id]);

A: Using the dart:mirrors package you can dynamically access your class properties and invoke methods using their string names.
https://api.dart.dev/stable/2.4.0/dart-mirrors/dart-mirrors-library.html

import 'dart:mirrors';

class Animal {
  int _id;
  String _title;

  Animal(this._id, this._title);

  int get id => _id;
  String get title => _title;
}

main() {
  var r = reflect(Animal(1, 'Dog'));

  print(r.getField(Symbol('id')).reflectee);
  print(r.getField(Symbol('title')).reflectee);
}

A: import 'dart:mirrors';

class MyClass {
  int i, j;
  void my_method() {  }

  int sum() => i + j;

  MyClass(this.i, this.j);

  static noise() => 42;

  static var s;
}

main() {
  MyClass myClass = new MyClass(3, 4);
  InstanceMirror myClassInstanceMirror = reflect(myClass);

  ClassMirror MyClassMirror = myClassInstanceMirror.type;

  InstanceMirror res = myClassInstanceMirror.invoke(#sum, []);
  print('sum = ${res.reflectee}');

  var f = MyClassMirror.invoke(#noise, []);
  print('noise = $f');

  print('\nMethods:');
  Iterable<DeclarationMirror> decls =
      MyClassMirror.declarations.values.where(
        (dm) => dm is MethodMirror && dm.isRegularMethod);
  decls.forEach((MethodMirror mm) {
    print(MirrorSystem.getName(mm.simpleName));
  });

  print('\nAll declarations:');
  for (var k in MyClassMirror.declarations.keys) {
    print(MirrorSystem.getName(k));
  }

  MyClassMirror.setField(#s, 91);
  print(MyClass.s);
}

the output:
sum = 7
noise = InstanceMirror on 42

Methods:
my_method

sum

noise

All declarations:
i
j
s
my_method

sum
noise
MyClass
91


text:
Q: Laravel - using route name in another route I am trying to use named route in another route like this, but it doesnt work.
Route::get('/home', ['as' => 'home', 'uses' => 'HomeController@index']);
Route::post(route('home'), '.....');

A: You can use route('home', [], false) in this case. Third parameter false here is to use relative path instead of absolute (default set to true):
public function route($name, $parameters = array(), $absolute = true);

A: Laravel could do this for you by using a RESTful Resource Controller and allow GET and STORE (to match your example with GET and POST ->http://laravel.com/docs/5.0/controllers)
Route::resource('photo', 'PhotoController', ['only' => ['index', 'store']]);

Run php artisan route:list to see the names of the routes. Or a group of routes (http://laravel.com/docs/5.0/routing):
Route::group(['namespace' => 'admin'], function()
{
    Route::get('home', ['as' => 'admin.home.index', 'uses' => 'HomeController@index']);
    Route::get('castle', ['as' => 'admin.castle', 'uses' => 'HomeController@castle']);
});


text:
Q: Strong law of large numbers modified This is exercise 6 from Chung's book: course in probability theory page 137.

If $(X_n)_n$ are independent and identically distributed with $E[X_1]=0$ and $(c_n)_n$ is a sequence of bounded real numbers, then $\frac{1}{n}\sum_{k=1}^n c_kX_k$ converges a.s to 0.

He put a hint : Truncate $X_n$ at $n$ and proceed as in the proof of the SLLN.
I succeeded solving the problem using his hint, but I have a question why to truncate $X_n$ at $n$ and not $c_nX_n$ at $n$? Also do we have the same result for the Marcinkiewics–Zygmund strong law of large numbers?


text:
Q: Spark history-server stays empty I set up spark alongside Hadoop with YARN as a resource manager. I set both spark.history.fs.logDirectory and spark.eventLog.dir to the same path in my hdfs file system. Also, spark.eventLog.enabled is set to true and I also checked history servers logs, but there are no errors (Only INFO). So I assume my problem isn't caused by permission errors. Also, I verified that application logs are actually created in the correct place, which is indeed the case. History servers logs also indicate that it is looking in the correct folder.
I don't have any idea why there are no application logs shown in the history server. Maybe I'm missing something fundamental.
Here are all important files (if that helps)

*

*Logs: https://pastebin.com/6TGE3NbQ

*spark-defaults.conf: https://pastebin.com/ZRv4JWbV

*ansible-playbook.yml: https://pastebin.com/dVqsGENk (Important lines: 166 - 192 and 370)

The ansible-playbook is used to set up the whole cluster.
Edit: The history server is even parsing files (see Logs) but it just refuses to display them.

A: To have a proper History server setup, you need 3 things (also documented here):

*

*Your Spark applications need to write their logs to a certain directory. This can be done with the following configurations:

spark.eventLog.enabled true
spark.eventLog.dir someDirectory

*

*Your History Server needs to be running. This can be done like so:

./$SPARK_HOME/sbin/start-history-server.sh

*

*Your History Server needs to be looking at the correct directory to look at the logs. This can be configured like so:

spark.history.fs.logDirectory sameDirectoryAsTheOneAbove

So in your case, it seems like something is going wrong. There are a few things you can verify:

*

*Are your spark application correctly writing event logs?

*

*Go to spark.eventLog.dir and check whether there are entries in there. You should have an entry per spark application that you ran.

*Is my History Server running?

*

*There are multiple ways to check this.

*

*Type jps on the machine on which you're running the History Server. You should see a Java Process called HistoryServer running.

*Visit port 18080 on that machine (if local, go to localhost:18080) to see if it's running

*If your applications are writing to the correct location, and your history server is running but you still don't see any application entry on port 18080 from the point above, your history server might not be reading from the correct directory. Verify the value of spark.history.fs.logDirectory.


text:
Q: How to connect Excel to Oracle database? I am trying to connect Excel to my Oracle database using VBA.
Sub dbConnect()

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Set con = New ADODB.Connection
    Set rs = New ADODB.Recordset

    strCon = "Driver={Microsoft ODBC for Oracle}; " & _
    "CONNECTSTRING=(description=(address=(protocol=tcp)(host=mydb.domain.com)(port=1522))(connect_data=(sid=mydb))); uid=user; pwd=pw;"
    con.Open (strCon)

End Sub

I get an error.

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I know from other questions and sources that the problem is most likely using the wrong version of the DSN.
However, I don't understand what I need to do to fix it.
My Windows is 64-bit, when I open the ODBC Data Source Administrator I see the following (among others):

*

*Name: Excel Files, Platform: 64-bit, Driver: Microsoft Excel Driver
User DSN

*Name: mydb, Platform: 32-bit, Driver: oracle in ORA121020_x86
under System DSN
What can I do to fix it? How do the connection string and the DNSs relate to each other? Should I change the version of one of the DNS and if yes how do I do that?
Edit:
The connection string is copied from the db connection in Oracel SQL Developer where I can access the db.

A: Ok I managed to fix it. My excel is 64 bit so in order to connect to the db, I had to create a System DNS for my connection that is also 64 bit. In order to do that, I had to go to the /Windows/system32 folder, choose the file odbcad32 and under system DNS add a new DNS with a 64 bit driver I had to download. Lets say I named that DNS abc
I then also changed the connection string that you can see in the above code to
strCon = "Data Source=abc;User=user;Password=pw"

According to this the connection string I used in the post above does not need a DNS, so I don't know why it didn't work, however after creating a new DNS as just described I switched to the new connection string that specifies a DNS.
And voila, after only several hours I was able to connect to my db.
Quick sidenote: As mentioned above, I edited the obcad32 file in /Windows/system32. This is the file for 64 bit DNS. There is a file with the exact same name in the folder /Windows/SysWOW64 that manages the 32 bit DNS, so if you have a similar problem as I had, pay attention to which file you edit.


text:
Q: xmgrace: Logarithmic histogram binwidths I have been creating histograms in xmgrace. Some of the bins at the tail end of the histogram are empty, so I want to use logarithmically spaced bins, where the binwidths at the start are very narrow and then become very large (under logarithmic scale, the bin spaces would show up even).
I tried doing this with "abscissas of another set" option in the xmgrace histogram interface, but all that does is if I created a file with logarithmic bin edges for 500 total bins,  it gives me 500 evenly spaced bins.
So how can I have variable bin widths in xmgrace histogram?

A: Abscissas of another set is the way to go. Create/Import another set (say G0.S2) of type XY with the desired logarithmic bin edges as its abscissa (X column). The values in Y column are not relevant. Here is an example set with 5 non-uniform bin edges.

Use this set to create a histogram from your original set (say G0.S0) as


text:
Q: How do I make a WPF data template fill the entire width of the listbox? I have a ListBox DataTemplate in WPF. I want one item to be tight against the left side of the ListBox and another item to be tight against the right side, but I can't figure out how to do this.
So far I have a Grid with three columns, the left and right ones have content and the center is a placeholder with it's width set to "*". Where am I going wrong?
Here is the code:
<DataTemplate x:Key="SmallCustomerListItem">
    <Grid HorizontalAlignment="Stretch">
        <Grid.RowDefinitions>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <WrapPanel HorizontalAlignment="Stretch" Margin="0">
            <!--Some content here-->
            <TextBlock Text="{Binding Path=LastName}" TextWrapping="Wrap" FontSize="24"/>
            <TextBlock Text=", " TextWrapping="Wrap" FontSize="24"/>
            <TextBlock Text="{Binding Path=FirstName}" TextWrapping="Wrap" FontSize="24"/>

        </WrapPanel>
        <ListBox ItemsSource="{Binding Path=PhoneNumbers}" Grid.Column="2" d:DesignWidth="100" d:DesignHeight="50"
     Margin="8,0" Background="Transparent" BorderBrush="Transparent" IsHitTestVisible="False" HorizontalAlignment="Stretch"/>
    </Grid>
</DataTemplate>

A: Ok, here's what you have:
Column 0: WrapPanel
Column 1: Nothing
Column 2: ListBox
It sounds like you want WrapPanel on the left edge, ListBox on the right edge, and space to take up what's left in the middle.
Easiest way to do this is actually to use a DockPanel, not a Grid.
<DockPanel>
    <WrapPanel DockPanel.Dock="Left"></WrapPanel>
    <ListBox DockPanel.Dock="Right"></ListBox>
</DockPanel>

This should leave empty space between the WrapPanel and the ListBox.

A: <Grid.Width>
    <Binding Path="ActualWidth"
             RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}" />
</Grid.Width>

A: Extending Taeke's answer, setting the ScrollViewer.HorizontalScrollBarVisibility="Hidden" for a ListBox allows the child control to take the parent's width and not have the scroll bar show up.
<ListBox Width="100" ScrollViewer.HorizontalScrollBarVisibility="Hidden">
    <Label Content="{Binding Path=., Mode=OneWay}" HorizontalContentAlignment="Stretch" Height="30" Margin="-4,0,0,0" BorderThickness="0.5" BorderBrush="Black" FontFamily="Calibri" >
        <Label.Width>
            <Binding Path="Width" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBox}}" />
        </Label.Width>
    </Label>
</ListBox >

A: I also had to set:
HorizontalContentAlignment="Stretch"

on the containing ListBox.

A: The Grid should by default take up the whole width of the ListBox because the default ItemsPanel for it is a VirtualizingStackPanel. I'm assuming that you have not changed ListBox.ItemsPanel.
Perhaps if you got rid of the middle ColumnDefinition (the others are default "*"), and put HorizontalAlignment="Left" on your WrapPanel and HorizontalAlignment="Right" on the ListBox for phone numbers. You may have to alter that ListBox a bit to get the phone numbers even more right-aligned, such as creating a DataTemplate for them.

A: If you want to use a Grid, then you need to change your ColumnDefinitions to be:
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

If you don't need to use a Grid, then you could use a DockPanel:
    <DockPanel>
        <WrapPanel DockPanel.Dock="Left">
            <!--Some content here-->
            <TextBlock Text="{Binding Path=LastName}" TextWrapping="Wrap" FontSize="24"/>
            <TextBlock Text=", " TextWrapping="Wrap" FontSize="24"/>
            <TextBlock Text="{Binding Path=FirstName}" TextWrapping="Wrap" FontSize="24"/>
        </WrapPanel>
        <ListBox DockPanel.Dock="Right" ItemsSource="{Binding Path=PhoneNumbers}"
 Margin="8,0" Background="Transparent" BorderBrush="Transparent" IsHitTestVisible="False"/>
        <TextBlock />
    </DockPanel>

Notice the TextBlock at the end.  Any control with no "DockPanel.Dock" defined will fill the remaining space.

A: Taeke's answer works well, and as per vancutterromney's answer you can disable the horizontal scrollbar to get rid of the annoying size mismatch. However, if you do want the best of both worlds--to remove the scrollbar when it is not needed, but have it automatically enabled when the ListBox becomes too small, you can use the following converter:
/// <summary>
/// Value converter that adjusts the value of a double according to min and max limiting values, as well as an offset. These values are set by object configuration, handled in XAML resource definition.
/// </summary>
[ValueConversion(typeof(double), typeof(double))]
public sealed class DoubleLimiterConverter : IValueConverter
{
    /// <summary>
    /// Minimum value, if set. If not set, there is no minimum limit.
    /// </summary>
    public double? Min { get; set; }

    /// <summary>
    /// Maximum value, if set. If not set, there is no minimum limit.
    /// </summary>
    public double? Max { get; set; }

    /// <summary>
    /// Offset value to be applied after the limiting is done.
    /// </summary>
    public double Offset { get; set; }

    public static double _defaultFailureValue = 0;

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || !(value is double))
            return _defaultFailureValue;

        double dValue = (double)value;
        double minimum = Min.HasValue ? Min.Value : double.NegativeInfinity;
        double maximum = Max.HasValue ? Max.Value : double.PositiveInfinity;
        double retVal = dValue.LimitToRange(minimum, maximum) + Offset;
        return retVal;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Then define it in XAML according to the desired max/min values, as well an offset to deal with that annoying 2-pixel size mismatch as mentioned in the other answers:
<ListBox.Resources>
    <con:DoubleLimiterConverter x:Key="conDoubleLimiter" Min="450" Offset="-2"/>
</ListBox.Resources>

Then use the converter in the Width binding:
<Grid.Width>
    <Binding Path="ActualWidth" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}" Converter="{StaticResource conDoubleLimiter}"  />
</Grid.Width>

A: The method in Taeke's answer forces a horizontal scroll bar. This can be fixed by adding a converter to reduce the grid's width by the width of the vertical scrollbar control.
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

namespace Converters
{
    public class ListBoxItemWidthConverter : MarkupExtension, IValueConverter
    {
        private static ListBoxItemWidthConverter _instance;

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return System.Convert.ToInt32(value) - SystemParameters.VerticalScrollBarWidth;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return _instance ?? (_instance = new ListBoxItemWidthConverter());
        }
    }
}

Add a namespace to the root node of your XAML.
xmlns:converters="clr-namespace:Converters"

And update the Grid width to use the converter.
<Grid.Width>
    <Binding Path="ActualWidth" RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollContentPresenter}}" Converter="{converters:ListBoxItemWidthConverter}"/>
</Grid.Width>


text:
Q: How to Update parameters every certain steps? I'm using a tensorflow based keras to train a object detection network.
Due to small GPU memory size, have to update params once per some steps to "expand" batch size.
But my implementation can't successfully converge in Mask Rcnn training or perform badly comparing normal optimizers in simple cifar10 classification:
class custom_SGD(Optimizer):
def get_updates(self, loss, params):
    """Main params updates operation
    """
    shapes = [K.int_shape(p) for p in params]
    if self.nesterov:
        sum_grads = [K.zeros(shape) for shape in shapes]

    moments = [K.zeros(shape) for shape in shapes]
    sum_moments = [K.zeros(shape) for shape in shapes]

    # Current gradients
    grads = self.get_gradients(loss, params)
    self.updates = [K.update_add(self.iterations, 1)]
    self.weights = [self.iterations] + moments

    cond1 = K.equal(self.iterations % self.steps_per_update, 0)

    # Learning rate decay
    lr = self.lr
    if self.initial_decay > 0:
        lr = lr * (1. / (1. + self.decay * K.cast(self.iterations,
                                                  K.dtype(self.decay))))
    if not self.nesterov:
        for p, g, m,sm in zip(params, grads,moments, sum_moments):
            v = self.momentum*m - lr*g
            # updates sum_moments, moments
            self.updates.append(K.update(sm, sm+v))
            self.updates.append(K.switch(cond1,K.update(m,sm/float(self.steps_per_update)),m))

            new_p = p + m
            # Apply constraint
            if getattr(p, 'constraint', None) is not None:
                new_p = p.constraint(new_p)
            self.updates.append(K.switch(cond1,K.update(p,new_p),p))
            # Clear up container
            self.updates.append(K.switch(cond1,K.update(sm,K.zeros_like(sm)),sm))

    return self.updates

Can anybody tell me why.
Thanks in advance.


text:
Q: Generate HTML with css from React elements i'm trying to generate HTML with css from react elements using the following code.
const html = ReactDOMServer.renderToString(<ReactComponent/>);

I'm using Material UI components in the react elements. Css is not applied in the generated HTML.
How to generate a HTML with css ?


text:
Q: QTableView how to get the scroll bar row position void scrollBarValueChanged(int value)
{
     int row = view->rowAt(value);
}

Such as the title, when the scroll bar rolling, how to get the scroll row index?

A: Use horizontalScrollBar() verticalScrollBar() functions and get scroll value from it.
QScrollBar *verticalScroll = ui->tableView->verticalScrollBar();
QScrollBar *horizontalScroll = ui->tableView->horizontalScrollBar();
int valueV = verticalScroll->value();
int valueH = horizontalScroll->value();

Also use scrollTo function to scroll to your table cell index. (horizontally and vertically)
ui->tableView->scrollTo( ui->tableView->model()->index(row,column) );

like this image:
ui->tableView->scrollTo(ui->tableView->model()->index(7,3));

The QTableView page on Qt website.

A: Looks like rowAt and columnAt are exactly what you need.


text:
Q: How can I retrieve files within a repo in Azure within a Powershell script? I need to (within a Powershell script) determine all the possible controller file names within a repository.   This is for a test that will hit every controller and verify it is functioning and not missing from the startup file. (MVC app)
Since all the files are DLLs I cannot simply ask for the files in the folder nor do I want to hard code the names.   How can I get a listing of files within a certain folder in order call each one to test within a powershell script?
Perhaps a better way to ask this is:
How can I list files within a folder that is inside a repo? (using a Powershell script)

A: You could refer to this doc:Interacting with Azure Web Apps Virtual File System using PowerShell and the Kudu API. It uses the VFS API in the wiki doc. And there is a api to list files at directory specified by path.
GET /api/vfs/{path}/
Lists files at directory specified by path.

And in the previous doc, under the title Downloading a File from an App Service, there is a scripts to download the files. I use the path without $kuduPath to list files. And you need to Getting the Kudu REST API Authorisation header via PowerShell. And then the scripts would be like this.
$kuduApiUrl="https://<webname>.scm.azurewebsites.net/api/vfs/site/wwwroot/"
 Invoke-RestMethod -Uri $kuduApiUrl `
 -Headers @{"Authorization"=$kuduApiAuthorisationToken;"If-Match"="*"} `
 -Method GET `
 -OutFile $localPath `
 -ContentType "multipart/form-data"

And here is the result pic.It will list all files and the folders.

hope this could help you, if you still have other questions,please let me know.


text:
Q: How to use "score highest" in a sentence I want to say that she has the highest score on the math exam.
Can I say it another way like below?

*

*She score highest on the math exam.

*She score the highest on the math exam.

Which one is correct (number 1 or number 2)?

A: As other answers have noted, neither is correct. You need

*

*She scored ...

or

*

*She scores ...

Although correct, these are awkward. In soccer/football you can say "she scored" but in this context I think the score belongs to the exam more than to the mathematician. So the sentence you want to replace is better: she had the highest score on the math exam.

A: Neither of those are correct. no2 is more correct, but you still must conjugate to "She scores the highest on the math exam" or "She scored the highest on the math exam
Hope this helped!

A: I think no2

She scores the highest (record) on the math exam

A: You could add "did".

She did score the highest on the math exam.


text:
Q: Complete Loop and then Insert if no records are found in any of the queries When a person submits their payment voucher, I have a query performed on the database to make sure a voucher hasn't already been submitted for the same date and time. If so, an error message appears and the voucher doesn't insert into the database. If the recordset pulls no records then, the voucher is inserted. This works fine. Where it gets complicated is a person can add multiple dates and start times. So, I have the query run for each instance of this. So, when the validation query runs sometimes it might be fine but, other times, there might be a match. So, the insert keeps happening if there is at least one validation. What I need to happen is that the loop completes through all iterations and then, it determines if there was any duplicates and if so, the insert doesn't happen. Instead it is comparing each iteration without going through the whole loop first.  Here is my code:
<?php
if (isset($_POST["submit"]) || isset($_POST["submit_x"])) {
    for($i=0;$i<count($_POST['date_performed']);$i++){
        $date_performed = $_POST['date_performed'][$i];
        $start_time = $_POST['start_time'][$i];
        $valid_form = new WA_MySQLi_RS("valid_form",$sa,0);
        $valid_form->setQuery("SELECT * FROM voucher_hourly_items left join payment_vouchers on payment_vouchers.voucherID = voucher_hourly_items.voucherID WHERE staffID = ? and service_agreementID = ? and date_performed = ? and start_time = ?");
        $valid_form->bindParam("i", "".$_GET['staffID']  ."", "-1"); //colname
        $valid_form->bindParam("i", "".$_GET['service_agreementID']  ."", "-1"); //colname2
        $valid_form->bindParam("t", "".$date_performed  ."", "-1"); //colname3
        $valid_form->bindParam("s", "".$start_time  ."", "-1"); //colname4
        $valid_form->execute();
    }
    if ($valid_form->TotalRows > 0) {
        echo '

There is already a payment voucher in the system with the same date performed and start time. Please try again!';
    }
    $saID= $service_agreements->getColumnVal("service_agreementID");
    $lname=$service_agreements->getColumnVal("lname");
    $fname=$service_agreements->getColumnVal("fname");
    $date = date('Y-m-d');
    $thesignature = $date."_".$saID."_". $fname."_". $lname.".png";
    if ($valid_form->TotalRows == 0) {
        $InsertQuery = new WA_MySQLi_Query($sa);
        $InsertQuery->Action = "insert";
        $InsertQuery->Table = "payment_vouchers";
        $InsertQuery->bindColumn("staffID", "i", "".((isset($_POST["staffID"]))?$_POST["staffID"]:"")  ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("service_agreementID", "i", "".((isset($_POST["service_agreementID"]))?$_POST["service_agreementID"]:"")  ."", "WA_DEFAULT");
        if ($service_agreements->getColumnVal("payment_terms") == 'Flat Rate') {
            $InsertQuery->bindColumn("start_date", "t", "".((isset($_POST["start_date"]))?$_POST["start_date"]:"")  ."", "WA_DEFAULT");
            $InsertQuery->bindColumn("end_date", "t", "".((isset($_POST["end_date"]))?$_POST["end_date"]:"")  ."", "WA_DEFAULT");
            $InsertQuery->bindColumn("description_of_services", "s", "".((isset($_POST["description_of_services"]))?$_POST["description_of_services"]:"")  ."", "WA_DEFAULT");
            $InsertQuery->bindColumn("total_stipend", "i", "".((isset($_POST["total_stipend"]))?$_POST["total_stipend"]:"")  ."", "WA_DEFAULT"); }
        $InsertQuery->bindColumn("phone_ext", "s", "".((isset($_POST["phone_ext"]))?$_POST["phone_ext"]:"") ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("status", "s", "".((isset($_POST["status"]))?$_POST["status"]:"")  ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("submitted_by", "s", "".((isset($_POST["submitted_by"]))?$_POST["submitted_by"]:"")  ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("date_submitted", "t", "".((isset($_POST["date_submitted"]))?$_POST["date_submitted"]:"") ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("signature", "s", "".$thesignature."", "WA_IGNORE");
        $InsertQuery->saveInSession("voucherID");
        $InsertQuery->execute();
        $folderPath = "../received/";

        $image_parts = explode(";base64,", $_POST['signed']);

        $image_type_aux = explode("image/", $image_parts[0]);

        $image_type = $image_type_aux[1];

        $image_base64 = base64_decode($image_parts[1]);

        $file = $folderPath . $date.'_'.$saID.'_'.$fname.'_'.$lname.'.'.$image_type;
        file_put_contents($file, $image_base64);
        $email_address = $service_agreements->getColumnVal("admin_email");
        $title = $service_agreements->getColumnVal("title");
        $fname= $service_agreements->getColumnVal("fname");
        $lname= $service_agreements->getColumnVal("lname");
        $website = 'https://secure1.cpsd.us/service_agreement/admin.php';
        $message = "A payment voucher has been submitted by $fname $lname for $title. Please visit $website to approve or deny the voucher. \r\n";
        $message=wordwrap($message);
        $to = $email_address;
        $subject = "Approval Needed: Payment Voucher Submitted for $title ";
        $headers = "From: schoolnews@cpsd.us\r\n";
        if ($service_agreements->getColumnVal("payment_terms") == 'Hourly') {

            for($i=0;$i<count($_POST['date_performed']);$i++){
        $voucherID = $_SESSION['voucherID'];
        $date_performed = $_POST['date_performed'][$i];
        $start_time = $_POST['start_time'][$i];
        $end_time = $_POST['end_time'][$i];
        $hours = $_POST['hours'][$i];
        $rate = $_POST['rate'][$i];
        $description_of_services = $_POST['description_of_services'][$i];
        if($voucherID!=='' && $date_performed!=='' && $start_time!=='' && $end_time!=='' && $hours!=='' && $rate!=='' && $description_of_services!==''){
                    $sql="INSERT INTO voucher_hourly_items(voucherID,date_performed,start_time,end_time,hours,rate,description_of_services)VALUES('$voucherID','$date_performed','$start_time','$end_time','$hours','$rate','$description_of_services')";
                    $stmt=$sa->prepare($sql);
                    $stmt->execute();
            //echo '
Submitted Successfully
';
        }
        else{

                    echo '
Error Submitting in Data
';
        }
            }
            echo "";
        }
        $InsertGoTo = "manage_service_agreements.php";
        if (function_exists("rel2abs")) $InsertGoTo = $InsertGoTo?rel2abs($InsertGoTo,dirname(__FILE__)):"";
        $InsertQuery->redirect($InsertGoTo);
    }}
?>

A: You're only checking $validForm->TotalRows from the last query. You need to check this inside the loop. If none of the queries returns anything, then the submission is valid.
<?php
if (isset($_POST["submit"]) || isset($_POST["submit_x"])) {
    $submission_is_valid = true;
    for($i=0;$i<count($_POST['date_performed']);$i++){
        $date_performed = $_POST['date_performed'][$i];
        $start_time = $_POST['start_time'][$i];
        $valid_form = new WA_MySQLi_RS("valid_form",$sa,0);
        $valid_form->setQuery("SELECT * FROM voucher_hourly_items left join payment_vouchers on payment_vouchers.voucherID = voucher_hourly_items.voucherID WHERE staffID = ? and service_agreementID = ? and date_performed = ? and start_time = ?");
        $valid_form->bindParam("i", "".$_GET['staffID']  ."", "-1"); //colname
        $valid_form->bindParam("i", "".$_GET['service_agreementID']  ."", "-1"); //colname2
        $valid_form->bindParam("t", "".$date_performed  ."", "-1"); //colname3
        $valid_form->bindParam("s", "".$start_time  ."", "-1"); //colname4
        $valid_form->execute();
        if ($valid_form->TotalRows > 0) {
            echo '

There is already a payment voucher in the system with the same date performed and start time. Please try again!';
            $submission_is_valid = false;
            break;
        }
    }
    $saID= $service_agreements->getColumnVal("service_agreementID");
    $lname=$service_agreements->getColumnVal("lname");
    $fname=$service_agreements->getColumnVal("fname");
    $date = date('Y-m-d');
    $thesignature = $date."_".$saID."_". $fname."_". $lname.".png";
    if ($submission_is_valid) {
        $InsertQuery = new WA_MySQLi_Query($sa);
        $InsertQuery->Action = "insert";
        $InsertQuery->Table = "payment_vouchers";
        $InsertQuery->bindColumn("staffID", "i", "".((isset($_POST["staffID"]))?$_POST["staffID"]:"")  ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("service_agreementID", "i", "".((isset($_POST["service_agreementID"]))?$_POST["service_agreementID"]:"")  ."", "WA_DEFAULT");
        if ($service_agreements->getColumnVal("payment_terms") == 'Flat Rate') {
            $InsertQuery->bindColumn("start_date", "t", "".((isset($_POST["start_date"]))?$_POST["start_date"]:"")  ."", "WA_DEFAULT");
            $InsertQuery->bindColumn("end_date", "t", "".((isset($_POST["end_date"]))?$_POST["end_date"]:"")  ."", "WA_DEFAULT");
            $InsertQuery->bindColumn("description_of_services", "s", "".((isset($_POST["description_of_services"]))?$_POST["description_of_services"]:"")  ."", "WA_DEFAULT");
            $InsertQuery->bindColumn("total_stipend", "i", "".((isset($_POST["total_stipend"]))?$_POST["total_stipend"]:"")  ."", "WA_DEFAULT"); }
        $InsertQuery->bindColumn("phone_ext", "s", "".((isset($_POST["phone_ext"]))?$_POST["phone_ext"]:"") ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("status", "s", "".((isset($_POST["status"]))?$_POST["status"]:"")  ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("submitted_by", "s", "".((isset($_POST["submitted_by"]))?$_POST["submitted_by"]:"")  ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("date_submitted", "t", "".((isset($_POST["date_submitted"]))?$_POST["date_submitted"]:"") ."", "WA_DEFAULT");
        $InsertQuery->bindColumn("signature", "s", "".$thesignature."", "WA_IGNORE");
        $InsertQuery->saveInSession("voucherID");
        $InsertQuery->execute();
        $folderPath = "../received/";

        $image_parts = explode(";base64,", $_POST['signed']);

        $image_type_aux = explode("image/", $image_parts[0]);

        $image_type = $image_type_aux[1];

        $image_base64 = base64_decode($image_parts[1]);

        $file = $folderPath . $date.'_'.$saID.'_'.$fname.'_'.$lname.'.'.$image_type;
        file_put_contents($file, $image_base64);
        $email_address = $service_agreements->getColumnVal("admin_email");
        $title = $service_agreements->getColumnVal("title");
        $fname= $service_agreements->getColumnVal("fname");
        $lname= $service_agreements->getColumnVal("lname");
        $website = 'https://secure1.cpsd.us/service_agreement/admin.php';
        $message = "A payment voucher has been submitted by $fname $lname for $title. Please visit $website to approve or deny the voucher. \r\n";
        $message=wordwrap($message);
        $to = $email_address;
        $subject = "Approval Needed: Payment Voucher Submitted for $title ";
        $headers = "From: schoolnews@cpsd.us\r\n";
        if ($service_agreements->getColumnVal("payment_terms") == 'Hourly') {

            for($i=0;$i<count($_POST['date_performed']);$i++){
        $voucherID = $_SESSION['voucherID'];
        $date_performed = $_POST['date_performed'][$i];
        $start_time = $_POST['start_time'][$i];
        $end_time = $_POST['end_time'][$i];
        $hours = $_POST['hours'][$i];
        $rate = $_POST['rate'][$i];
        $description_of_services = $_POST['description_of_services'][$i];
        if($voucherID!=='' && $date_performed!=='' && $start_time!=='' && $end_time!=='' && $hours!=='' && $rate!=='' && $description_of_services!==''){
                    $sql="INSERT INTO voucher_hourly_items(voucherID,date_performed,start_time,end_time,hours,rate,description_of_services)VALUES('$voucherID','$date_performed','$start_time','$end_time','$hours','$rate','$description_of_services')";
                    $stmt=$sa->prepare($sql);
                    $stmt->execute();
            //echo '
Submitted Successfully
';
        }
        else{

                    echo '
Error Submitting in Data
';
        }
            }
            echo "";
        }
        $InsertGoTo = "manage_service_agreements.php";
        if (function_exists("rel2abs")) $InsertGoTo = $InsertGoTo?rel2abs($InsertGoTo,dirname(__FILE__)):"";
        $InsertQuery->redirect($InsertGoTo);
    }
}
?>


text:
Q: how to properly configure jenkins swarm as a service to get proper scrshoots? I have a trouble to find out what is the problem in node setup (centos+gnome+swarm as a service) as it does connect,run gui tests properly but returns "broken" (whole white or "something went wrong) screenshots.
In our CI env, we build and test GUI application (RED - Robot Editor) using Eclipse tool RCPTT which can click on GUI elements to validate functionalities.
Tests are are executed on nodes Centos7 with metacity+gnome+vncserver, whenever something with GUI is wrong (GUI element is not found,validation is not consistant with test criteria), report is created together with screenshot,so tester is able to have a look what has changed in tested app.
When node is manually configured (from Jenkins Nodes configuration page) or swarm script is executed by user on Node (via ssh), screenshots are fine.
When swarm as a service is executed (node is connected, systemctl status  is green,by the same user as run manually), everything is ok besides sreenshots are off (screen res is fine,whole screen is white or with error "Oh no! Something has gone wrong".
I do not see any error in logs from RCPTT,xvnc,in job console.
What can be a root cause of broken screenshots?
env setup:
service definition
[Unit]
Description=Swarm client to create Jenkins slave
After=network.target
After=display-manager.service

[Service]
ExecStart=<path>/swarm_client.sh start
ExecStop=<path>/swarm_client.sh stop
Type=forking
PIDFile=<path>/slave.pid
User=root
Group=root

[Install]
WantedBy=graphical.target

swarm_client.sh
function startclient {
                PUBIP=`public ip string`

        java  \
           -jar ${SWARM_HOME}/swarm-client-3.3.jar \
           -executors 1 \
           -deleteExistingClients \
           -disableClientsUniqueId \
           -fsroot ${CLIENT_HOME} \
           -labels "linux"  \
           -master <jenkins> \
           -name node-Swarm-${PUBIP} 2>&1 > ${CLIENT_HOME}/slave.log &
    PID=$!
        RETCODE=$?
        echo $PID > ${CLIENT_HOME}/slave.pid
        exit $RETCODE
}

function stopclient {
        if [ -f ${CLIENT_HOME}/slave.pid ];then
                PID=`head -n1 ${CLIENT_HOME}/slave.pid`
                kill $PID
                rm -f ${CLIENT_HOME}/slave.pid
        fi
}
SWARM_HOME=<path>/jenkins/swarm
CLIENT_HOME=<path>/jenkins
case "$1" in
  start)
        startclient
        ;;
  stop)
        stopclient
        ;;
  *)
        echo "Usage: systemctl {start|stop} swarm_client.service" || true
        exit 1
esac

xvnc logs:
Fri Jul  7 11:05:40 2017
 vncext:      VNC extension running!
 vncext:      Listening for VNC connections on all interface(s), port 5942
 vncext:      created VNC server for screen 0
gnome-session-is-accelerated: llvmpipe detected.

A: ok, after rubber duck session and some googling it seems that while setting up a service which will be dependant on user environment properties/settings (swarm client is indeed a reverse remote shell), such service should import at least env properties from user shell.
In my case, if swarm_client.sh was working fine from ssh but not as service, it needed to use user's ssh/bash env properties
#export environment of user to file
env > user.env

Add such file to service description under [Service] section:
EnvironmentFile=<path>/user.env

I have not investigated what exactly was missing but this is good enough for my case.
Hope that it will help someone with the same problems with swarm as a service under Centos/RH


text:
Q: Magick++.h: No such file or directory (Even after installing Magick++) I am using a WSL Ubuntu terminal.
I executed the following command to install Magick++:
sudo apt-get install libmagick++-dev

After this, I checked to make sure that Magick++.h has been installed or not by the following command:
sudo apt-file find Magick++.h

This showed me the following result:
graphicsmagick-libmagick-dev-compat: /usr/include/Magick++.h
libgraphicsmagick++1-dev: /usr/include/GraphicsMagick/Magick++.h
libmagick++-6-headers: /usr/include/ImageMagick-6/Magick++.h

Which I assume, means that the Magick++.h header file has been successfully installed for use.
So I try to execute my C++ programme like so:
g++ -o main mycppprog.cpp

But this throws me the following error:
fatal error: Magick++.h: No such file or directory
   11 | #include <Magick++.h>
      |          ^~~~~~~~~~~~
compilation terminated.

I don't understand why this inconsistency is there. Or is there something that I am missing?
Kindly guide. Thanks.

A:
Which I assume, means that the Magick++.h header file has been successfully installed for use.

This will show you what packages provide the file you searched for and does not show what is installed on your system.
Using the command:
apt-file find Magick++.h

shows:
graphicsmagick-libmagick-dev-compat: /usr/include/Magick++.h
libgraphicsmagick++1-dev: /usr/include/GraphicsMagick/Magick++.h
libmagick++-6-headers: /usr/include/ImageMagick-6/Magick++.h

so this tells you that the following packages:
graphicsmagick-libmagick-dev-compat
libgraphicsmagick++1-dev
libmagick++-6-headers

provide the files listed accordingly.
Therefore, run the following commands to install the packages that provide those files:
sudo apt update
sudo apt install graphicsmagick-libmagick-dev-compat libgraphicsmagick++1-dev libmagick++-6-headers


text:
Q: Advice: Template structure - php blocks in sidebar or someting else? I'm trying to create certain modulair blocks which I can add to multiple pages in Wordpress. But I use sidebar-[name].php files for this, what is the best practice for this? Should you add them to a function or add them in a sidebar...
It feels Kinda off using many sidebar's. It would be nice if I could add them to a sub-folder in the template. Checkout the image. How do you do this?

A: I would say to add them as template parts as in content-[name].php. For instance in page.php you could have something like:
<?php while ( have_posts() ) : the_post(); ?>
            <?php if (is_page( 'home' ) ){
                 get_template_part( 'content', 'benefits' );
                } elseif (is_page( 'Contact' ) ){
                 get_template_part( 'content', 'contact' );
                }
             }

            get_template_part( 'content', 'popup' ); ?>
        <?php endwhile; // end of the loop. ?>

It seems to make more sense as it is content after all.

A: Who says you can not put template files into sub-directories?
Your custom-templates can be put wherever you want them to be - because it is you who includes them, anyway.
If you see the Codex on get_template_part, you find the following:
get_template_part( 'partials/content', 'page' );


text:
Q: building a gl3 app under cygwin i've got a small opengl 3.2 app that i've been developing on linux using the standard gnu tools (gmake/gcc). the code seems pretty portable--i had no problems running it on osx until i started using gl3 features that the mac mini gl drivers don't seem to support. i've got a bootcamp partition with windows xp on the same mini, and i'd like to run my app there if possible.
the windows drivers definitely support gl 3.2, but i'm having trouble linking. this seems like a really common issue, but i haven't found any answers online that address using opengl > 1.2 under cygwin. i'm using glew-1.5.5 and linking like so:
g++ -o glToy *.o -L/cygdrive/c/Program\ Files/glew-1.5.5/lib -lglew32 -lglut32 -lglu32 -lopengl32
but i get a whole lot of this sort of output:

Program.o:/home/Jacob/glToy/Program.cpp:134: undefined reference to `__imp____glewUseProgram'
Program.o:/home/Jacob/glToy/Program.cpp:235: undefined reference to `__imp____glewActiveTexture'
Program.o:/home/Jacob/glToy/Program.cpp:73: undefined reference to `__imp____glewGetShaderiv'
...

any ideas what i'm doing wrong? or perhaps this isn't a workable setup? other ideas for getting this going on the mac mini (2009 version)? thanks!

A: you can also skip linking, just get glew.c and put it in /include (not /include/GL like glew.h) and then change your #include to <glew.c>

A: you aren't linking glew properly or glew is broken... nothing to do with gl itself
the easy fix is just to use the extension api and forget about glew.


text:
Q: Replace Version Info Resource
I'm Loading a certain Exe in My Program and I'm trying to replace It's Version Info Resource.
I'm Using UpdateResource() but for some reason It isn't replacing the original resource as it is supposed to do.
UpdateResource(hHandle,RT_VERSION,"1",MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),pRsrcMemory,rsrcSize)

When The Exe is opened in a resource editor , I see two version Info resources with the same ID 1 , But the Version Info Displayed in Windows Explorer is the Original Info.(Probably because it comes first in the .rsrc section of the exe but i'm not sure)
Any Help is appreciated.

A: Resource IDs can be either strings or numbers.  Which is the problem here, it is not resource ID "1", it is MAKEINTRESOURCE(1).
Fun puzzler.

A: Are you following all the steps called out for in the MSDN for updating resources? Namely:

*

*Use the BeginUpdateResource function to open an update handle to your exe.

*Use the UpdateResource function to update it.

*Use the EndUpdateResource function to complete the update.


text:
Q: Consolidate query results in sql I have following data in my table
column1 count1
1   2
2   3
2   5
3   4
3   1
4   3
5   4
6   7
7   3
8   0
9   2
10  1

Following is the output I want:
id  sum(count1)
1   2
2   8
3+  25

Following is the query I am using for this :
SELECT column1 AS id,sum(count1) FROM test
WHERE column1 < 3
GROUP BY id
UNION
SELECT '3+' AS id,sum(count1) FROM test
WHERE column1 >= 3
GROUP BY id

This is a rather inefficient way because we scan the table twice. Is there a better way of doing this ?

A: You just need simple GROUP BY clause but conditional with case expression
select
     case when column1 >= 3 then 3 else column1 end AS id, sum (count1) count1
from table t
group by case when column1 >= 3 then 3 else column1 end

You could explore your desired result with sub-query or something similar

A: A simple formulation in Impala is:
select least(column1, 3) as id, sum(count1) as count1
from table t
group by least(column1, 3)
order by min(id);

This does not return the 3+.  For that, we need to be careful about types:
select (case when column1 < 3 then cast(column1 as string) else '3+' end) as id, sum(count1)
from table t
group by (case when column1 < 3 then cast(column1 as string) else '3+' end)
order by min(id);

I also find order by min(id) a convenient way to get the result set in the right order.


text:
Q: Умножение узла (Node) Мне нужно умножить узел (Node) в таком порядке: получаемый узел это 1 2 3 4 5 а узел после выполнения метода имеет такой вид 1 2 3 4 5 1 2 3 4 5.
Написал метод: выдаёт бесконечный узел который увеличивается сам по себе. При этом предыдущее действие перед распечаткой завершилось. Как мне решить данную задачу?
Код входит в бесконечный цикл:
public static void tr12(Node<Integer> n1) {
    Node<Integer> p = n1;
    while (p.hasNext()) {
        p = p.getNext();
    }
    Node<Integer> p2 = new Node<Integer>(n1.getValue(), n1.getNext());
    while (p2 != null) {
        Node<Integer> temp = new Node<Integer>(p2.getValue());
        p.setNext(temp);
        p = p.getNext();
        p2 = p2.getNext();
    }
    print(p2);
}

A: Вы каждый раз добавляете элемент в конец, берёте следующий и повторяете бесконечно этот цикл.

*

*Нужно перед началом всех этих добавлений запомнить последний элемент.

*В цикле по добавлению элементов проверять текущий элемент на равенство с тем последним. Это будет условием выхода.
public static void tr12(Node<Integer> n1) {
    Node<Integer> p = n1;
    while (p.hasNext()) {
        p = p.getNext();
    }

    Node<Integer> pLast = p;

    Node<Integer> p2 = new Node<Integer>(n1.getValue(), n1.getNext());
    while (p2 != null) {
        Node<Integer> temp = new Node<Integer>(p2.getValue());
        p.setNext(temp);
        p = p.getNext();

        if (p2 == mPlast)
            break;

        p2 = p2.getNext();
    }
    print(p2);
}


text:
Q: Variable scoping with an except block: Difference between Python 2 and 3 I came across a weird difference with local variable scopes between Python 2.7 and Python 3.7.
Consider this artificial script unboundlocalexception.py (I realize that I could just have used an else-block after except, but I extracted this example from a longer function):
def foo():
  arithmetic_error = None
  try:
    y = 1.0 / 0
  except ZeroDivisionError as arithmetic_error:
    print("I tried to divide by zero")

  if arithmetic_error is None:
    print("Correct division")

foo()

Under Python 2 it works as I expected it to:
$ python2 unboundlocalexception.py
I tried to divide by zero

But, surprisingly, under Python 3 an UnboundLocalError is raised!
$ python3 unboundlocalexception.py
I tried to divide by zero
Traceback (most recent call last):
  File "unboundlocalexception.py", line 11, in <module>
    foo()
  File "unboundlocalexception.py", line 8, in foo
    if arithmetic_error is None:
UnboundLocalError: local variable 'arithmetic_error' referenced before assignment

Is this difference documented anywhere?

A: This behaviour was introduced in Python 3, to prevent reference cycles, because the exception target - arithmetic_error in the question - keeps a reference to the traceback.
From the Language Reference

When an exception has been assigned using as target, it is cleared at
  the end of the except clause. This is as if

except E as N:
    foo

was translated to

except E as N:
    try:
        foo
    finally:
        del N

This means the exception must be assigned to a different name to be
  able to refer to it after the except clause. Exceptions are cleared
  because with the traceback attached to them, they form a reference
  cycle with the stack frame, keeping all locals in that frame alive
  until the next garbage collection occurs.

This was originally documented in PEP3110.


text:
Q: NSAttributedString initWithHTML incorrect character encoding? -[NSMutableAttributedString initWithHTML:documentAttributes:] seems to mangle special characters:
NSString *html = @""Hello" World"; // notice the smart quotes
NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];
NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithHTML:htmlData documentAttributes:nil];
NSLog(@"%@", as);

That prints "Hello†World followed by some RTF commands. In my application, I convert the attributed string to RTF and display it in an NSTextView, but the characters are corrupted there, too.
According to the documentation, the default encoding is UTF-8, but I tried being explicit and the result is the same:
NSDictionary *attributes = @{NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]};
NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithHTML:htmlData documentAttributes:&attributes];

A: Use [html dataUsingEncoding:NSUnicodeStringEncoding] when creating the NSData and set the matching encoding option when you parse the HTML into an attributed string:
The documentation for NSCharacterEncodingDocumentAttribute is slightly confusing:

NSNumber, containing an int specifying the NSStringEncoding for the
  file; for reading and writing plain text files and writing HTML;
  default for plain text is the default encoding; default for HTML is
  UTF-8.

So, you code should be:
NSString *html = @""Hello" World";
NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                    NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};
NSMutableAttributedString *as =
    [[NSMutableAttributedString alloc] initWithHTML:htmlData
                                            options: options
                                 documentAttributes:nil];

A: The previous answer here works, but mostly by accident.
Making an NSData with NSUnicodeStringEncoding will tend to work, because that constant is an alias for NSUTF16StringEncoding, and UTF-16 is pretty easy for the system to identify.  Easier than UTF-8, which apparently was being identified as some other superset of ASCII (it looks like NSWindowsCP1252StringEncoding in your case, probably because it's one of the few ASCII-based encodings with mappings for 0x8_ and 0x9_).
That answer is mistaken in quoting the documentation for NSCharacterEncodingDocumentAttribute, because "attributes" are what you get out of -initWithHTML.  That's why it's NSDictionary ** and not just NSDictionary *.  You can pass in a pointer to an NSDictionary *, and you'll get out keys like TopMargin/BottomMargin/LeftMargin/RightMargin, PaperSize, DocumentType, UTI, etc.  Any values you try to pass in through the "attributes" dictionary are ignored.
You need to use "options" for passing values in, and the relevant option key is NSTextEncodingNameDocumentOption, which has no documented default value.  It's passing the bytes to WebKit for parsing, so if you don't specify an encoding, presumably you're getting WebKit's encoding-guessing heuristics.
To guarantee the encoding types match between your NSData and NSAttributedString, what you should do is something like:
NSString *html = @""Hello" World";
NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];

NSMutableAttributedString *as =
    [[NSMutableAttributedString alloc] initWithHTML:htmlData
                                            options:@{NSTextEncodingNameDocumentOption: @"UTF-8"}
                                 documentAttributes:nil];

A: Swift version of accepted answer is:
let htmlString: String = "Hello world contains html</br>"
let data: Data = Data(htmlString.utf8)

let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
    .documentType: NSAttributedString.DocumentType.html,
    .characterEncoding: String.Encoding.utf8.rawValue
]

let attributedString = try? NSAttributedString(data: data,
    options: options,
    documentAttributes: nil)


text:
Q: Is it bad to store user uploaded images in MongoDB? I am building a social media application that uses multiple user-uploaded images. I was told that the best tool for handling user-uploading images is Cloudinary, but if possible I want to directly store images in my database. I heard that databases have poor horizontal scaling, which is why solutions like cloudinary are pushed. Is it true that it is a bad idea to have images stored in mongodb? I do not want to use other APIs like cloudinary.

A: Ussually image URL is stored in database because it always takes less space than whole image data. For example Wordpress stores images on server in uploads folder and in database you can only find URL plus title, type, and some additional data, but not whole image file.
You don't have to use cloud services to store your images, but it can be faster than loading images from your server. Saving every image in database is definetly not a good idea.

A: It appears good to store image or any BLOB in database in development, as it would organise very well with other associated data or transaction, However, there are caveats of storing BOLOB (binary, image, ...) in database,

*

*non-indexable.

*non-searchable.

*non-compressible.

*Manipulations not easy.

Still, you can store but it will perform poorly at scale and in that case you should avoid storing image in database.
Storing image in any could provider's CDN service becomes best choice for performance including other features of image optimisations.


text:
Q: Real time Motion History Image (MHI) in Matlab My project was to detect human activity through stored video clips. I have used following code in order to get the Motion History Image (MHI) of the video clip.
function MHI = MHI(fg)

% Initialize the output, MHI a.k.a. H(x,y,t,T)
MHI = fg;

% Define MHI parameter T
T = 15; % # of frames being considered; maximal value of MHI.

% Load the first frame
frame1 = fg{1};

% Get dimensions of the frames
[y_max x_max] = size(frame1);

% Compute H(x,y,1,T) (the first MHI)
MHI{1} = fg{1} .* T;

% Start global loop for each frame
for frameIndex = 2:length(fg)

    %Load current frame from image cell
    frame = fg{frameIndex};

    % Begin looping through each point
    for y = 1:y_max
        for x = 1:x_max
            if (frame(y,x) == 255)
                MHI{frameIndex}(y,x) = T;
            else
                if (MHI{frameIndex-1}(y,x) > 1)
                    MHI{frameIndex}(y,x) = MHI{frameIndex-1}(y,x) - 1;
                else
                    MHI{frameIndex}(y,x) = 0;
                end
            end
        end
    end
end

However, now I want to extend my project and display the Motion History Image (MHI) in real time. That is, the frames will be captured from the webcam, and as they are captured, a Motion History Image (MHI) will be displayed. How can I achieve this?
Any help will be appreciated. Thank you.

A: You should definitely vectorize your loops. You can also use a 3D array for MHI instead of a cell array. I have not tested it, but the code should look something like this:
MHI = zeros(y_max, x_max, numel(fg));
MHI(:,:,1) = fg{1} .* T;
for frameIndex = 2:length(fg)
  mhi = MHI(:,:,frameIndex);
  mhi(fg{frameIndex} == 255) = T;

  prevMHI = MHI(:,:,frameIndex-1);
  idx = prevMHI > 1;
  mhi(idx) = prevMHI(idx) - 1;
end


text:
Q: Storing spatial points in Symfony 2 / Doctrine 2 Entities? Symfony 2 doesn't have the spatial points datatype that MySQL supports. I couldn't find anything on the Doctrine 2 documentation about this particular data type, so, does anyone know how to work with points in Symfony 2? Also, how to query based on a radius? Thanks! :)

A: The easiest way would be to implement custom types for the spatial data types, and then declare custom DQL functions to make querying them simpler.
I wrote about this here: http://codeutopia.net/blog/2011/02/19/using-spatial-data-in-doctrine-2/

A: Another option would be to use the djlambert/doctrine2-spatial bundle, found here: https://github.com/creof/doctrine2-spatial
No need to implement any custom stuff.

A: If you speak french, youd could get some inspiration with another article here : http://blog.fastre.info/2012/02/doctrine2-2-2-et-types-geographiques/
This classes were build for a Postgresql + Postgis Database.


text:
Q: How to find all the colors in a photo with Ruby Does anyone know of a Ruby library that can list all of the colors in a photo, as well as listing them in order of frequency?  Or is it possible that RMagick already can do something like this?
If no one knows of one, how exactly could I get started on making such a tool?  I have a great idea for a program I'd love to try, however I just don't know much about image processing as I've never done it.
I'd be very grateful for any tips or info to point me in the right direction!  Thanks!

A: color_histogram


text:
Q: .NET Process to open web page without tabs or address bar Is there a way in .NET to have a Process open the default web browser with no address bar and no tabs, WITHOUT using kiosk mode? I can't use the WebBrowser object because it uses IE7, and the pages that need to be opened use JavaScript. I can't use kiosk mode because the client needs the window to appear in a specific area of the screen. I also need to maintain access to the browser because I have to know when the page is closed.

A: Try this:
dynamic ie = Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application"));

ie.AddressBar = false;
ie.MenuBar = false;
ie.ToolBar = false;

ie.Visible = true;
ie.Navigate("www.google.com");

This uses automation to achieve what you want.
You can also set the position, add event handlers, etc.
The documentation for this interface is here.

A: If you want to acheive browser automation then you should use Selenium webdriver


text:
Q: Segfault everywhere even when reinstalling the OS Lately my PC keeps getting segmentation fault, everywhere, on almost every apps (thunderbird, firefox, chromium, google-chrome, wine, byobu)
here's the last few output of dmesg:
[ 1474.815026] traps: chrome[2134] general protection ip:7f38bb407aef sp:7fff59358350 error:0 in chrome[7f38b9b18000+51d2000]
[ 3867.645750] traps: chrome[10568] general protection ip:7fb4864ed072 sp:7fffceacd7a0 error:0 in chrome[7fb4848e0000+51d2000]
[ 5075.793435] traps: chrome[5951] general protection ip:7fb486530bbe sp:7fffceaceaa0 error:0 in chrome[7fb4848e0000+51d2000]
[ 6232.893991] traps: chrome[6031] general protection ip:7fb486530bbe sp:7fffceacd4f0 error:0 in chrome[7fb4848e0000+51d2000]
[ 6270.321944] traps: chrome[15562] general protection ip:7fb4864f0150 sp:7fffceacedb8 error:0 in chrome[7fb4848e0000+51d2000]
[ 6284.271553] traps: HTMLParserThrea[15673] general protection ip:7fb4869ed85b sp:7fb4702b6910 error:0 in chrome[7fb4848e0000+51d2000]
[ 6390.844552] traps: chromium[15700] general protection ip:7f63e065b76e sp:7fff367a4ba0 error:0 in chromium[7f63debd0000+5864000]
[ 7645.971546] traps: chromium[18004] general protection ip:7f63e0653e64 sp:7fff36799df0 error:0 in chromium[7f63debd0000+5864000]
[ 7927.389333] traps: chrome[18743] general protection ip:7f3acfd00150 sp:7fff42406438 error:0 in chrome[7f3ace0f0000+51d2000]
[ 8075.937762] traps: chrome[18674] general protection ip:7f3acfd00150 sp:7fff42406438 error:0 in chrome[7f3ace0f0000+51d2000]
[ 8159.218088] chromium[2966]: segfault at 180816000388 ip 00007f63e06a62c5 sp 00007fff367a47a0 error 4 in chromium[7f63debd0000+5864000]
[ 8515.463384] traps: chromium[20359] general protection ip:7f63e06bfcdf sp:7fff36798100 error:0 in chromium[7f63debd0000+5864000]
[ 8540.132912] traps: komodo[14107] trap stack segment ip:7f81c87b158a sp:7ffff8021890 error:0
[ 8745.165817] Key type dns_resolver registered
[ 8745.174187] FS-Cache: Netfs 'cifs' registered for caching
[ 8745.174286] Key type cifs.spnego registered
[ 8745.174293] Key type cifs.idmap registered
[ 8771.698855] traps: chrome[21109] general protection ip:7f3acfd038ce sp:7fff42406390 error:0 in chrome[7f3ace0f0000+51d2000]
[ 8956.317097] Chrome_IOThread[2374]: segfault at 39 ip 00007f18935a8d00 sp 00007f18775279a8 error 6 in chromium[7f1892658000+5864000]
[ 8959.347113] traps: chromium[22247] general protection ip:7f72f97c6f0a sp:7fffeb74ac90 error:0 in chromium[7f72f7db8000+5864000]
[ 8979.590397] traps: chromium[22514] general protection ip:7f72f983931e sp:7fffeb753070 error:0 in chromium[7f72f7db8000+5864000]
[ 8982.106736] chromium[22627]: segfault at 96dfb2e4e0 ip 00007f72f9842bd8 sp 00007fffeb754670 error 4 in chromium[7f72f7db8000+5864000]
[ 9031.249176] traps: chromium[22333] general protection ip:7f72f97068d0 sp:7fffeb7546f8 error:0 in chromium[7f72f7db8000+5864000]

And first few second during execution of firefox:
(process:23183): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failed
Segmentation fault

When using gdb firefox:
[New Thread 0x7fffc33ff700 (LWP 22838)]

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffda3ff700 (LWP 22692)]
0x00007ffff386e905 in ?? () from /usr/lib/firefox/libxul.so

On chromium:
[2333:2374:0731/105842:ERROR:raw_channel_posix.cc(139)] recvmsg: Connection reset by peer
[2333:2374:0731/105842:ERROR:channel.cc(297)] RawChannel fatal error (type 1)

*snip*

[2333:2374:0731/105903:ERROR:raw_channel_posix.cc(139)] recvmsg: Connection reset by peer
[2333:2374:0731/105903:ERROR:channel.cc(297)] RawChannel fatal error (type 1)
../../third_party/tcmalloc/chromium/src/free_list.h:118] Memory corruption detected.
Segmentation fault

When using google-chrome-stable:
[18495:18528:0731/105816:ERROR:raw_channel_posix.cc(139)] recvmsg: Connection reset by peer
[18495:18528:0731/105816:ERROR:channel.cc(297)] RawChannel fatal error (type 1)
--2014-07-31 10:58:16--  https://clients2.google.com/cr/report
Resolving clients2.google.com (clients2.google.com)... 111.94.248.52, 111.94.248.38, 111.94.248.18, ...
Connecting to clients2.google.com (clients2.google.com)|111.94.248.52|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: '/dev/fd/3'

    [<=>                                          ] 0           --.-K/s
Crash dump id: 8d43b07b2158483d

When using thunderbird:
[Exception... "'Method not implemented' when calling method:
[imIAccount::loadBuddy]"  nsresult: "0x80004001 (NS_ERROR_NOT_IMPLEMENTED)"  location: "JS frame :: resource://gre/components/imContacts.js :: <TOP_LEVEL> :: line 1237"  data: no]

*snip*

[Exception... "'Method not implemented' when calling method: [imIAccount::loadBuddy]"  nsresult: "0x80004001 (NS_ERROR_NOT_IMPLEMENTED)"  location: "JS frame :: resource://gre/components/imContacts.js :: <TOP_LEVEL> :: line 1237"  data: no]
Segmentation fault

And many more.. Currently I'm using Manjaro Linux:
Linux archpc 3.14.13-1-MANJARO #1 SMP PREEMPT Fri Jul 18 09:02:40 UTC 2014 x86_64 GNU/Linux

Previously I'm using latest ArchLinux, it also happened..
I'm seriously don't know what to do.. It's only happened since past 3 weeks, before that, Chrome and Chromium only crash "Aw snap" once in a while.
Here's the list of installed program in my computer: http://pastie.org/9433158
Could anyone help me to find the causation of this problem?

A: Sounds like a hardware fault. Segfaults across the whole system can be caused by bad sectors on the disk or bad memory.
Run a memory test and see if there's some faulty memory that is causing your issue.
After that if the memory test does not find an issue, I would run a badblocks scan on your hard drive.


text:
Q: subtracting one image from another how can i subtract one image from another either row wise or column wise ?

A: I don't quite understand what you mean with 'row-wise' or 'column-wise'. In MATLAB, you can subtract two images from one another directly, as long as they're the same size, of course.
%# load the images
im1 = imread('firstImage.tif')
im2 = imread('secondImage.tif')

%# subtract
deltaImage = im1 - im2;

Note: If you have the image processing toolbox, you can use deltaImage = imsubtract(im1,im2) to deal with underflow if your images are integer arrays.

A: Use OpenCV Have two IPlImage variables point to your two images and subtract them..like this
IplImage im1=your image1;
IplImage im2=your image2;
IplImage im3;
cvSub(im1,im2,im3);

Obviously you need to open the images first. This works because iplimage is a derived structure from mat

A: Here is a possible solution:
[file path]=uigetfile('*.jpg');
I=imread([path file]);
[file path]=uigetfile('*.jpg');
J=imread([path file]);
K=I-J;
figure;
imshow(K);
title('SUBTRACTED IMAGE ');


text:
Q: VBA - referring range in other worksheet using Worksheet_Change - Error 1004 I need to refer the range in different worksheet, so I have used Worksheet_change event but getting error 1004. Below is the code -
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim inputSheetName As String
    Dim dataSheetName As String
    inputSheetName = Range("Selected_State").Worksheet.Name
    dataSheetName = Range("Selected_City").Worksheet.Name
End Sub

here Range-"Selected_State" is range in Sheet1 and "
Range - "Selected_City is range in Sheet2

A: A range is always within a specific worksheet. If you use
Range("Selected_State")

then Excel assumes that this range is in the active sheet. It is exactly the same as this:
ActiveSheet.Range("Selected_State")

So if you want to know in which worksheet a named range is you should use this:
ThisWorkbook.Names("Selected_State").RefersToRange.Worksheet.Name

Note: This does only work if the name is within the workbook scope but not when within a worksheet's scope. Therefore you would need to loop through all worksheets to find that name.