text:
Q: Batch if statement multiple inputs So i was writing a batch file for fun and i had a multiple choice statement, so i had it like this:
@echo off
title John's apples
echo.
echo John got 3 apples, he gives 1 away. How many does he have then?
echo (Please answer with ONE capital letter, or type Exit to exit.)
echo =============
echo.
echo A) 2.5
echo B) 3.459475945
echo C) 2
echo D) 1
echo Exit
echo.
:answer
set /p ans=Your Answer:
if "%
if "%ans%"=="a" Echo Please answer with a capital letter!&set /p ans=Your Answer:
if "%ans%"=="b" Echo Please answer with a capital letter!&set /p ans=Your Answer:
if "%ans%"=="c" Echo Please answer with a capital letter!&set /p ans=Your  Answer:
if "%ans%"=="d" Echo Please answer with a capital letter!&set /p ans=Your Answer:
if "%ans%"=="A" Echo Wrong! The answer was 2.
if "%ans%"=="B" Echo Wrong! The answer was 2.
if "%ans%"=="C" Echo Right! Good job! The answer was 2.
if "%ans%"=="D" Echo Wrong! The answer was 2.
if "%ans%"=="Exit" exit

Pause
Exit

So now i wanna know, if someone puts the wrong answer in (because you have to put a capital letter in, otherwise it will not work) it says nothing. So i wanna know how i do something like:
If A,B,C,D are not the input, print "Please enter a valid answer!"
Can anybody help? this might be asked already, sorry for that...there might be some random thingy's in the script because i was testing some around.

A: @echo off
title John's apples
echo.
echo John got 3 apples, he gives 1 away. How many does he have then?
echo (Please answer with ONE capital letter, or type Exit to exit.)
echo =============
echo.
echo A) 2.5
echo B) 3.459475945
echo C) 2
echo D) 1
echo Exit
echo.
:answer
set /p ans=Your Answer:
if "%ans%"=="a" Echo Please answer with a capital letter!&goto answer
if "%ans%"=="b" Echo Please answer with a capital letter!&goto answer
if "%ans%"=="c" Echo Please answer with a capital letter!&goto answer
if "%ans%"=="d" Echo Please answer with a capital letter!&goto answer
if "%ans%"=="A" Echo Wrong! The answer was 2.&goto end
if "%ans%"=="B" Echo Wrong! The answer was 2.&goto end
if "%ans%"=="C" Echo Right! Good job! The answer was 2.&goto end
if "%ans%"=="D" Echo Wrong! The answer was 2.&goto end
if "%ans%"=="Exit" exit
echo Please enter a valid answer!
goto answer

:end
Pause
Exit

A: I'm guessing the seperation of capital letters is desired to single out, rather than being forgiving with the '/i' parameter. Here's my attempt.
@echo off
title John's apples

rem delayed expansion by preference.
setlocal enableDelayedExpansion

:init
cls
rem Added an initial label, and a clear for the 'ans' variable.
set "ans="
echo.
echo John got 3 apples, he gives 1 away. How many does he have then?
echo (Please answer with ONE capital letter, or type Exit to exit.)
echo =============
echo.
echo A) 2.5
echo B) 3.459475945
echo C) 2
echo D) 1
echo Exit
echo.
set /p ans=Your Answer:

rem Check if input is empty, then check for [a,b,c,d] in any case using the '/i' parameter,
rem Upon a valid letter, check for case. As well as a last check for a valid answer.
if not defined ans (
    echo Empty input . . .
) else (
    if /i "!ans!" equ "exit" (
        exit /b
    ) else (
        if /i "!ans!" equ "A" (
            if "!ans!" equ "a" echo Please answer with a capital letter!
            echo Wrong! The answer was 2.
        ) else (
            if /i "!ans!" equ "B" (
                if "!ans!" equ "b" echo Please answer with a capital letter!
                echo Wrong! The answer was 2.
            ) else (
                if /i "!ans!" equ "C" (
                if "!ans!" equ "c" echo Please answer with a capital letter!
                echo Right! Good job! The answer was 2.
                ) else (
                    if /i "!ans!" equ "D" (
                        if "!ans!" equ "d" echo Please answer with a capital letter!
                        echo Wrong! The answer was 2.
                    ) else (
                        echo Invalid input . . .
                    )
                )
            )
        )
    )
)
pause
goto :init

A: I may have modified a little, but this works a lot better:
@echo off
color 0a
cls
:game
title John's apples
cls
echo John got 3 apples, he gives 1 away. How many does he have then?
echo (Please answer with ONE capital letter)
echo ===============================================================
echo A) 2.5
echo B) 3.459475945
echo C) 2
echo D) 1
echo E) Exit
set /p ans=

if %ans%== a goto capital
if %ans%== A goto wrong
if %ans%== b goto capital
if %ans%== B goto wrong
if %ans%== c goto capital
if %ans%== C goto correct
if %ans%== d goto capital
if %ans%== D goto wrong
if %ans%== e exit

:wrong
Echo Wrong! The Answer was 2.
pause
exit

:capital
echo Please answer with a capital letter!
pause
goto game

:correct
echo Right! Good job! The answer was 2!
pause
exit


text:
Q: Can a method that does not return a value contain 0 formal parameters? Can a method that does not return a value contain 0 formal parameters?
I understand this means that there won't be any actual parameter either but I'm just wondering if this is correct in any case?

A: Of course it can.
What about a function, for example, that prints the current time?
A more concrete case in Java is System.gc() which suggests a garbage collection.
The Java language doesn't attempt to make rather pointless restrictions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Easier way to execute the last echo command in a shell? I'm using bash shell.  If I want to execute the last echo command, I can run
history | grep echo

and then grab the last echo command from what is displayed and run it.  I was wondering, is there a shorter way to do this?  I'm happy to use another shell if that allows me to somehow more easily execute the last "echo" command if all I know is the command started with "echo."

A: type to command line this: !echo

A: Using reverse interactive search:

*

*hit Ctrlr

*start typing for the command you want

*when the shell has found the one you want, hit Enter.

If you want to use a previous echo command

*

*hit Ctrlr

*type echo

*hit Ctrlr again, repeatedly until you find the command you want.

*if you go too far back in history, Ctrls searches in the opposite direction.

If you don't want to execute the command, but edit it a bit, when you find the command you want:

*

*don't hit Enter

*instead, hit the ESC or left or right arrow key

If you want to reject the command,

*

*clear the command-line Ctrlg or Ctrlc (the latter leaves the line behind, though).


text:
Q: How to style the ActionBar background and overflow menu (color & text) Hi i want to change the click Backround color of my ActionBar Menu.
i tried a lot of things with selectors and so on, but nothing works.
i don't want to use ActionBar generators or anything like this. i want to change the click event color by standard XML Code. But i don't know how.
this is my styles.xml
<resources>

<style name="keksRatingBar" parent="@android:style/Widget.RatingBar">
<item name="android:progressDrawable">@drawable/keks_ratingbar_full</item>
<item name="android:minHeight">23dip</item>
<item name="android:maxHeight">78dip</item>
</style>

<style name="MyadaptHoloLightTheme" parent="@android:Theme.Holo.Light">

<item name="android:actionBarStyle">@style/ActionBar</item>
<item name="android:popupMenuStyle">@style/ActionBarPopup</item>
</style>

<!--ActionBarBackround Color -->
<style name="ActionBar" parent="android:style/Widget.Holo.Light.ActionBar">
<item name="android:background">@color/ActionBarRed</item>
<item name="android:dropDownSelector">@color/ActionBarSelection</item>
</style>

<!-- ActionBar Backround Color Popup -->
<style name="ActionBarPopup" parent="android:style/Widget.Holo.Light.ListPopupWindow">
<item name="android:popupBackground">@color/ActionBarMenu</item>

</style>

</resources>

A: There are several different text and background (color/drawable) styles that deal with the different sections of the ActionBar.
For the Main Title and ActionBar/ActionMode background:
<style name="ColorTheme.DeviceDefault.Dark" parent="@style/Theme.AppCompat">
    <!-- ActionBar -->
    <item name="android:actionBarStyle">@style/ColorTheme.ActionBar.Dark.Solid</item>

    <item name="android:actionModeStyle">?android:actionBarStyle</item>
    <item name="android:actionModeBackground">@drawable/cab_background_top_dark</item>
</style>

<style name="ColorTheme.ActionBar.Dark.Solid" parent="@android:style/Widget.Holo.ActionBar.Solid">
    <item name="android:titleTextStyle">@style/TitleTextStyle</item>
    <item name="android:background">@drawable/ab_solid_dark</item>

    <!-- Added in API 14 -->
    <item name="android:backgroundStacked">@drawable/ab_stacked_solid_dark</item>
    <item name="android:backgroundSplit">@drawable/ab_bottom_solid_dark</item>
</style>

For the Menu Items:
<style name="ColorTheme.DeviceDefault.Dark" parent="@style/BaseTheme.DeviceDefault.Dark">

    <item name="android:actionMenuTextAppearance">@style/TitleTextStyle</item>
    <item name="android:actionMenuTextColor">?colorButtonText</item>

    [Also various action...Style attributes]
</style>

For the Overflow Menu:
<style name="ColorTheme.DeviceDefault.Dark" parent="@style/BaseTheme.DeviceDefault.Dark">
    <item name="android:popupMenuStyle">@style/ColorTheme.ActionBar.PopupMenu.Dark</item>

    <item name="android:textAppearanceLargePopupMenu">@style/PopupMenuTextStyle</item>
    <item name="android:textAppearanceSmallPopupMenu">@style/PopupMenuTextStyle.Small</item>
</style>

<style name="PopupMenuTextStyle" parent="@android:attr/textAppearance">
    <item name="android:textColor">?colorTitleText</item>

    <item name="android:typeface">sans</item>
    <item name="android:textSize">@dimen/text_size_small_plus</item>
    <item name="android:textStyle">normal</item>
</style>

<style name="PopupMenuTextStyle.Small">
    <item name="android:textSize">@dimen/text_size_small</item>
</style>

Also note that some of these are API 11+ or API 14+ only, so to use lower-SDK versions, you'll need the AppCompat Support Library, and drop the "android:" namespace. So for example, "android:actionBarStyle" would be "actionBarStyle" on pre-API 11 styles.


text:
Q: git: How to get more information (when, sha) about a branch merging into another? I found git branch -r --merged master to see all the branches ever merged into master
Our flow is pretty standard: develop == feature branch --> develop == release branch --> master  ("==" create a branch from; "-->" PR into)
I want to find out when the branch merged (or the latest sha) in order to generate a list of branches merged since the last PR into master
Ideally, we would have an inventory of each release branch
Cheers

A: "git branch" is probably the wrong tool for this job: it will only tell you about branches that still exist, and merged feature branches aren't something you particularly need lying around.
Its definition of "merged" also can't tell you "when" - it just means there's at least one path working backwards from "master" that gets you to the current tip of that branch. (A commit is never really "on" a branch in git; a branch only exists as a pointer to a single commit, and from there to its entire history.)
A different approach to the problem is this:
git log --first-parent master..develop

As long as the only commits that get into develop are merge commits - no fast-forward merges or direct commits to that branch - this will give you a list of them.

*

*The --first-parent stops it listing out the individual commits from each feature merged in.

*The master..develop notation means roughly "everything on develop that's not also on master". (Again, "on" actually means "reachable from the current tip of".)

You can use the --pretty option to customise exactly what gets shown here. I frequently use it with --pretty='format:%s' which just shows the commit message on the merge commit.

A: I found a good solution for me:
I compare the release branches against each other
import sys
from subprocess import run, PIPE, CompletedProcess

if len(sys.argv) > 1:
    branch1 = sys.argv[1]
else:
    branch1 = "master"

if len(sys.argv) > 2:
    branch2 = sys.argv[2]
else:
    branch2 = "develop"

base_command = ["git", "branch", "-r", "--merged"]

branch2_command = base_command + [branch2]
process_result : CompletedProcess = run(branch2_command, stdout=PIPE, check=True)
branch2_result = process_result.stdout.decode("utf-8")
branch2_list = branch2_result.split()

branch1_command = base_command + [branch1]

process_result : CompletedProcess = run(branch1_command, stdout=PIPE, check=True)
branch1_result = process_result.stdout.decode("utf-8")
branch1_list = branch1_result.split()

result = [item for item in branch2_list if item not in set(branch1_list)]

print(branch2 + " minus " + branch1 + " is\n" + "\n".join(result))

if I compare origin/release/1 to origin/release/2, I get the new stuff in release/2
Cheers


text:
Q: Distinct elements of relations R is the relation on Z (integers) given by xRy ( X is related to Y )
if 3 divides (x-y),
what are the distinct elements of  R?

A: I would start by writing out what it means for 3 to divide a number, that is, $3 | n$ if and only if  $\exists k$ s.t. $n = 3k$. When does $3 | (x - y)$ is the next question we should ask ourselves. As suggested in one of the comments on your post, often this is where it helps to come up with some examples, for instance, does $1R5$? does $5R8$ ? does $8R5$ ? Now that we've considered some examples, lets expand on the definition a little, when $3 | (x - y)$ we have that $\exists k$ s.t. $(x - y) = 3k$ or alternatively, x is related to y whenever their difference is a multiple of 3.


text:
Q: How to simplify this mass of similar ifs I am trying to figure out how to simplify this piece of code. The logic for every if condition is basically the same so I want to get rid of the duplicate ifs:
      if "video_codec" in profile:
          self.video_codec = profile["video_codec"]
      if "resolution_width" in profile:
          self.resolution_width = profile["resolution_width"]
      if "resolution_height" in profile:
          self.resolution_height = profile["resolution_height"]
      if "ratio" in profile:
          self.ratio = profile["ratio"]
      if "video_bitrate" in profile:
          self.video_bitrate = profile["video_bitrate"]
      if "profile" in profile:
          self.profile = profile["profile"]
      if "audio_codec" in profile:
          self.audio_codec = profile["audio_codec"]
      if "audio_channels" in profile:
          self.audio_channels = profile["audio_channels"]
      if "audio_bitrate" in profile:
          self.audio_bitrate = profile["audio_bitrate"]

I hope this can be done in 3-4 lines instead of my 18 lines.

A: If you just want to copy all key/value pairs from profile to attributes in self, you can use the following:
self.__dict__.update(profile)

If there are some items in profile that you do not want to copy, then you can use the following:
for attr in ("video_codec", "resolution_width", "resolution_height", "video_bitrate",
             "ratio", "profile", "audio_codec", "audio_channels", "audio_bitrate"):
    if attr in profile:
        setattr(self, attr, profile[attr])

A: for key, value in profile.iteritems():
    setattr(self, key, value)

Should do what you want


text:
Q: How to call closure function obtained through reflection? I'm experimenting with using Go's reflection library and have come to an issue I cannot figure out: How does one call on a function returned from calling a closure function via reflection? Is it possible to basically have a sequence of:
func (f someType) closureFn(i int) int {
  return func (x int) int {
     return x+i
  }
}
...

fn := reflect.ValueOf(&f).MethodByName("closureFn")
val := append([]reflect.Value{}, reflect.ValueOf(99))
fn0 := fn.Call(val)[0]
fn0p := (*func(int) int)(unsafe.Pointer(&f0))
m := (*fn0p)(100)

Which should get m to equal 199?
The following is the simplified code that demonstrates the issue. The call to the "dummy" anonymous function works ok, as does the reflective call to the closure. However attempts at calling on the closure return fail with a nil pointer (the flag set on the address of the Value in the debugger is 147, which comes down to addressable).
Any suggestions on what's going on, or if it's at all possible are welcome.
Link to playground: https://play.golang.org/p/0EPSCXKYOp0
package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

// Typed Struct to hold the initialized jobs and group Filter function types
type GenericCollection struct {
    jobs []*Generic
}

type Generic func (target int) int

func main() {
    jjf := &GenericCollection{jobs: []*Generic{}}
    jjf.JobFactoryCl("Type", 20)
}

// Returns job function with closure on jobtype
func (f GenericCollection) Job_by_Type_Cl(jobtype int) (func(int) int) {
    fmt.Println("Job type is initialized to:", jobtype)

    // Function to return
    fc := func(target int) int {
        fmt.Println("inside JobType function")
            return target*jobtype
    }
    return fc
}

// Function factory
func (f GenericCollection) JobFactoryCl(name string, jobtype int) (jf func(int) int) {

    fn := reflect.ValueOf(&f).MethodByName("Job_by_" + name + "_Cl")
    val := append([]reflect.Value{}, reflect.ValueOf(jobtype))
    if fn != reflect.ValueOf(nil) {

        // Reflected function -- CALLING IT FAILS
        f0 := fn.Call(val)[0]
        f0p := unsafe.Pointer(&f0)

        //Local dummy anonymous function - CALLING IS OK
        f1 := func(i int) int {
            fmt.Println("Dummy got", i)
            return i+3
        }
        f1p := unsafe.Pointer(&f1)

        // Named function

        pointers := []unsafe.Pointer{f0p, f1p}

        // Try running f1 - OK
        f1r := (*func(int) int)(pointers[1])
        fmt.Println((*f1r)(1))
        (*f1r)(1)

        // Try calling f0 - FAILS. nil pointer dereference
        f0r := (*func(int) int)(pointers[0])
        fmt.Println((*f0r)(1))

        jf = *f0r
    }
    return jf
}

A: Type assert the method value to a function with the appropriate signature.  Call that function.
First example from the question:
type F struct{}

func (f F) ClosureFn(i int) func(int) int {
    return func(x int) int {
        return x + i
    }
}

func main() {
    var f F
    fn := reflect.ValueOf(&f).MethodByName("ClosureFn")

    fn0 := fn.Call([]reflect.Value{reflect.ValueOf(99)})[0].Interface().(func(int) int)
    fmt.Println(fn0(100))

    // It's also possible to type assert directly
    // the function type that returns the closure.
    fn1 := fn.Interface().(func(int) func(int) int)
    fmt.Println(fn1(99)(100))
}

Run it on the Playground
Second example from the question:
func (f GenericCollection) JobFactoryCl(name string, jobtype int) func(int) int {
    jf := reflect.ValueOf(&f).MethodByName("Job_by_" + name + "_Cl").Interface().(func(int) func(int) int)
    return jf(jobtype)
}

func main() {
   jjf := &GenericCollection{jobs: []*Generic{}}
   jf := jjf.JobFactoryCl("Type", 20)
   fmt.Println(jf(10))
}

Run it on the Playground


text:
Q: clipping Tikzpicture within math Every time I try to clip a Tikzpicture within math environments (id est, \begin{equation}\end{equation}, [] or $$) I get the following error

Package tikz Error: Extra options not allowed for clipping path command.

Here is the exact code:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath,amssymb,amsthm}
\usepackage{parskip}
\usepackage{tikz}
\usepackage{tikz-cd}
\usepackage{float}
\usepackage{makeidx}
\usepackage{enumerate}
\usepackage{bm}
\usepackage{fancyhdr}
\usepackage[top=2cm,bottom=2cm]{geometry}
\usepackage{framed}
\usepackage{mdframed}
\usepackage{graphicx}
\usepackage{pict2e}

\usetikzlibrary{knots,intersections,decorations.pathreplacing,hobby,arrows,patterns}
\tikzset{every path/.style={black,thick}, every node/.style={transform shape, knot crossing, inner sep=2.5pt}}

\begin{document}

\[ \epsilon\left(\begin{tikzpicture}[scale=0.4]
 \clip (-1.5,-0.7)--(-1.5,0.7)--(1.5,0.7)--(1.5,-0.7)--(-1.5,-0.7)--cycle;
  \begin{scope}[yshift=-0.3cm]
   \draw[->,thin] (-1,-1)--(1,1);
   \draw[ultra thick,double distance=0.4pt,double=black,white] (-1,1)--(1,-1);
   \draw[->,thin] (-1,1)--(1,-1);
  \end{scope}
 \end{tikzpicture}\right) \]

\end{document}

I saw Drawing the rules for the bracket polynomial and got some ideas on how to fix my code. More specifically, following @egreg's answer by defining macros for the picture. However, I have a lot of knot diagrams drawn in mathematical environments, and most are scaled differently. The answer given by @GuM looked useful, but I did not understand how to implement it.
tl;dr: what is the best method to clip tikzpictures that are surrounded by mathematical environments, given that most are scaled differently?
edit: I am assuming it has something to do with the following line of code I have
\tikzset{every path/.style={black,thick}, every node/.style={transform shape, knot crossing, inner sep=2.5pt}}
edit2: When I try adding \tikzset{every path/.style={}} before the clip, and \tikzset{every path={black,thick}} after the clip, it does remove the error. However, it does not end up drawing all diagrams properly. For instance,
\begin{align*}
  \left\langle\begin{tikzpicture}[scale=0.005]
  \tikzset{every path/.style={}}
  \clip (0,0)--(150,0)--(150,100)--(0,100);
  \tikzset{every path={black,thick}}
   \begin{scope}[yshift=-70cm]
    \draw[thin]    (98.5,132) .. controls (48.07,199.48) and (-22.7,112.44) .. (13.82,70.28) .. controls (26.55,55.59) and (52.31,46.35) .. (96.5,51) ;
    \draw[thin]    (44.5,39) .. controls (78.5,-45) and (130.5,45) .. (114.5,102) ;
    \draw[thin]   (127.5,58) .. controls (195.69,97.4) and (107.74,133.35) .. (64.59,109.76) .. controls (50.78,102.21) and (41.56,88.57) .. (43.5,67) ;
   \end{scope}%
  \end{tikzpicture}\right\rangle
\end{align*}

removes some curves. Not sure why.

A: Not sure if that error is really helpful, or should it be changed to warning by applying following patch?
\usepackage{xpatch}
\makeatletter
\xpatchcmd\tikz@finish
  {\tikzerror{Extra options not allowed for clipping path command.}}
  {\PackageWarning{tikz}{Extra options not allowed for clipping path command.}}
  {}{\fail}
\makeatother

IMOH, discarding unused \tikz@options in clip mode won't cause severe problems.

A: I completely forgot to answer my question. @egreg's comment fixed the mistake.
I first made a new command to use:
\newcommand{\knotsinmath}[1]{%
 \tikzset{every path/.style={}}
 \begin{tikzpicture}[baseline=-\dimexpr\fontdimen22\textfont2\relax]
  #1
 \end{tikzpicture}%
}

Then, this works perfectly fine. The problem I was facing back then happened to do with the clip itself, but this also makes the error go away.
\begin{align*}
  \left\langle\knotsinmath{\begin{scope}[scale=0.005,yshift=-70cm]
   \clip (0,0)--(160,0)--(160,160)--(0,160)--cycle;
   \draw[thin]    (98.5,132) .. controls (48.07,199.48) and (-22.7,112.44) .. (13.82,70.28) .. controls (26.55,55.59) and (52.31,46.35) .. (96.5,51) ;
   \draw[thin]    (44.5,39) .. controls (78.5,-45) and (130.5,45) .. (114.5,102) ;
   \draw[thin]   (127.5,58) .. controls (195.69,97.4) and (107.74,133.35) .. (64.59,109.76) .. controls (50.78,102.21) and (41.56,88.57) .. (43.5,67) ;
   \end{scope}}\right\rangle
\end{align*}


text:
Q: What is Gitkraken's default git-config esp. for gitflow Gitkraken does not follow the default Git settings. When I use git and git flow from the command line, the operations taken are different from what Gitkraken performs.  On the command line, doing git merge by default does a fast forward.  Gitkraken does not fast-forward when merging.  When using git flow from the command line, finishing a feature also does a fast forward by default.  When finishing a hotfix, if nobackmerge is false and notag is true, gitflow will merge master into develop, which seems at odds with the git flow workflow.  This does not happen in Gitkraken when a hotfix is not tagged.  I looked through Gitkran's .gitkraken directory and could not find any git settings.  I also looked in the .gitconfig directories where I used Gitkraken, hoping to find what settings it uses.  It appears Gitkraken passes built-in default arguments to the git commands that it runs without disclosing it, and ignoring any user Git settings. So far, by using git flow on the command line and Gitkraken in separate directories, and then looking at the git reflog, I've been able to find that these settings are being emulated:
[merge]
    ff = false
[pull]
    ff = true
[gitflow]
    multi-hotfix = true
[gitflow "hotfix.finish"]
    nobackmerge = true
    no-ff = true
[gitflow "feature.finish"]
    no-ff = true

These options are selected interactively
[gitflow "hotfix.finish"]
    notag = true|false
    keep = true|false
[gitflow "feature.finish"]
    notag = true|false
    keep = true|false

I am trying to set up .gitconfig so that command line Git's default behavior approximates Gitkraken's behavior.


text:
Q: jQuery code working on Chrome and Mozilla web browser but not on Internet Explorer I have the following code on aspx file:
<asp:GridView ID="GridView1"  runat="server" ShowFooter="true"
AutoGenerateColumns="False" >
   <Columns>
            <asp:TemplateField>
              <ItemTemplate>
<asp:LinkButton ID="Button1" runat="server" Text="Active" OnClientClick="return
confirmMessage(this);" />
             </ItemTemplate>
    </Columns>
</asp:GridView>

I have the following Jquery/client side code
function confirmMessage(obj)
{
if ($(obj).attr("text")=="Active")
{
return confirm("Convert from active to inactive");
}
else
{
return confirm("Convert from inactive to active");
}
}

The above mentioned code is working fine on Mozilla and Chrome browswer but in case of Internet Explorer , it's always executing the 2nd block i.e.
return confirm("Convert from inactive to active");

Help would be appreciated.

A: Your problem is very likely related to the string comparison differences between different browsers, as well as the differences in text-from-DOM generation mechanics. Have you tried to see under a debugger (such as IE9 Developer Tools/Scripting tab), what returns the $(obj).attr("text") under IE?
Furthermore, the approach of comparing texts is not highly reliable anyway (e.g. it would fail after any change in the Text of your LinkButton). I would advise you to rely on either classes or different link buttons instead, for example:

*

*Use the following markup for the LinkButton: (notice the CssClass property):
<asp:LinkButton ID="Button1" runat="server" Text="Active"
OnClientClick="return confirmMessage(this);" CssClass="button-activate" />

*Then use the following JavaScript:
function confirmMessage(obj) {
     if ($(obj).is(".button-activate")) {
          return confirm("Convert from active to inactive");
     } else {
          return confirm("Convert from inactive to active");
     }
}

When your button is not 'Activate' anymore but 'Deactivate', simply put any other CssClass value to the LinkButton.

A: There is no attribute called 'text', an ASP.NET server control 'Text' attribute gets converted to the 'value' attribute on the client side.
You need to refer to the value as so:
$(obj).attr("value");

Or more simply as:
$(obj).val();


text:
Q: Activate hover CSS of another class? In this code the CSS will make the Image "grow" when you hover over it. However , I'd like to make the image grow when you hover over the word "github" (next to the image).

 GitHub

A: Since the image is a child to the anchor element, you can use the child selector notation:


text:
Q: how to change textbox input language in web application Im workin on a web application , and I have a form  on which I have a textbox that users
must fill it using arabic language.
how can I control it using javascript ?
Changing the default language of the operting system to arabic will solve my problem.
How can i change the default language to arabic using javascript ???
and is it the best approch to do it??
Is their another method ?

A: Refer to this question and it will solve your problem pal
Arabic text box
EDIT:
Change the code to this
$().ready(function () {
    $("input#NameTextBox").attr("lang", "fa");
});

A: a better solution may be:
Farsi type java script code

A: If using jquery in your application is possible you may take a look at the jquery direction plugin. You may see it in action here.

A: If you want to limit the characters entered into a text box there is no use to set the language of the operating system.
You can use a RegularExpressionValidator or a CustomValidator which checks the characters entered, and displays a message saying those characters are not allowed.
Or add some form of javascript which limits the same. You have to decide if you want to block characters as they are typed, or display a message.

A: You want to change the default language of the OS using JS? Never, ever, going to happen - your web page has absolutely no rights over the client machine.
As for making the page itself "be arabic", I really don't think there's anything you can do about this from a culture point of view, but in terms of merely making the page right-to-left there's a lot that needs to be done in terms of mirroring content, but you'll definitely want to know about direction. You're best bet for the rest is to deal with culture and cultural validation on the server-side but it's going to depend enormously on what exactly you're trying to force, e.g. actual language validation assumes things like dictionaries and grammar checking and that would be something you probably want to look at 3rd party solutions for.


text:
Q: Cannot get External URL from UploadFileWithIDSelector object I am trying to create an action that opens a tab, inserts an uploaded file's external URL into the tab, and navigates to that URL just like as if a user clicked the Files button and then clicked one of the File's titles and it opened up the tab with the contents of the file.
Here is the code I used to get the External Link. Please note that I have the FileID stored as an extension column in the InventoryItem table for this example:
PXView item = Base.Views["Item"];

InventoryItem item = PXSelect<InventoryItem, Where<InventoryItem.inventoryCD,
   Equal<Current<InventoryItem.inventoryCD>>>>
   .Select(Base, Base.Views["Item"].Cache.Current);

InventoryItemExt itemext = item.Cache.GetExtension<InventoryItemExt>(item);
UploadFileWithIDSelector fileInfo = PXSelect<UploadFileWithIDSelector,
   Where<UploadFileWithIDSelector.fileID,
   Equal<Current<PX.Objects.IN.InventoryItemExt.usrDefaultSpecID>>>
   .Select(Base, itemext.UsrDefaultSpecID);

I then try to execute the following code to open the page using the ExternalLink:
throw new PXRedirectToUrlException(fileInfo.ExternalLink, "");

This results in the following error:

Object reference not set to an instance of an object.

Is the DAC unable to directly get the external link? Is there any way to fix this so it retrieves the external link? Is there another (possibly simpler) way to retrieve the external link of an uploaded file?
Thanks

A: You should be able to redirect to the file with this syntax:
throw new PXRedirectToUrlException(PXRedirectToFileException.BuildUrl(fileInfo.fileID), "");

Consider using this syntax to redirect since you don't need a message:
throw new PXRedirectToFileException(fileInfo.fileID, true);


text:
Q: What is wrong with these sentences? my sql command
ALTER TABLE orders
ADD size varchar(255),
    CHECK(size in ('s','m','l','xl'));

A: MySql expect the check directly after the declaration of the column, so if you remove the comma everything works sine
ALTER TABLE orders ADD size varchar(255) CHECK(size in ('s','m','l','xl'));


text:
Q: Destroying a ZFS file system Back when I set my server up a couple of years ago, I did some research and decided to go with a zfs file system for the 3 disks I'd be using for my storage.
Overall I've been very happy with it. To start with I just used 3 500gb hard drives I had from old laptops and when I decided to upgrade them, the process of replacement was incredibly easy and I had all 3 disks replaced within a few hours.
But I'm wanting to make a few changes. I want to be able to quickly view the total capacity of the system and how much of it has been used, but when I set it up, I created some separate mount points.
Essentially I have the entire pool mounted as /willzpool, but then within it I have 5 separate folders -
/willzpool/will (my storage)
/willzpool/MrsWill (my wife's storage)
/willzpool/media (a common folder we can both access and also used as a storage for my plex library and downloaded distros/torrents etc)
All 3 are also shared by samba for windows compatibility.
For whatever reason I gave these 3 folders their own mount points of /willzpool/will, /willzpool/MrsWill, /willzpool/media. This means that when I use 'zfs list' I don't really get an exact figure for how much the entire pool is using, it's split down into 4 seperate filesystems.
I also have 2 folders within the main /willzpool of /willzpool/backups (used for an rsync backup of my entire / system minus some folders so I can easily recover if I break something) and /willzpool/nextcloud (used for my nextcloud data folder)
These 2 folders are counted against /willzpool's storage when I run 'zfs list' and I have the backups folder shared by samba too so I can verify it's all working as I want it (only set it up last week) so as far as I can see the seperate mounts for will/MrsWill/media are actually pointless.
If I destroy the mount with zfs destroy, will it delete the contents of the folders or just destroy the mount points, leaving me with my top level /willzpool zfs entry that 'zfs list' will then give me totals for?

A: Ok, so I think I've answered my own question.
I moved the contents of one of my zfs file systems to a new folder
mv /willzpool/MrsWill/* /Willzpool/MrsWillbackup
which emptied the folder. I then created a test file, ran zfs destroy willzpool/MrsWill and the MrsWill folder and its contents were gone.
I mv /willzpool/MrsWillBackup /willzpool/MrsWill and accessed the folder through a laptop via samba and everything works just as it did before except now the top level zfs /willzpool/ now references the total size of the data.
For reference, the reason this was helpful is that I'm using conky & webmin to remotely monitor my hdd usage on the server and neither accurately reflect the overall size of the willzpool volume (comprised of 3 disks) when it's broken down into separate file systems)


text:
Q: Good CRM commercial or open source Can someone please recommend a good CRM system?  If this question should not be asked here, please let me know where to ask it as I thought this was the best place.

A: After checking out a few cloud-based services, we chose CapsuleCRM because of its easy integration with our cloud-based accounting system (Xero). We did have a look at Zoho too.
And you're right, this is not the place to ask this question - perhaps try superuser, but I'm not sure. Also not sure why you've used those other tags for this question.

A: How about vtiger http://www.vtiger.com/

A: This is new and pretty simple - Onekloud CRM.


text:
Q: How to change position of element div? Here is the picture of the website and how it looks:

And I want to make it so that there are two pictures first then below those two pictures put 3 pictures, but I don't know how to move them.
This is the code that I had tried:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"/>

Sandra Najera | MBA Management

CARES Engagement Manager

 | MBA Finance

CARES Engagement Graduate Assistant

 | Ed.D. Educational Leadership and Administration

CARES Engagement Manager

 | MA Latin American and Border Studies

CARES Engagement Community Worke

 | CARES Undergraduate Assistant

And I want to make it so that there are two pictures first then below those two pictures put 3 pictures, but I don't know how to move them. This is the code I want to make it look kind of like a pyramid but I don't know how!

A: Here's the code you want!

Sandra Najera | MBA Management

CARES Engagement Manager

Blanca A. Hernandez | MBA Finance

CARES Engagement Graduate Assistant

Dr. Joshua Acevedo | Ed.D. Educational Leadership and Administration

CARES Engagement Manager

Sandra I. Morales | MA Latin American and Border Studies

CARES Engagement Community Worke

Catherine Ross | CARES Undergraduate Assistant

`

Check it here.


text:
Q: How to portably detect whether a compiler supports  vs  I'm working on a utility that needs to be able to compile on both standard C++ compilers and pre-standard compilers.  The code can and will be thrown at just about any C++ compiler in existence.
I am looking for a means to robustly and portably determine whether the target compiler supports header files with or without an .h extension.  I will also need to detect whether namespaces are supported.  Both of these needs may or may not be possible.
A little background: The utility is the Inline::CPP language extension for Perl.  The extension automatically includes <iostream>, and tries to make a good guess whether a '.h' is required or not (and of course whether or not the compiler supports namespaces).  But it's far from perfect in that regard, and this issue is diminishing the breadth of the utility's usefulness.
So to reiterate the question: How do I portably detect whether a compiler supports standard headers such as <iostream>, or pre-standard headers such as <iostream.h>?

A: Not in the code, but in the build/configure system. For example in CMake, you could use try_compile and provide it a sample file.
...
try_compile(PRE_STANDARD_HEADERS tmp_builds pre_standard_headers_test.cpp)
if ( ${PRE_STANDARD_HEADERS} )
    add_definitions( -D PRE_STANDARD_HEADERS )
endif()

You'd need to make that pre_standard_headers_test.cpp .. just a simple compilable exe that #include <iostream.h> for example.
Then in your normal code just an
#ifdef PRE_STANDARD_HEADERS

would do the trick.

A: The standard approach for Linux and other Unix-friendly platforms is to use a configure script. The script will generate as its output a Makefile and a config.h header file that turns on or off any compiler features that your code could rely on when available.
For Windows it is kind of expected that you will provide solution and project files for Visual Studio, with a pre-generated config.h header file.


text:
Q: Container stop because of: "httpd: Could not open configuration file /etc/httpd/conf/httpd.conf: No such file or directory", why? I am working on a Docker version of PyroCMS. This is the repository I have with the latest files. As you can see I have a stack running: CentOS 7 (with Supervisord), MySQL, Apache and PHP. This is the docker-compose.yml file:
version: '2.1'
services:
    httpd:
        build: docker/httpd
        ports:
            - "8080:80"
        volumes_from:
            - php-fpm
    php-fpm:
        build:
            context: docker/php-fpm
            args:
                INSTALL_XDEBUG: "false"
                INSTALL_MONGO: "false"
                INSTALL_REDIS: "false"
                INSTALL_HTTP_REQUEST: "false"
                INSTALL_UPLOAD_PROGRESS: "false"
                INSTALL_XATTR: "false"
        depends_on:
            db:
                condition: service_healthy
    db:
        image: mysql
        healthcheck:
            test: "exit 0"
        environment:
            MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
            MYSQL_DATABASE: ${MYSQL_DATABASE}
            MYSQL_USER: ${MYSQL_USER}
            MYSQL_PASSWORD: ${MYSQL_PASSWORD}

This is the Dockerfile for the httpd image:
FROM reynierpm/centos7-supervisor
RUN yum install -y httpd nano && \
    yum clean all && rm -rf /tmp/yum*
RUN rm -f /etc/httpd/conf/httpd.conf /etc/httpd/conf.d/* /etc/httpd/conf.modules.d/*
COPY container-files /
EXPOSE 80

I am having a problem since the httpd container exit with status 1 and seeing the logs I got the following:
httpd_1  | httpd: Could not open configuration file /etc/httpd/conf/httpd.conf: No such file or directory

At first glance you will say:
you're deleting the files!!! in this line RUN rm -f /etc/httpd/conf/httpd.conf /etc/httpd/conf.d/* /etc/httpd/conf.modules.d/*
And you're right but if you take a closer look you'll see I am copying it back (because I am running a minimal Apache configuration) in the line:
COPY container-files /

I am not sure why the file can't be found and why the container is stopping and exiting, can any take a look to this and let me know where I am making a mistake if there is one?

A: You have this in your php-fpm Dockerfile:
VOLUME ["/data/www", "/etc/httpd"]

And this in docker-compose.yml:
httpd:
    build: docker/httpd
    ports:
        - "8080:80"
    volumes_from:
        - php-fpm

So your httpd image ends up with a volume mount at /etc/httpd. The contents of that volume override whatever was baked into the httpd image at build time.


text:
Q: Is there a good way to engage the initialization of a test suite when running an individual test case? Under JUnit4, I have a test suite which uses a @classrule annotation to bootstrap a framework. This is needed to be able to construct certain objects during tests. It also loads some arbitrary application properties into a static. These are usually specific to the current test suite and are to be used by numerous tests throughout the suite. My test suite would look something like this (where FrameworkResource extends ExternalResource and does a lot of bootstrap work):
@RunWith(Suite.class)
@SuiteClasses({com.example.test.MyTestCase.class})
public class MyTestSuite extends BaseTestSuite {

    @ClassRule
    public static FrameworkResource resource = new FrameworkResource();

    @BeforeClass
    public static void setup(){
        loadProperties("props/suite.properties")
    }
}

The above works really well and the main build has no problem executing all testsuites and their respective test cases (SuiteClasses?). The issue is when I'm in eclipse and I want to run just one test case individually withough having to run the entire suite (as part of the local development process). I would right click the java file Run As > JUnit Test and any test needing the framework resource or test properties would fail.
My question is this:

*

*Does JUnit4 provide a solution for this problem (without duplicating the initialization code in every test case)? Can a Test Case say something like @dependsOn(MyTestSuite.class)?.

*If Junit doesn't have a magic solution, is there a common design pattern that can help me here?

A: As you are running just one test class, a good solution would be to move the initialisation code to the test class. You would need to add the @Before annotation to initialise the properties.
That would require that you duplicate the code on all your tests classes. For resolving this, you could create an abstract parent class that has the @Before method so all the child classes have the same initialization.
Also, the initialised data could be on static variables for checking if it is already initialised for that particular execution.


text:
Q: send automatic mail to respective user when user uploads file to database I am new with servlets. I have created MySQL database. User will upload file(or more than one files). Then automatically mail should be send to respective user who will upload file. please suggest me how to do this?. I have read about JAVA Mail API but I don't know how to use it. Is there any other way to do it? please suggest.
Note:- I don't want to send an email to one user. I want to send mail to that user who will upload file.
This is index.jsp page that I have created.

<form action="UploadServletClass" method="post" enctype="multipart/form-data">

Welcome to Document Management System...

      Form Details

      First Name

        <input list="firstnamelist" required="" name="firstname" />

      Last Name

        <input list="lastnamelist" required="" name="lastname" />

      Division

        <input type="text" required="" name="division" />

      Reporting Unit

        <input type="text" required="" name="reportingunit" />

      Document Number

        <input type="text" required="" name="documentnumber" />

      Document Name

        <input type="text" required="" name="documentname" />

      Document Uploader

        <input type="text" required="" name="documentuploader" />

      Document Owner

        <input type="text" required="" name="documentowner" />

      Document Type

        <select name="Document_Type">

          <option value="Agreement">Agreement</option>
          <option value="Contract">Contract</option>
          <option value="PO">PO</option>
          <option value="Invoice">Invoice</option>
          <option value="COA">COA</option>
          <option value="Lease Deed">Lease Deed</option>
          <option value="AMC">AMC</option>
          <option value="Direct Material">Direct Material</option>
          <option value="Indirect Material/Services">Indirect Material/Services</option>

        </select>

      Document Category

        <select name="Document_Category">
          <option value="Customer">Customer</option>
          <option value="Vendor">Vendor</option>
          <option value="Internal">Internal</option>

        </select>

      Mail id

        <input type="email" required="" name="mailid" />

      Select File

        <input type="file" name="fileName" multiple="multiple" />

        <input type="submit" value="Submit" name="Submit" />

</form>


text:
Q: QMessageBox and QFileDialog in a loop I have a program that needs to check at startup if a path to project is set. For that I have subclassed QMessageBox, added some custom stuff (like spacer to make dialog wider) and I am calling QFileDialog::getExistingDirectory to get directory.
Thing is, user can click Cancel in QFileDialog. But I want user to be returned to QMessageBox to have another chance to set path or quit program altogether. To achieve that I wrote method loop():
CustomMessageBox::loop()
{
    while (true) {
        this->exec();

        if (this->clickedButton() == setPathButton) {
            path = QFileDialog::getExistingDirectory(...);
            if (!path.isEmpty()) { break; }
        } else if (this->clickedButton() == quitButton) {
            break;
        }
    }
}

Then, I have a method getPath():
CustomMessageBox::getPath()
{
    loop();
    return path;
}

which I call in main.cpp:
CustomMessageBox box;
QString path = box.getPath();

if (!path.isEmpty()) {
    // save path, bla, bla
} else {
    exit(EXIT_FAILURE)
}

This works, but is this a good practice? I am specifically asking regarding this while inside which resides method exec().

A: IMO disadvantages of your decision:

*

*Non-standard usage of dialog class. Put strange loop inside some GUI method and call standard exec() method inside it, when the method can easily be called in a standard way.

*Hide exec() call from "user" (another programmer)

*Dual, or even triple, purpose of the one getPath() method:

*

*show dialog

*flag that the dialog was accepted/rejected via empty - non-empty string

*return directory path string

I suggest inherit QDialog (why message box?):
In Degister I put on form standard Push Button setPathButton and Dialog Button Box buttonBox. Then I removed "Ok" button from the box:

#include <QtWidgets/QDialog>
#include "ui_CustomDialog.h"

class CustomDialog : public QDialog
{
    Q_OBJECT

public:
    CustomDialog(QWidget *parent = nullptr);

    QString path() const { return m_path; };

private slots:
    void on_setPathButton_clicked();
    void on_buttonBox_rejected(); // You can use any pushButton instead: on_closeButton_clicked()

private:
    Ui::CustomDialogClass ui;
    QString m_path;
};

...
#include "CustomDialog.h"
#include <QFileDialog>

CustomDialog::CustomDialog(QWidget *parent)
    : QDialog(parent)
{
    ui.setupUi(this);
}

void CustomDialog::on_setPathButton_clicked()
{
    m_path.clear();
    QString dir = QFileDialog::getExistingDirectory();

    if (!dir.isEmpty())
    {
        m_path = dir;
        done(QDialog::Accepted);
    }
}

// You can use any pushButton instead: void on_closeButton_clicked()
void CustomDialog::on_buttonBox_rejected()
{
    reject();
}

main.cpp
#include "CustomDialog.h"
#include <QtWidgets/QApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    CustomDialog box;
    int code = box.exec();

    if (code == QDialog::Accepted)
    {
        qDebug() << box.path();
        // save path, bla, bla
    }
    else
    {
        exit(EXIT_FAILURE);
    }

    return a.exec();
}


text:
Q: Returning a specific item from a list fetched using HttpClient.get() I'm fairly new to Angular and following a course on Pluralsight. While trying to show details for a certain item, I can't seem to figure out how to filter the list of items I'm retrieving from a file, based on an id.
I have a service for getting the data and in there I have this method for retrieving all the items
private _productUrl = './api/products/products.json';
getProducts(): Observable<IProduct[]>{
        return this._http.get<IProduct[]>(this._productUrl)
        .do(item => console.log(JSON.stringify(item)))
        .catch(this.handleError);
    };

Fairly simple, trying to wrap my head around promises, observables, etc. What I can't seen to figure out is how to retrieve the list in memory and only return the element that matches a given id.
getProduct(id: number): IProduct{
        this._http.get<IProduct>(this._productUrl).do(item => {if (item.productId == id) return item;});
        return null;
    }

I'm getting a null value back. So how do I go about and filter a list return from a get call?

A: Use the rxjs Filter Operator after flatMap Operator:
.flatMap(item => item)
.filter(item => item.productId === id)

Then the subscription will only resolve with this item.
Within your component then:
public selectedItem: IProduct;
public ngOnInit() {
    service.getProduct(id).subscribe(item => this.selectedItem = item);
}

Or using the async Pipe:
In Component:
public item$: Observable<IProduct>;
public ngOnInit() {
    this.item$ = service.getProduct(id);
}

In template:
<cmp product="item$ | async"></cmp>


text:
Q: Create a new dataframe by applying function to columns of another dataframe I try to learn more about the apply method in python and asking myself how to write the following code using apply:
I have a dataframe df like the following:
  A B C D E points
0 0 0 0 1 43 94
1 0 0 1 1 55 62
2 1 1 0 1 21 84
3 1 0 1 0 13 20

Furthermore I have a function like the following, which does its job:
def f1(df):
  df_means = pd.DataFrame(columns = ['Mean_Points'])
  for columnname in df.columns:
    if len(df[df[columnname] == 1]) > 1:
      df_means.loc[columnname] = [df[df[columnname] == 1]['points'].mean()]
  return df_means

So the output of f1 is
  'Mean_Points'
A      52
C      41
D      80

and that's totally fine.
But I am wondering if there is a possibility (I am sure there is) to obtain the same result with the apply method.
I tried:
df_means = pd.DataFrame(columns = ['Mean_Points'])
cols = [col for col in df.columns if len(df[df[col] == 1]) > 1]
df_means.loc[cols] = df[cols].apply(lambda x: df[df[x] == 1]['points'].mean(), axis = 1)

or similar:
df_means = pd.DataFrame(columns = ['Mean_Points'])
df.columns.apply(lambda x: df_means.loc[x] = [df[df[x] == 1]['points'].mean()] if len(df[df[x] == 1]) > 1 else None)

and 2,3 other things, but nothing worked...
I hope somebody can help me here?!

A: In general, you should try to see if you can avoid using .apply(axis=1).
In this case, you can get by with DataFrame.mulitply(), replacing 0 with np.NaN so it doesn't count toward the average.
import numpy as np

s = df.replace(0, np.NaN).multiply(df.points, axis=0).mean()
#A           52.0
#B           84.0
#C           41.0
#D           80.0
#E         2369.0
#points    5034.0
#dtype: float64

Now we'll add your condition to only consider columns with multiple instances of 1, and subset to those with .reindex
m = df.eq(1).sum().gt(1)
s = s.reindex(m[m].index)

Output s:
A      52.0
C      41.0
D      80.0
dtype: float64

A: pd.DataFrame.dot
#                      filters s to be just those
#                      things greater than 1
#                      v
s = df.eq(1).sum().loc[lambda x: x > 1]
df.loc[:, s.index].T.dot(df.points).div(s)

A    52.0
C    41.0
D    80.0
dtype: float64

One liner approach
This removes the chaff but probably does more calculations than necessary.
df.T.dot(df.points).div(df.sum())[df.eq(1).sum().gt(1)]

A    52.0
C    41.0
D    80.0
dtype: float64

A: Here is another way to do it, not purely pandas as others have shown.
cols = ['A', 'B', 'C', 'D']

def consolidate(series):
    cond = series > 0
    points = df.loc[cond, 'points']
    if len(points) > 1:
        return series.name, points.mean()
    else:
        return series.name, np.nan

df1 = pd.DataFrame([consolidate(df[col]) for col in cols], columns=['name', 'mean_points'])

print(df1)

  name  mean_points
0    A         52.0
1    B          NaN
2    C         41.0
3    D         80.0

If no NaN needed then
df1.dropna()

  name  mean_points
0    A         52.0
2    C         41.0
3    D         80.0

And using apply
df[cols].apply(consolidate,result_type='expand')
        .T.dropna()
        .reset_index()
        .drop('index', axis=1)

0  A  52
1  C  41
2  D  80


text:
Q: Is the sum of two sub-sheaves a sheaf? Let $X$ be a topological space, let $\mathcal{E}$ be a sheaf of abelian groups on $X$ and let $\mathcal{F}$ and $\mathcal{G}$ be two sub-sheaves of $\mathcal{E}$. Let $\mathcal{F}+\mathcal{G}$ be the presheaf $U\mapsto \mathcal{F}(U)+\mathcal{G}(U)$. Is $\mathcal{F}+\mathcal{G}$ a sheaf ?

A: No, you need to sheafify. For instance, let $j_U:U\to X$ be the inclusion of an open subset. Then ${j_U}_!\underline{\mathbb{Z}}_U$ is a subsheaf of the constant sheaf $\underline{\mathbb{Z}}_X$. Now, if $U,V$ is an open cover of $X$, then ${j_U}_!\underline{\mathbb{Z}}_U+{j_V}_!\underline{\mathbb{Z}}_V$ is not a sheaf in general and its sheafification is $\underline{\mathbb{Z}}_X$.
To see this, note that the presheaf ${j_U}_!\underline{\mathbb{Z}}_U+{j_V}_!\underline{\mathbb{Z}}_V$ is the presheaf image of ${j_U}_!\underline{\mathbb{Z}}_U\oplus{j_V}_!\underline{\mathbb{Z}}_V\to\underline{\mathbb{Z}}_X$ and that the sheaf morphism is onto as you can see by looking at the stalks, this implies that the sheafification of ${j_U}_!\underline{\mathbb{Z}}_U+{j_V}_!\underline{\mathbb{Z}}_V$ is indeed $\underline{\mathbb{Z}}_X$. In fact, you have a short exact sequence of sheaves :
$$0\to {j_{U\cap V}}_!\underline{\mathbb{Z}}_{U\cap V}\to{j_U}_!\underline{\mathbb{Z}}_U\oplus{j_V}_!\underline{\mathbb{Z}}_V\to \underline{\mathbb{Z}}_X\to 0$$
If $X$ is compact, then $H^i(X,{j_U}_!\mathbb{Z}_U)=H^i_c(U,\mathbb{Z})$ is the usual cohomology with compact support, and the above short exact sequence gives rise to the Mayer-Vietoris long exact sequence with compact supports :
$$0\to H_c^0(U\cap V,\mathbb{Z})\to H^0_c(U,\mathbb{Z})\oplus H^0_c(V,\mathbb{Z})\to H^0(X,\mathbb{Z})\to H^1_c(U\cap V,\mathbb{Z})\to...$$
It follows that if the boundary map $H^0(X,\mathbb{Z})\to H^1_c(U\cap V,\mathbb{Z})$ is non zero, then ${j_U}_!\underline{\mathbb{Z}}_U+{j_V}_!\underline{\mathbb{Z}}_V$ is different from its sheafification hence not a sheaf. For an actual example, take $X=S^1$ and $U,V$ the open cover you get when removing the north and the south pole.


text:
Q: ADO.NET: Need help to understand the basics of 'Dataset' As context, I am new to ADO.NET and have been using 'Programming ADO.NET 2.0' by David Sceppa to help build my knowledge.
I have been trying to understand the Dataset object but think I may have completely misunderstood the point and am looking for guidance.
As an example, I have built a really simple Form with a combobox with an aim of filling the combobox with the names of people in a database ("MyDatabase"). The following code works fine for me:
    Private Sub frmEmployee_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim strConn, strSQL As String
    strConn = "Data Source=.\SQLExpress;Initial Catalog=MyDatabase;Integrated Security=True;"
    strSQL = "SELECT LastName, FirstName FROM EmployeeTable"

    Dim da As New SqlDataAdapter(strSQL, strConn)
    Dim ds As New DataSet()
    da.Fill(ds, "AllEmployeesList")

    For i As Integer = 0 To ds.Tables("AllEmployeesList").Rows.Count - 1
        Dim row As DataRow = ds.Tables("AllEmployeesList").Rows(i)
        cbAllEmployeesList.Items.Add(row("LastName") & ", " & row("FirstName"))
    Next

End Sub

Now suppose I have a button on my Form ('GetAge') which is designed to retrieve the age of the employee selected in the combobox from the dataset "AllEmployeesList" and display in a TextBox on the same Form.
The bit I really don't understand is how I can interact with the original dataset that I have created to get the age? It seems to me that the dataset is only in memory during the Load event? If my dataset persists beyond the Load event then where can I find it?
My understanding is that a dataset object is an offline cache of data and has no links to the underlying database.This is useful as it allows you to manipulate the data without keeping a connection open and later on you can submit any changes in the Dataset back to the original database. So once I have built my dataset in the Load event how can I then further interact with it?
I suspect there is a large error in my understanding of what a Dataset object is. Can anybody set me straight?
Thanks to anybody who can help
Alex

A: A data set can hold multiple data tables, so if you fill that same dataset that already has the "AllEmployeesList" datatable filled, you can fill another datatable with the age under another table name.  Picture a dataset as an in-memory database.
You can store the dataset in the datasource of the datagrid view, or make it a form level variable so you can interact with it without casting anytime.
Another part of datasets to be aware of is you can make a design-time dataset so things are more type-safe and explicit.

A: You seem to have a good grasp on the concept and reason of the DataSet. Your question is really more about managing state than the ins and outs of a DataSet.
You never stated if you are using WebForms, WinForms, or something else. If you're using WinForms, promote the DataSet to be a member variable of the form. It'll stay in memory as long as the form is open.
If you're using WebForms, then this becomes much more complex. This is a good overview to get you started.

A: Unless your application needs to operate in a disconnected mode, it's not strictly necessary nor always a good idea to cache database data on the client. In this case, you're extracting the age data for all employees without knowing whether you'll ever need it for any of them.
I would just pull the first and last name data (probably using SqlCommand.ExecuteReader) to populate the list box, and then make a separate call to the database to get the age if the user clicks the button. I posted an example of something similar using SqlCommand.ExecuteScalar on your other question.

A: When a Function or Sub has finished executing, all the variables you declared with the Dim statement will be gone. If you want a variable to exist as long as your form exists then declare a variable outside your Sub/Function:
Public Class frmEmployee
    Private dsEmployeeList As DataSet

    Private Sub frmEmployee_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ...
    dsEmployeeList = New DataSet()
    da.Fill(dsEmployeeList, "AllEmployeesList")
    ...
    End Sub

    Private Sub GetAge_Click(sender As Object, e As EventArgs) Handles GetAge.Click
        Dim iRowIndex As Integer

        iRowIndex = cbAllEmployeesList.SelectedIndex 'In this case the rownumber is the same as the index of the selected item in the combobox

        'Check to see if an item from the combobox has been selected
        If iRowIndex >= 0 Then
            txtEmployeeAge.Text = dsEmployeeList.Tables("AllEmployeesList").Rows(iRowIndex).Item("Age").ToString()
        End If
    End Sub

This code might work but it's not a recommended solution. Like the previous poster said: only get the data you want, when you need it.

A: You should bind the DataGrid to the DataSet. When reqd you can retrieve the DataSet back from the DataGrid.DataSource and cast it to a DataSet.
Edit: Added sample code
    DataSet ds = new DataSet();
    // Code to populate DataSet from your DB
    ...
    ...

Assign ds to the datasource of data grid
this.dataGridView1.DataSource = ds;

To retrieve the dataset use the code below
DataSet retrievedFromGrid = (DataSet)this.dataGridView1.DataSource;

However, if you need to perform operations on this DataSet a number of times and memory is not an issue, I would suggest you store it in a class variable to avoid the overhead of casting in a DataSet object from the DataGrid again and again.


text:
Q: Using \line Inside of \title I am currently working on formatting a title page for my MSc thesis and am having a hard time getting some lines over and under my title to line up.
Here is what I have so far:
\linethickness{0.05cm}

\title{\line(1,0){450} \\ MSc Thesis \line(1,0){450}}

\author{\Large John Smith \\ \normalsize Supervisor: Dr. John Smith}

\maketitle

As you can see from the picture, the bottom line is further from the title than the top line and I cant figure out how to fix it. Does anyone have any suggestions?

Thanks!

A: The titling package has several tools to customise the layout of title pages:
\documentclass[a4paper, twoside, 11pt]{article}
\usepackage[utf8]{inputenc}
 \usepackage{titling}
\makeatletter
\def\supervisor#1{\gdef\@supervisor{#1}}
\supervisor{John Smith, Esq.}
%
\setlength{\droptitle}{2cm}
\maketitlehooka{\thispagestyle{empty}}
\pretitle{\noindent\rule{\textwidth}{0.5mm }\vspace*{3ex}\par\centering\bfseries\LARGE}
\title{MSc Thesis}
\posttitle{\vspace{2ex}\par\rule{\textwidth}{0.5mm}}
\preauthor{\bigskip\begin{center}\Large}
\author{Jack Smith}
\postauthor{\medskip\par\normalsize Supervisor: \@supervisor\par\end{center}}
\predate{\bigskip\begin{center}}
\postdate{\end{center}\cleardoublepage}
\makeatother

\begin{document}

\maketitle

Blablabla

\end{document}

A: I think that it's better to redefine the environment. In this way you can define a new command for supervisor and don't use author for both you and the supervisor. Also you have more control over the page.
You could create commands like \title, \author, etc... with:
\makeatletter
\newcommand{\@supervisor}{}
\newcommand{\supervisor}[1]{\renewcommand{\@supervisor}{#1}}
\makeatother

You can set the supervisor with \supervisor{Dr. John Smith} and you can use its value with \@supervisor just like \title, \author and similar.
The original definition of the title page is through the titlepage environment.
\begin{titlepage}%
  \let\footnotesize\small
  \let\footnoterule\relax
  \let \footnote \thanks
  \null\vfil
  \vskip 60\p@
  \begin{center}%
    {\LARGE \@title \par}%
    \vskip 3em%
    {\large
     \lineskip .75em%
      \begin{tabular}[t]{c}%
        \@author
      \end{tabular}\par}%
      \vskip 1.5em%
    {\large \@date \par}%       % Set date in \large size.
  \end{center}\par
  \@thanks
  \vfil\null
\end{titlepage}%

You could modify it adding lines and supervisor. In the following the complete solution with the result.
\documentclass{article}

\makeatletter
\newcommand{\@supervisor}{}
\newcommand{\supervisor}[1]{\renewcommand{\@supervisor}{#1}}
\makeatother

\title{MSc Thesis}
\author{John Smith}
\supervisor{Dr. John Smith}

\begin{document}

\makeatletter
\begin{titlepage}%
  \let\footnotesize\small
  \let\footnoterule\relax
  \let \footnote \thanks
  \null\vfil
  \vskip 60\p@
  \begin{center}%
    \hrule height .5mm
    \vspace{25pt}
    {\LARGE \@title \par}%
    \vspace{25pt}
    \hrule height .5mm
    \vskip 3em%
    {\large
     \lineskip .75em%
      \begin{tabular}[t]{c}%
        {\Large\@author} \\
        {\normalsize\@supervisor}
      \end{tabular}\par}%
      \vskip 1.5em%
    {\large \@date \par}%       % Set date in \large size.
  \end{center}\par
  \@thanks
  \vfil\null
\end{titlepage}%
\makeatother

\end{document}

Of course another valid solution is to redefine \maketitle command. However in my humble opinion there is no need for that if you're not going to create a class.

A: It is probably better to use \hrule in this case,
\documentclass[a4paper,12pt]{article}
\usepackage[english]{babel}

\title{
\hrule height 1mm
\vspace{25pt}
MSc Thesis
\vspace{25pt}
\hrule height .25mm
}

\author{\Large John Smith \\ \normalsize Supervisor: Dr. John Smith}

\begin{document}
\maketitle

\end{document}

You can tune the height of each \hrule by passing the right argument, also the width can be adjusted.

Hope that helps.
Romain


text:
Q: boot repair in terminal (glade2script:7962): Gtk-CRITICAL **: _gtk_style_cascade_get_for_screen: assertion 'GDK_IS_SCREEN (screen)' failed

(glade2script:7962): Gtk-CRITICAL **: _gtk_style_provider_private_lookup: assertion 'GTK_IS_STYLE_PROVIDER_PRIVATE (provider)' failed

(glade2script:7962): Gtk-CRITICAL **: _gtk_css_lookup_resolve: assertion 'GTK_IS_STYLE_PROVIDER_PRIVATE (provider)' failed
/usr/share/boot-sav/gui-g2slaunch.sh: line 29:  7962 Segmentation fault      (core dumped) $G2S $1 -g ./$PACK_NAME.glade -s ./$APPNAME.sh --combobox="@@_combobox_format_partition@@col" --combobox="@@_combobox_bootflag@@col" --combobox="@@_combobox_ostoboot_bydefault@@col" --combobox="@@_combobox_purge_grub@@col" --combobox="@@_combobox_separateboot@@col" --combobox="@@_combobox_efi@@col" --combobo

A: Boot-Repair uses glade2script and therefore needs some gui. Not sure if just installing glade2script would work or not.
Better to just use the Ubuntu Desktop and add Boot-Repair or download the Boot-RepairCD itself.
It expects to see glade2script.

Glade2script allows a script (Bash, Python or other) to display and
  interact with a GUI (created with Glade).


text:
Q: Upload images with ajax and nodejs using Formdata - CORS error issue I am using vanilla javascript (AJAX) to post a form and using Formdata(). The submission of form is captured by nodejs and connecting to database.
The issue is while i am sending normal data to nodejs, I am able to connect database and response as success. But while I am adding a file upload input(to store file path) and trying to connect, the CORS error is coming. I have set header for allow cross origin as * value in express(nodejs).
HTML:

            Description 2
            <textarea  name="descr2" class="form-control" id="textareaLbl2" rows="3"></textarea>

            Upload:
            <input type="file" name="img" class="form-control" id="img" />

JS:
testForms.onsubmit = function(event) {
    event.preventDefault();
    var formData = new FormData(testForms);
    request.open( "POST", "https://xyz.domain.com/addList", true);
    request.send(formData);
}

Nodejs:
app.use(function (req, res, next) {
    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

A: Does this work? If not have you tried the cors middleware:
https://www.npmjs.com/package/cors
 app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

Also try setting Content-Type on node side.


text:
Q: Laravel 7: MariaDB in combination with Redis but Redis behaves slower with large objects I have successfully implemented a combination of redis and mysql. At one section of my application I thought I would reduce load on mysql server and use redis until the data gets changed, however I observe that it's still faster when the same data is fetched from Mysql than redis.
Here is scenario.
User1: 10,000 records with seldom one off change in a day or so.
What I do is whole object that fetches these 10K records, (serialized object of about 20mb in size) is saved to  redis. The idea is that since subsequent 100 to 1000 requests will only be just page refreshes so why not avoid mysql hits and get this data from redis.
However, I have observed that when this object is fetched from Redis, it takes more time than when I flush redis and the mysql query is hit. I thought redis would have been faster or have the same mysql-like speed at least, but here it's different.
Also, I have observed that while fetching the 20mb object from Redis my php gives the "allowed memory exhausted" error (which I know how to fix) but it doesn't give out any error when the same data is fetched from mysql.
Could it be that Redis is not fit for caching huge objects? Or is there something else?
Thanks

A: Redis is not designed/fit for storing/fetching large objects. You will suffer while getting/setting these objects in network/bandwidth. Since it is single threaded, other requests also will suffer while storing/fetching these large objects.
As it is stated in the benchmark documentation;

Speed of RAM and memory bandwidth seem less critical for global performance especially for small objects. For large objects (>10 KB), it may become noticeable though. Usually, it is not really cost-effective to buy expensive fast memory modules to optimize Redis.

What you may do is, redesign your cache layer with hashes or lists depending on the query requirements of your application. You may check here for additional information. Also i answered a similar question in here


text:
Q: how to link a new user to google analytics property/view using javascript My requirement is, I need to add a new email id to an existing google analytics account's property.

function insertPropertyUserLink() {
  var request = gapi.client.analytics.management.webpropertyUserLinks.insert(
    {
      'accountId': '123456',
      'webPropertyId': 'UA-123456-1',
      'resource': {
        'permissions': {
          'local': [
            'EDIT',
            'MANAGE_USERS'
          ]
        },
        'userRef': {
          'email': 'liz@gmail.com'
        }
      }
    });
  request.execute(function (response) { // Handle the response. });
}

Above code i got from google documentation and i am using the following code for authorization:

<button id="sign-in-or-out-button"
        style="margin-left: 25px">
    Sign In/Authorize
</button>
<button id="revoke-access-button"
        style="display: none; margin-left: 25px">
    Revoke access
</button>

I have changed the API key and client id with mine and enabled the Analytics API for the app in console. Can anyone help me to integrate the above two code snippets to a single one and can be able to add a new user to analytics property.

A: To solve this: **gapi.client.analytics is undefined**
Change:
 `gapi.load(**'client:auth2'**, initClient);`

to
gapi.load(**'client:analytics'**, initClient);

It worked for me.


text:
Q: C++ Inject into Java application I'm having a really hard time figuring out why I cannot get my hooks to work in a java application..
I create a C++ WINAPI window. I load my "hook" dll and every time I send fake input to the application, it raises a flag perfectly fine.
However, if I do the same with a Java application, it does NOT work at all!
My dll looks like this:
#include <windows.h>

HINSTANCE hInstance = nullptr;
HHOOK MouseHook = {0};   /** Structure for hooking the mouse **/
HHOOK KeyboardHook = {0};  /** Structure for hooking the keyboard **/

LRESULT __stdcall MouseHookProc(int Code, WPARAM wParam, LPARAM lParam)
{
    if (Code == HC_ACTION)
    {
        MSLLHOOKSTRUCT* Info = reinterpret_cast<MSLLHOOKSTRUCT*>(lParam);
        if ((Info->flags & LLMHF_INJECTED) == LLMHF_INJECTED)
        {
            MessageBox(NULL, "DETECTED Mouse", "", 0);
        }
    }
    return CallNextHookEx(MouseHook, Code, wParam, lParam);
}

LRESULT __stdcall KeyboardHookProc(int Code, WPARAM wParam, LPARAM lParam)
{
    if (Code == HC_ACTION)
    {
        KBDLLHOOKSTRUCT* Info = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
        if ((Info->flags & LLKHF_INJECTED) == LLKHF_INJECTED)
        {
            MessageBox(NULL, "DETECTED Keyboard", "", 0);
        }
    }
    return CallNextHookEx(KeyboardHook, Code, wParam, lParam);
}

extern "C" __declspec(dllexport) bool __stdcall DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    switch (fdwReason)
    {
        case DLL_PROCESS_ATTACH:
        {
            hInstance = hinstDLL;
            SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProc, hInstance, 0);
            SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, hInstance, 0);
        }
        break;

        case DLL_PROCESS_DETACH:
        {
            UnhookWindowsHookEx(KeyboardHook);
            UnhookWindowsHookEx(MouseHook);
        }
        break;
    }
    return true;
}

Then I created a C++ WINAPI application with the following WM_CREATE block:
case WM_CREATE:
    LoadLibrary("JavaHook.dll");
    mouse_event(MOUSEEVENTF_LEFTDOWN, 100, 100, 0, 0);
    mouse_event(MOUSEEVENTF_LEFTUP,100, 100,0,0);
break;

The MessageBox of the MouseHook pops up. This is expected behaviour.
However with Java I did:
public class HookTest {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test Window");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        System.loadLibrary("JavaHook");
    }
}

Then I used SendInput on the application like so:
INPUT input;
input.type = INPUT_MOUSE;
input.mi.mouseData = 0;
input.mi.dx =  100 * (65536 / GetSystemMetrics(SM_CXSCREEN)); //x being coord in pixels
input.mi.dy =  100 * (65536 / GetSystemMetrics(SM_CYSCREEN)); //y being coord in pixels
input.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
SendInput(1, &input, sizeof(input));

and NOTHING pops up. I tried using mouse_event and keybd_event, still nothing. I tried using a Java mouse listener and keyboard listener and faking events.. Still NOTHING..
The hook loads for sure because I can see my mouse lag for a good 3 seconds before I can move it. Also made a popup to confirm it upon load.
However, I still cannot figure out why it doesn't work on the Java application. Any ideas how I can get them to work. Or is there another way to do it for Java preferably from C/C++? If not, is there a way to do it in Java?

A: You might want to read remarks to SetWindowsHookEx documentation.
Specifically it says that the thread that installed a global hook should continue to process Windows messages in order to allow both 32-bit and 64-bit applications to run the hook code in the context of the hooking application.
So, I suggest you create a separate thread from DllMain. The thread will install a hook and then run into GetMessage/ProcessMessage loop: http://pastebin.com/JmMvMX78
#include <windows.h>
#include <stdio.h>

HHOOK MouseHook = {0};
HHOOK KeyboardHook = {0};

LRESULT WINAPI MouseHookProc(int Code, WPARAM wParam, LPARAM lParam) {
    if (Code == HC_ACTION) {
        printf("Mouse\n");
    }
    return CallNextHookEx(MouseHook, Code, wParam, lParam);
}

LRESULT WINAPI KeyboardHookProc(int Code, WPARAM wParam, LPARAM lParam) {
    if (Code == HC_ACTION) {
        printf("Keyboard\n");
    }
    return CallNextHookEx(KeyboardHook, Code, wParam, lParam);
}

DWORD WINAPI ThreadProc(LPVOID param) {
    HINSTANCE hInstance = (HINSTANCE)param;
    MouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, hInstance, 0);
    KeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProc, hInstance, 0);

    MSG message;
    while (GetMessage(&message, (HWND)-1, 0, 0) > 0) {
        TranslateMessage(&message);
        DispatchMessage(&message);
    }

    UnhookWindowsHookEx(KeyboardHook);
    UnhookWindowsHookEx(MouseHook);

    return 0;
}

extern "C" __declspec(dllexport) BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    if (fdwReason == DLL_PROCESS_ATTACH) {
        CloseHandle(CreateThread(NULL, 0, ThreadProc, hinstDLL, 0, NULL));
    }
    return TRUE;
}


text:
Q: SharePoint Lists and Microsoft Flow - Get new items only? I would like to create a Flow so that once a day I can export new list data from a SharePoint Online list into Smartsheet so that a dashboard can be displayed to managers with this data.
I have been able to setup the Schedule action just fine, and the actual import of data into Smartsheet action is fine, but the Get Items SharePoint action is pulling in all list items every time.
Will I need to setup an additional column/action to track if the item has been moved to Smartsheet already so that I can filter down the Get Items action?

A: You could use Filter array to filter the items.
For example: use addDays(utcNow(),-1) to filter Created greater than yesterday.


text:
Q: Appium - Android - Unable to interrogate elements in certification apks I need some help understanding why driver.findElement() or find element APIs of Appium doesn't work in any of the apks from certification builds, but they work in the official released version from the app store.
Just need expert advise before I talk to the dev team since I'm a contractor located in different region than the dev team.
Here is the situation :

*

*signed apk (debug version) installed through adb - Doesn't work

*certification build apk installed from app store - Doesn't work

*Official released version from app store - WORKS OK !
I'm fairly new to Android build process. Appreciate any help.

A: After days of debugging, this doesn't appear to be related to the app signature.
My app launches the camera with onReady state with an alert message that conceals the elements from Appium which is why the elements are not found. Note that this alert is set up to appear the first time launching the app.
Simplest work around is to dismiss the alert box if present. Solved !


text:
Q: How to connect accounts with Django rest auth / all auth? I'm using Django rest-auth for authentication and account creation with Django rest framework. Currently, I have six providers set up and I'd like to start connecting them.
It's not clear from the documentation (either rest-auth or all-auth) what I have to do to connect the accounts.
For example, if I try to connect a Google account to a LinkedIn one (same email address), even if I make a POST request to /rest-auth/linkedin/connect/ with the correct access token for the Google provider, I get a 400 response saying: "non-field-errors": [ "Incorrect value" ].
I'm using JWTs for authentication, and providing the correct token in the Authorization header.
views.py
class GoogleConnect(SocialConnectView):
    adapter_class = GoogleOAuth2Adapter

class LinkedInConnect(SocialConnectView):
    adapter_class = LinkedInOAuth2Adapter

A: I've written a tutorial that should cover your question. This should be the part you are looking for.
In short: You have to write your own ConnectView which inherits from the rest_auth view like this:
class GoogleCallbackConnect(SocialConnectView):
    """
    Connects the provider's user account to the currently logged in user.
    """
    adapter_class = GoogleOAuth2Adapter
    client_class = OAuth2Client

    @property
    def callback_url(self):
        url = self.adapter_class(self.request).get_callback_url(
            self.request,
            None,
        )
        return url


text:
Q: allocate and free API on array of structures How do I get an API for allocating, freeing.
Something like this:
char x[size];
pool = pool_init(x, size, sizeof(struct x));
y = pool_allocate(pool);
...
pool_free(y);

note the the allocating must occur on a static buffer (no malloc).
Is there any open source library for this API?


text:
Q: How to make duration slider in control center? Swift I make Media Player. I want to create a duration slider in control center. How can I make it? Please help me.

A: func controlCenter() {
    let mpPlaysCenter = MPNowPlayingInfoCenter.defaultCenter()
    mpPlaysCenter.nowPlayingInfo = [MPMediaItemPropertyArtist: artistSongForLabel, MPMediaItemPropertyTitle: nameSongForLabel, MPMediaItemPropertyPlaybackDuration: player.duration, MPMediaItemPropertyPlayCount: player.currentTime]
}


text:
Q: If date string found to be between dates, return pay_period_start & pay_period_end. How? The following code works if I manually type in every day for every single month in each hard coded array.
I then loop through the arrays for a match and if I find it, I return the first index and the last index value of that array. These are the pay period start and end dates later to be used with mysql select queries.
// MOUNTAIN DAYLIGHT SAVINGS TIME
date_default_timezone_set('MST7MDT');

// = PHP Default TimeZone
//print 'MOUNTAIN DAYLIGHT SAVINGS TIME';
//print '
';

// = MySQL CURRDATE() in MySQL DATETIME Format.
$php_current_date = date('Y-m-d');

// 2019 Pay Periods - MONTHLY

$parent_array = array(
1 => array('2019-01-01','2019-01-31'),
2 => array('2019-02-01','2019-02-28'),
3 => array('2019-03-01','2019-03-31'),
4 => array('2019-04-01','2019-04-30'),
5 => array('2019-05-01','2019-05-31'),
6 => array('2019-06-01','2019-06-30'),
7 => array('2019-07-01','2019-07-31'),
8 => array('2019-08-01','2019-08-31'),
9 => array('2019-09-01','2019-09-30'),
10 => array('2019-10-01','2019-10-31'),
11 => array('2019-11-01','2019-11-30'),
12 => array('2019-12-01','2019-12-31'),
13 => array('2020-01-01','2020-01-31'),
14 => array('2020-02-01','2020-02-29'),
15 => array('2020-03-01','2020-03-31'),
16 => array('2020-04-01','2020-04-30'),
17 => array('2020-05-01','2020-05-31'),
18 => array('2020-06-01','2020-06-30'),
19 => array('2020-07-01','2020-07-31'),
20 => array('2020-08-01','2020-08-31'),
21 => array('2020-09-01','2020-09-30'),
22 => array('2020-10-01','2020-10-31'),
23 => array('2020-11-01','2020-11-30'),
24 => array('2020-12-01','2020-12-31')
);

$current_pay_period_start = '';
$current_pay_period_end = '';

// For each child Array of date Strings inside parent Array of arrays...
foreach($parent_array as $child_array){

   // Speculate the variable name as $result_found while searching each child Array of date Strings
   // for the Current date in *Mountain Daylight Savings Time
   $result_found = in_array($php_current_date, $child_array);

    // if we have a match...
    if ($result_found) {

        // GET LEFT-MOST index and assign it to a variable.
        $current_pay_period_start = current($child_array);

        // GET RIGHT-MOST index and assign it to another variable.
        $current_pay_period_end = end($child_array);
        // Add a day for mysql query logic...
        // because mysql uses < instead of =< for comparison in the query the follows...
        $current_pay_period_end = date('Y-m-d', strtotime($current_pay_period_end . ' + 1 days'));

        /*
        Following Works ONLY on direct access.
        Debug Only.
        Eg. localhost/folder/filename.php
        */

        print 'Php Current Date: ' . $php_current_date;
        print '
';
        print 'Current Pay Period Start: ' . $current_pay_period_start;
        print '
';
        print 'Current Pay Period End: ' . $current_pay_period_end;
        exit;

    }
}

I have tried to implement the solution below but, I keep getting errors related to me not being able to compare date strings... It seems I have learned to find date strings in an array of arrays but they aren't really dates as far as php is concerned.
/**
 * @param DateTime $date Date that is to be checked if it falls between $startDate and $endDate
 * @param DateTime $startDate Date should be after this date to return true
 * @param DateTime $endDate Date should be before this date to return true
 * return bool
 */
function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate) {
    return $date > $startDate && $date < $endDate;
}

$fromUser = new DateTime("2012-03-01");
$startDate = new DateTime("2012-02-01 00:00:00");
$endDate = new DateTime("2012-04-30 23:59:59");

echo isDateBetweenDates($fromUser, $startDate, $endDate);

Here's how I try to call it and get the error...
isDateBetweenDates($php_current_date, $current_pay_period_start, $current_pay_period_end);

A: I have wrote the following for you, that compares the two dates from your array. Hopefully it will help!
        $php_current_date = date('Y-m-d');
        $parent_array = array(
            1 => array('2019-01-01','2019-01-31'),
            2 => array('2019-02-01','2019-02-28'),
            3 => array('2019-03-01','2019-03-31'),
            4 => array('2019-04-01','2019-04-30'),
            5 => array('2019-05-01','2019-05-31'),
            6 => array('2019-06-01','2019-06-30'),
            7 => array('2019-07-01','2019-07-31'),
            8 => array('2019-08-01','2019-08-31'),
            9 => array('2019-09-01','2019-09-30'),
            10 => array('2019-10-01','2019-10-31'),
            11 => array('2019-11-01','2019-11-30'),
            12 => array('2019-12-01','2019-12-31'),
            13 => array('2020-01-01','2020-01-31'),
            14 => array('2020-02-01','2020-02-29'),
            15 => array('2020-03-01','2020-03-31'),
            16 => array('2020-04-01','2020-04-30'),
            17 => array('2020-05-01','2020-05-31'),
            18 => array('2020-06-01','2020-06-30'),
            19 => array('2020-07-01','2020-07-31'),
            20 => array('2020-08-01','2020-08-31'),
            21 => array('2020-09-01','2020-09-30'),
            22 => array('2020-10-01','2020-10-31'),
            23 => array('2020-11-01','2020-11-30'),
            24 => array('2020-12-01','2020-12-31')
        );
        foreach ($parent_array as $child_array) {
            //compare dates using strtotime, did the conversion in the if statement to retain the original date format, for output if results are found.
            if (strtotime($php_current_date) >= strtotime($child_array[0]) && strtotime($php_current_date) <= strtotime($child_array[1])) {
                // match found...
                $current_pay_period_start = $child_array[0];
                $current_pay_period_end = $child_array[1];
                print 'Php Current Date: ' . $php_current_date;
                print '
';
                print 'Current Pay Period Start: ' . $current_pay_period_start;
                print '
';
                print 'Current Pay Period End: ' . $current_pay_period_end;
                exit;
            }
        }

I have tested it and the following is outputted:
Php Current Date: 2019-03-07
Current Pay Period Start: 2019-03-01
Current Pay Period End: 2019-03-31

Hopefully this will help!


text:
Q: Properly remove sockets accidentally created with tmux I just started using tmux; out of muscle memory (was a screen user) I tried to create a new session like this: tmux -S mySession, and after I detached, a socket named mySession= appeared in my working directory. I just rmed it and now there's a stale file handle like .nfs00000000014e6d6b000160d2= which I can't remove (Device or resource busy).

A: A file such as .nfs00000000014e6d6b000160d2 is generated whenever an open file is deleted from an NFS mounted filesystem.
In your case you'll still have a tmux background process running.  If you do a ps ax you'll see it.  If you kill that off then the file will be closed and should be autocleaned.


text:
Q: How to present an XML file in HTML format in different ways, according to user input? I have an XML file consisting of book nodes, and each book contains 1-4 authors, 1 title & 1 Year
I've also created an XSL file related to the above XML file so that whenever I open the XML file in a browser, its contents are presented in a html table format consisting of 3 rows "Author","Title","Year"
What I want to do now is create an HTML file that will present the above table but not all of its contents, only the ones asked through user input (appropriate fields for user input should be found on that same html file as well I guess..)
e.g. a user can type in the name of an author, or a year, or a title, or a word contained in a title or in an author's name and then have the appropriate table presented to him.
I'm a new to all this so my questions are the following :

*

*Will I have to mess with the content in the XML and XSL files again or should I leave them intact from now on and only deal with the html file I'll be creating?

*In order to achieve what I want what should my html file contain? Javascript functions that will be presenting only parts of the XML file but always according to the XSL file? Will I be using XSLT in the html file again or simply javascript?
What I need is to create smth that will take input from the user (javascript?) and then use a parser (XSLT?) to parse through the XML according to the user's input? and then return the result on screen filtered through the XSL template I created??
Could someone please indicate me the process I should follow step by step (not in detail but in which order should I deal with all the issues involved in this..) ?
Thank you very much for your understanding and help! I know there's lots of information on w3schools but the problem is that everything is fragmented and I still don't know how to combine all that, in which order and which method to choose!
btw. I don't want to use jquery for this, only XML,XSLT,XPATH,HTML,Javascript standards..

A: You need to pass the user-wanted processing as parameter(s) to the transformation.
Read about the xsl:param instruction.
External parameters to the transformation can be any globally declared (children of the top element xsl:stylesheet) xsl:param elements.
The way the invoker of the XSLT transformation specifies the values for these parameters on invoking the transformation is implementation - dependent and varies from one XSLT processor to another. You need to read the documentation of the particular XSLT processor for the exact information how to do this.
For example, if the XSLT processor is the .NET XslCompiledTransform, the way to pass parameters to the transformation is via the XsltArgumentList.AddParam() method.

A: You need to load the XSL and XML files to the javascript, you can use ajax requests for that, and you can use an iframe to load them for you. Once you have them in javascript you can use XPath and XSLT to do exactly what you want.
For example, here's a simple way to load an xml and then use XPath on it using the iframe way, it uses the input value to query the xml:
<html>
<head>
    <title> xml test </title>
    <script type="text/javascript">
        var xml = null;

        function getXml(path) {
            document.getElementById("loader").src = path;
        }

        function loaded(frm) {
            if (frm.contentWindow) {
                xml = frm.contentWindow.document;
            }
        }

        function query() {
            var value = document.getElementById("query").value;
            var evaluator = new XPathEvaluator();
                var result = evaluator.evaluate("//" + value,
                    xml,
                    null,
                    XPathResult.FIRST_ORDERED_NODE_TYPE,
                    null);

                console.log(result.singleNodeValue);
        }
    </script>
</head>
<body>
    Query the xml: <input type="text" id="query" />
    <input type="button" value="Go" onclick="query()" />
    <iframe style="width: 0px; height: 0px; display: none;" id="loader" onload="loaded(this)"></iframe>
    <script type="text/javascript">
        getXml("index.xml");
    </script>
</body>

As for the XSLT part, here's a tutorial for how to do that: XSLT - On the Client. In this tutorial they also show how to load the files using ajax.
You can of course load the XSL file just like the XML one in my example.