text:
Q: Reverse the order of $ \int_{0}^{a}\int_{(a^2 - x^2)/2a}^{\sqrt{a^2 - x^2}}f(x, y)dydx $
Reverse the order of integration of
$$ \int_{0}^{a}\int_{(a^2 - x^2)/2a}^{\sqrt{a^2 - x^2}}f(x, y)dydx  $$

The usual method to reverse the order of integration is to sketch the region of integration first. But in this case the region of integration is defined by parametric equations, therefore the region of integration depends on the value of $a$. So I don't really know how to proceed here. I even checked Thomas Calculus for some example of double integrals like this, but there isn't any.

A: The integration domain $D$ is the region sited in first quadrant between the circle $x^2+y^2=a^2$ and the parabola $y=\frac{a^2-x^2}{2a}$:
$$ D=\left\{(x,y)\,\,|\,\,\frac{a^2-x^2}{2a}<y<\sqrt{a^2-x^2}\,\,,\,\,0<x<a\right\}$$ If you want reverse the order, that is, variable $x$ between "functions" and variable $y$ between constants, you must split the domain in two parts $D=D_1\cup D_2$ (as in picture)

with
$$ D_2=\left\{(x,y)\,\,|\,\,\sqrt{a^2-2ay}<x<\sqrt{a^2-y^2}\,\,,\,\,0<y<a/2\right\}$$
$$ D_1=\left\{(x,y)\,\,|\,\,0<x<\sqrt{a^2-y^2}\,\,,\,\,a/2<y<a\right\}$$
and then
$$\int_0^{a/2}\int_{\sqrt{a^2-2ay}}^{\sqrt{a^2-y^2}}f(x,y)dx\,dy+\int_{a/2}^a\int_{0}^{\sqrt{a^2-y^2}}f(x,y)dx\,dy$$


text:
Q: Browser Back button does not fire componentDidMount() React life cycle method I have react with redux app the gets a list of order items from Rest API and put on array filled with redux. There is a link in the same list that navigates to the details of an order. When navigating to the details and press the browser back button in order to load the list again I got the following error.

TypeError: fetchedOrders.map is not a function

this is the code inside orders list container
    componentDidMount() {
        this.props.handleFetchOrders(1);
    }

render() {

  { fetchedOrders && fetchedOrders.map(order => {
            return (
              <OrdersWE
                order={order}
                onDelete={onDelete}
                history = {this.props.history}
                key={order.OrderHID}
              />
            );
          })}

}

const mapDispatchToProps = dispatch => {
  return {
    handleFetchOrders: (pageNumber) => {
      dispatch(fetchOrders(pageNumber));
    }
  };
};

A: You missed the return statement from render function, also you have to return a single ReactElement:
class App extends React.Component {
  ...
  render() {
    return (
      <>
        {fetchedOrders &&
          fetchedOrders.map(order => {
            return (
              <OrdersWE
                order={order}
                onDelete={onDelete}
                history={this.props.history}
                key={order.OrderHID}
              />
            );
          })}
      </>
    );
  }
}

Moreover, try to log fetchedOrders, according to the error it may be not an array object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get the price from AdMob in Unity AIP? I am trying to pull in the price for In App Purchases (IAP) using Unity Ads and  AdMob.
public void InitializePurchasing()
{
    // If we have already connected to Purchasing ...
    if (IsInitialized())
    {
        // ... we are done here.
        return;
    }
    var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());

    builder.AddProduct(PRODUCT_REMOVE_ADS, ProductType.NonConsumable);

    UnityPurchasing.Initialize(this, builder);

    removeAdsPriceText.text = m_StoreController.products.WithID("removeads").metadata.localizedPrice.ToString(); // This should be the code to get the price
}

Price in the Editor when I hit play:

This is the price when I build the app to Google Play and run the app.

It is suppose to be $1.99.

Am I missing a step?

A: I finally figured out the solution
The code needs to be called OnInitialized
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
    m_StoreController = controller;
    m_StoreExtensionProvider = extensions;

    removeAdsPriceText.text = m_StoreController.products.WithID("removeads").metadata.localizedPriceString;
}

Thanks everyone for the help!


text:
Q: Ubuntu connects to wireless but doesn't work! I just installed Ubuntu 14.04 LTS on my laptop, it connects to my wireless network and shows that it is connected, but when I try to load a webpage or do anything like download Steam for Dota 2, it doesn't work. When I try to connect my Facebook account to Ubuntu, it doesn't work. I want to be able to use Ubuntu with working Internet access. What do I do?.
ifconfig

this shows up

eth0      Link encap:Ethernet  HWaddr 88:ae:1d:60:56:eb
          inet addr:192.168.1.13  Bcast:192.168.1.255  Mask:255.255.255.0
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:16

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:24 errors:0 dropped:0 overruns:0 frame:0
          TX packets:24 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1856 (1.8 KB)  TX bytes:1856 (1.8 KB)

When I type
ping askubuntu.com

this shows up
ping: unknown host askubuntu.com


text:
Q: Run a nested vscode launch.json from a git submodule I have two projects as submodules in my main project and each submodule has its own launch.json with environment variables. I'd like to maintain this as others on the team are working separately on these projects.
Using the following launch.json in the root will let me launch one of the submodules but without the environment variables of the nested launch.json
{
  "name": "Test",
  "type": "node",
  "request": "launch",
  "cwd": "${workspaceRoot}/unit-api",
  "runtimeExecutable": "npm",
  "runtimeArgs": ["run-script", "debug"],
  "port": 9229
},

How can i launch, merge or reference the nested launch.json without directly altering the submodule? Should i move the environment variables elsewhere?

A: After intense google-fu, I found some git conversation that pointed me to use .env files. I have moved my submodule environment variables to a .env file and I load this using the "envFile" parameter in the root launch.json.
This allows me to run a custom launch configuration with submodule env vars.
[Edit] Which, btw, shouldn't be stored in a git repo any way I just remember :|


text:
Q: Example of convex function with empty subdifferential at some point Let $X$ be a normed space and $C$ an open convex subset of $X$. Let $f: C \to \mathbb R$ be convex. If $f$ is continuous at some point in $C$, then $f$ has non-empty subdifferential at all points in $C$. If $X$ is finite-dimensional, then $f$ is continuous.

Could you provide an example of a convex function $f$ that has empty subdifferential at some point?

A: Here is a counterexample for which $f$ has some "problems", since it is defined on an incomplete space.
We take $X = \ell^1$, but we equip it with the norm from $\ell^2$, i.e.,
$$
\|x\|_X := \left( \sum_{n=1}^\infty x_n^2 \right)^{1/2}.$$
Now, we define $f(x) := \| x \|_{\ell^1} = \sum_{n=1}^\infty |x_n| \in \mathbb R$ for all $x \in X$.
Then, $f \colon X \to \mathbb R$ has the following properties:
convex (clear), lower semicontinuous (using, e.g., Fatou's lemma)
but
discontinuous everywhere (rather straightforward).
Moreover, one can show (recall that $X^*$ can be identified with $\ell^2$)
$$
\partial f(x) =
\{ y \in \ell^2 \mid y_n \in \partial |\cdot|(x_n) \;\forall n \in \mathbb N\}
$$
and this, in particular, yields
$$
\partial f(x) \ne \emptyset
$$
if and only if $x \in c_c$ (subspace of finite sequences).

A: I formalize @daw's comment as below.

Let $f:X \to \mathbb R$ be a discontinuous linear functional. We will prove that $\partial f (a) = \emptyset$ for all $a \in X$. Assume the contrary that $x^* \in \partial f (a)$ for some $a \in X$. Then
$$
f(x)-f(a) =\langle f, x-a \rangle \ge \langle x^*, x-a \rangle \quad \forall x \in X.
$$
It follows that $x^* \le f$. We define $g:X \to \mathbb R$ by $g(x) :=f(x)-f(0)$. Then $g$ is linear. By this result, $g=x^*$. Hence $g$ and thus $f$ are continuous. This is a contradiction.


text:
Q: How to minimize $f(x,y,z)$ on a closed subset of $\mathbb{R}^3$? Consider the minimization of $$f(x,y,z) = (x-\frac{y}{2})^2 + \frac{3}{4}(y-2)^2 +z^2 -3$$ on the set $$\{(x,y,z)\in\mathbb{R}^3|x^2+y^2\leq1\}$$
I'm trying to use the first and second order necessary conditions ($\nabla f \cdot v \geq 0$ and $v^T\nabla^2f v\geq 0$ for feasible $v$) to identify minimum points.
I think I've narrowed down the set of feasible $v$ to $v=\begin{bmatrix}u\\v\\w\end{bmatrix}$ such that $xu+yv <0$.
And I was able to show that $\nabla^2f(x,y,z)$ is positive definite (determinant of all leading minors are strictly positive).
However, I can't figure out how to generate a system of equations to actually identify any "critical" points.
Any suggestions would be appreciated. Thank you!

A: We need to look at first at the "interior points" s.t. $x^2+y^2<1$ by the condition $\nabla f=0$.
I've found no critical interior points.
Then we need to check the points $x^2+y^2=1$ using directly that condition.
That should lead to the minimization of $g(x,y)=xy+\frac32 y$ under the given condition.


text:
Q: How to center one div and have another div float to the right of it? Tried searching for this and I couldn't find an answer.
I have a container set at 728px with two divs inside of it, and both divs are set to width: auto;. I would like to center one of those divs, and have the other float on the right like in this example.
The closest I've gotten is using text-align: center; for the main container, display: inline-block; for the center div, and float: right for the right div, but I ended up with this result instead.
Any ideas?

A: Make the floating one absolutely positioned and tweak its position accordingly.


text:
Q: c++ how do i get the current console conhost process i have searched on so many websites after "how i get the conhost process", and  nothing is really what i'm looking for.
i have searched on.

*

*superuser/stackoverflow when-is-conhost-exe-actually-necessary

*stackoverflow how-can-a-win32-process-get-the-pid-of-its-parent

*stackoverflow c-how-to-fetch-parent-process-id

*stackoverflow c-how-to-determine-if-a-windows-process-is-running

*stackoverflow get-full-running-process-list-visual-c

*stackoverflow ms-c-get-pid-of-current-process

*stackoverflow get-list-of-dlls-loaded-in-current-process-with-their-reference-counts

*codeproject Get-Parent-Process-PID

*cplusplus Getting list of running processes

*msdn.microsoft GetModuleFileNameEx

*msdn.microsoft GetModuleFileName

*msdn.microsoft GetCurrentProcessId

*msdn.microsoft GetProcessId

*msdn.microsoft GetModuleHandle

*msdn.microsoft GetConsoleWindow

*msdn.microsoft Tool Help

*msdn.microsoft CreateToolhelp32Snapshot

*msdn.microsoft NextModule32

*msdn.microsoft DebugActiveProcess

*msdn.microsoft Enumerating All Modules For a Process
and i can't find anything about "how to get the conhost process".
i have some code that works for the current "cmd.exe / program.exe" and that gives me the "PID, NAME, PATH, READ/WRITE ADDRESS".
i can get the parent process but that is not conhost.exe.
code "need to link library 'psapi' first":
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <psapi.h>
#include <iostream>
#include <tlhelp32.h>

int PrintModules(DWORD processID) {
    HMODULE hMods[1024];
    HANDLE hProcess;
    DWORD cbNeeded;
    unsigned int i;

    printf( "\nProcess ID: %u\n", processID);

    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
    if(NULL == hProcess) return 1;

    if(EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
        for(i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
            TCHAR szModName[MAX_PATH];

            if(GetModuleFileNameEx(hProcess, hMods[i], szModName,sizeof(szModName) / sizeof(TCHAR))) {
                _tprintf( TEXT("  %s (0x%08X)\n"), szModName, hMods[i]);
            }
        }
    }

    CloseHandle(hProcess);

    return 0;
}

int main(void) {
    DWORD cpid = GetCurrentProcessId();
    PrintModules(cpid);

    int ppid = -1;
    HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 pe = { 0 };
    pe.dwSize = sizeof(PROCESSENTRY32);
    if(Process32First(h, &pe)) {
        do {
            if(pe.th32ProcessID == cpid) {
                printf("PID: %i; PPID: %i\n", cpid, pe.th32ParentProcessID);
                ppid = pe.th32ParentProcessID;
            }
        } while(Process32Next(h, &pe));
    }
    PrintModules(ppid);
    CloseHandle(h);
    std::cin.get();
    return 0;
}

and i can't figure out a way to get the current conhost process.
when you open a program that uses the console, a conhost.exe process is created.
and my question is how do i get that conhost.exe process...
Thanks! :)

A: One method that comes to mind is to obtain the start time of the CMD.EXE process. Then iterate through all of the CONHOST processes looking for the same (or very close) start time.
As a proof of concept download and install Process Explorer. Find your CMD.EXE process in ProcExp, then look at Properties, Image tab. Note the start time. Then look through each CONHOST process looking for one that starts at the same time.
Note that ProcExp displays 1 second resolution, but whatever underlying API ProcExp uses probably has better resolution.
You may need to google some to get an idea what API(s) ProcExp uses to gather the process start time. Additionally there are a variety of tools you can use to see what APIs an executable (ProcExp in this case) import. You may be able to deduce from the API names that ProcExp imports which one(s) would provide a process' start time.

A: In case you still need it (after reading the comments), here's a piece of code that gets the conhost.exe processes. Please note that I only wrote it for demonstrative purposes (to check whether [MSDN]: Tool Help Functions can be used for this scenario), so don't mind its structure or other coding NO-NOs.
code.c:
#include <Windows.h>
#include <TlHelp32.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>

int main(int argc, char **argv) {
    DWORD pid = 0, i = 0, cPid = 0;
    PROCESSENTRY32 pe32;
    BOOL res = FALSE;
    HANDLE snap = INVALID_HANDLE_VALUE, proc = INVALID_HANDLE_VALUE;
    char c = 0;
    if (argc > 1) {
        pid = atoi(argv[1]);
    } else {
        pid = GetCurrentProcessId();
    }
    printf("PID: %d\n", pid);
    snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, pid);
    if (snap == INVALID_HANDLE_VALUE) {
        printf("CreateToolhelp32Snapshot failed: %d\n", GetLastError());
        return -1;
    }
    pe32.dwSize = sizeof(PROCESSENTRY32);
    res = Process32First(snap, &pe32);
    if (res == FALSE) {
        printf("Process32First failed: %d\n", GetLastError());
        CloseHandle(snap);
        return -2;
    }
    do {
        if (_tcscmp(pe32.szExeFile, TEXT("conhost.exe")) == 0) {
            _tprintf(TEXT("    Idx: %02d  PID: %5d  PPID: %5d  Name: %s\n"), i++, pe32.th32ProcessID, pe32.th32ParentProcessID, pe32.szExeFile);
            if (pe32.th32ParentProcessID == pid) {
                cPid = pe32.th32ProcessID;
            }
        }
    } while ((res = Process32Next(snap, &pe32)));
    CloseHandle(snap);

    if ((proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, cPid)) == INVALID_HANDLE_VALUE) {
        printf("OpenProcess failed: %d\n", GetLastError());
        return -3;
    }
    printf("Conhost handle: 0x%08X\n", proc);
    CloseHandle(proc);

    printf("Press a key to exit...\n");
    c = getch();
    return 0;
}

Output (as a VStudio 2010, Console App (Debug - x86) on Win 10):

e:\Work\Dev\StackOverflow\q035102238>ver

Microsoft Windows [Version 10.0.17134.48]

e:\Work\Dev\StackOverflow\q035102238>"Debug\q035102238.exe"
PID: 22388
    Idx: 00  PID: 19892  PPID: 20164  Name: conhost.exe
    Idx: 01  PID: 21128  PPID: 21120  Name: conhost.exe
    Idx: 02  PID:  1144  PPID: 20572  Name: conhost.exe
    Idx: 03  PID:  8184  PPID: 19572  Name: conhost.exe
    Idx: 04  PID: 10976  PPID: 20608  Name: conhost.exe
    Idx: 05  PID: 21284  PPID:  8792  Name: conhost.exe
    Idx: 06  PID:  8172  PPID: 20444  Name: conhost.exe
    Idx: 07  PID:  4396  PPID: 19484  Name: conhost.exe
    Idx: 08  PID: 12484  PPID:  2580  Name: conhost.exe
    Idx: 09  PID: 18636  PPID: 11552  Name: conhost.exe
    Idx: 10  PID: 21456  PPID: 21016  Name: conhost.exe
    Idx: 11  PID:   960  PPID:  3528  Name: conhost.exe
    Idx: 12  PID: 20616  PPID: 18404  Name: conhost.exe
    Idx: 13  PID: 21548  PPID: 21528  Name: conhost.exe
    Idx: 14  PID: 20192  PPID:  8316  Name: conhost.exe
    Idx: 15  PID:  2496  PPID:  9284  Name: conhost.exe
    Idx: 16  PID:  5820  PPID: 23140  Name: conhost.exe
    Idx: 17  PID:  6032  PPID: 26512  Name: conhost.exe
Connhost handle: 0x00000000
Press a key to exit...

So, it is possible to enumerate all running conhost.exe processes, and also get PROCESS_ALL_ACCESS to the one associated with my current application (I have to mention here that my Win user has full administrative privileges).
@EDIT0:

*

*As @BladeMight noticed, on Win 7 all conhost.exe processes are children of crss.exe (as it can be also seen in ProcExp)

Output:

c:\Work\Dev\StackOverflow\q035102238>ver

Microsoft Windows [Version 6.1.7601]

c:\Work\Dev\StackOverflow\q035102238>q035102238.exe
PID: 1548
    Idx: 00  PID:  4960  PPID:  3472  Name: conhost.exe
    Idx: 01  PID:  5024  PPID:  3472  Name: conhost.exe
    Idx: 02  PID:  5076  PPID:  3472  Name: conhost.exe
    Idx: 03  PID:  2676  PPID:  3472  Name: conhost.exe
    Idx: 04  PID:  1888  PPID:  3472  Name: conhost.exe
Connhost handle: 0x00000000
Press a key to exit...

A: Some unbelievably convoluted answers here. Use process explorer to get the pid of the console application and then do the following in kd -kl
lkd> !process 0n16592 0
Searching for Process with Cid == 40d0
Cid handle table at fffff8a001db8000 with 4368 entries in use

PROCESS fffffa8042eb9590
.
.
.

lkd> .process /P fffffa8042eb9590
Implicit process is now fffffa80`42eb9590

lkd> !peb
PEB at 000007fffffd3000
.
.
.
    ProcessParameters: 0000000000202880
.
.
.

lkd> dt nt!_RTL_USER_PROCESS_PARAMETERS 0000000000202880
.
.
.
   +0x010 ConsoleHandle    : 0x00000000`00003d98 Void
   +0x018 ConsoleFlags     : 0
   +0x020 StandardInput    : 0x00000000`00000003 Void
   +0x028 StandardOutput   : 0x00000000`00000007 Void
   +0x030 StandardError    : 0x00000000`0000000b Void
.
.
.
.

lkd> ? 0x3d98
Evaluate expression: 15768 = 00000000`00003d98

This is the pid of the conhost process that it is attached to. In C++, you'd have to get the current PEB, take a look at how that is done programmatically here, study the structure of the PEB and ParameterBlock and then you'll know how to get the parameter block and at what offset it is in the parameter block. You can use the type definition for _PEB and _RTL_USER_PROCESS_PARAMETERS in winternl.h or the one here, or write your own using the ntkrnlmp.pdb symbols.


text:
Q: Database not adding while having a social login in MySQL in php I'm trying to build a social media login option in my login page with the help of hybrid auth plugin.
When the user clicks on login as facebook or any other social media plugin, I'm getting the logged in page or success page in which I'm trying to fetch data of the user and adding it to my own database in MySql, but it is not adding up. Following is my code:
<?php
include(dirname(__FILE__) . '/../nits-admin/version.php');

//database connection  at top and also once only

global $link;
$server   = 'localhost';
$user     = 'root';
$password = '';
$db       = 'nits_editor';

$link = mysqli_connect($server, $user, $password, $db);

if (!$link) {
    die("Connection Failed!:" . mysqli_connect_error());
}

session_start();

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
    header("location: index.php");
    exit();
}

include(dirname(__FILE__) . '/../nits-db/db.php');

if (isset($_POST["user_email"]) && isset($_POST["password"])) {
    $useremail = $_POST["user_email"];
    $password  = $_POST["password"];

    $sql = "SELECT * FROM nits_user WHERE user_email ='$useremail' AND user_password ='$password'";

    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while ($row = mysqli_fetch_array($sql)) {
            $user_id = $row["user_id"];
        }
        $_SESSION["user_id"]    = $user_id;
        $_SESSION["loggedin"]   = ture;
        $_SESSION["user_email"] = $useremail;
        $_SESSION["password"]   = $password;
        $_SESSION["user_name"]  = $row["user_name"];
        header("location: index.php");
        exit();
    } else {
        echo 'Information incorrect';
    }
} elseif (isset($_REQUEST["provider"])) {
    //the selected provider
    $provider_name = $_REQUEST["provider"];
    try {
        // inlcude HybridAuth library
        // change the following paths if necessary
        $config = dirname(__FILE__) . '/hybridauth/config.php';
        require_once("hybridauth/Hybrid/Auth.php");

        // initialize Hybrid_Auth class with the config file
        $hybridauth = new Hybrid_Auth($config);

        // try to authenticate with the selected provider
        $adapter = $hybridauth->authenticate($provider_name);

        // then grab the user profile
        $user_profile = $adapter->getUserProfile();
    }

    // something went wrong?
    catch (Exception $e) {
        header("Location: login.php");
    }

    /*
     * get the user data from database by provider name and provider user id
     **/
    function get_user_by_provider_and_id($provider_name, $provider_user_id, $link)
    {
        $qry1 = "SELECT * FROM nits_user WHERE hybridauth_provider_name = '$provider_name' AND hybridauth_provider_uid = '$provider_user_id'";

        $result1 = mysqli_query($link, $qry1);

        return mysqli_fetch_object($result1);

    }

    // check if the current user already have authenticated using this provider before
    $user_exist = get_user_by_provider_and_id($provider_name, $user_profile->identifier, $link);

    // if the used didn't authenticate using the selected provider before
    // we create a new entry on database.users for him
    if (!$user_exist) {

        function create_new_hybridauth_user($email, $first_name, $last_name, $provider_name, $provider_user_id, $link)
        {
            // let generate a random password for the user
            $password = md5(str_shuffle("0123456789abcdefghijklmnoABCDEFGHIJ"));

            $qry2 = ("INSERT INTO nits_user
                        (
                            user_email,
                            user_password,
                            user_firstname,
                            user_lastname,
                            hybridauth_provider_name,
                            hybridauth_provider_uid,
                            user_createdate
                        )
                        VALUES
                        (
                            '$email',
                            '$password',
                            '$first_name',
                            '$last_name',
                            $provider_name,
                            $provider_user_id,
                            NOW()
                        );");

            $result2 = mysqli_query($link, $qry2);

            //$last_insert_id = mysqli_insert_id($link);

            return $email;
        }

        $val = create_new_hybridauth_user($user_profile->email, $user_profile->firstName, $user_profile->lastName, $provider_name, $user_profile->identifier, $link);

        if ($val) {

            $_SESSION['loggedin'] = true;

            if (isset($_SESSION['loggedin'])) {
                header('Location: index.php');
            }
        }

    } else {

        // set the user as connected and redirect him

        $_SESSION['loggedin'] = $user_profile->email;

        if (isset($_SESSION['loggedin'])) {
            header('Location: index.php');
        }
        header("Location: login.php");

    }
}

?>

I'm not getting Database connection error, I mean connection is appropriate, as while logging in with username and password it matches with the database and redirects the defined page.
Don't be concern with the password, I'll be using password_hash().
Please help me out!!!
Thanks

A: Try to debug your code as below
if (isset($_REQUEST["provider"])) {
    //the selected provider
    $provider_name = $_REQUEST["provider"];
    try {
        // inlcude HybridAuth library
        // change the following paths if necessary
        $config = dirname(__FILE__) . '/hybridauth/config.php';
        require_once("hybridauth/Hybrid/Auth.php");

        // initialize Hybrid_Auth class with the config file
        $hybridauth = new Hybrid_Auth($config);

        // try to authenticate with the selected provider
        $adapter = $hybridauth->authenticate($provider_name);

        // then grab the user profile
        $user_profile = $adapter->getUserProfile();
    }

    // something went wrong?
    catch (Exception $e) {
        header("Location: login.php");
    }

    /*
     * get the user data from database by provider name and provider user id
     * */

    function get_user_by_provider_and_id($provider_name, $provider_user_id, $link) {
        $qry1 = "SELECT * FROM nits_user WHERE hybridauth_provider_name = '".$provider_name."' AND hybridauth_provider_uid = '".$provider_user_id."'";

        $result1 = mysqli_query($link, $qry1);

        return mysqli_fetch_object($result1);
    }

    // check if the current user already have authenticated using this provider before
    $user_exist = get_user_by_provider_and_id($provider_name, $user_profile->identifier, $link);
    echo '<pre>'; print_r($user_exist);
    // if the used didn't authenticate using the selected provider before
    // we create a new entry on database.users for him
    if (!$user_exist) {

        function create_new_hybridauth_user($email, $first_name, $last_name, $provider_name, $provider_user_id, $link) {
            // let generate a random password for the user
            $password = md5(str_shuffle("0123456789abcdefghijklmnoABCDEFGHIJ"));

            $qry2 = ("INSERT INTO nits_user
                        (
                            user_email,
                            user_password,
                            user_firstname,
                            user_lastname,
                            hybridauth_provider_name,
                            hybridauth_provider_uid,
                            user_createdate
                        )
                        VALUES
                        (
                            '".$email."',
                            '".$password."',
                            '".$first_name."',
                            '".$last_name."',
                            '".$provider_name."',
                            '".$provider_user_id."',
                            NOW()
                        );");

            $result2 = mysqli_query($link, $qry2)or die(mysqli_error($link));

            $last_insert_id = mysqli_insert_id($link);
            echo 'lastinsertid:'.$last_insert_id;

            return $email;
        }

        $val = create_new_hybridauth_user($user_profile->email, $user_profile->firstName, $user_profile->lastName, $provider_name, $user_profile->identifier, $link);

        if ($val) {
            echo 'email:'.$val;
            $_SESSION['loggedin'] = true;

            if (isset($_SESSION['loggedin'])) {
                header('Location: index.php');
            }
        }
    } else {
        echo 'userexist:';
        // set the user as connected and redirect him

        $_SESSION['loggedin'] = $user_profile->email;

        if (isset($_SESSION['loggedin'])) {
            header('Location: index.php');
        }
        header("Location: login.php");
    }
}


text:
Q: Ionic 2 platform height and width inconsistency with orientation changes I am trying to get the screen height and width of the platform object, but evidently the screen orientation confuses these values.
Test code:
platform.ready().then(() => {
      console.log("orientation", screenOrientation.type);
      console.log("platform height", this.platform.height());
      console.log("platform width", this.platform.width());

      events.subscribe('orientation-changed', (screenOrientation) => {
        console.log("orientation", screenOrientation.type);
        console.log("platform height", this.platform.height());
        console.log("platform width", this.platform.width());
      });
    });

I run the app starting in portrait mode, and I get:
orientation portrait-primary
platform height 567
platform width 360

I rotate the phone to landscape, and I get:
orientation landscape-primary
platform height 567
platform width 360

Until now, everything seems to be in order.
But now, if I turn the phone back to portrait mode, I get:
orientation portrait-primary
platform height 335
platform width 598

If I turn it again to landscape:
orientation landscape-primary
platform height 567
platform width 360

How can I get the correct height and width, without being concerned about the phone orientation?


text:
Q: Spring singleton created, destroyed, created again I am seeing a peculiar behavior in Spring 3.2.5
One of my beans is created as a consequence of AbstractBeanFactory#getType
Then Spring throws an exception along the lines of
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'A' defined in class path resource [config.xml]: Cannot resolve reference to bean 'B' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'B': Requested bean is currently in creation: Is there an unresolvable circular reference?

As the result of that exception, my bean is destroyed.
Later, my bean is created again, from a different getType() call. Tghis time Spring does not have any circular path problems.
Eventually, the entire context is created successfully, with the second copy of my bean retained as singleton.
My question is - is that behavior normal? Or am I doing something wrong? My bean has side effects in its init() method, so if this is a normal behavior of Spring, I'll need to add a destroy() method to it...
Edit:
To clarify the questions about the exception: The beans mentioned in exception are not exactly relevant because the context (including the beans A and B) is eventually created successfully, so there really is no circular dependency. However, for the completeness' sake, bean A takes bean B as constructor argument.


text:
Q: How do i push my microservice folders to Github as one repository I have a micro-service app built in Laravel 9. It is built as two micro-services: frontend and backend.
Each micro-service has sub-folders and file because each is a Laravel installation.

I want to commit the whole as one repository to GitHub using my Git GUI but my windows shows no files and i keep getting :

No changes to commit
You must stage at least 1 file before you can commit.

A: Prior to committing, you must add files.
Some commands for git flow:
git init creates new repository
git add <filename> stages a file
git add * or git add --all stages all files on the repository
git commit -m "message" commits staged files
git push <remote> <branch> Pushes branch to a remote repository e.g. on github
Some basic documentation:
https://rogerdudler.github.io/git-guide/


text:
Q: listar todos los usuarios yii2 en el form Hola mi duda es la siguiente tengo esta vista
y al crear una asistencia se me despliega esta otra vista

ahí puedo escoger la fecha y el nombre de solo un mecánico y abajo sale un checkbox para ver si asistió o no

mi pregunta es la siguiente se puede hacer que en vez de que tenga que escoger yo el nombre del mecánico se me despliegue instantáneamente todos los mecánicos y al lado de ellos el checkbox y así cuando guarde, se me guardara la fecha y si presiono "ver"  se desplegara todos los mecánicos con su respectiva asistencia
este es el código del form para buscar un mecanico
<?= $form->field($model, 'mecanico_id')
        ->dropDownList(
        ArrayHelper::map(Mecanico::find()->all(), 'id_mecanico', 'nombre'),['prompt'=>'Escoja el Mecánico'])
    ?>

A: hola buenas solo tienes que añadir un multiple para que puedas escoger varios a la vez, lo lógico sería que después tuvieras otra vista para cumplimentar que mecánico asistió y ahí si quieres pongas el checkbox de los que guardes o como en este caso con un arrayhelper y una consulta específica los cargues.
el código de arriba debería ser así;
$form->field($model, 'mecanico_id[]')
         ->dropDownList(
           ArrayHelper::map(Mecanico::find()->all(), 'id_mecanico', 'nombre'),
         [
          'prompt'=>'Escoja al menos un mecánico'
          'multiple'=>'multiple'
          'class'=>'chosen-select input-md required',
         ]
        );


text:
Q: Drop-out voltage at the input using MOSFET Please have a look at my below circuits.
The first one is an MOSFET. N-MOS.
Gate is fed with a function generator input of 5V peak to peak. 1kHz frequency. 1ms period. 90% duty cycle.
Drain is provided with 10V and the source is connected to a load resistor.

If I probe at the gate and the source, I get the below waveform :

Please consider only the yellow and blue trace in the above waveform. Yellow is probed at the gate. Blue is probed at the source of the MOSFET.
If I connect the MOSFET to the circuit shown above, i.e., my second circuit, the same FG input is provided to the GATE of the MOSFET.
Now, I probe at the point A and the Gate of the MOSFET. Below is the waveform :

Yellow is the GATE of the MOSFET. While blue is probed at Node A.
My questions are :

*

*In the second waveform and the second circuit, shouldn't the voltage at node A, follow the voltage at the GATE of the MOSFET? The node A voltage should also go to 0V while the Gate voltage goes to 0V. Why am I not getting that 0V waveform at the Node A?

*What effect does the resistor connected to the source of the MOSFET and the purpose of the C1 50nF capacitor in this circuit.

A: *

*It does. But the capacitors hold some charge for a while before losing it slowly. Without capacitor voltage falls immediately. This is normal.

*This resistor limits the current being sunk to ground. Without it you would create a short circuit situation.
IMO this circuit is build upside down. The resistor should be on the drain side (to be a pull up resistor. Value between 10K to 50K at 10V) with all the capacitors and stuffs, and the source connected to GND directly. While the current setup works in practice, it's not intended to work like that.


text:
Q: How do I configure another instance of redis on ubuntu? I basically want to have 2 instances of redis on Ubuntu. I looked at /etc/init.d/redis-server script and tried to create a new one (redis-server-dev)  pointing to another config file (new port etc) but it didn't seem to work.
What is the correct procedure?
Thanks

A: Adding to Dan's answer,
According to this error in the log file we have to create one extra directory
# Can't chdir to '/var/lib/redis-new': No such file or directory

so
mkdir /var/lib/redis-new

Otherwise /etc/init.d/redis-server-new won't start.
Don't forget to add proper rights by
chown redis:redis /var/lib/redis-new

A: *

*Create a new config file /etc/redis/redis-new.conf (copied from redis.conf) and change these fields in the new config

*

*pidfile

*port

*logfile

*dir (for the default db)

*Create a new file /etc/init.d/redis-server-new (copied from the file redis-server) and change these fields in the new file

*

*name

*pidfile (same as in the config file in step 1)

*deamon_args (the path to the config file in step 1).

*Create the needed directorymkdir /var/lib/redis-new  (and give it the proper rights chown redis:redis /var/lib/redis-new)

*Make the new file executable: chmod +x /etc/init.d/redis-server-new

*Register the new deamon: update-rc.d redis-server-new defaults

A: Also there is another way, we can use the installation script which is at https://github.com/antirez/redis/blob/3.0/utils/install_server.sh (comes with the source if you have compiled redis from source), there are 2 template files:

*

*redis_init_script.tpl (is in the utils directory)

*redis.conf (is in the ../ directory from utils in the source

You need to tell just the port on which new instance is to be run(there are other configurable choices, but defaults can be used), rest of the placement of files will be done automatically.


text:
Q: Curve Sprite Movement COCOS2D I'm trying with no luck to move a sprite position in an simetric curve way with the touch drag. So far I use the following code with no luck
-(BOOL) ccTouchBegan:(UITouch*)touch withEvent:(UIEvent *)event
{
lastTouchLocation = [MultiLayer locationFromTouch:touch];
return YES;
}

-(void) ccTouchMoved:(UITouch*)touch withEvent:(UIEvent *)event
{
CGPoint currentTouchLocation = [MultiLayer locationFromTouch:touch];
moveTo = ccpSub(lastTouchLocation, currentTouchLocation);
lastTouchLocation = currentTouchLocation;
}

-(void) update:(ccTime)delta
{
CCSprite* sprite = [sprites objectAtIndex:1];
if (moveTo.x != 0){
    float X = sprite.position.x + moveTo.x;
    float Y =  sprite.position.y + (pow(X,2));
    sprite.position = CGPointMake(X, Y);
}
}

The curve way i'm trying to simulate is in the form y=x^2. Is this posible?
Thanks in advance!

A: Yes it's possible. You can do it manually as your are trying, but it's better to use a built-in solution. There is a CCJumpTo and CCJumpBy actions in cocos2d engine. They are created for parabolic moves. Use them


text:
Q: Custom line drawing in WPF I'm trying to manually draw a line in WPF by overriding the OnRender method of a control and calling the DrawLine method on the given DrawingContext. I read somewhere that this method call doesn't instantly draw the line, but I can't work out how to actually cause the line to appear.
I've tried using a combination of PathGeometry, LineSegments, Line and Polyline controls. I could draw what I wanted then, but offsets weren't quite right (i.e. when drawing a line, it was fine, when drawing a polyline, everything became incorrectly offset).
Any advice on this would be great.
EDIT
Pen Code
    private static readonly Pen LinePen = new Pen(new SolidColorBrush(Colors.Green), 3.0d);
    private static readonly Pen WayPointPen = new Pen(new SolidColorBrush(Colors.Gray), 3.0d);

Render Code
    protected override void OnRender(DrawingContext drawingContext)
    {
        // Draw way points
        this.DrawWayPoints(drawingContext);

        if (mDrawing)
        {
            // Draw current line
            this.DrawCurrentLine(drawingContext);
        }
    }

    private void DrawCurrentLine(DrawingContext context)
    {
        if(mStartPoint.HasValue && mEndPoint.HasValue)
        {
            // Draw the line
            context.DrawLine(LinePen, mStartPoint.Value, mEndPoint.Value);
        }
    }

    private void DrawWayPoints(DrawingContext context)
    {
        if (mWayPoints.Count < 2)
        {
            return;
        }

        // Draw all points
        for (int i = 0; i < mWayPoints.Count - 1; i++)
        {
            var start = mWayPoints[i];
            var end = mWayPoints[i + 1];

            // Draw the line
            context.DrawLine(WayPointPen, start, end);
        }
    }

EDIT
Test Project: http://dl.dropbox.com/u/12763956/DrawingTest.zip
(Test Project written in Visual Studio 2010)
Usage:
 - Left click within the raised area to add points to the list.
 - Right click to end drawing and clear points.
Note: Custom drawn lines (in OnRender override) do not appear.

A: There are actually two issues here. The first is your Canvas's Background covers up anything you'd draw on your DrawingControl. So if you set the Canvas Background to Transparent, you can temporarily work around that issue.
The second issue is you need to call InvalidateVisual after you add a point to your collection to force it to redraw.
You would probably need to add another control that appears on top of the Canvas, and render the lines there. Or you'd need to render the Background yourself in the DrawingControl.OnRender method.


text:
Q: How do I print the difference of a tuple in python I want to output difference two tuple and remove one element on tuple
a = [(1,2),(2,3),(3,3)]
if (1,2) in a:
       ## how to remove (1,2) on tuple

i need output [(2,3),(3,3)] how to do it?
Thanks,

A: You can simply use .remove method for lists when you know the element that is to be removed.
>>> a = [(1,2),(2,3),(3,3)]
>>> a.remove((1,2))
>>> a
[(2, 3), (3, 3)]

A: Other way, you can use del
>>> a = [(1,2),(2,3),(3,3)]
>>> del a[a.index((1,2))]
>>> a
[(2, 3), (3, 3)]
>>>

or using .pop
>>> a = [(1,2),(2,3),(3,3)]
>>> a.pop(a.index((1,2)))
(1, 2)
>>> a
[(2, 3), (3, 3)]
>>>


text:
Q: Are there restrictions to applying $\lim\limits_{x\to0}\frac {\tan x} {x}$? Question
Evaluate $$\lim\limits_{x\to0}\ \left(\frac {\tan x} {x}\right)^\frac {1} {x^2}\ .$$

My working
So far, I have gotten to the step where
\begin{align}
\lim\limits_{x\to0}\ \left(\frac {\tan x} {x}\right)^\frac {1} {x^2} & =
\exp\left(\lim\limits_{x\to0}\ \frac {\ln(\frac {\tan x} {x})} {x^2}\right)
\\[5 mm] & =
\exp\left(\lim\limits_{x\to0}\ \left[\left(\frac {x\sec^2 x - \tan x} {x^2} \div \frac {\tan x} {x} \right) \div 2x \right]\right)
\end{align}
Here, I note that $\lim\limits_{x\to0}\frac {\tan x} {x} = 1$, so I continue with
\begin{align}
\lim\limits_{x\to0}\ \left(\frac {\tan x} {x}\right)^\frac {1} {x^2} & =
\exp\left(\lim\limits_{x\to0}\ \left[\left(\frac {x\sec^2 x - \tan x} {x^2} \div 1 \right) \div 2x \right]\right)
\\[5 mm] & =
\exp\left(\lim\limits_{x\to0}\ \frac {x\sec^2 x - \tan x} {2x^3}\right)
\end{align}
This is where I believe I have made a mistake. I tried to use the fact that $\lim\limits_{x\to0}\frac {\tan x} {x} = 1$ again by factoring out an $x$ from the denominator, so I proceeded with
\begin{align}
\lim\limits_{x\to0}\ \left(\frac {\tan x} {x}\right)^\frac {1} {x^2} & =
\exp\left(\lim\limits_{x\to0}\ \frac {x\sec^2 x - \tan x} {2x^3}\right)
\\[5 mm] & =
\exp\left(\lim\limits_{x\to0}\ \frac {\sec^2 x - \frac {tan x} {x}} {2x^2}\right)
\\[5 mm] & =
\exp\left(\lim\limits_{x\to0}\ \frac {\sec^2 x - 1} {2x^2}\right)
\\[5 mm] & =
\exp\left(\lim\limits_{x\to0}\ \frac {2\sec^2 x \tan x} {4x}\right)
\\[5 mm] & =
\exp\left(\lim\limits_{x\to0}\ \frac {\sec^2 x \tan x} {2x}\right)
\\[5 mm] & =
\exp\left(\lim\limits_{x\to0}\ \frac {2\sec^2 x \tan^2 x + \sec^4 x} {2}\right)
\\[5 mm] & =
\exp\left(\lim\limits_{x\to0}\ \frac {\sec^4 x} {2}\right)
\\[5 mm] & =
e^\frac {1} {2}
\end{align}

Answer
$$\lim\limits_{x\to0}\ \left(\frac {\tan x} {x}\right)^\frac {1} {x^2} = e^\frac {1} {3}$$

The solution provided by my professor also used the fact that $\lim\limits_{x\to0}\frac {\tan x} {x} = 1$ at the same point where I used it for the first time, so I believe there is nothing wrong with my steps until that point. I am thinking that I have gone wrong when I applied it the second time, but I am not sure. If so, can anyone tell me why I cannot apply $\lim\limits_{x\to0}\frac {\tan x} {x} = 1$ for the second time? Or perhaps, did I go wrong somewhere else? I certainly hope it is not because of some careless mistake...
Any help/intuition/explanation will be greatly appreciated :)

Edit
Seeing how my professor worked out part of the limit to simplify the limit, I tried to be smart and extend his idea, but that did not work out too well for me, as pointed out by the answers! Really insightful comments from the community once again :)

A: $\lim_{x\to0}\sec^2x=1$ too. The expression $\sec^2x-\frac{\tan x}x$ in the numerator before your mistake step has limit $0$, so forms the numerator of an $0/0$ indeterminate form. It cannot be immediately split into its constituent parts.

A: Indeed in the first step we have that
$$\lim\limits_{x\to0} \frac{x\sec^2 x - \tan x  }{  2x^3 \frac {\tan x} {x}} $$
and since $\frac {\tan x} {x} \to 1$ we reduce to study the following
$$\lim\limits_{x\to0} \frac{x\sec^2 x - \tan x  }{  2x^3 } $$
this one is a perfectly fine step but in the subsequent steps this is not allowed as for example for
$$\lim\limits_{x\to0} \frac{\sin x-x  }{  x^3 } = \lim\limits_{x\to0} \frac{\frac{\sin x}x-1  }{  x^2 } \neq 0$$
Refer to the related

*

*Analyzing limits problem Calculus (tell me where I'm wrong).


text:
Q: Center of mass of a collection of points We have a system of N points $(x_i, y_i)$ with masses $m_i$ and fixed distances. I want to show that there is a center of mass and derive a formula to compute its coordinates. I have argued that we can imagine those points as crystallized in a mass-less coordinate plain and that there are a vertical and a horizontal line $x=x_s$ and $y=y_s$ where we can balance the whole plain on an infinitely long knife blade. Solving the equations for the angular momenta
$$ 0 = \sum_{i=1}^N \left(x_S-x_i\right) \cdot m_i \quad \text{and} \quad 0 = \sum_{i=1}^N \left(y_S-y_i\right) \cdot m_i$$
yields the formula
$$(x_s,y_s) = \dfrac{1}{m_{tot}} \cdot \left(\sum_{i=1}^N x_i \cdot m_i \ , \ \sum_{i=1}^N y_i \cdot m_i \right).$$
I would then like to argue that at $S = (x_S, y_S)$ we could actually balance the plane on a needle, and to show that, it would suffice to say that the plane cannot tilt in any direction, i.e. that we can balance it on ANY straight line through $S$. Any clues on how to do that, using what we have so far?

A: In polar coordinates by the same logic it follows.
$$ \sum_{i=1}^N \left(r_S-r_i\right) \cdot m_i =0$$
yields formula for any arbitray orientation $\alpha$ passing through center of mass
$$ r_S= \sqrt{x_s^2+y_s^2}$$
EDIT1:
$$ r_s= \left(\sum_{i=1}^N r_i \cdot m_i \right )/{m_{tot}} $$
We can balance a flat weightless lamina on a point of concurrency of all straight lines through $S$. It is a physical  invariant for all or any coordinate system used. Position of center of mass/gravity same for equilibrium whether the laminate is vertical or horizontal.
Horizontal or Vertical

A: Firstly, angular momentum is defined for moving particles, not to particles at rest. So you should state the moment of weights about $x_s$ or $y_s$ lines and not angular momenta.
Translate the coordinate plane to make $S$ as the origin. The corresponding coordinates of particles will change accordingly.
New $x_i' = x_i - x_s$ and $y_i' = y_i - y_s$.
Thus $$ 0 = \sum_{i=1}^N \left(x_S-x_i\right) \cdot m_i \quad \text{and} \quad 0 = \sum_{i=1}^N \left(y_S-y_i\right) \cdot m_i$$ can be rewritten as $$ 0 = \sum_{i=1}^N x_i' \cdot m_i \quad \text{and} \quad 0 = \sum_{i=1}^N y_i' \cdot m_i$$
Now rotate this coordinate plane by an arbitrary angle, say $\theta$ in counter clockwise direction. The equation of coordinate axes and the particles will change once again.
$x_i''= x_i'\cos\theta + y_i'\sin\theta$ and $y_i''= -x_i'\sin\theta + y_i'\cos\theta$.
But we see that the net moment about each of those axes is still zero.
For example,
$$ \sum_{i=1}^N x_i'' \cdot m_i = \sum_{i=1}^N (x_i'\cos\theta + y_i'\sin\theta) \cdot m_i = (\sum_{i=1}^N x_i' \cdot m_i)\cos\theta + (\sum_{i=1}^N y_i' \cdot m_i)\sin\theta = (0)\cos\theta + (0)\sin\theta = 0$$
Similarly, $$ \sum_{i=1}^N y_i'' \cdot m_i = 0$$
Hence proved.


text:
Q: How to copy an interface value in Go? How to copy an interface value in Go?
My User interface:
type User interface {
    Name() string
    SetName(name string)
}

My Admin struct:
type Admin struct {
    name string
}

func (a *Admin) Name() string {
    return a.name
}

func (a *Admin) SetName(name string) {
    a.name = name
}

I try to copy user1's value.
Main Function:
func main() {
    var user1 User
    user1 = &Admin{name:"user1"}

    fmt.Printf("User1's name: %s\n", user1.Name())

    var user2 User
    user2 = user1
    user2.SetName("user2")

    fmt.Printf("User2's name: %s\n", user2.Name()) // The name will be changed as "user2"
    fmt.Printf("User1's name: %s\n", user1.Name())  // The name will be changed as "user2" too, How to make the user1 name does not change?
}

How to achieve that changing the copy's name the original doesn't change?

A: Another solution could be to add a Clone() method to your User interface:
type User interface {
    Clone() User
    Name() string
    SetName(name string)
}

type Admin struct {
    name string
}

func (a *Admin) Clone() User {
    u := *a
    return &u
}

func (a *Admin) Name() string {
    return a.name
}

func (a *Admin) SetName(name string) {
    a.name = name
}

func main() {
    var user1 User
    user1 = &Admin{name:"user1"}

    fmt.Printf("User1's name: %s\n", user1.Name())

    var user2 User
    user2 = user1.Clone()
    user2.SetName("user2")

    fmt.Printf("User2's name: %s\n", user2.Name())
    // output: User2's name: user2

    fmt.Printf("User1's name: %s\n", user1.Name())
    // output: User1's name: user1
}

Of course in this case, the implementation gets linked to the interface, which might not be desired, but that's a solution.

A: The problem here is that your user1 variable (which is of type User) holds a pointer to an Admin struct.
When you assign user1 to another variable (of type User), the interface value which is a pair of the dynamic type and value (value;type) will be copied - so the pointer will be copied which will point to the same Admin struct. So you only have one Admin struct value, both user1 and user2 refer (point) to this. Changing it through any of the interface values changes the one and only value.
To make user1 and user2 distinct, you need 2 "underlying" Admin structs.
One way is to type assert the value in the user1 interface value, and make a copy of that struct, and wrap its address in another User value:
var user2 User
padmin := user1.(*Admin) // Obtain *Admin pointer
admin2 := *padmin        // Make a copy of the Admin struct
user2 = &admin2          // Wrap its address in another User
user2.SetName("user2")

Now they will be distinct, output (try it on the Go Playground):
User1's name: user1
User2's name: user2
User1's name: user1

Of course this solution has its limitation: the dynamic type stored in the User interface value is "wired" in the solution (*Admin).
Using reflection
If we want a "general" solution (not just one that works with *Admin), we can use reflection (reflect package).
For simplicity let's assume user1 always contains a pointer (for now).
Using reflection we can get the dynamic type (here *Admin), and even the dynamic type without a pointer (Admin). And we can use reflect.New() to obtain a pointer to a new value of that type (whose type will be identical to the original dynamic type in user1 - *Admin), and wrap this back into a User. This is how it could look like:
var user3 User
user3 = reflect.New(reflect.ValueOf(user1).Elem().Type()).Interface().(User)
user3.SetName("user3")

Output (try this one on the Go Playground):
User1's name: user1
User3's name: user3
User1's name: user1

Note that reflect.New() will create a new value which is initialized to its zero value (so it will not be a copy of the original). It's not a problem here as Admin only has one field which we're about to change anyway, but must be kept on our mind in general.
Our initial assumption was that user1 contains a pointer. Now the "full" solution must not make such assumption. If the value in user1 would not be a pointer, this is how it could be "cloned":
var user3 User
if reflect.TypeOf(user1).Kind() == reflect.Ptr {
    // Pointer:
    user3 = reflect.New(reflect.ValueOf(user1).Elem().Type()).Interface().(User)
} else {
    // Not pointer:
    user3 = reflect.New(reflect.TypeOf(user1)).Elem().Interface().(User)
}
user3.SetName("user3")

A: There is a more generic way to do that.
func Clone(oldObj interface{}) interface{} {
    newObj := reflect.New(reflect.TypeOf(oldObj).Elem())
    oldVal := reflect.ValueOf(oldObj).Elem()
    newVal := newObj.Elem()
    for i := 0; i < oldVal.NumField(); i++ {
        newValField := newVal.Field(i)
        if newValField.CanSet() {
            newValField.Set(oldVal.Field(i))
        }
    }

    return newObj.Interface()
}

However, it has one pitfall: it cannot set unexported fields. It can be worked around using this solution with the help of unsafe's black magic, but I would rather avoid it.

A: The easiest way of doing this is using a library (I'd recommend https://github.com/jinzhu/copier) combined with some reflection magic:
var cloneObj MyCustomStruct = reflect.New(reflect.ValueOf(sourceObj).Elem().Type()).Interface()
copier.Copy(cloneObj, sourceObj)

This gives you a deep copy of the source struct correctly typed (which is important). If you don't use an interface, you may need to customize the reflection use a bit (remove the .Interface()).


text:
Q: How to get a list of my own created USERCONTROLs I have created two UserControls in my WinFroms Application. Some more UserControls will be created.
Now I want to get a list of my created UserControls by name.
For example:

UserControl ctrl1
UserControl ctrl2
UserControl ctrl3

The UserControls are created like this:
namespace Test.Controlls
{
    public partial class ctrl1 : UserControl
    {

On my WinForms Application it will be included like this:
 public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            contrctrl1.Visible = true;
            contrctrl1.BringToFront();

Now I want ot get the names ctrl1, ctrl2 and ctrl3 in a list to loop through it afterwards.
Something like this:
List<> ctrllist = new List<>();
ctrllist.Add();

for (int i =0; <ctrllist>.count; i++)
{
   switch (ctrllist.toString())
   {
     case "ctrl1": //do seomething
               break;
     case "ctrl2": //do seomething
               break;
     case "ctrl2": //do seomething
               break;
   }
}

Please help me to find a solution.
Thank you.
EDIT: I don't want to know textbox, button controls etc. I have created by own UserControl "Form" and want to store these Names in a list or datatable to retreive back the names if needed.

A: Since all controls will be part of your mainform control you can get all children of that and loop through that.
Accesing Mainform.Controls (docs) likely wont be enough, you need to dig deeper. check this question on how to do that:
How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

A: If you want to traverse all custom controls ctrl1, you can refer to the following code.
List<ctrl1> ctrl1s = new List<ctrl1>();

private void btnGetAllCtrl_Click(object sender, EventArgs e)
{
    foreach(Control control in this.Controls)
    {
        if (control is ctrl1)
        {
            ctrl1s.Add((ctrl1)control);
        }
    }
}

And then traverse the ctrl1 list.
private void btnTraverse_Click(object sender, EventArgs e)
{
    foreach (ctrl1 c in ctrl1s)
    {
        Console.WriteLine(c.Name);
    }
}


text:
Q: how to serialize object to concrete object I have a method:
public object getData()
{
   //make an external call
}

when executing getData(), we get an object that looks like this:
{
   "Location":
      {
         "LocationID":1,
         "ABCIsCopperFiberNidBit":0,
         "ABCCopperJunctionID":0,
         "ABCFiberJunctionID":0,
         "ABCGrade":0,
         "ABCCopperDSLAMDistance":0
      }
}

from the above i need to convert this to a concrete datatype
such as a List of these:
public class LocationModel
{
   public int locationId{get;set;}
   public string key {get;set;}
   public string value {get;set;}
}

the result I am looking for is a List<LocationModel>:
locationid=1,
key=ABCIsCopperFiberNidBit,
value=0

locationid=1
key = ABCCopperJunctionID,
value=0

etc
How do I convert from this object to the desired strongly-typed datatype?
My question is not for the purpose of you to do my work for me. I am a moderately-experienced developer, and I am having trouble digging through all the different ways of accomplishing this task.

A: Something like Json.NET would work well:
string json = @"{
 ""Location"":
      {
         ""LocationID"":1,
         ""ABCIsCopperFiberNidBit"":0,
         ""ABCCopperJunctionID"":0,
         ""ABCFiberJunctionID"":0,
         ""ABCGrade"":0,
         ""ABCCopperDSLAMDistance"":0
      }
}";

then:
    var obj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(json);
    var loc = obj["Location"];

    var locid = loc["LocationID"].Value<int>();
    var list = new List<LocationModel>();
    foreach(var prop in loc.Children().OfType<JProperty>())
    {
        if (prop.Name == "LocationID") continue;
        list.Add(new LocationModel
        {
            locationId = locid,
            key = prop.Name,
            value = prop.Value.ToString()
        });
    }


text:
Q: How can I save a simple counter in an iphone application such that I can increment is and the change will be saved between application launches? All I want is an integer which everytime my app opens is incremented by one. Is there an easy way to do this? Please help.
Thanks, in advance.

A: Store the integer in NSUserDefaults. The documentation is here.

A: You will want to do something like this:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger counter = [defaults integerForKey:@"counterKey"];
counter++;
[defaults setInteger:counter forKey:@"counterKey"];

This also works if the key has never been registered. integerForKey will just return 0, which is actually what we want. However, if you want to be extra-secure, you can check it beforehand. after the second line by something like this:
NSInteger counter = 0;
if ([defaults objectForKey:@"counterKey"] != nil)
    counter = [defaults integerForKey:@"counterKey"];

A: While you could use NSUserDefaults this way isn't the most elegant solution.
Defaults are a place to keep application settings not application data. A good guideline is to think of your data item as appearing in your app's settings and whether it is valid there. In your case the number of times the app has been opened is not a user setting; it isn't something that the user will be able to change, is it?
A better way would be to write the data to a plist, which is a simple and fast way of storing application data. Have a look at the instructions here for example (there are others available with a quick search), which should get you started.


text:
Q: Where to save DS1307 program to get real time value? I am integrating DS1307 in my project and using PIC32MX795F512L MCU. I have somehow managed to do I2C communication in it and getting the real time values. I am displaying the real time value in terminal using UART. So the time is updating automatically. But when I turned off the power to the device and turn it ON again, the DS1307 doesnt gave me the real time value instead it starts the time which I set in the code.
In the code I set, 14:27:12, so after turning it off and on again, the time started from 14:27:12 which I think should not happen. I have battery attached with DS1307.
So I thought to get a real time value, I might have to save the code somewhere else in the Micro Controller.
Need help regarding this.!
CODE:
int main(void)
{
  OpenUART1( UART_EN | UART_NO_PAR_8BIT | UART_1STOPBIT  , UART_RX_ENABLE | UART_TX_ENABLE, (FPB/16/BAUDRATE)-1 );

  I2C2BRG = 0xA3;     //I2C Baudrate
  I2CEnable(EEPROM_I2C_BUS, TRUE);    //I2C module On
  if( !StartTransfer(FALSE) )
  {
    while(1);
  }
  TransmitOneByte(0xD0);  //slave address
  TransmitOneByte(0x00); //register pointer pointing to first register
  TransmitOneByte(0x00); //seconds  value
  TransmitOneByte(0x56); //min value
  TransmitOneByte(0x12); //hr value
  StopTransfer(); //I2C Stop
  if(!Success)
  {
     while(1);
  }
  while(1)
  {
    RTC_read();
    **//sending time to UART**
    putsUART1("Time: ");
    putsUART1(value6);
    putsUART1(value5);
    putsUART1(":");
    putsUART1(value4);
    putsUART1(value3);
    putsUART1(":");
    putsUART1(value2);
    putsUART1(value1);
    putsUART1("\n");
   }
}

**///******** FUNCTION TO READ FROM I2C ****************//**
void RTC_read()
 {

  StartTransfer(FALSE); //I2C Start
  TransmitOneByte(0xD0); //I2C slave address
  TransmitOneByte(0x00);
  StopTransfer(); //I2C Stop

 IdleI2C2(); //i2C Stop

 StartTransfer(TRUE);    //I2C Restart
 TransmitOneByte(0xD1);  //Slave address to read
 **//Reading from I2C slave**
 if(I2CReceiverEnable(EEPROM_I2C_BUS, TRUE) == I2C_RECEIVE_OVERFLOW)
 {
  putsUART1("Error: I2C Receive Overflow1\n");
 }
 else
 {
    **//read sec**
   while(!I2CReceivedDataIsAvailable(EEPROM_I2C_BUS));
   Nop();
   sec = I2CGetByte(EEPROM_I2C_BUS);
   AckI2C2();
   while (!I2CAcknowledgeHasCompleted(I2C2));

   **//read min**
   I2CReceiverEnable(EEPROM_I2C_BUS, TRUE);
   while(!I2CReceivedDataIsAvailable(EEPROM_I2C_BUS));
   Nop();
   min = I2CGetByte(EEPROM_I2C_BUS);
   AckI2C2();
   while (!I2CAcknowledgeHasCompleted(I2C2));

   **//read hr**
   I2CReceiverEnable(EEPROM_I2C_BUS, TRUE);
   while(!I2CReceivedDataIsAvailable(EEPROM_I2C_BUS));
   Nop();
   hr = I2CGetByte(EEPROM_I2C_BUS);
   NotAckI2C2();
   while (!I2CAcknowledgeHasCompleted(I2C2));

 }

 StopTransfer(); //I2C Stop
 if(!Success)
 {
    while(1);
 }

    **//converting sec to ASCII**
    x1 = sec & 0x0F;
    p1 = x1 | 0x30;
    y = sec & 0xF0;
    y = y >> 4;
    p2 = y | 0x30;

    sprintf(value1,"%c",p1);
    sprintf(value2,"%c",p2);

    **///converting min to ASCII**
    x2 = min & 0x0F;
    p3 = x2 | 0x30;
    y2 = min & 0xF0;
    y2 = y2 >> 4;
    p4 = y2 | 0x30;
    sprintf(value3,"%c",p3);
    sprintf(value4,"%c",p4);

    **////converting hr to ASCII**
    x3 = hr & 0x0F;
    p5 = x3 | 0x30;
    y3 = hr & 0xF0;
    y3 = y3 >> 4;
    p6 = y3 | 0x30;
    sprintf(value5,"%c",p5);
    sprintf(value6,"%c",p6);

}

EDIT
Following are the functions used in code:
StartTransfer(BOOL restart):-
//Description:This routine starts (or restarts) a transfer to/from the EEPROM, waiting (in a blocking loop) until the start (or re-start) condition has completed.

 //Parameters:restart - If FALSE, send a "Start" condition
         //         - If TRUE, send a "Restart" condition

 //Returns: TRUE    - If successful
  //         FALSE   - If a collision occured during Start signaling

BOOL StartTransfer( BOOL restart )
{
I2C_STATUS  status;

// Send the Start (or Restart) signal
if(restart)
{
    I2CRepeatStart(EEPROM_I2C_BUS);
}
else
{
    // Wait for the bus to be idle, then start the transfer
    while( !I2CBusIsIdle(EEPROM_I2C_BUS) );

    if(I2CStart(EEPROM_I2C_BUS) != I2C_SUCCESS)
    {
        DBPRINTF("Error: Bus collision during transfer Start\n");
        return FALSE;
    }
}

// Wait for the signal to complete
do
{
    status = I2CGetStatus(EEPROM_I2C_BUS);

} while ( !(status & I2C_START) );

return TRUE;
}

BOOL TransmitOneByte( UINT8 data ):-
 //Description:This transmits one byte to the EEPROM, and reports errors for any bus collisions.
//Returns:TRUE    - Data was sent successfully
          FALSE   - A bus collision occured

BOOL TransmitOneByte( UINT8 data )
{
// Wait for the transmitter to be ready
while(!I2CTransmitterIsReady(EEPROM_I2C_BUS));

// Transmit the byte
if(I2CSendByte(EEPROM_I2C_BUS, data) == I2C_MASTER_BUS_COLLISION)
{
    DBPRINTF("Error: I2C Master Bus Collision\n");
    return FALSE;
}

// Wait for the transmission to finish
while(!I2CTransmissionHasCompleted(EEPROM_I2C_BUS));

return TRUE;
}

void StopTransfer( void ):-
 //Description:This routine Stops a transfer to/from the EEPROM, waiting (in //a blocking loop) until the Stop condition has completed.

void StopTransfer( void )
{
I2C_STATUS  status;

// Send the Stop signal
I2CStop(EEPROM_I2C_BUS);

// Wait for the signal to complete
do
{
    status = I2CGetStatus(EEPROM_I2C_BUS);

} while ( !(status & I2C_STOP) );
}

A: At a quick glance, it looks like the only way that the code WILL NOT update the DS1307, is if StartTransfer(FALSE) detects that the DS1307 has already been initialised.
Does it do that? (To understand the program, we'd need to see the code, and an explanation of how it works. )
Otherwise, the code looks like it always tries to set the same old time into the DS1307.
Copy the program, and change it so that it does not set the time in the DS1307, and run it again.
Think of the problem as two different (use) cases:

*

*Set the DS1307 time

*Use the DS1307 time

for simplicity, write two programs, one which only sets the time, and the other solves the problem (the other case).
Edit:
You say the application doesn't have a user interface, and will normally store data onto an SD Card.
So the options are:

*

*Add an extra button (or even just a pin which can safely be shorted to ground) which will be used to trigger the program to set
the timer. It might use a variant of methods 2 or 3, below

*Write the time into a file with a specific name on the SD card using a PC (of some kind). Depending on your SD Card library, you might even get the data and time from the time stamp of the file. If the file exists when the system is RESET, the system should read the date and time information, set the DS1307, and then delete the file to avoid accidentally reseting the clock again.

*Use your 'debug' terminal, connected over UART, to set the DS1307
clock. Write a bit of code to detect if the terminal is connected (I
assume normally it isn't), and if the terminal is connected, read
the time information.
There is also the option to keep the 'clock set program' separate, and run it when the system is ready to install, and replace it with the production code. (Not as tidy)

A: You only have to set time once and then just read it.
So next time don't include the setting time function in your code because earlier you have set time. The registers of DS1307 will contain the updated time and you will have to read it.
Lets say, you have below functions:
RTC_init     : to initialise I2C channel
RTC_setTime  : to set time
RTC_readTime : to read time

Then at first include all the three functions in your code. Something like below:
main()
{
  RTC_init();
  RTC_setTime();

  while(1)
  {
    RTC_readTime();
  }
}

and then second time, comment out the function RTC_setTime() and again program your device. Like below
main()
{
  RTC_init();
  //RTC_setTime();

  while(1)
  {
    RTC_readTime();
  }
}

Now if you didn't give power to your device, the battery will help DS1307 to hold the updated values of time & date to their registers and it will keep on doing this.


text:
Q: Ms-Access GROUP BY, TOP query I am using the following query on a .mdb file with the following results.
SELECT tableA.id, tableA.type, tableA.date, SUM(tableA.val) AS total, tableB.SumB
FROM tableA LEFT JOIN tableB ON tableB.id = tableA.id
GROUP BY tableA.id, tableA.type, tableA.date, tableB.SumB ;

results:

I need only the first record from the group of records with the same type and date.
I would use DISTINCT but the problem is that I have a different field (in this example id).
Any suggestions?
Thanks
P.S. Case 2:
Ids are the same for the red records but we have an additional column 'name' with different string values.

A: Use min of id and remove it from Group by clause
SELECT min(tableA.id) as id, tableA.type, tableA.date,
SUM(tableA.val) AS total, tableB.SumB
FROM tableA LEFT JOIN tableB ON tableB.id = tableA.id
GROUP BY tableA.type, tableA.date, tableB.SumB ;


text:
Q: Oyoaha look and feel in Java Swing I m using windows 7. I want to use Oyoaha look and feel in Java Swing. I dont know the class name for Oyoaha. Please tell me how to use the LookAndFeel?
Oyoaha.jar can be found in : http://sourceforge.net/projects/oalnf/

A: Either:
OyoahaLookAndFeel laf = new OyoahaLookAndFeel();
UIManager.setLookAndFeel(laf);

or:
...
// get laf class name
System.out.println(laf.getClass().getName());
// prints "com.oyoaha.swing.plaf.oyoaha.OyoahaLookAndFeel"
...
UIManager.setLookAndFeel("com.oyoaha.swing.plaf.oyoaha.OyoahaLookAndFeel");


text:
Q: AT commands in embedded systems I am using embedded C and trying to make application for GPRS terminal. My main problem is working with AT commands. I send AT command using serial line, but if it is some network oriented command its response could take time and because of that I have a lot of waiting, while processor don`t do anything. Idea is to make this waiting to be done in same way parallel like in different thread. Does anyone have idea how to do that because my system does not support threads?
  I had idea to use some timers, because we have interrupt which is called every 5ms, but I don't know ho many seconds I have to wait for response, and if I compare strings in interrupt to check if all message is received it could be very inefficient, right?

A: you could either use interrupts, configure the serial interface to interrupt when data is available, or use an RTOS something, like FreeRTOS, to run two threads, one for the main code and the other to block and wait for the serial data.
Update: based on your comments, you say you don't know the size of the data, that's fine, in the interrupt handler check for the byte that terminates the data, this is a simple and generic example you should check the examples for your MCU:
void on_serial_char()
{
  //disable interrupts
  disable_interrupts();

  //read byte
  byte = serial.read();

  //check if it's the terminating byte
  if (byte == END) {
      //set the flag here
      MESSAGE_COMPLETE = 1;
  }

  //add byte to buffer
  buf[length++] = byte;

  //enable interrupts
  enable_interrupts();
}

And check for that flag in your main loop:
...
if (MESSAGE_COMPLETE) {
    //process data
    ...

    //you may want to clear the flag here
    MESSAGE_COMPLETE = 0;

    //send next command
    ...
}

A: You can simply call a packetHandler in each mainLoopCycle.
This handler checks if new characters are available from the serial port.
The packetHandler will build the response message bit for bit, if the message is complete (CR LF found) then it calls a messageReceive function, else it simply returns to the mainLoop.
int main()
{
  init();
  for (;;)
  {
     packetHandler();
  }
}

char msgBuffer[80];
int pos=0;
void packetHandler()
{
  char ch;
  while ( isCharAvailable() )
  {
    ch=getChar();
    msgBuffer[pos++] = ch;
    if ( ch == '\n' )
    {
       messageReceived(msgBuffer);
       pos=0;
    }
  }
}

A: It sounds like you are rather close to the hardware drivers. If so, the best way is to use DMA, if the MCU supports it, then use the flag from the DMA hardware to determine when to start parse out the received data.
The second best option is to use rx interrupts, store every received byte in a simple FIFO, such as a circular buffer, then set some flag once you have received them. One buffer for incoming data and one for the latest valid data received may be necessary.


text:
Q: wait and notify coordination There is a main thread that has a while loop, in this while he checks for some conditions and if all conditions are met he starts another threads enters wait() state.
Other threads that run in parallel notify the main thread upon work completion.
There is a problem when "sub thread" notifies the main thread before the main thread enters the wait state = dead lock.
What is the best practice to avoid it?

A: Just make sure the main thread doesn't wait for something that has already happened. (Why would anyone do that anyway? It makes no sense.)

A: I would prefer to use Explicit Locks. See Java Concurrent Api.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/Lock.html

A: Use a semaphore for the notification.
That's it, really.  A semaphore has a count and can record the notification until the main thread gets around to waiting on it.

A: The easy answer is to use the concurrency package in Java 5. A CountDownLatch seems suitable here.
If you are limited to a pre Java 5 environment, you will have to create a custom implementation which uses the same algorithm. The main thread would call signalReady after creation of all child threads. The child threads would call signalComplete after completing their work.
A simple implementation would be to have an Object called a Latch with two two member fields.

The below implementation will work for one parent and one child. For additional children, each child could be given its own latch to signal when complete. There would still be cases where this will be race conditions. Adding a spin lock or maybe a sleep between the signalling would reduce the probability of a race conditions. It would not eliminate it

class Latch{
  Object readyLock;
  Object completeLock;

  public void signalComplete(){
    synchronized(readyLock){
      readyLock.wait()
    }
    //spin lock as a precaution
    synchronized(completeLock){
      completeLock.notify()
    }
  }

  public void signalReady(){
    synchronized(readyLock){
      readyLock.notify()
    }
    synchronized(completeLock){
      completeLock.wait()
    }
  }
}

Hope this helps!

A: It is a very common practice to almost always put the wait() method in a while loop whose "iteration condition" is to check whether a particular event has occurred, on occurrence of which the other thread would have called the notify() method.
ex:
while(!event_occurrence) {
    ...
    wait();
    ...
}

where event_occurrence is the event on which the other thread would have called notify() method.


text:
Q: Spectral sequence from a stratification by closed subvarieties I am looking for a reference for the following result: If $X$ is an algebraic variety and
$$X = T_n \supset T_{n-1} \supset \cdots \supset T_{-1} = \varnothing$$
is a stratification (edit: filtration) by closed subvarieties, then there is a spectral sequence
$$E^{p,q}_1 = H^{p+q}_c(T_p \setminus T_{p-1}) \implies H^{p+q}_c(X).$$
Looking for a reference I have found Dan Petersen using it several times here in MathOverflow, such as here, here and here. So what is the specific result and where can I find a proof of it?


text:
Q: How to daily journalctl the status of my systemd units? Once a day I check my units by manually typing these steps:

*

*Search my units

*For each unit I query journalctl --user -u unitname -n
How can I See all my user units status and error if failed?
Not working example of hardcoded units and linenumbers. acme gets skipped: journalctl --user -u foo -u bar -u acme -n
I imagine there must be plenty of cli-tools etc. that solved my problem gracefully, yet I fail to find one.
Note:
-n, --lines Shows the most recent lines...default 10


text:
Q: React Native loops with remote data I have a remote api that gives this data
{ "images" :
    [
    { "image_link" : "http://example.com/image1.png"},
    { "image_link" : "http://example.com/image2.png"},
    ]
}

I have a class with the functions. I have not included constructor here.
componentWillMount() {

    var url = 'https://naren.com/images.json';
    var that = this;
    fetch( url )
        .then((response) => response.json())
        .then((responseJson) => { that.setState({ images : responseJson.images }); })
        .catch((error) => { console.error(error); });
    }

render() {
    return ( <View>
        this.state.images.map(( image, key ) => {
           console.log(image);
           return (
              <View key={key}>
                 <Image source={{ uri : image.image_link }} />
              </View>
           );
            });
       </View>);
        }

I cannot seem to get the images fetched from the api to loop through the view. If I use a static array without the remote source i.e. fetch. THis seems to work perfectly.But when I use the fetch and get data from the api this does not work. I can confirm that I am getting the data because the console.log(image) inside the return statements consoles the expected data.

A: I quickly Simulated this, and it does not seem to have an issue to loop over the Image array and Render each Image.
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native';

export default class ImageLoop extends Component {

  constructor(props){
    super(props)
    this.state = {
      images : []
    }
  }

  componentWillMount() {

    var url = 'https://api.myjson.com/bins/2xu3k';
{/*

or any API that can return the following JSON
{"images":[{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"},{"image_link":"https://facebook.github.io/react/img/logo_og.png"}]}

*/}

var that = this;
        fetch( url )
            .then((response) => response.json())
            .then((responseJson) => {
              console.log('responseJson.images',responseJson.images);
              that.setState({ images : responseJson.images });
            })
            .catch((error) => { console.error(error); });
        }

render() {
  return (
    <View style={{height:100,width:100}}>
      {this.state.images.map((eachImage)=>{
        console.log('Each Image', eachImage);
        return (
          <Image key = {Math.random()} style={{height:100,width:100}} source ={{uri:eachImage.image_link}}/>
        );
      })}
    </View>
   );

    }
}

AppRegistry.registerComponent('ImageLoop', () => ImageLoop);

Please see the output Here: https://rnplay.org/apps/bJcPhQ

A: Try setting a width and a height on the Image style. Because the images come from a remote url, react-native does not know what size it is going to be.
 render() {
    return ( <View>
        this.state.images.map(( image, key ) => {
           console.log(image);
           return (
              <View key={key}>
                 <Image
                   source={{ uri : image.image_link }}
                   style={{ width: 120, height: 120 }}
                 />
              </View>
           );
            });
       </View>);
        }


text:
Q: Alternative Magento Frontend After many months we have reached our frustration point with our Magento 2 migration path - it's a long sad story for a separate thread - so we are seriously considering instead a lightweight custom frontend using our existing Magento 1.7.x database / admin backend.
The benefits we see:

*

*Reduced risk: Existing backend/admin continue to work as usual. No data migration necessary. No staff retraining. Consideration for a future date migration to 1.9.x is a much smaller risk than Magento 2.

*Improved developer experience: We understand our use case and don't need the kitchen sink of flexibility that Magento framework offers and the burden that goes with such. We want an F5 - or livereload - experience that computes under a second, a directory structure with a max depth of 2 or 3, and just simple code.

*Easier to recruit non Magento developers: As we are considering either PHP + a MVC framework, or Node.js  - with session sharing code, and nginx/haproxy handling the backend split - The talent pool of either seems larger than those with Magento specific experience. We also hope this converts to saner estimates time wise when we need to outsource, we've been getting ridiculous quotes for even the most basic of tasks recently.

So at high-level our implementation plan is to handle in our custom frontend - the homepage and other CMS pages, collectively the category, search result and listing page, and the product detail page. These parts are essentially read-only at the request level - excluding recently viewed, logging and session concerns. We will maintain a flat fast read no-EAV database of information required for these parts, for now we have built a one time sync for testing but will probably rely on triggers, or some form of mysql notify  or even code an observer with the m1.7 backend to populate this fast read db as information changes.
We intend to utilize the existing cart, checkout, and account management, and postpone the rewrite, if ever, for these parts to stage 2. Accessing the M1.7 session state was an easy spike outside of Mage::app.
We prototyped the most difficult part early this week - the listing page that touches products (stock, images, parent relationships), category, attributes sets, attributes, and even a third party Amasty plugin for 'better navigation', and it was quite a smooth experience, performant, and almost identical in functionality - we didn't replicate Amasty bugs though.
So it's been a interest week, we go carefully..
Of course we must consider the risk, some things that have come up in discussion:

*

*How can we keep our lightweight frontend simple enough that a new developer can pick it up in a morning, do we risk creating a system like Magento without any community, documentation, third party support

*If we add a new Magento functionality via a module, how much burden are we shouldering by having to implement the frontend part ourselves. Stakeholders have already mentioned a new coupon plugin.

*Can we always figure out the intent from the backend and database tables? Many plugins are obfuscated.

*The time saved is it then spent on documentation and other unconsidered pitfalls.

Have anyone attempted or even considered a custom frontend for Magento before? What were the pitfalls you encountered? What other considerations would you factor into a decision like this?

A: Here's a thread about this topic, it's mainly about magento 2:
Magento 2 as a headless solution
Zefiryn gives some practical insight in his second answer, as he has developed 2 headless magento projects.
I myself also did a 1 week prototype for a headless magento 2 solution with a Polymer Frontend, but my company decided to go the saver route of implementing a full magento stack.
The anwser if you should do such a project or not, of course, heavily depens on your requirements. If you don't rely heavily on third-party extensions, then I can see a headless approach being more effective. I've personally enjoyed working on the prototype much more than working with the horrendous magento frontend.


text:
Q: If Else block trouble I am have trouble with this If ElseIf block and I cannot figure out where the error is.
The message I get is "Else without if".
I am very new to using if elseif any help or guidance would be appreciated.
Line of Error:
ElseIf booSM = True And _
       booInv = True And _
       booHOP = False _
       Then strTo = Me.txtServiceManager.Column(1) & ";" & Me.txtInvestigator.Column(1)

Full code:
Dim txtScan As String
Dim strTo As String
Dim booSM As Boolean
Dim booInv As Boolean
Dim booHOP As Boolean

Me.Refresh
txtScan = Me.txtScanLocation
booSM = booComDocSMSent
booInv = booComDocInvSent
booHOP = booComDocHOPSent

If booSM = True And _
   booInv = True And _
   booHOP = True _
   Then strTo = Me.txtServiceManager.Column(1) & ";" & Me.txtInvestigator.Column(1) & ";" &  Me.txtHop.Column(1)
ElseIf booSM = True And _
       booInv = True And _
       booHOP = False _
       Then strTo = Me.txtServiceManager.Column(1) & ";" & Me.txtInvestigator.Column(1)
ElseIf booSM = True And _
       booInv = False And _
       booHOP = True _
       Then strTo = Me.txtServiceManager.Column(1) & ";" & Me.txtHop.Column(1)
ElseIf booSM = False And _
       booInv = True And _
       booHOP = True _
       Then strTo = Me.txtInvestigator.Column(1) & ";" & Me.txtHop.Column(1)
ElseIf booSM = True And _
       booInv = False And _
       booHOP = False _
       Then strTo = Me.txtServiceManager.Column(1)
ElseIf booSM = False And _
       booInv = True And _
       booHOP = False _
       Then strTo = Me.txtInvestigator.Column(1)
ElseIf booSM = False And _
       booInv = False And _
       booHOP = True _
       Then strTo = Me.txtHop.Column(1)
End If

A: Look into the following logic of If statement code sections:
Sub Logic()
'Attempt 1st
    If a = 1 And _
        b = 1 _
        Then C = 1 'end of if statement

'Attempt 2nd
    If a = 1 And _
        b = 1 _
        Then _
        C = 1 'end of if statement

'Attempt 3rd
    If a = 1 And _
        b = 1 _
        Then
        C = 1 'and continuation below
    ElseIf a = 1 And _
        b = 1 _
        Then
        'something here
    End If
End Sub

There are three different logic of writing if conditions check. in your situation you either missed some _ underline marks or you should move some lines into next line (the code after Then key words).

A: I don't have VBA to hand, but it looks like its a problem with your line endings
The format
if condition then
  statement
elesif conditon
  statement
end if

you are using line continuation ( _ ) and your format looks like
if condition then statement
elseif condition then statement
endif

so
If booSM = True And booInv = True And booHOP = True Then
   strTo = Me.txtServiceManager.Column(1) & ";" & Me.txtInvestigator.Column(1) & ";" &  Me.txtHop.Column(1)
ElseIf booSM = True And booInv = True And booHOP = False Then
  strTo = Me.txtServiceManager.Column(1) & ";" & Me.txtInvestigator.Column(1)
End If

might work better for you
or if you want to keep some multi line formatting
If booSM = True And _
   booInv = True And _
   booHOP = True Then
       strTo = Me.txtServiceManager.Column(1) & ";" & Me.txtInvestigator.Column(1) & ";" &  Me.txtHop.Column(1)
ElseIf booSM = True And _
       booInv = True And _
       booHOP = False _
Then
      strTo = Me.txtServiceManager.Column(1) & ";" & Me.txtInvestigator.Column(1)
End If


text:
Q: bison recursion error with struct pointer I have a simple struct called Polyn like this:
typedef struct Polyn {
  int sign;
  int coeff;
  int exp;
  struct Polyn *next;
} Polyn;

In my bison grammar for recursively building polynomials I only get the first and last element. I use these functions to add and make terms with the Polyn struct:

Polyn *addmonomial(Polyn *pol, Polyn *monom) {
    pol -> next = monom;
    return pol;
}

So for a=1x2+2x+3, it only gives me 1x2+3.
The recursion will only build the first and last elements. I don't know whether to change the return value of the add function or how to change the grammar so the middle terms are included.
It seems like the problem is $1 in my last two recursive rules is always the first term and doesn't become the middle terms. I need to return the first term for my other grammar rules but also build the polynomial.
    |poln T_PLUS poln   { $$ = addmonomial($1, $3);}
    |poln T_MINUS poln  { Polyn *p2n = negate($3); $$ = addmonomial($1, p2n); }

A: Polyn *addmonomial(Polyn *pol, Polyn *monom) {
    pol -> next = monom;
    return pol;
}

This will override the existing value of next if pol already has a next value. So if pol represent the expression 1x2+2x and monom represents 3, then the 2x part will be overridden by 1.

A: Get rid of your addmonomial function and instead use an addpolynomial function.  While you're at it, get rid of the sign field, it is redundant with the sign of the coeff field.  You might also want to make the coeff field a double rather than an int.
Your addpolynomial function should merge the two linked lists of terms, combining terms with the same exponent.  Probably easiest if you always keep them sorted in exponent order.


text:
Q: forget widgets inside a PanedWindow in Tkinter since from what I understood in Tkinter the PanedWindow widget is such that what goes inside doesnt have to be packed/gridded, but added to the parent, e.g.
pwin = PanedWindow()
pwin.pack()
top = Label(pwin, text="top pane")
pwin.add(top)
bottom = Label(pwin, text="bottom pane")
pwin.add(bottom)

how can I have inside it (pwin) objects that I want to make appear/disappear, since I usually do this by .pack()/.pack_forget() ?

A: PanedWindow have a forgetmethod accepting a widget as parameter.
In your example, you migh use pwin.forget(bottom).


text:
Q: How to merge values inside stateless component? Updating a state variable always replaces it instead of merging it. How can I merge it? Function addFruits receives multiple objects like:
{fruitName: banana} {fruitName: apple} {fruitName: watermelon}

How to push this fruitName's into fruits state?
My code returns only the last fruitName. But how to merge all fruitNames like array.push(val);
const [fruits, setFruits] = useState([]); // this is the state

    function addFruits(value){
    Api.get(`${PATH.GET_SELECTED_FRUITS}/${value}/fruits`).then(res => { // this method gives me multiple object, (like {fruitName: banana} {fruitName: apple} {fruitName: watermelon})
        res.map(result => {
            setProps(result.fruitName);
        })
    })
}

A: You need to combine the existing fruits array with the result from the API:
.then((res) => {
  setFruits([
    ...fruits,
    ...res.map(fruit => fruit.fruitName)
  ]);
});

A: You can merge the response with the state -
function addFruits(value){
    Api.get(`${PATH.GET_SELECTED_FRUITS}/${value}/fruits`).then(response => {
           totalFruits = [...fruits,
             ...response.map(fruit => fruit.fruitName)]
          setFruits(totalFruits);
        })
    })


text:
Q: Sftp adapter file size limit I need to filter out files that are too large (1MB) before downloading from remote SFTP server.
What kind of filter should I use? Is it possible to check file size before download (and if it is too large send an Error)?

A: I found answer.
private FileListFilter<ChannelSftp.LsEntry> filter() {
    return files -> Arrays.stream(files)
            .filter(file -> file.getAttrs().getSize() < 0)
            .collect(Collectors.toList());
}


text:
Q: Why is my Variable set to 0? import java.lang.Math;
public class NewtonIteration {

    public static void main(String[] args) {
        System.out.print(rootNofX(2,9));
    }

    // computes x^n
    public static double power(double x, int n) {
        if (n==0) {
            return 1;
        }
        double Ergebnis = 1;
        for (int i=0; i<=Math.abs(n)-1; i++) {
            Ergebnis *= x;
        }
        if (n<0) {
            Ergebnis = 1/Ergebnis;
        }

        return Ergebnis;
    }

    // computes x^(1/n)
    public static double rootNofX(int n, double x) {
        return power(x, 1/n);
    }
}

Whenever power(x,1/n) is called, n is reset to 0. But isn't n a parameter given to rootNofX with the value 2?

A: Try:
// computes x^(1/n)
    public static double rootNofX(int n, double x) {
        return power(x, 1.0/n);
    }
Because 1 is an int and n is an int so 1/n is an integer division which return 0 when n is not 1 and throw error when n is 0.
1.0 is a double so it make 1.0/n a double division that you want.

A: 1/n is going to be a fraction, usually, but in the declaration of power you declare n to be integer. That's going to knock off the decimal places every time!

A: It's because power is defined with "n" as an int so 1/n will always be less than 1 which will be zero when stored as an int. Update "int n" to "double n". Example below:
public static double power(double x, double n) { ... }

A: It's because you're using integers, so 1 / 2 = 0.5 which as an integer is 0. Change the prototypes to rootNofx(double n, double x) and power(double x, double n).
Also, since rootNofx uses power, in my opinion, it would be better to have the parameters ordered the same way, to avoid confusion.

A: The problem is that you are passing 1/2 from rootNofX into an int, so it becomes zero.

A: There is a big difference between 1/n and 1.0/n
Consider what declaring n to be an int really means...


text:
Q: Order of elements in group Given $G$ is a group, and $ab=ba$ for $a,b\in G$, we know $o(a)=12,o(b)=18$, in order to calculate $o(ab),o(ab^2),o(a^2b^3)$.
Do we need to assume group is a cyclic group in order to use formula $o(g^k)\mathbb{gcd}(n,k)=n$ for $g$ is a generator and $n=|G|$ ?
Or is there some other way to calculate ? Because in the method above, we don't use value of $o(a),o(b)$ at all.

A: Using commutativity, the following inelegant method seems to work for the first one (as an example of how to proceed):
For $ab$ we know that $(ab)^{36}=a^{36}b^{36}=1$ so $o(ab)|36$
Suppose $o(ab)=2$ then $(ab)^2=1 \implies (ab)^{12}=1\implies b^{12}=1$ and similarly for if $o(ab)=r$ for some $r|12$ (contradicts $o(b)=18$).
Suppose $o(ab)=9$ then $(ab)^9=1 \implies (ab)^{18}=1\implies a^{18}=a^6=1$ and similarly for if $o(ab)=r$ for some $r|18$ (contradicts $o(a)=12$).


text:
Q: C pointer shenanigans I'm trying to implement a Queue in C (using a Linked List) to store pointers to data.  The en-queuing seems to be working fine, but some trouble with pointers upon de-queuing.
In my main():
void* data = malloc(sizeof(int));
dequeue(&Q, data);
printf("(%d) %d\n", k, *(int*)data);

dequeue():
int dequeue(struct queue *q, void *value)
{
    struct queue_node *tmp;

    if (!q->first) {
        value = 0;
        return 1;
    }
    value = q->first->data;
    tmp = q->first;
    if (q->first == q->last)
        q->first = q->last = NULL;
    else
        q->first = q->first->next;

    free(tmp);
    return 0;
}

Based on my debugging, it seems that the value of the *data pointer in the main() for loop doesn't retain the value that it's set to in dequeue().  What am I missing?
Edit:
struct queue_node
{
    struct queue_node *next;
    void* data;
};

struct queue
{
    struct queue_node *first;
    struct queue_node *last;
};

A: You're setting the value of the "value" variable, which is a pointer local to the function.
If you want to set the value to which it points, use:
*value = 0;

and:
*value = q->first->data;

Edit (after question edit): Since queue_node.data is itself a pointer, it makes more sense to pass a void**, as @Andrei notes above.

A: The queue_node's data holds a pointer to some value (here it is an int, but it may not be true always, otherwise you'd use an int instead...)
Since this value was allocated with malloc (and is not a local variable) you need to also free it at some point.
So, change the function's signature to accept a void**, don't allocate space for an int in main() but call dequeue with &data as a parameter, where void * data = 0. Don't forget to free data when done.
In dequeue, set *value = q->first->data.

A: Assuming data is a (void *) and you want the (int) value pointed to by data, you'll have to replace
value = q->first->data;
with
*(int *)value = *(int *)q->first->data;
in the function deque();