text:
Q: ERR_TOO_MANY_REDIRECTS from Shiro security AuthController in Grails app Shiro security works great with my grails app with the exception of if a user enters incorrect login information. If they put in the wrong username and password combination (which is authenticated via an LDAP server), it seems that I'm entering an infinite loop between the index and login actions. The general form of my AuthController is
class AuthController
{
    def shiroSecurityManager

    def index =
    {
        println "in index..."
        redirect(action: "login", params: params)
    }

    def login =
    {
        println "in login..."
        return [ username: params.username, rememberMe: (params.rememberMe != null), targetUri: params.targetUri ]
    }

    def signIn =
    {
        println "in signin..."
        Subject subject = SecurityUtils.getSubject()
        request.getSession().removeAttribute("subject")
        request.getSession(true).setAttribute("subject", subject)
        String lowerCaseUserName=params.username.toLowerCase()
        def authToken = new UsernamePasswordToken(lowerCaseUserName, params.password)

        // Support for "remember me"
        if (params.rememberMe)
        {
            authToken.rememberMe = true
        }

        try
        {
            println "in signin try..."
            subject.login(authToken)
            if (subject.isAuthenticated())
            {
                println "in signin try if 1..."
                def currentUser = User.findByEmployeeLogin(lowerCaseUserName)

                if (currentUser == null)
                {
                    log.info "Authentication failure for user '${lowerCaseUserName}'."
                    flash.message = message(code: "login.failed")

                    // Remember the target URI too.
                    if (params.targetUri)
                    {
                        m['targetUri'] = params.targetUri
                        redirect(controller: 'auth', action: 'login', params: m)
                    }
                    else
                    {
                        redirect(controller: 'auth', action: 'login')
                    }
                }
                else
                {
                    ...
                    redirect(controller: 'home', action: 'index')
                }
            }
        }
        catch (AuthenticationException ex)
        {
            println "in signin catch..."
            // Authentication failed, so display the appropriate message
            // on the login page.
            log.info "Authentication failure for user '${lowerCaseUserName}'."
            flash.message = message(code: "login.failed")

            // Keep the username and "remember me" setting so that the
            // user doesn't have to enter them again.
            def m = [ username: lowerCaseUserName ]
            if (params.rememberMe)
            {
                m['rememberMe'] = true
            }

            // Remember the target URI too.
            if (params.targetUri)
            {
                m['targetUri'] = params.targetUri
            }

            // Now redirect back to the login page.
            redirect(controller: 'auth', action: 'login', params: m)
        }
    }
}

The println's produce the following output
in signin...
in signin try...
Could not connect to <MYLDAPSERVER>: javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1 ]
Could not connect to <MYLDAPSERVER>: javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1 ]
No LDAP server available.
in signin catch...
in login...
in index...
in login...
in index...
in login...
in index...
in login...

The login/index output just keeps going until I get the error
This webpage has a redirect loop

ERR_TOO_MANY_REDIRECTS

Does anyone see why I'm having this issue?
Edit: I believe it may be due to my SecurityFilters baseFilter:
    baseFilter(controller: "*", action: "*") {
        before = {
            /*====================================================================
             * if auth controller then ok to continue
             *===================================================================*/
            if (controllerName.equals("auth"))
            {
                println "1.."
                return true;
            }

            /*=====================================================================
             * If no subject (user) and not auth controller
             * then user must authenticate
             *===================================================================*/
            if (!session.subject && !(controllerName.equals("auth")))
            {
                println "2.."
                params.targetUri = request.forwardURI
                redirect(controller:'auth', action:'login', params: params)
                return false;
            }
        }

        after = {
            try
            {
                println "3.."
                if (!(session.subject.isAuthenticated()))
                {
                    println "4.."
                    redirect(controller:'auth', action:'login', params: params)
                    return false;
                }
            }
            catch(Exception e)
            {
                println "5.."
            }
        }
    }

This results in the following output
in login...
3..
4..
1..
in login...
3..
4..
1..
in login...
3..
4..
1..

So it looks like I've found my issue, but I'm not sure how to fix it still.

A: Removing the after action in the beforeFilter
    after = {
        try
        {
            println "3.."
            if (!(session.subject.isAuthenticated()))
            {
                println "4.."
                redirect(controller:'auth', action:'login', params: params)
                return false;
            }
        }
        catch(Exception e)
        {
            println "5.."
        }
    }

Fixed my problem. Now to get the 'rememberMe' to work!


text:
Q: Update value by using previous value to increment I have a query that inserts a new row and creates a unique date. If there is a conflict, I want to update the row instead.
const updateInsight = await Insight.createQueryBuilder("Insight")
    .insert()
    .values({ sales: 1 })
    .onConflict("(date) DO UPDATE SET sales = sales + 1")
    .execute();

This is the same as:
INSERT INTO "Insight" ("sales") VALUES(1) ON CONFLICT (date) DO UPDATE SET sales = sales + 1;

The table looks like this where the date field is default: NOW() with type: Date:

Running the query I get the following error:

"column reference "sales" is ambiguous"

I have tried using Insight.sales = Insight.Sales + 1 in the UPDATE SET, but then I get:

"missing FROM-clause entry for table "insight\

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to boot into macOS directly in Boot Camp? I just got Boot Camp with Windows 10 on my Mac. How can I boot into macOS without having to press the Alt/Option key after the chime sound?
Currently, when I start the Mac normally, it boots into Windows, and then I have to switch from there to Mac which requires another restart. Is there any way I can do this?

A: If you go to the Boot Camp Control Panel in Windows, you can select the boot drive in there. This will be in effect until you change it again from within macOS's Startup Disk system preference.


text:
Q: Same code executed on different servers (same version) yields different results Issue with Delphi legacy code. Added one line of code to correct one error and created a new error.
New error is causing the same executable to yield different results on different servers(switched the pointer from dev to prod environment on the executable).
code:
sEscapedString:=stringreplace(sStringIn,'[','''+char(27)+''[',[rfReplaceAll]);
sEscapedString:=stringreplace(sEscapedString,']','''+char(27)+'']',[rfReplaceAll]);
sEscapedString:=stringreplace(sEscapedString,'''','''''',[rfReplaceAll]);// this line created new
bug
result:=' like ''' + Trim(sEscapedString) + '%'''+'  escape char(27) ';

When running the code against dev this query finds objects with the characters '[' and ']' in it
Against prod the query does not find those items:
The first thing I checked was the data: Exactly identical in both cases
The second thing I checked was SQL server versions (11.0.3128 on BOTH servers)
The third thing I am checking is settings on those servers:
    DBCC USEROPTIONS; -- same on both
    SELECT name, collation_Name FROM sys.databases -- same on both
    select @@OPTIONS -- same on both.
    Quoted identifiers are 'ON' for both servers
It comes down to the fact that I know one server is treating the escape character (chr(27)) differently than the other but I do knot know why.
Does anyone have a theory(or answer) as to why the 2 similar servers are treating the escape characters differently?
The goal here is getting the prod server to return values with '[' and ']', as setting up my system to work with the legacy code will take a LOT of additional time. I do have a fix for the code
sEscapedString:=stringreplace(sStringIn,'[','[[]',[rfReplaceAll]);

But the faster option would seem to be getting the server to read the values the same.
Update: We found the root cause of the difference and it was more mundane than what we expected, turns out the query we were running was actually executed twice. The second execution was missing the key piece on the production server.
The issue was resolved by moving the new line of code so that it executed first rather than last.

A: I would first try to find out if this SQL only causes different behaviour when it is sent from the application: by sending the SQL from an interactive SQL client tool to both servers.
To make sure that the manually tested SQL is exactly the same as in the application, I would try to log or capture the exact SQL as sent from the application as a text file and then paste its content to the SQL client tool.
If the server is the culprit, then using the SQL from a different client tool should cause the same difference with the two servers. If the client tool shows the same (correct) result on both servers, then something is going on in the Delphi application.
p.s. upvoted, it is an interesting phenomenon


text:
Q: SSRS Hide columns based on Multi valued parameter I have an SSRS report that has two parameters. A Description and Partner name. You can select more than one description or all of them but only one partner. When i select one or more descriptions report must only show columns that have values.
Issue is when i select all of them the report defaults to the structure of the first description regardless of the fact that when the 2nd or 3rd description row starts there is data in that column and it should be showing it. So it ends up hiding columns that should be showing
I have the below code in code visibility expression
=IIF(IsNothing(Fields!Working_Office.Value),True,False)
I suspect my issue has to do with the Multi valued parameter,
HELP


text:
Q: How to use POST request to create an object in C# API? So I'm trying to make this parking ticket system and I'm currently creating these objects manually in the code for testing. Now I've come to the step where my POST request in postman should be able to create an object in the memory of the app. I've got two classes one for a ''Car'' and one for the ''Ticket''.
public class Car
    {

        public string regNr { get; set; }

        public string carBrand { get; set; }

        public string carColor { get; set; }

        public List<Ticket> ticketlist {get; set;}

        public Car()
        {
            this.ticketlist = new List<Ticket>();

        }
        public void addNewTicket(Ticket newTicket)
        {

            ticketlist.Add(newTicket);
        }
    }
}

public class Ticket
    {

        public int ticketID { get; set; } = 0;

        public DateTime date { get; set; }

        public string comment { get; set; }

        public int parkingAreaID { get; set; }

        public int parkingsOfficerID { get; set; }

    }
}

List<Bil> list = new List<Car>();
public void Post([FromBody]Bil val)
        {

            list.Add(val);
        }

The GET requests work and I want to be able to add a new ticket to a registration number by using my post request.
My current output is this;
{
    "regNr": "BT66358",
    "carBrand": "BMW",
    "carColor": "Yellow",
    "ticketlist": [
        {
            "ticketID": 1,
            "date": "2020-12-12T17:49:34.4000401+01:00",
            "comment": "very bad parking",
            "parkingsAreaID": 1,
            "parkingsOfficerID": 2
        },
        {
            "ticketID": 2,
            "date": "2020-12-12T17:49:34.4000401+01:00",
            "comment": "very bad parking",
            "parkingsAreaID": 2,
            "parkingsOfficerID": 2
        }
    ]
}
---------------UPDATE-----------

Bil = Car
botliste = ticketlist
liste = list
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/q3UaO.png

A: If I understood you correctly, then most likely you just need to add some attributes, and you get something like this:
List<Car> list = new List<Car>();

[HttpPost]
[HttpPost("SomeRoute")]
public IActionResult Post([FromBody] Car val)
{

    if (val == null)
    {
        return BadRequest("Car data must be filled");
    }

    if (string.IsNullOrEmpty(val.regNr))
    {
        return BadRequest("Reg number must be filled");
    }

    var car = list.FirstOrDefault(c => string.Equals(c.regNr, val.regNr));

    if (car != null)
    {
        car.ticketlist.AddRange(val.ticketlist);
    }
    else
    {
        list.Add(val);
    }

    /// And return IActionResult
    return Ok();
}

P.S. Give a description of the Bil type to get a more detailed answer.
upd:
You can also add attributes to the fields of your classes that will validate the values, for example:
...
public class Car
{
    [MinLength(6, ErrorMessage = "regNr field must be at least 6 characters")]
    public string regNr { get; set; }

...
The "MinLength" attribute indicates that the value for this property is required, and must be at least 6 characters.
More details here: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations?view=net-5.0
upd2:
This is how I get to invoke this method:


text:
Q: Integrity Restrictions in SQL I`m trying to create a new database in SQL.
So, I've written this code;
CREATE TABLE datum (
    datum_zajezdu       DATE NOT NULL,
    zajezd_id           INTEGER NOT NULL,
    pruvodci_osoba_id   INTEGER NOT NULL,
    zajezd_zajezd_id1   NUMBER NOT NULL
);

ALTER TABLE datum
    ADD CONSTRAINT datum_pk PRIMARY KEY ( datum_zajezdu,
    zajezd_id,
    pruvodci_osoba_id );

CREATE TABLE osoba (
    osoba_id   INTEGER NOT NULL,
    jmeno      VARCHAR2(32 CHAR) NOT NULL,
    prijmeni   VARCHAR2(32 CHAR) NOT NULL
);

ALTER TABLE osoba ADD CONSTRAINT osoba_pk PRIMARY KEY ( osoba_id );

CREATE TABLE pracovnik (
    misnost_id                   INTEGER NOT NULL,
    zamestnanec_osoba_osoba_id   INTEGER NOT NULL
);

ALTER TABLE pracovnik ADD CONSTRAINT pracovnik_pk PRIMARY KEY ( zamestnanec_osoba_osoba_id );

CREATE TABLE pruvodci (
    tel                          INTEGER NOT NULL,
    mail                         VARCHAR2(32 CHAR) NOT NULL,
    zamestnanec_osoba_osoba_id   INTEGER NOT NULL
);

ALTER TABLE pruvodci ADD CONSTRAINT pruvodci_pk PRIMARY KEY ( zamestnanec_osoba_osoba_id );

CREATE TABLE rezervace (
    rezervace_id              INTEGER NOT NULL,
    zakaznik_osoba_osoba_id   INTEGER NOT NULL,
    zajezd_zajezd_id          INTEGER NOT NULL,
    pracovnik_osoba_id        INTEGER NOT NULL
);

ALTER TABLE rezervace ADD CONSTRAINT rezervace_pk PRIMARY KEY ( rezervace_id );

CREATE TABLE typ_cestovani (
    nazev_typu   VARCHAR2(30 CHAR) NOT NULL
);

ALTER TABLE typ_cestovani ADD CONSTRAINT typ_cestovani_pk PRIMARY KEY ( nazev_typu );

CREATE TABLE zajezd (
    zajezd_id    INTEGER NOT NULL,
    nazev        VARCHAR2(32 CHAR) NOT NULL,
    stat         VARCHAR2(32 CHAR) NOT NULL,
    mesto        VARCHAR2(32 CHAR) NOT NULL,
    cena         NUMBER NOT NULL,
    zajezd_id1   NUMBER NOT NULL
);

ALTER TABLE zajezd ADD CONSTRAINT zajezd_pk PRIMARY KEY ( zajezd_id1 );

CREATE TABLE zajezd_ma_typ (
    typ_cestovani_nazev_typu   VARCHAR2(30 CHAR) NOT NULL,
    zajezd_zajezd_id           INTEGER NOT NULL
);

ALTER TABLE zajezd_ma_typ ADD CONSTRAINT zajezd_ma_typ_pk PRIMARY KEY ( typ_cestovani_nazev_typu,
zajezd_zajezd_id );

CREATE TABLE zakaznik (
    tel              INTEGER NOT NULL,
    mail             VARCHAR2(32 CHAR),
    osoba_osoba_id   INTEGER NOT NULL
);

ALTER TABLE zakaznik ADD CONSTRAINT zakaznik_pk PRIMARY KEY ( osoba_osoba_id );

CREATE TABLE zamestnanec (
    cislo_uctu       INTEGER NOT NULL,
    osoba_osoba_id   INTEGER NOT NULL
);

ALTER TABLE zamestnanec
    ADD CONSTRAINT arc_1_lov CHECK ( osoba_osoba_id IN (
        '1',
        '2'
    ) );

ALTER TABLE zamestnanec ADD CONSTRAINT zamestnanec_pk PRIMARY KEY ( osoba_osoba_id );

ALTER TABLE datum
    ADD CONSTRAINT datum_pruvodci_fk FOREIGN KEY ( pruvodci_osoba_id )
        REFERENCES pruvodci ( zamestnanec_osoba_osoba_id );

ALTER TABLE datum
    ADD CONSTRAINT datum_zajezd_fk FOREIGN KEY ( zajezd_zajezd_id1 )
        REFERENCES zajezd ( zajezd_id1 );

ALTER TABLE pracovnik
    ADD CONSTRAINT pracovnik_zamestnanec_fk FOREIGN KEY ( zamestnanec_osoba_osoba_id )
        REFERENCES zamestnanec ( osoba_osoba_id );

ALTER TABLE pruvodci
    ADD CONSTRAINT pruvodci_zamestnanec_fk FOREIGN KEY ( zamestnanec_osoba_osoba_id )
        REFERENCES zamestnanec ( osoba_osoba_id );

ALTER TABLE rezervace
    ADD CONSTRAINT rezervace_pracovnik_fk FOREIGN KEY ( pracovnik_osoba_id )
        REFERENCES pracovnik ( zamestnanec_osoba_osoba_id );

ALTER TABLE rezervace
    ADD CONSTRAINT rezervace_zajezd_fk FOREIGN KEY ( zajezd_zajezd_id )
        REFERENCES zajezd ( zajezd_id );

ALTER TABLE rezervace
    ADD CONSTRAINT rezervace_zakaznik_fk FOREIGN KEY ( zakaznik_osoba_osoba_id )
        REFERENCES zakaznik ( osoba_osoba_id );

ALTER TABLE zajezd_ma_typ
    ADD CONSTRAINT zajezd_ma_typ_typ_cestovani_fk FOREIGN KEY ( typ_cestovani_nazev_typu )
        REFERENCES typ_cestovani ( nazev_typu );

ALTER TABLE zajezd_ma_typ
    ADD CONSTRAINT zajezd_ma_typ_zajezd_fk FOREIGN KEY ( zajezd_zajezd_id )
        REFERENCES zajezd ( zajezd_id );

ALTER TABLE zakaznik
    ADD CONSTRAINT zakaznik_osoba_fk FOREIGN KEY ( osoba_osoba_id )
        REFERENCES osoba ( osoba_id );

ALTER TABLE zamestnanec
    ADD CONSTRAINT zamestnanec_osoba_fk FOREIGN KEY ( osoba_osoba_id )
        REFERENCES osoba ( osoba_id );

CREATE OR REPLACE TRIGGER arc_arc_1_pracovnik BEFORE
    INSERT OR UPDATE OF zamestnanec_osoba_osoba_id ON pracovnik
    FOR EACH ROW
DECLARE
    d   INTEGER;
BEGIN
    SELECT
        a.osoba_osoba_id
    INTO
        d
    FROM
        zamestnanec a
    WHERE
        a.osoba_osoba_id =:new.zamestnanec_osoba_osoba_id;

    IF
        ( d IS NULL OR d <> 1 )
    THEN
        raise_application_error(-20223,'FK Pracovnik_Zamestnanec_FK in Table Pracovnik violates Arc constraint on Table Zamestnanec - discriminator column Osoba_osoba_id doesn''t have value 1'
);
    END IF;

EXCEPTION
    WHEN no_data_found THEN
        NULL;
    WHEN OTHERS THEN
        RAISE;
END;
/

CREATE OR REPLACE TRIGGER arc_arc_1_pruvodci BEFORE
    INSERT OR UPDATE OF zamestnanec_osoba_osoba_id ON pruvodci
    FOR EACH ROW
DECLARE
    d   INTEGER;
BEGIN
    SELECT
        a.osoba_osoba_id
    INTO
        d
    FROM
        zamestnanec a
    WHERE
        a.osoba_osoba_id =:new.zamestnanec_osoba_osoba_id;

    IF
        ( d IS NULL OR d <> 2 )
    THEN
        raise_application_error(-20223,'FK Pruvodci_Zamestnanec_FK in Table Pruvodci violates Arc constraint on Table Zamestnanec - discriminator column Osoba_osoba_id doesn''t have value 2'
);
    END IF;

EXCEPTION
    WHEN no_data_found THEN
        NULL;
    WHEN OTHERS THEN
        RAISE;
END;
/

CREATE SEQUENCE zajezd_zajezd_id1_seq START WITH 1 NOCACHE ORDER;

CREATE OR REPLACE TRIGGER zajezd_zajezd_id1_trg BEFORE
    INSERT ON zajezd
    FOR EACH ROW
    WHEN ( new.zajezd_id1 IS NULL )
BEGIN
    :new.zajezd_id1 := zajezd_zajezd_id1_seq.nextval;
END;

As the result, I should get something like:
this (relational schema)
but I have one problem. In my logical schema, I put 2 Integrity Restrictions and I don`t know how to write that in create.sql file.
First one is:
 "Osoba" should be "Zamestnanec" or "Zakaznik" or both."Osoba" can`t be without any relation.
Second one:
"Osoba" can't get a reservation (ENTITY "Rezervace") if "Osoba" is "Pruvodci" and has own work on the same date (entity "datum") as the reservation.
EDIT: my logical schema looks


text:
Q: How do I set up the Windows 10 "Your Phone" App's Calls feature? I've got the Windows 10 "Your Phone" app set up, except for the "Calls" feature, which allows you to receive phone calls using your PC's audio.  It keeps prompting me to pair my phone and my PC over Bluetooth, even though they're already paired. All the notifications pop up, such as the one asking for permission to make my phone discoverable over bluetooth, but after the pairing succeeds, the setup still fails with the message "We couldn't finish connecting. Wait a bit, then try again".
My only clue to what is going on is that when I open Bluetooth on my phone, and tap on my computer to connect to it, it says "Connection failed", and when I open my Windows 10 notifications and click "Connect", my phone doesn't appear in the list.
After unpairing, re-pairing, uninstalling the Your phone app from my PC and phone, then reinstalling, I'm stumped. Do I need a new bluetooth dongle? I'm currently using a TECHKEY usb dongle, which works fine for bluetooth headphones and game controllers.

A: the following guide may help you:
1. Swiping downwards from the top of your screen to reveal the Android Notification panel. Tap and hold the Bluetooth icon.
2. A list of nearby devices will be displayed. Locate the name of your PC in this list and tap on it.
3. You should see notifications on both your Android phone and Windows 10 PC. Tap or click on these toasts to confirm.
4. The connection process should now be complete, and you'll be able to use the Calls feature.
https://support.microsoft.com/en-us/help/4531607/troubleshooting-calls


text:
Q: Let $P$ be the transition matrix of random walk on $n$-cycle($n$ is odd). Find the smallest value of $t$ such that $Pt(x, y) > 0$ for all $x$ and $y.$ Let $P$ be the transition matrix of a random walk on the $n$-cycle,
where $n$ is odd. Find the smallest value of $t$ such that $Pt(x, y) > 0$ for all states $x$ and $y$.
My solution:
If I have $n$ states, I will need a minimum of $n-1$ steps ahead of $1$st state, to cover all $n$ states. As I have covered all states, $Pn-1(x, y) > 0$ for all states $x$ and $y$.Thus minimum $t$ is $n-1$.
Where am I lacking in the proof? What things have I discarded/overlooked?
What more do I need to prove my claim?

A: Okay, this turned out slightly more finicky than I was really expecting. The upshot is that yes, $n-1$ is the minimal number and you were right all along. However, your argument remains somewhat lacking in detail, so here is a full solution:
First, some formalities:
Label the vertices $1,...,n$ in order and let $\oplus$ denote addition mod $n$. I'll denote going around the cycle in increasing order as 'going to the right'.
Clearly, since the walk is symmetric and the graph is transient, $P_t(x,y)=P_t(y,x)=P_t(y\oplus (n-y),x\oplus (n-y))$. Hence, it suffices to consider $P_t(1,j)$ for general $j$.
And now, a proof:
You're absolutely correct that $P_t(1,j)>0$ if and only if there exists a path $(\alpha_s)_{1\leq s\leq t}$ of neighbours such that $\alpha_1=1$ and $\alpha_t=j$. Hence, we want to find the minimal $t$ such that there exists some path of length $t$ from $1$ to $j$ for all $j$. Let's argue that $t\leq n-1$, i.e. that $t=n-1$ satisfies the condition.
It's clear that there is a path of said length from $1$ to $n$ , namely the path of length $n-1$ that keeps going to the right. If you have a path of length $n-1$ from $1$ to $j$ such that the second to last step is $j-1$, you also get a pth of length $n-1$ from $1$ to $j-2$ by simply reversing the last step. Thus, there is a path of length of $n-1$ from $1$ to every odd $j$. However, the same logic applies to the path of length $n-1$ which goes left from $1$ until it hits $2$, and we get that there exists a path of length $n-1$ from $1$ to any even $j$. Thus, $t\leq n-1$.
Now, let $t<n-1$ and let us find a $j$ such that $P_t(1,j)=0$. If $t$ is odd, then $P_t(1,1)=0$, since no path of length less than $n$ can form a full loop of the cycle. If, on the other hand, $t$ is even, we see that $P_t(1,2)=0$. Indeed, for any walk $(\alpha_s)_{0\leq s\leq t}$ with $\alpha_0=1$, we see that $\alpha_s-2$ is odd for even $s$ unless at some point $\alpha$ goes from $1$ to $n$ and never crosses back again to $1$ - in particular it $\alpha_t-2$ could not be $0$. However, $n-2>t-1$, so even if $\alpha_1=n$, it's impossible that $\alpha_t$ could be $2$.
We conclude that $t=n-1$ is, indeed, minimal.


text:
Q: How do I make one list from multiple columns using Python's Pandas? I have database that I want to use make one list of numbers so I can count how many times each number occurs throughout the database. I want to use the columns Number_1 - Number_5. The most I've been able to do is just make separate lists for each column.
To clarify further, I want the list to look something like this:
list_of_numbers = (11,18,5,14,31,26,12,37,12,13,3,2,4,14,41,22,31,26,15,35,32,20,49,20,15,7,5,10,18,58,...)
BTW, the database is pretty big, so the list is going to have 7650 elements to it
It looks something like this:
Draw # Draw DateNumber_1Number_2Number_3Number_4Number_5Mega
1004 Tue. Feb 03, 2015  11  22  25  58  69  13
1003 Fri. Jan 30, 2015  18  31  39  45  55  6
1002 Tue. Jan 27, 2015  5   26  27  44  57  7
1001 Fri. Jan 23, 2015  14  15  32  68  72  8
1000 Tue. Jan 20, 2015  31  35  56  59  63  6
999 Fri. Jan 16, 2015   26  32  44  45  58  11
998 Tue. Jan 13, 2015   12  20  25  50  51  7
997 Fri. Jan 09, 2015   37  49  50  56  57  8
996 Tue. Jan 06, 2015   12  20  27  38  75  4
995 Fri. Jan 02, 2015   13  15  35  62  74  12
994 Tue. Dec 30, 2014   3   7   44  63  67  12
993 Fri. Dec 26, 2014   2   5   10  20  38  14
992 Tue. Dec 23, 2014   4   10  31  56  66  7
991 Fri. Dec 19, 2014   14  18  58  59  68  4
990 Tue. Dec 16, 2014   41  58  68  72  73  1

A: df.iloc[:, -6: -1].values.T.ravel()

yields
array([11, 18,  5, 14, 31, 26, 12, 37, 12, 13,  3,  2,  4, 14, 41, 18,  5,
       14, 31, 26, 12, 37, 12, 13,  3,  2,  4, 14, 41, 31, 26, 15, 35, 32,
       20, 49, 20, 15,  7,  5, 10, 18, 58, 39, 27, 32, 56, 44, 25, 50, 27,
       35, 44, 10, 31, 58, 68, 45, 44, 68, 59, 45, 50, 56, 38, 62, 63, 20,
       56, 59, 72, 55, 57, 72, 63, 58, 51, 57, 75, 74, 67, 38, 66, 68, 73,
        6,  7,  8,  6, 11,  7,  8,  4, 12, 12, 14,  7,  4,  1])

You can call the tolist() method on the resulting array if you prefer lists.


text:
Q: Finding minimum by groups and among columns I am trying to find the minimum value among different columns and group.
A small sample of my data looks something like this:
     group cut group_score_1 group_score_2
1        a   1             3           5.0
2        b   2             2           4.0
3        a   0             2           2.5
4        b   3             5           4.0
5        a   2             3           6.0
6        b   1             5           1.0

I want to group by the groups and for each group, find the row which contains the minimum group score among both group scores and then also get the name of the column which contains the minimum (group_score_1 or group_score_2),
so basically my result should be something like this:
      group cut group_score_1 group_score_2
1        a   0             2           2.5
2        b   1             5           1.0

I tried a few ideas, and came up eventually to dividing the into several new data frames, filtering by group and selecting the relevant columns and then using which.min(), but I'm sure there's a much more efficient way to do it. Not sure what I am missing.

A: We can use data.table methods
library(data.table)
setDT(df)[df[, .I[which.min(do.call(pmin, .SD))],
     group, .SDcols = patterns('^group_score')]$V1]
#   group cut group_score_1 group_score_2
#1:     a   0             2           2.5
#2:     b   1             5           1.0

A: For each group, you can calculate min value and select the row in which that value exist in one of the column.
library(dplyr)

df %>%
  group_by(group) %>%
  filter({tmp = min(group_score_1, group_score_2);
          group_score_1 == tmp | group_score_2 == tmp})

#  group   cut group_score_1 group_score_2
#  <chr> <int>         <int>         <dbl>
#1 a         0             2           2.5
#2 b         1             5           1

The above works well when you have only two group_score columns. If you have many such columns it is not possible to list down each one of them with group_score_1 == tmp | group_score_2 == tmp etc. In such case, get the data in long format and get the corresponding cut value of the minimum value and join the data. Assuming cut is unique in each group.
df %>%
  tidyr::pivot_longer(cols = starts_with('group_score')) %>%
  group_by(group) %>%
  summarise(cut = cut[which.min(value)]) %>%
  left_join(df, by = c("group", "cut"))

A: Here is a base R option using pmin + ave + subset
subset(
  df,
  as.logical(ave(
    do.call(pmin, df[grep("group_score_\\d+", names(df))]),
    group,
    FUN = function(x) x == min(x)
  ))
)

which gives
  group cut group_score_1 group_score_2
3     a   0             2           2.5
6     b   1             5           1.0

Data
> dput(df)
structure(list(group = c("a", "b", "a", "b", "a", "b"), cut = c(1L,
2L, 0L, 3L, 2L, 1L), group_score_1 = c(3L, 2L, 2L, 5L, 3L, 5L
), group_score_2 = c(5, 4, 2.5, 4, 6, 1)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))


text:
Q: Stop a recursive function from 'outside' the function I am currently taking a computer graphics course in C++ and having to do exams for it. The current task says:

Make sure, the recursive function 'trace_recursive' gets stopped at
the recursion depth 'max-depth' without changing the code of
'trace-recursive'.

I have worked with recursion before, but always with my own recursive functions, where I could set my own end to the function. Is there any way to kill a recursive function from 'outside' the function in C++ without killing the whole program?
I always thought you need to stop recursion from inside the function and I did not find anything online that helps me with my problem.
Edit:
This is the method, that calls 'trace_recursive':
glm::vec3 evaluate_reflection(
RenderData &data,           // class containing raytracing information
int depth,                  // the current recursion depth
glm::vec3 const& P,         // world space position
glm::vec3 const& N,         // normal at the position (already normalized)
glm::vec3 const& V)         // view vector (already normalized){

glm::vec3 Refl = reflect(V, N);
float epsilon = data.context.params.ray_epsilon;
Ray ray(P + epsilon*Refl, Refl);
glm::vec3 Mirror = trace_recursive(data, ray, depth);

return Mirror;}

I am not allowed to post the code of the actual function 'trace_recursive'
What my method is asked to do is:
Create the vector Refl;
create the ray;
create the vector mirror by using trace_recursive. If trace recursive reaches a recursive depth of for example 5, it should return the current value and stop, even if it would not stop by itself.


text:
Q: How to make regular expression with negative value or non negative value? I am focusing on data with a regular expression. My data have this template:
Timestamp 1549033386  ID=02141592cc0000000700000000000000 Dest_ID=02141592cc00000007ffffffb0ba2c53 Nbr_packet_not_acK_ti9-ti5 -91

I am using python and I implement this regular expression:
'Nbr_packet_not_acK_ti9-ti5': r'\bTimestamp\s+([0-9]+)\s+ID=(\w{32})0*\s+Dest_ID=(\w{32})0*\sNbr_packet_not_acK_ti9-ti5\s+([0-9]+)',

But It does not work correctly, the problem is with  the negative values that I have.
I have another example that works correctly:
Timestamp 1549033599  ID=02141592cc0000000600000000000000 Dest_ID=00000000000000000000000000000000Delay_T2R2 -1

\bTimestamp\s+([0-9]+)\s+ID=(\w{32})0*\s+Dest_ID=(\w{32})0*Delay_T2R2\s+(-?[0-9]+)

A: If I try this, it matches 3 groups:
1549033386
02141592cc0000000700000000000000
02141592cc00000007ffffffb0ba2c53

but the whole regular expression doesn't match because of the trailing ([0-9]+) which, as you correctly note, doesn't match the negative number. Fixing the regular expression either this way:
\bTimestamp\s+([0-9]+)\s+ID=(\w{32})0*\s+Dest_ID=(\w{32})0*\sNbr_packet_not_acK_ti9-ti5\s+([-0-9]+)

or this way, as suggested by Engineero:
\bTimestamp\s+([0-9]+)\s+ID=(\w{32})0*\s+Dest_ID=(\w{32})0*\sNbr_packet_not_acK_ti9-ti5\s+(-?[0-9]+)

gives me a full match on all 4 capturing groups.
1549033386
02141592cc0000000700000000000000
02141592cc00000007ffffffb0ba2c53
-91

So I conclude that either fix does in fact work, and the failure to match that you report is caused by a confounding error.
To demonstrate that it must be a confounding error, try this at the interpreter prompt, to eliminate such errors:
>>> exp = r"\bTimestamp\s+([0-9]+)\s+ID=(\w{32})0*\s+Dest_ID=(\w{32})0*\sNbr_packet_not_acK_ti9-ti5\s+(-?[0-9]+)"
>>> rx = re.compile(exp)
>>> m=rx.match("Timestamp 1549033386  ID=02141592cc0000000700000000000000 Dest_ID=02141592cc00000007ffffffb0ba2c53 Nbr_packet_not_acK_ti9-ti5 -91")
>>> m.groups()
('1549033386', '02141592cc0000000700000000000000', '02141592cc00000007ffffffb0ba2c53', '-91')

I tried this in Python 2.5, 2.7, 3.6 and 3.7. I don't have 3.5 anymore, but if there had been a bug of this seriousness in 3.5 I'm pretty sure I would have heard about it.
So it's not the version, and it's not the regular expression itself. That leaves the data, which might not look quite the way it looks in your question, or the code that surrounds the check.


text:
Q: Is there a max number of parallel Bolts-Android Tasks? I'm using the BoltsFramework (Parse) in an android Application. Let's say I want to launch in background several Parallel Tasks (so several Threads). Is there a limit to avoid to use too much Threads? Or can we put in a queue if the tasks are too many? I would like to avoid call the tasks in series.
The use case should be something like launch several task in parallel (huge number) and when All are completed do something….

A: Bolts-Android uses a thread pool with a queue behind the scenes, so you don't have to worry about managing it yourself. If you want to see how it's implemented, you can see BoltsExecutors.java and AndroidExecutors.java.
In a JVM environment, it'll use the default Executors.newCachedThreadPool() which has a limit of Integer.MAX_INT simultaneous parallel threads and a synchronous queue when it runs out of threads.
In an Android environment, it uses a custom pool size that sizes itself depending on how many cores your CPU has and has a synchronous queue when it runs out of threads as well.
You can also pass in your own Executor in several methods to manage the thread pool yourself.
https://github.com/BoltsFramework/Bolts-Android/blob/master/bolts-tasks/src/main/java/bolts/BoltsExecutors.java
https://github.com/BoltsFramework/Bolts-Android/blob/master/bolts-tasks/src/main/java/bolts/AndroidExecutors.java


text:
Q: How to find if a class has any objects created based on it's definition? Is it possible to search the ruby environment for variables of a given class?
I have a class Connection. From any code in my application I want to be able to return any Connection that have been instantiated. Is that possible?
For example:
conns = ObjectSpace.find_objects_with_class(Connection)

I'm trying to find a globally defined database connection object that may or may not be there, if it's not there my code creates the connection.

A: ObjectSpace.each_object(Connection).to_a

will give you the list of all Connection instances.
Connection.instance_variables
Connection.class_variables

will give you instance and class variables of Connection respectively.


text:
Q: Can't install wordpress plugins locally using XAMPP In reference to this question:
Wordpress plugin install: Could not create directory
Would simply comment but can't comment with less than 50.
I followed the instructions of updating permissions with chown using the following command:
sudo chown -R _www:_www wp-content/plugins/

However I get operation not permitted on a long list of all the contents of the folder.

A: Try with this code.
Put in functions.php
if(is_admin()) {
  add_filter('filesystem_method', create_function('$a', 'return "direct";' ));
  define( 'FS_CHMOD_DIR', 0751 );
}

A: The FS_METHOD can be defined in wp_config.php like so:
define('FS_METHOD', 'direct');


text:
Q: C++ when to use delete[] and properly deallocate memory? So I see that there's pairings with memory management functions such as malloc/free, new/delete, and new[]/delete[], but sometimes you're not always calling new or new[] and you still have to call delete, delete[], or free. For example, strdup is one such function which encapsulates the allocation of memory and you'd still have to deallocate that memory yourself later on.
So when do you know to free memory, if you're not always writing new or malloc in some sense? I'm particularly curious about deleting arrays of objects. Just simple arrays. Because, that seems to be one of the use cases that delete[] is made for. (I'm looking at cplusplus.)
So, is this valid? Is this necessary? Is anything missing?
unsigned char bytes[4] = {0xDE, 0xAD, 0xBE, 0xEF};
for(int i = 0; i < 4; i++)
    std::cout << std::hex << +bytes[i];
delete[] bytes;

bytes is technically an unsigned char * type, right? I know I technically have a pointer, but because this isn't an array of objects, I'm unsure whether or not it gets automatically destroyed.

A:
C++ when to use delete[] and properly deallocate memory?

When the memory was allocated memory with new[] and that memory has not yet been deallocated, and won't be deallocated by anyone else.

So, is this valid?

Not valid. What you've shown has undefined behaviour. You may not deallocate automatic variables. You may not call delete[] on anything that wasn't allocated with new[].

Is this necessary?

Not necessary. Automatic variables are destroyed... automatically, when they go out of scope.

bytes is technically an unsigned char * type, right?
I know I technically have a pointer

Not right. bytes is in all regards, an array. Not a pointer.

So is C++ different from C in that regard about pointers to arrays?

Not different. Arrays are arrays in C as well.
You may be confused with array decaying. When used in a value context, array name will decay into a pointer to first element. The pointer that the array decays into is a pointer, but the array is not. Example:
int  arr[4] = {1, 2, 3, 4}; // an array
int* ptr  = arr;            // a pointer; arr decays and is assignable to a pointer
int* ptr2 = &arr[0]         // decaying is syntactic sugar for this
int size1 = sizeof arr;     // size of the array == sizeof(int)*4
int size2 = sizeof ptr;     // size of the pointer == sizeof(int*)

Also, in a function argument list, array declaration is the same as a pointer declaration. Which is highly confusing. You just have to remember that arrays can not be passed by value, so an array as function argument must mean something else.
void foo(int[4]); // confusing
void foo(int*);   // actually means this

A: No, this is not valid.
Every single call to delete[] should be paired with new[].  If it doesn't pair up (e.g. strdup), it's because some function internally calls malloc/new[].
unsigned char bytes[4] = {0xDE, 0xAD, 0xBE, 0xEF}; declares 4 bytes of memory on the stack.  Stack memory is automatically destroyed at the end of the enclosing scope.  They share the same memory as those needed for function calls.
new/delete allocates and deallocates heap memory.  Heap memory has no specific order of acquisition or destruction (unlike a stack, which is first-in-last-out), so you have to delete it explicitly or the program won't know when to deallocate it.


text:
Q: alamofire multipartformdata use urlrequest I want to use Alamo fire multipart form data use request, for example, I use upload API
let profile = self.photoView.imageView?.image

    let parameters : [String:String] = [
        "homePageUrl": webURLField.text!,
        "nickName": nickNameField.text!,
        "selfIntro": introField.text!,
        ]

    let uri = Constants.APIURL.changeProfile
    let fileName = "\(nickNameField.text!).jpg"

    Alamofire.upload(multipartFormData: { (multipartFormData) in
         if let imageData = UIImageJPEGRepresentation(profile!, 1.0) {
            multipartFormData.append(imageData, withName: "profile", fileName: fileName, mimeType: "image/jpg")
        }

        for ( key, value ) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8, allowLossyConversion: false)!, withName: key)
        }

    }, usingThreshold: UInt64.init(), to: uri, method: .patch, headers: Constants.VyrlAPIConstants.getHeader(), encodingCompletion:
        {
            encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                 })

                upload.responseString { response in
                    if ((response.response?.statusCode)! == 200){
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            case .failure(let encodingError):
                print(encodingError.localizedDescription)
            }
    })

this code sends 400 response from server
log is.

PATCH 'http://blablabla.com:8080/users/profile':
Content-Type: multipart/form-data;
  boundary=alamofire.boundary.53a2e440bad1fabd X-Device: ios
  X-APP-Version: 1.0.0 Accept-Language: ko-kr 400
  'http://blablabla.com:8080/users/profile' [0.0976 s]:
  X-Application-Context: application:dev Connection: close
  Transfer-Encoding: Identity Date: Thu, 13 Jul 2017 01:57:41 GMT
server want to receive
  http://blablabla.com:8080/users/profile?nickName=abcd&selfIntro=hi%20my%20name%20is..
  server log is.. (success 200 code)
curl -X PATCH --header 'Content-Type: multipart/form-data' --header
  'Accept: /' --header 'X-APP-Version: 1.0.0' --header 'X-Device: ios'
  --header 'Accept-Language: ko-KR' {"type":"formData"} 'http://blablabla.com:8080/users/profile?nickName=abcd&selfIntro=hi%20my%20name%20is..'

definitely, i want to attach ?nicName=abcd
use multiformpart data
How to use alamofire code?

A: Please Try This it's working for me for image upload
 var parameters = [String:AnyObject]()

    let profile = self.photoView.imageView?.image

    parameters = ["homePageUrl": webURLField.text as AnyObject,
                  "nickName": nickNameField.text as AnyObject,
                  "selfIntro": introField.text as AnyObject]

    let imgData = UIImageJPEGRepresentation(profile!, 0.2)!

    let uri = Constants.APIURL.changeProfile
    let fileName = "\(nickNameField.text!).jpg"

    Alamofire.upload(multipartFormData:{ multipartFormData in
        multipartFormData.append(imgData, withName: "profile",fileName: fileName, mimeType: "image/jpg")
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        }
    },
                     usingThreshold:UInt64.init(),
                     to:uri,
                     method:.post,
                     headers:Constants.VyrlAPIConstants.getHeader(),
                     encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload.responseJSON { response in
                                 print(response.result.value)
                            }
                        case .failure(let encodingError):
                            print(encodingError)
                        }
    })

A: if not work then make url with parameter like this.
 Alamofire.upload(multipartFormData:{ multipartFormData in
        multipartFormData.append(imgData, withName: "profile",fileName: fileName, mimeType: "image/jpg")},
                     usingThreshold:UInt64.init(),
                     to:uri + "?" +nickNameField.text! +"?"+ webURLField.text!+"?"+introField.text!,
                     method:.post,
                     headers:Constants.VyrlAPIConstants.getHeader(),
                     encodingCompletion: { encodingResult in
                        switch encodingResult {
                        case .success(let upload, _, _):
                            upload.responseJSON { response in
                                 print(response.result.value)
                            }
                        case .failure(let encodingError):
                            print(encodingError)
                        }
    })

A: In Swift 3 Alamofire 4
This is a demo Code for the Reference
Alamofire.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(UIImageJPEGRepresentation(self.Imgprofile.image!, 1)!, withName: "Prescription", fileName: "Profile_Image.jpeg", mimeType: "image/jpeg")
    }, to:" Your URL here ")
    { (result) in
        switch result {
        case .success(let upload, _, _):
            print(result)

            upload.uploadProgress(closure: { (progress) in
                print(progress)
            })

            upload.responseJSON { response in
                //print response.result
                print(response);
            }

        case .failure(let encodingError):
            print(encodingError);
        }
    }
}

Hope This should Work
Thanks


text:
Q: Solve to find $y(x)$ of the $\frac{1}{\sum_{n=0}^{\infty }y^n}-\sum_{n=0}^{\infty }x^n=0$ Solve the equation to find the $y$ as a function to respect $x$ without $n$ $$\frac{1}{\sum_{n=0}^{\infty }y^n}-\sum_{n=0}^{\infty }x^n=0$$

A: Assuming $|x| < 1$ and $|y| < 1$, the two geometric series simplify to:
$$\frac{1}{\frac{1}{1 - y}} = \frac{1}{1 - x}.$$
Consequently:
$$(1 - x)(1 - y) = 1.$$
Solving for $y$ in terms of $x$, you get:
$$1 - y = \frac{1}{1 - x}$$
which implies that
$$y(x) = 1 - \frac{1}{1 - x} = \frac{x}{x - 1}.$$
Note that $|y(x)| < 1$, so that $|x/(x - 1)| < 1$.  This implies that:
$$|x| < |x - 1|,$$
which further implies that
$$x^2 < (x - 1)^2 = x^2 - 2x + 1.$$
Consequently,
$$x < \frac{1}{2}.$$


text:
Q: When is a programmable logical controller the best choice? I am studying PLCs as a part of my Elements of Industrial Automation class. Trouble is, I can't imagine why would anyone use such a thing.
For complex tasks, microcontrollers are available. The vast majority of practicing programmers are well-versed in C, so creating a system with an ARM core (for example) is relative cheep. Furthermore, there are numerous free and tested RTOS for hard-realtime design to rest upon.
For massively parallelizable, hard realtime, low-latency tasks, there are FPGA-s. Those are a little harder to program. Yet there are many VHDL/Verilog guys out there in the job market.
Now to address the reliability of PLCs:

the PLC is designed for multiple inputs and output arrangements, extended temperature ranges, immunity to electrical noise, and resistance to vibration and impact

The same can IMHO be acheaved (and far surpassed) by extensive redundancy e.g. 3 identical systems operating simultaniously, upon detection of a problem in the primary system, another one, located at a different place, and programmed in a different way, kick in.
Where are PLCs used in modern industry? Why are they the best solution in those situations, instead of one of the solutions above?

A: In my world PLCs are used to control manufacturing machines.
PLCs are used instead of microcontrollers for many reasons:

*

*They are modular.  In trouble shooting a spare processor, I/O card or power supply can be swapped out.

*Technicians can get online with troubleshooting software and view/troubleshoot the running program.  This practice isn't really troubleshooting the program as much as checking to see what real world inputs are inhibiting operation.

*PLCs can communicate with other vendors hardware through common protocols such as DeviceNet, Profibus or Firewire.  This allows almost plug and play integration with drives, temperature controllers and other hardware.

*In large factory floors with multiple production machines, made by multiple vendors around the world, it becomes advantageous to standardize on common PLC hardware.

*Integration with an HMI product becomes an important factor.  You must have some touch screen application to interface your controller to a person operating it.  Again standardizing on an HMI product becomes a benefit.  Wonderware, Intellution or WinCC are some common products.

The simple answer to your question is using a PLC standardizes the platform for Operators, Technicians and Engineers.


text:
Q: How to use Mysql SELECT CASE WHEN expression I am trying to use a select case statement on mysql DB.
SELECT
t.name, t.colour,
CASE WHEN (Amount < 0) AS small,  CASE WHEN (Amount > 0) AS large FROM t

Error:
......for the right syntax to use near 'AS small, CASE (Amount > 0)
I want my output like so
Name      Colour     Small     Large
item1     red        -35
item2     blue                 48
etc.

Been trying with no luck. Help please.

A: Here it is:
SELECT
 t.name,
 t.colour,
 CASE WHEN (t.Amount < 0) THEN t.Amount END AS small,
 CASE WHEN (t.Amount > 0) THEN t.Amount END AS large
FROM t

Understanding CASE WHEN:
Example #1:
Suppose,
IF n < 0 THEN
    'N is negative'
else if n == 0 THEN 'N is Zero'
else 'N is positive'

Let's convert this if-else if chain in MySQL using CASE WHEN expression:
SET @n := -9;
SELECT
CASE WHEN @n <0 THEN 'N is Negative'
     WHEN @n =0 THEN 'N is 0'
     ELSE 'N is positive' END AS output;

Output:
    output
N is Negative

Example #2:
Now we want to convert the following three if statements in MySQL
IF n <0 THEN 'N is Negative'
IF n == 0 THEN 'N is Zero'
IF n > 0 THEN 'N is Positive'

SET @n := 5;
SELECT
    CASE WHEN @n <0 THEN 'N is Negative' END AS negativeOutput,
    CASE WHEN @n =0 THEN 'N is 0' END AS zeroOutput,
    CASE WHEN @n > 0 THEN 'N is positive' END AS positiveOutput;

Output:
Now the output has three columns:
negativeOutput     zeroOutput     positiveOutput
                                   N is positive

A: You can only alias entire expressions, not individual components of an expression:
SELECT ... (CASE WHEN 'foo'='bar' THEN 'baz' ELSE 'qux' ) AS foo
           ^--------------------------------------------^


text:
Q: Java executable jar location best practice for systemd and Jenkins CI? I have Spring Boot 2 executable jar (runs by command java -jar myapp.jar) which I need to deploy to remote linux server as systemd service. Jenkins CI will manage building this jar from source and copy to proper location and restart java service associated with myapp.jar. Linux server has just one user 'jonas' with sudo privilege, in addition to jenkins user.  Where do I need to put myapp.jar on linux server from security best practice point of view in production environment ? Possible location:
 /var/myapplications/myapp.jar
 /home/jona/myapplications/myapp.jar
 /opt//myapplications/myapp.jar

Also where the log files generated by myapp.jar are going to be located?

A: Based on my experience, I would recommend to keep all third parties and applications under /opt/{{ app_name }}
You can follow if you like following structure which makes deployment of new artefacts much easier with option to quickly rollback if needed.
/opt/{{ app_name }}/releases/{{ app_version }}
/opt/{{ app_name }}/current <- Symlink to above
/opt/{{ app_name }}/current/logs <- directory for logs which would be part of the releases/{{ app_version }}
Your deployment script can create respective folders, manage permissions and symlinks for this purpose.
What i personally like is to make sure it runs under a non-privileged user with proper permissions to ensure only that particular user can read/execute/write on the directory recursively which would include logs which might have some sensitive information that might be included as part of the exception, however this purely depends on how you log.


text:
Q: classes, returning an intact array So i've got a CRM that i'm working with and I'm programming a class to interact with it.  I've got it all written but it's having 1 issue..
The return on the last function doesn't seem to return what it's supposed to.  The code below is the class function itself, with several of the functions edited out to preserve space but many of the functions are alike.
<?php
class Limelight {
public $loginUsername = 'www.domain.com'; // your limelight API username
public $loginPassword = 'password'; // your limelight API password
public $apiDomain = 'https://www.domain.com/admin/'; // ie: https://www.mydomain.com/admin/

public $LL_Data = array();
public $postUrl = '';

     function setUrl($meth = "transact") {
    if ($meth == "transact") {
        $this->postUrl = $this->apiDomain."transact.php?username=".$this->loginUsername."&password=".$this->loginPassword;
    }
    if ($meth == "membership") {
        $this->postUrl = $this->apiDomain."membership.php?username=".$this->loginUsername."&password=".$this->loginPassword;
    }

    return $this;
}

function method ($meth = 'NewOrder') {
    $this->LL_Data['method'] = $meth;
    return $this;
}
    function postData($data) {
    $this->LL_Data .= $data;
    return $this;
}

function process() {
    $this->LL_Data['tranType'] = 'sale';
    $this->LL_Data['ipAddress'] = $_SERVER['REMOTE_ADDR'];
    $data = $this->LL_Data;
    return $data;
}
}

This is currently the code, but later it'll change as process() will have CURL added to it. And here is the utilization for it, once it's included and initialized.
$data = $this->limelight
             ->setUrl('transact')
             ->method('NewProspect')
             ->campaignId('3')
             ->postData($_POST)
             ->process();
echo "<pre>";
print_r($data);
echo "</pre>";

but, when it is supposed to echo out the array all I get out is:
9rrayArray
No clue what's going on or why it's not working how it should.  Any help appreciated.

A: You're using concatenation in postData() when you probably want to use either array_merge or a plain old assignment.


text:
Q: Google Calendar - Get events not reacting on parameters I've a script where I try to get all upcoming events from a Google Calendar.
Regarding to the API documentation, I have used "timeMin" for this, but it still gives me results in the past.
Have Google changed anything about this and if yes, what is the new way to do this?
My code is:
                $calendarId = 'primary';
                $optParams = array(
                    'maxResults' => 100,
                    'timeMin' => ''.date("Y-m-d",time()).'T00:00:00-00:00'
                );

                try{

                    $events = $service->events->listEvents('primary',$optParams);

                }catch (Exception $e) {
                    echo 'Caught exception: ',  $e->getMessage(), "\n";
                }

A: I'm unable to reproduce your issue. The timeMin parameter is being observed by the API. I don't get events that are before timeMin.


text:
Q: Getting data from XML file depending on the ItemClick of listView Hello Friends I am looking for a solution to an XML parsing below is my database sample :-
        <inneritem id="1" title="Cells" thumbnail="">
            <Seconditem id="3" title="Intro" thumbnail="" />
            <Seconditem id="4" title="Erythroc" thumbnail="" />
            <Seconditem id="5" title="Band Nerophil" thumbnail="" />
            <Seconditem id="6" title="Segmented Ntrophil" thumbnail="" />
            <Seconditem id="7" title="Eosinil" thumbnail="" />
        </inneritem>

        <inneritem id="2" title="Cells" thumbnail="">
            <Seconditem id="8" title="2Intro" thumbnail="" />
            <Seconditem id="9" title="2Erythroc" thumbnail="" />
            <Seconditem id="10" title="2Band Nerophil" thumbnail="" />
            <Seconditem id="11" title="2Segmented Ntrophil" thumbnail="" />
            <Seconditem id="12" title="2Eosinil" thumbnail="" />
        </inneritem>

Now here I had set Item with id 1 and 2 in the listview and on click on any item for example if I click on Item with id 1 it will give me id 1 and on its click I want to load data with tag Seconditem related to id 1 into new listview.So how can I accomplish that. Thanks in advance.
In Short I want to check condition of id's and then load data so how can I check these conditions. My Code for the same is :-
            try {

                InputStream is = getActivity().getAssets().open("public_material.xml");

                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

                Document doc = dBuilder.parse(is);
                doc.getDocumentElement().normalize();

                doc.getElementsByTagNameNS("id", ItemsID);
                NodeList nList = doc.getElementsByTagName("Seconditem");
                Log.d("List count :- ", "" + nList.getLength());
                for (int temp = 0; temp < nList.getLength(); temp++) {
                    Node GetEementNode = nList.item(temp);
                    if (GetEementNode.getNodeType() == Node.ELEMENT_NODE) {

                        Element eElement = (Element) GetEementNode;

                        String strID = eElement.getAttribute("id");

                        String Title = eElement.getAttribute("title");
                        //String Thumbnail = eElement.getAttribute("thumbnail");

//                      GetterSetter row = new GetterSetter(strID,Title, Thumbnail);
                        GetterSetter row = new GetterSetter(strID,Title);
                        arrList.add(row);
                    }
                }

            } catch (Exception e) {

            }

            BaseAdapterData data = new BaseAdapterData(getActivity(), arrList);

            list2NewView.setAdapter(data);

A: This is what I was looking for where public_material is my xml in which data is saved:-
try{InputStream is = getActivity().getAssets().open("public_material.xml");

                    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

                    doc = dBuilder.parse(is);
                    doc.getDocumentElement().normalize();

                    nList = doc.getElementsByTagName("inneritem");
                    for (int temp = 0; temp < nList.getLength(); temp++) {
                        Node GetEementNode = nList.item(temp);
                        if (GetEementNode.getNodeType() == Node.ELEMENT_NODE) {

                            eElement = (Element) GetEementNode;
                            String strID = eElement.getAttribute("id");

                            if(strID.equals(ItemsID)){
                                NodeList conditionList = eElement.getElementsByTagName("Seconditem");

                                for(int secondTemp = 0; secondTemp<conditionList.getLength();secondTemp++){
                                    Node getSecondNode = conditionList.item(secondTemp);
                                    if(getSecondNode.getNodeType() == Node.ELEMENT_NODE){
                                        Element SecondElement  = (Element) getSecondNode;
                                        String secondItemsDataID = SecondElement.getAttribute("id");
                                        String secondItemsData = SecondElement.getAttribute("title");
                                        GetterSetter row = new GetterSetter(secondItemsDataID,secondItemsData);
                                        arrList.add(row);

                                    }
                                }
                            }
    //                      String Title = eElement.getAttribute("title");
                            //String Thumbnail = eElement.getAttribute("thumbnail");

    //                      GetterSetter row = new GetterSetter(strID,Title, Thumbnail);
    //                      GetterSetter row = new GetterSetter(strID,Title);
    //                      arrList.add(row);
                        }
                    }

                } catch (Exception e) {

                }

A: on a click of listview get the id and compare it with the arrList.getStrId() in for loop and if matches get the data and do whatever you want....

A: Try below code:
list2NewView.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
            {
                  if(list2NewView.get(arg2).toString().equals(arrList.get(arg2).toString())
                  {
                      // do your code here
                  }
            }
        });


text:
Q: Reusable ASP.NET User Control Library : Virtual path provider or ascx/aspx copy? I have a ASP.Net web application that I want to use as a reusable user control library in other web applications.
One solution for this problem is to use what Scott Guthrie has described here:
http://weblogs.asp.net/scottgu/archive/2005/08/28/423888.aspx
that is to copy ascx/aspx files (without their code-behind) in the web applications which use the control library.
I actually see another solution: to embed the ascx/aspx in the User control library and then use a custom virtual path provider to get them.
Does anybody know which solution is the best ?
From the deployment point-of-view, the virtual path provider seems to be better.
However the 'ascx/aspx copy' solution is easier to implement (no need to create a custom virtual path provider).

A: I really do not like Scott's solution. I believe it is ungly and creates overhead that is not necessary. I have also seen something similar in action and it just didn't work for me.
I too had the same requirement as you describe and I used the virtual path provider option. This way I could reuse all my user controls between web applications easily and without work arounds.
The virtual path provider has a couple of issues though:

*

*If your ascx file has any server tags (in javascript or any other place for that matter) that cause an issue you will get a run time error that is not that helpful.

*You have to rebuild your application every time you do a change to the ascx's mark up or to Javascript that exists on the file it self in order to see the results. That can be a real pain if you are trying to change the design of an existing control.

I have used the solution as described in this article and it worked very well:
http://www.codeproject.com/KB/user-controls/EmbeddedUserControl.aspx
I hope that helps...

A: I ran into this same situation a few weeks ago and I could not make Scott's solution work.  I instead used Custom Server Controls and put those in their own Class Library.

A: I really don't think its a good idea to use user controls that way.  If you need them in a separate library, you should convert them to server controls.


text:
Q: Modify method behaviour at runtime I have a scenario where user has multiple filters in a web application and a displayed list of items. In the gui it has multiple FilterGUI that he/she can tune interacting in the browser (these are React web components).
Every specific implementation of the FilterGUI do the same: tune parameters and according to parameters create at runtime an arrow function that will filter (according to some algorithm/criteria) the dataset items.
Example:
i have data like this:
user {
    name: "bob",
    age: 25
    }

FilterGUI1 {
    createFilterFunction() {
         return (userSelectedInterval) => {
                      I filter user by age based on an interval selected by the user
                      }

    }
}

FilterGUI2 {
     createFilterFunction() {
          return (criteria1, criteria2 ...) => {
          i filter user item based on nested if else criteria
          }
     }
}

It seems to me that createFilterFunction() may be replaced by a FilterFunctionFactory
such that:
FilterGUI {
    this.filterFunctionFactory = new FilterFunctionFactory()

    makeFilter(someParams) {
        return this.filterFunctionFactory.makeFilter(someParams)
    }
}

I read also something about Strategy pattern. In particular that it allows selection of an algorithm's behaviour during runtime. Can this pattern be used somehow here to modify the filterFunction produced by the factory at runtime?
How would you do that ?
I'm not an expert on software design patterns by i would like to write this code in a much elegant way.
UPDATE
After @BartvanIngenSchenau pointing to great article on how choosing design pattern I try to reformulate the question. Possibly avoiding to make it appear less "how to combine design patterns to write code".
I have different web components all implementing FilterGUI interface. For example FilterByAgeGUI, FilterByPriceGUI ...
interface FilterGUI {
    makeFilter(someFilterCrieria) : IFilter
}

interface IFilter {
    someFilterCriteria
    filter(someFilterCriteria, datasetNode) : boolean
}

filter method should accept someCriteria provided at runtime by FilterGUI and a datasetNode, and decide based on criteria if keeping node or not.
My question is: is there a way to have a general Filter implementing IFilter interface and change it's filter method at runtime ?
Would be bad coding something like:
interface IFilter {
    filter(FilteringFunction): boolean
}

Or i need to create a specific FilterByPrice, FilterByAge class for every IFilter implementation i would like to have in my GUI?
I cited Strategy pattern because I read it can be useful to change algorithm at runtime. Can it be used to tackle this problem?
What i wouldn't like is to create dozens of FilterInSomeWay class for every GUI filtering component.
Thank you.

A: After better introspection this was easily solved with Strategy pattern.
IFilterGui {
    makeFilter(someParams) : IFilteringStrategy

Filter {
    constructor(filterStrategy : IFilteringStrategy)
    filter(node) {
         this.filterStrategy.filter(node)
    }
}

Concrete example:
TimeFilterGUI implements IFilterGUI {
    setStartTime()
    setEndTime()
    makeFilter() {
        return new FilterByTimeStrategy(this.startTime, this.endTime)
    }

}

FilterByTimeStrategy implements IFilteringStrategy {
    constructor(startTime, endTime)
    filter(node) {
        if (node.startTime >= startTime && node.endTime <= endTime) keep else discard
    }
}


text:
Q: Scala matching, resolving the same variable from two different patterns Say I have the following
case class IntWrap(value:Int)

I would like to extract the same variable from two cases as follows:
x match {
  case value:Int | IntWrap(value) => dosomethingwith(x)
  case _ => ???
}

but the only way I have been able to do this is as:
x match {
  case value:Int => dosomethingwith(x)
  case IntWrap(value) => dosomethingwith(x)
  case _ => ???
}

Is there a better way, as in my real life case dosomething is actually a large block of code which is not so easy to encapsulate.

A: If it is really the case that you want to do something with x, not with the extracted value, then the following would work:
case class IntWrap(value:Int) // extends T

def dosomethingwith(x: Any) = x

val x: Any = IntWrap(101)

x match {
  case _: Int | _: IntWrap => dosomethingwith(x)
  case _ => ???
}

If you actually want to work with the extracted value, you could factor out the corresponding match block into its own extractor and reuse that wherever necessary:
x match {
  case Unwrap(value) => dosomethingwith(value)
  case _ => ???
}

object Unwrap {
  def unapply(x: Any) = x match {
    case x: Int => Some((x))
    case IntWrap(value) => Some((value))
    case _ => None
  }
}

A: I honestly don't see an issue with the way you are doing things.  As long as dosomethingwith is a separate function then I don't see any issues with duplicate code.  If your code looked like this then I don't see any need to come up with other solutions:
def foo(x:Any){
  x match {
    case value:Int => dosomethingwith(value)
    case IntWrap(value) => dosomethingwith(value)
    case _ => ???
  }
}

def dosomethingwith(x:Int){
  //do something complicated here...
}

A: I came up with sth a little bit different, but it may help you avoid duplicates:
  case class IntWrap(value: Int)
  implicit def intWrapToInt(intWrap: IntWrap) = intWrap.value

  def matchInt(x: AnyVal) = x match {
    case i: Int => println("int or intWrap")
    case _ => println("other")
  }

  //test
  matchInt(IntWrap(12))          //prints int or intWrap
  matchInt(12)                   //prints int or intWrap
  matchInt("abc")                //prints other

It won't work for every reference, though. So, be careful.


text:
Q: Access MS SQL server from CentOS (OpenOffice calc) I installed FreeTDS in CentOS 6 and I can connect from php to remote MS SQL server. However I cannot set up odbc connection so that it shows in list of ODBC connections in OpenOffice apps.
If my server is called [10.0.0.11\myinstance] in freetds.conf what should I put in odbcinst.ini, and what in odbc.ini in order to be able to see this connection availabe for use in OpenOffice Base and Calc?

A: *

*In odbcinst.ini add
[FREETDS]
Description     = v0.91 with protocol v7.2
Driver          = /usr/lib/libtdsodbc.so

*In ~/.odbc.ini add:
[MSSQLTestServer]
Driver  = FreeTDS
Description     = MSSQL DB
Trace   = No
Server      = 10.0.0.11\myinstance
Database        = MyDataBaseName

Now I have MSSQLTestServer listed as an available source and can use it in OO.


text:
Q: What is the difference between Test Case and Tested By link types in TFS If I open a User Story in VS and go to the All Links Tab I can add a new lint where the Work Item Type is test Case and I have a choice of Link Types.
However, if I go to the Test Cases tab, I can add a link to a Test Case but only with the Link Type of Tested By.
Can anyone explain to a relative TFS newbie what the difference is when adding a link on each of the 2 tabs and perhaps what the various Link Types are supposed to represent?

A: Found this article on StackOverflow. Guess I should have tried there first. https://stackoverflow.com/questions/2627629/work-item-link-types-in-visual-studio-tfs-2010


text:
Q: XIB Displaying SubComponent I created a custom view, which has one button and one text field , as given below
@interface CommUICustomSignInView : CommUICustomView {

 IBOutlet NSButton *pBtn;
 IBOutlet NSTextField *pTextField;
 NSTrackingArea *pTrackingArea;
 NSCursor *pPonitHandCursor;
}
@property (nonatomic,retain)IBOutlet NSButton *pBtn;
@property (nonatomic,retain)IBOutlet NSTextField *pTextField;

All items are linked properly, with the view,
In Another window controller XIB, i have added one tab view, in one of the tab item view, i am going to add this view,
added one tab view and assigning this view as below,
NSTabViewItem *pTabViewItem = [pTabView tabViewItemAtIndex:0];

if(pOfflineCTlist == nil){
  pOfflineCTlist = [[CommUIOfflineCTlist alloc]
                initWithNibName:@"CommUIOfflineViewController" bundle:nil];
}

[pTabViewItem setView : [pOfflineCTlist view]];

[pTabView selectTabViewItemAtIndex:0];

Now with that, i could able to track the mouse event in customSignInview, in nstrackregion,
but i couldn't see the other controls, sign-in button and text field,
Am i doing something wrong,

A: Finally i found following way to do this,
1 -- Created a Resource like Button / text field in the Main view,
2 -- Put them over the custom view,
3 -- Link them with the custom view,
now i could able to see it,
Is there any other approach then please suggest me,


text:
Q: Do we have to avoid the verb 'get' in formal writing? I just saw someone's comment (probably a native BrE) on Facebook, she wrote that the verb get should be avoided and she also told said that she had a professor that was always crossing out papers when he saw get/got and suggested substituting that verb with another synonym which is more preferable.
I was also looking for information related to this, here. The site I gave tells that the verb get is very common in informal speaking and writing. I have also read some examples in some dictionaries with the keyword get and I could sense the sentences are all rather informal.
I just want to confirm it here whether I should avoid the verb get in formal writing such as articles, thesis, etc. or is it just somebody being overly fussed about it. If it turns out to be allowable in formal condition, could you give a counterexample to disprove this?
To add a specific matter, I took this sentence from OALD and I want to know whether it could be more formal:

95 per cent of the UK can now get superfast broadband.

A: Yes, the example sentence you provide could be more formal and more specific (replacing "get" with "access" or "obtain" or "purchase" depending on which meaning is appropriate).
The answer to your question is, to some degree, a matter of style and opinion. "Get" is generally informal, but an absolute prohibition on the word "get" is extreme. For an example of use in a formal setting, here is a quote from a U.S. Supreme Court case (Rucho v. Common Cause): "Free and fair and periodic elections are key to that vision. The people get to choose their representatives."
Despite that example, it probably is a good idea to avoid "get" in formal writing. Beginning (and even experienced) writers often use informal, vague verbs instead of more specific and appropriate choices, and the professor's prohibition on "get" is likely designed to encourage students to think more carefully about their writing. In most cases, "get" can easily be replaced with a more formal option.


text:
Q: slow webview with android instant apps I have an instant game that uses WebView.
If I build apk and run it as a normal Android application, the rendering on the view works very quickly on all versions of Android.
I upload this game to Google Play as an Instant App, and try to launch it via Try Now button.
In this case, rendering will lag very much, and the problem is only on devices with 5-7.x android versions, for 8+ everything is fine.
Logs show that on these devices Canvas Renderer is used instead of WebGl Renderer.
However, the usual launch of the game (not from Try now) on all devices uses WebGL.
I started the game on Android 5.0 with android:hardwareAccelerated=true setting, and the application did not slow down using the Canvas Renderer.
So, even old devices without WebGl rendering has an acceptable speed.
Then I launched the game on 8+ devices with the android:hardwareAccelerated=false
First, the device began using Canvas renderer instead of WebGl.
Secondly, the rendering has become clearly slow down.
Proceeding from all this, I am almost sure that the problem is only in configuring hardwareAccelerated setting.
In this case, the question arises. Why the Instant version of the game disable the hardwareAccelerated setting, and
does it only for 5-7.x devices? Are there any other reasons that WebView has slow rendering speed only in the Instant version and only
for 5-7.x devices?


text:
Q: java Generic wildcard "?" I referred to documentation on Java Generics, and trying to use the wildcard "?" in a simple program:
class Unknown <?> {

}

public class UnknownTypes {

    public static void main(String s[] ) {

    }
}

Wildcard "?" refers to an Unknown type, so in class Unknown, I used type-parameter wildcard itself; however when I compile I get compilation error. If I had used like this it would have worked.
class Unknown <T> {

}

If wildcard "?" refers to unknown type, why can't we use "?" as type parameter.
The following is the compile error that I get.
UnknownTypes.java:1: error: <identifier> expected
class Unknown <?> {
           ^
UnknownTypes.java:1: error: '{' expected
class Unknown <?> {
            ^
UnknownTypes.java:10: error: reached end of file while parsing
}

Is wildcard "?" used in conjunction with something else?

A: You can't name a generic parameter as ?, because ? is not a valid identifier - a valid name of a variable. You have to give a generic parameter a valid java name so you can refer to it in the implementation.
You can only specify ? as a generic bound:
List<?> list; // a variable holding a reference to a list of unknown type

You can't use ? when creating an instance:
new ArrayList<?>(); // can't do this

or as a parameter name of a class :
class MyClass<?> { // can't do this

A: To define a generic class with a type parameter, you cannot use a wildcard (in the generic class it is a type)
class Unknown <TYPE> {
  TYPE foo; // <-- specifies the type of foo.
}

When using it, you can use the wildcard
Unknown<?> some = new Unknown<String>(); // <-- some is any kind of Unknown.

A: You only use the wildcard when referring to an instance of a class. Not in the class declaration.
class Unknown<T>{}

Unknown<?> instance= new Unknown<Integer>();

public void canHandleAnyUnknown(Unknown<?> wild){
}

A: Wildcard means 'anything' not unknown. You can use only Alphabets as type parameter.


text:
Q: When toggling a javascript hide and show, open.png will change to close.png I have a working toggle spoiler - thanks for adrian for the code.
It closes instantly when opening another spoiler.
I added a plus image on the right, and i want the plus change into minus a image once opened and then change back to plus once closed or switched spoiler.
This is what I have currently:
http://justxp.plutohost.net/slyfiles/index.html
How do i make the plus image turn into a minus image on spoiler toggle and change back on spoiler toggle close?
My codes:

Networks

We have a very security system, including secure logging in, management, balance management and more.
We do a SQL backup every hour to protect us from our data being lost.

Payment Avarge

We have a very security system, including secure logging in, management, balance management and more.
We do a SQL backup every hour to protect us from our data being lost.

Control Panel - SlyPanel

We have a very security system, including secure logging in, management, balance management and more.
We do a SQL backup every hour to protect us from our data being lost.

Security

We have a very security system, including secure logging in, management, balance management and more.
We do a SQL backup every hour to protect us from our data being lost.

JS:

CSS
.featurelist_2-text-margin{
    margin-top: 10px;
    position: absolute;
    margin-left: 20px;
    text-align: left;
    color: #259acb;
}

.spoiler {
        font-size: 16px;
    background-color: #c0e6d2;
    border: 1px solid #a7c8b7;
    height: 45px;
    width: 530px;
        text-shadow: 0px 1px 0px #f4f4f4;
        filter: dropshadow(color=#fff, offx=0, offy=1);
                margin-top: 3px;
                cursor: pointer;
                    min-width: 511px;
                        position: relative;
}

.hide{
    font-size: 15px;
    background-color: #dedede;
    border: 1px solid #c1c1c1;
    width: 530px;
    height: auto;
    color: #262626;
        text-shadow: 0px 1px 0px #f4f4f4;
        filter: dropshadow(color=#fff, offx=0, offy=1);
                margin-top: 3px;
    display: none;
}

#plus {
float: right;
margin-top: 17px;
margin-right: 10px;
}

Hide1,2,3,4 are empty.
Live preview: http://justxp.plutohost.net/slyfiles/index.html
Thanks!

A: Try this..
$('.spoiler').click(function() {
    var hiddenid = $(this).data('hidden');
    $('#' + hiddenid).slideToggle();
    $('.hide:not(#' + hiddenid + ')').slideUp();

    var $img = $(this).find('img');
    if( $img.attr('src').indexOf('plus') > -1){

       $img.attr('src', 'http://cdn4.iconfinder.com/data/icons/iconic/raster/12/minus.png')
    }
    else{
       $img.attr('src', 'http://cdn4.iconfinder.com/data/icons/iconic/raster/12/plus.png')
    }

});

I am assuming the src of the images to end with plus.png and minus.png


text:
Q: table relationship and how to use it in laravel controller so, I have 2 tables, stage and event. Stage hasMany event, and Event belongsTo Stage. And I want to show all stage and its event as json. Here is my code in controller:
public function getschedule(){
    $schedule = Stage::all();

    //$event = Event_schedule2020::all();
    if (!$schedule) {
      return response()->json(['msg'=>'Error not found','code'=>'404']);
    }

    foreach($schedule->events as $array){

        $datax[] = [
          'id'=>$array->id,
          'time'=>$array->time,
          'category'=>$array->category,
          'type'=>$array->title,
          'designer'=>$array->designer,
        ];
      }

      foreach ($schedule as $item) {
        $jadwal[] = [

          'id'=>$item->id,
          'date'=>$item->date,
          'place'=>$item->stage,
          'data'=>$datax,

        ];
      }

   return response()->json($jadwal);
  }

but I always get this error
the error
so, is there anything I can do about this?

A: You can utilize inbuilt functions to do what you want to. Laravel automatically transforms model into JSON, no need to built arrays with it.
public function getschedule() {
    // tell laravel you want to eager load events
    $stages = Stage::with('events')->get();

    // laravel knows you loaded events and therefor you can just return it and it does the rest automatically
    return response()->json($stages);
}

A: in your Stage model you have to create relationship like this
public function events()
{
    return $this->hasMany('App\Event');
}

then in your Controller
public function getschedule(){

   $schedules = Stage::with('events')->get()->toArray();

   return response()->json($schedules );
}

A: your mistake is call events on a collection for solve this you can change foreach like followings :
public function getschedule(){
  $schedules = Stage::all(); // I add a 's' to $schedule because is better set plural name;

  if (!$schedule) {
    return response()->json(['msg'=>'Error not found','code'=>'404']);
  }

  foreach($schedules as $schedule){

    $datax = [];
    foreach($schedule->events as $event){
        $datax[] = [
          'id'=>$event->id,
          'time'=>$event->time,
          'category'=>$event->category,
          'type'=>$event->title,
          'designer'=>$event->designer,
        ];
     }

     $jadwal[] = [
        'id'=>$item->id,
        'date'=>$item->date,
        'place'=>$item->stage,
        'data'=>$datax,
      ];
  }

  return response()->json($jadwal);
}

but above solution is not recommended because send many request to server in any foreach loop, following solution is better:
    public function getschedule(){
      $schedules = Stage::with('events')->get(); // only this difference with above soloution and the rest is the same
  if (!$schedule) {
    return response()->json(['msg'=>'Error not found','code'=>'404']);
  }

  foreach($schedules as $schedule){

    $datax = [];
    foreach($schedule->events as $event){
        $datax[] = [
          'id'=>$event->id,
          'time'=>$event->time,
          'category'=>$event->category,
          'type'=>$event->title,
          'designer'=>$event->designer,
        ];
     }

     $jadwal[] = [
        'id'=>$item->id,
        'date'=>$item->date,
        'place'=>$item->stage,
        'data'=>$datax,
      ];
  }

  return response()->json($jadwal);
}


text:
Q: Derivative of noised function
Given a noisy smooth enough function, $f(x)=sin(x)$ find the derivative using the sliding derivative technique.

In the sliding derivative technique, we are performing the following steps:
The neighborhood of point $i$ in domain is characterized by the half-window length hw, thus for the i-point in the domain we are considering $[i-hw:i+hw]$ window
In this window the closest approximating line has to be found and the coefficient of it has to be determined which would be an approximation of the derivative.
I followed the above steps and applied regression to get the best line fit on the plotted points in the given window and then finding its coefficient.
But in this case the slope is remaining same for the given window. I tried it with multiple $hw$ values for the window.
Can you please let me know the correct approach for the same?


text:
Q: how to match the exact value contained in one string to the other string I have two database tables .first table contains 'Destination' column which has destination phone numbers and second table contains 'Areacode' which has the areacodes.
Suppose : Destination number='001891191080'
          Areacode :001,0018,00185 etc
Now the problem is this that the destination number is matching 001 Areacode instead of 0018..
 for (int i = 10; i >= 0; i--) {
        try {
            String ss = destination.substring(0, i);
            Statement st = null;
            ResultSet rs = null;

            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/asteriskcdrdb", "root", "techsoft");
            st = con.createStatement();
            rs = st.executeQuery("Select * from sp1 where areacode like '" + ss + "'");
            while (rs.next()) {
                areacode = rs.getString("AreaCode");

Here Sir as per my need i am taking the destination value and checking with for loop starting from the last .but as soon as it matches the first value it skips and doesnot check other and exact possibility...
How to match the exact values out of so many possibilities ...
Any help will be highly appreciated..
Thanx in advance

A: Destination number='001891191080' Areacode :001,0018

By using String#subString(begin index,End index) you can make short string and try to match both .
you should not create connection and statement` in a for loop.

A: First sort the 'Areacode' based on length of string (more to less), then check for the match in 'destination number'.

A: Start from the big string match first e.g.
   String destNumber = "001891191080";
   String[] areaCodes = new String[]{ "001","0018"};

   if(destNumber.indexOf(areaCodes[1])>=0){   //<- use 0018 first
     //....
   }else if(destNumber.indexOf(areaCodes[0])>=0){
     //...
   }

A: Can you try using this query?
"Select * from sp1 where areacode like '" + ss + "%' order by areacode desc"

So that should give you
00185
0018
001

in the resultset and the comparison would return you the first value from the list.


text:
Q: Sessions over multiple rows I have a table that has start_time, end_time (both timestamp) for an ID. The sessions can be contiguous and appear over multiple rows but each session can be belong to 2 additional columns. I am trying to find the session length for a single day, for a given set of columns.
Input Table:
ID   Start                   End          Website  Webpage
U1  11/02/17 10:27:14   11/02/17 10:27:20     W1    P1
U1  11/02/17 10:27:40   11/02/17 10:27:51     W1    P1
U2  11/02/17 10:27:20   11/02/17 10:27:38     W2    P2
U2  11/02/17 10:41:20   11/02/17 10:41:50     W3    P3
U3  11/02/17 10:27:20   11/02/17 10:27:51     W2    P2
U1  11/04/17 9:27:30    11/04/17 9:28:30      W1    P1

How to get the below Desired output?
ID    Website  Webpage     time_diff   start_time
U1    W1         P1         17         11/02/17
U2    W2         P2         18         11/02/17
U2    W3         P3         30         11/02/17
U3    W2         P2         31         11/02/17
U1    W1         P1         60         11/04/17

A: Forgot to post the answer for this.
This query worked. Thanks all for the help.
SELECT ID, Website, Webpage, SUM(DATEDIFF(second,start,end))
AS time_diff, DATE(Start) as start_time
from web_sessions_table
GROUP BY
start_time, ID,
Webpage,
Website


text:
Q: Android Studio console not showing logs of application running I am running application on real android device. I want to view logs in console to figure out errors and APIs responses. But I don't know sometimes it stop showing logs in console.
Here is the screenshot of my console.

I is not showing anything after this even though I am printing in logcat.
Can anyone tell me what is the issue and how to resolve.

A: Try restarting your logcat and then rerun you application. ( If your logcat window tab does not show up in Android Studio you can follow this: Logcat tab missing from debug window in Android Studio )

A: You can simply follow my steps down below.
Step - 1
Goto File --> Invalidate Caches

Step - 2
Click to "Invalidate and Restart"

I hope this might solve your problem.
Thank you and Happy coding.


text:
Q: List from IEnumerable I have a 3rd party library I am working with and have no access to change it. It has a property on one of its components that only accepts a ThirdPartyList<T>(IList<T> items), but at the point I am about to set the property I have only an IEnumerable.
I can figure out what the type is going to be in my IEnumerable by looking at the first item and figuring it out with reflection and all the items in the IEnumerable will be of the same type, but the question is how do I turn that type into a new ThirdPartyList<what do I put here>().
Thanks
CD

A: Your element type , for example
IEnumerable<Product> products = GetProductList(); //Your code

ThirdPartyList<Product> customList = new ThirdPartyList<Product>(products);


text:
Q: Is it possible to configurate gerrit to always send the push requests to refs/for? my team is implementing gerrit on their git repositories.
We liked the way it works.
As far as I understand (please, correct me if I am wrong) once gerrit is implemented it is kind of optional. If you use refs/for at the time you push, your push is sent to gerrit for review. But if you do not use refs/for it automatically pushes the code.
My question:

*

*Is there a way to not give the user the opportunity to push directly? I want every push to be sent to revision because sometimes the user can get to forget to add refs/for to his/her push request.

A: It's optional but a person need to have a "special" permission to be able to push straight to the branch (bypassing Gerrit review). Have this permission is not the default for the most people in the most of Gerrit servers. Normally only Configuration Managers or Administrators have this permission:
Reference refs/heads/* Push

If someone who doesn't have this permission pushes straight to the branch the push will fail with "Prohibited by Gerrit" error (See here for more details).


text:
Q: Continue code execution after starting powershell proces I want to do the following within an XUnit test:

*

*run a PS script to start a site on IIS

*return to the test class and execute a set of Selenium tests against the site

I can start the site easily enough via PS, but the process is blocking - if I close the PS window, the XUnit test continues, but IIS has obviously stopped so the test fails.
How do I start the IIS process and have the test continue? My PS script is below.
$iisExpressExe = '"c:\Program Files\IIS Express\iisexpress.exe"'
$path = "..\..\..\.vs\config\applicationhost.config"
$site = "SITE NAME"
$apppool = "Clr4IntegratedAppPool"
$params = "/config:$path /site:$site"
get-process | where { $_.ProcessName -like "IISExpress" } | stop-process
$command = "$iisExpressExe $params"
cmd /c start cmd /k "$command"

And the calling C#:
    string script = File.ReadAllText("Boot.ps1");
    PowerShell shell = PowerShell.Create();

    shell.AddScript(script);
    shell.BeginInvoke();

    Thread.Sleep(2000);

    _driver = new ChromeDriver
    {
        Url = "http://localhost:56565/umbraco"
    };

    // do tests here

    _driver.Dispose();
    shell.Stop();

This runs, but doesn't dispose the shell...

A: Create new thread and run ps script from that thread. Then wait several seconds with Thread.Sleep() method in main thread to let iis start site and start selenium tests.
Alternative way to solve problem BeginInvoke() async method, if you are familiar with async methods.


text:
Q: How can I solve 401 error on image render? I'm getting a 401 error when I want to show an image.
I'm using an API that returns data related to images (description, size, etc.). Previously I use an API that gives me a token which I use in the search API to get all the images data.
Everything works ok, but when I want to show the img in my view, I get 401 error.
I understand that this happens because the URL of the image refers to another site (which has a login)
What can I do? I'm working on asp.net core 5 with mvc pattern.


text:
Q: codeigniter pagination customizing I am browsing trough the CI documentation particularly http://codeigniter.com/user_guide/libraries/pagination.html .
First thing that was stuck in my mind was "CodeIgniter's Pagination class is very easy to use, and it is 100% customizable, either dynamically or via stored preferences." but there always but something.
My pagination is as following Previous 1 2 3 4 ... n Next now for each of these I can create opening html tags and closing html tags in my controller.
For ex:
Previous
$config['prev_tag_open'] = '
';

The opening tag for the "previous" link.
$config['prev_tag_close'] = '
';

Next
$config['next_tag_open'] = '
';

The opening tag for the "next" link.
$config['next_tag_close'] = '
';

And for Last first etc. Now in my design I made Previous float left Next float right and I have a
 which holds all page numbers together in the middle.
From what I see in the documentation I don't have a option in CI to put all page numbers in between html tags, I only have option to put each page number inside some tags, maybe there is a way but I missed a point. Anybody can help?
Thank you

A: The trick is, that you have to think out of the box.
You should add a an opening tag to the end of of your "prev_tag_close"
$config['prev_tag_open'] = '
';

The opening tag for the "previous" link.
$config['prev_tag_close'] = '
**<opening tag>**';

and a closing tag at your "next_tag_open" like
$config['next_tag_open'] = '**</opening tag>**
';

The opening tag for the "next" link.
$config['next_tag_close'] = '
';

that should do the trick.

A: That hardly resolves the problem, how would you deal with this situation on the first and last page? The next_tag_open/close would not appear on the final page of the pagination and the prev_tag_open/close would not appear on the first page of pagination.
This will obviously cause both of the block elements for these pages to break
Ok so I had this same problem earlier today and it was really doing my head in. The only solution I came up with (works prefectly) is this;
Create a div around the output -

    <?php echo $link; ?>

Then use the pagination tags provided by the class around use these tags to wrap around the digit tags (num_tag_open/close).
$config['full_tag_open'] = '
';
    $config['full_tag_close'] = '
';
    $config['num_tag_open'] = '
;
    $config['num_tag_close'] = '
';

Now jump into css and relatively position the outer block element pagination2, then go and absolutely position the inner block class pagination, center it and then you can use a negative value to push the absolutely positioned nextlink or prevlink elements however you wish. See below for css I used.
 .pagination2{
  position: relative;
  right: -10px;
  height: 45px;
  width: 500px;
  background-color:#f8f8f8;
  border: 1px solid #d3d3d3;
  outline:none;
  }

  .pagination{
  position: absolute;
  left: 180px;
  height: 35px;
  width: 120px;
  }

  .pagination-button-previous{
    position: absolute;
    top: 10px;
    left: -160px;
    width: 74px;
    height: 24px;