问:
Access the parent object of an object in PHP
This is my test code:

```<code>class Base
{
    public $property;

    public function method() {
        return 456;
    }

    public function setProperty($value) {
        $this->property = $value;
    }
}

class Derived extends Base
{
    public function method() {
        return 789;
    }
}

$derived = new Derived;
$derived->setProperty(123);

$base = getParentInstance($derived);

echo $base->property; // Should print 123
echo $base->method(); // Should print 456
</code>```

Looking around I found a lot of stuff related but nothing direct to the point. I just need to cast an instance to an ancestor class. Is this even possible on PHP?

Up to now I came out with this wrong code that (I think) just instantiate a new Base class:

```<code>function getParentInstance($object)
{
    $reflection = new ReflectionObject($object);
    $parent_class = $reflection->getParentClass();
    return $parent_class->newInstanceWithoutConstructor();
}
</code>```

Another complication is I can only modify Derived... Base is provided by an external framework.

Addendum

Here is the proof what I'm requesting is not absurd. Same code in C++:

```<code>class Base
{
public:
    int property;

    int method() {
        return 456;
    }

    void setProperty(int value) {
        this->property = value;
    }
};

class Derived: public Base
{
public:
    int method() {
        return 789;
    }
};

#include <iostream>
int main()
{
    Derived *derived = new Derived;
    derived->setProperty(123);

    Base *base = (Base *) derived; // Is **this** possible in PHP?

    std::cout << base->property; // It prints 123
    std::cout << base->method(); // It prints 456

    return 0;
}
</code>```

答:
Just figured I would put this here since it sort of answers the question. While there is not an instantiated Base object you still have access to parent data through php's parent.

I am not 100% sure what the attempt here is but you could use it like

```<code>//No changes to Base

class Derived extends Base {
    public function method($p=false) {//Adding a flag
        if($p){// true mean you want the parent method
            return parent::method(); //Use parent:: to call that method
        } else { //False do your own thing
            return 'def';
        }
    }
}

$derived = new Derived;

$derived->setProperty(123);

echo $derived->property; // Print 123

echo $derived->method(); // Prints def

echo $derived->method(false); // Prints def

echo $derived->method(true); // Prints 456
</code>```

This is strange but one way to at least get the expectations.

Also, the easiest way is to not overwrite your parent method when parent and child function differently.

```<code>//No changes to Base

class Derived extends Base {
    public function child_method() {
        return 'def';
    }
}

$derived = new Derived;

$derived->setProperty(123);

echo $derived->property; // Print 123

echo $derived->method(); // Prints 456

echo $derived->child_method(false); // Prints def
</code>```

Body:
This is my test code:

class Base
{
    public $property;

    public function method() {
        return 456;
    }

    public function setProperty($value) {
        $this->property = $value;
    }
}

class Derived extends Base
{
    public function method() {
        return 789;
    }
}

$derived = new Derived;
$derived->setProperty(123);

$base = getParentInstance($derived);

echo $base->property; // Should print 123
echo $base->method(); // Should print 456

Looking around I found a lot of stuff related but nothing direct to the point. I just need to cast an instance to an ancestor class. Is this even possible on PHP?

Up to now I came out with this wrong code that (I think) just instantiate a new Base class:

function getParentInstance($object)
{
    $reflection = new ReflectionObject($object);
    $parent_class = $reflection->getParentClass();
    return $parent_class->newInstanceWithoutConstructor();
}

Another complication is I can only modify Derived... Base is provided by an external framework.

Addendum

Here is the proof what I'm requesting is not absurd. Same code in C++:

class Base
{
public:
    int property;

    int method() {
        return 456;
    }

    void setProperty(int value) {
        this->property = value;
    }
};

class Derived: public Base
{
public:
    int method() {
        return 789;
    }
};

#include <iostream>
int main()
{
    Derived *derived = new Derived;
    derived->setProperty(123);

    Base *base = (Base *) derived; // Is **this** possible in PHP?

    std::cout << base->property; // It prints 123
    std::cout << base->method(); // It prints 456

    return 0;
}

Body:
Just figured I would put this here since it sort of answers the question. While there is not an instantiated Base object you still have access to parent data through php's parent.

I am not 100% sure what the attempt here is but you could use it like

//No changes to Base

class Derived extends Base {
    public function method($p=false) {//Adding a flag
        if($p){// true mean you want the parent method
            return parent::method(); //Use parent:: to call that method
        } else { //False do your own thing
            return 'def';
        }
    }
}

$derived = new Derived;

$derived->setProperty(123);

echo $derived->property; // Print 123

echo $derived->method(); // Prints def

echo $derived->method(false); // Prints def

echo $derived->method(true); // Prints 456

This is strange but one way to at least get the expectations.

Also, the easiest way is to not overwrite your parent method when parent and child function differently.

//No changes to Base

class Derived extends Base {
    public function child_method() {
        return 'def';
    }
}

$derived = new Derived;

$derived->setProperty(123);

echo $derived->property; // Print 123

echo $derived->method(); // Prints 456

echo $derived->child_method(false); // Prints def


来源: stackexchange

问:
Numpy delete rows of array inside object array
I am trying to delete rows from arrays which are stored inside an object array in numpy. However as you can see it complains that it cannot broadcast the smaller array into the larger array. Works fine when done directly to the array. What is the issue here? Any clean way around this error other than making a new object array and copying one by one until the array I want to modify?

```<code>In [1]: import numpy as np

In [2]: x = np.zeros((3, 2))

In [3]: x = np.delete(x, 1, axis=0)

In [4]: x
Out[4]:
array([[ 0.,  0.],
       [ 0.,  0.]])

In [5]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [6]: x[0] = np.delete(x[0], 1, axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-1687d284d03c> in <module>()
----> 1 x[0] = np.delete(x[0], 1, axis=0)

ValueError: could not broadcast input array from shape (2,2) into shape (3,2)
</code>```

Edit: Apparently it works when arrays are different shape. This is quite annoying. Any way to disable automatic concatenation by np.array?

```<code>In [12]: x = np.array([np.zeros((3, 2)), np.zeros((5, 8))], dtype=object)

In [13]: x[0] = np.delete(x[0], 1, axis=0)

In [14]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [15]: x.shape
Out[15]: (2, 3, 2)

In [16]: x = np.array([np.zeros((3, 2)), np.zeros((5, 8))], dtype=object)

In [17]: x.shape
Out[17]: (2,)
</code>```

This is some quite inconsistent behaviour.

答:
The fact that np.array creates as high a dimensional array as it can has been discussed many times on SO.  If the elements are different in size it will keep them separate, or in some cases raise an error.

In your example

```<code>In [201]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)
In [202]: x
Out[202]:
array([[[0.0, 0.0],
        [0.0, 0.0],
        [0.0, 0.0]],

       [[0.0, 0.0],
        [0.0, 0.0],
        [0.0, 0.0]]], dtype=object)
</code>```

The safe way to make an object array of a determined size is to initialize it and then fill it:

```<code>In [203]: x=np.empty(2, dtype=object)
In [204]: x
Out[204]: array([None, None], dtype=object)
In [205]: x[...] = [np.zeros((3, 2)), np.zeros((3, 2))]
In [206]: x
Out[206]:
array([array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]]),
       array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])], dtype=object)
</code>```

A 1d object array like this, is, for most practical purposes a list.  Operations on the elements are performed with Python level iteration, implicit or explicit (as with your list comprehension).  Most of the computational power of a multidimensional numeric array is gone.

```<code>In [207]: x.shape
Out[207]: (2,)
In [208]: [xx.shape for xx in x]   # shape of the elements
Out[208]: [(3, 2), (3, 2)]
In [209]: [xx[:2,:] for xx in x]    # slice the elements
Out[209]:
[array([[ 0.,  0.],
        [ 0.,  0.]]), array([[ 0.,  0.],
        [ 0.,  0.]])]
</code>```

You can reshape such an array, but you can't append as if it were a list.  Some math operations cross the 'object' boundary, but it is hit-and-miss.  In sum, don't use object arrays when a list would work just as well.

Understanding non-homogeneous numpy arrays

ContentLicense: CC BY-SA 3.0

Body:
I am trying to delete rows from arrays which are stored inside an object array in numpy. However as you can see it complains that it cannot broadcast the smaller array into the larger array. Works fine when done directly to the array. What is the issue here? Any clean way around this error other than making a new object array and copying one by one until the array I want to modify?

In [1]: import numpy as np

In [2]: x = np.zeros((3, 2))

In [3]: x = np.delete(x, 1, axis=0)

In [4]: x
Out[4]:
array([[ 0.,  0.],
       [ 0.,  0.]])

In [5]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [6]: x[0] = np.delete(x[0], 1, axis=0)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-1687d284d03c> in <module>()
----> 1 x[0] = np.delete(x[0], 1, axis=0)

ValueError: could not broadcast input array from shape (2,2) into shape (3,2)

Edit: Apparently it works when arrays are different shape. This is quite annoying. Any way to disable automatic concatenation by np.array?

In [12]: x = np.array([np.zeros((3, 2)), np.zeros((5, 8))], dtype=object)

In [13]: x[0] = np.delete(x[0], 1, axis=0)

In [14]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)

In [15]: x.shape
Out[15]: (2, 3, 2)

In [16]: x = np.array([np.zeros((3, 2)), np.zeros((5, 8))], dtype=object)

In [17]: x.shape
Out[17]: (2,)

This is some quite inconsistent behaviour.

Body:
The fact that np.array creates as high a dimensional array as it can has been discussed many times on SO.  If the elements are different in size it will keep them separate, or in some cases raise an error.

In your example

In [201]: x = np.array([np.zeros((3, 2)), np.zeros((3, 2))], dtype=object)
In [202]: x
Out[202]:
array([[[0.0, 0.0],
        [0.0, 0.0],
        [0.0, 0.0]],

       [[0.0, 0.0],
        [0.0, 0.0],
        [0.0, 0.0]]], dtype=object)

The safe way to make an object array of a determined size is to initialize it and then fill it:

In [203]: x=np.empty(2, dtype=object)
In [204]: x
Out[204]: array([None, None], dtype=object)
In [205]: x[...] = [np.zeros((3, 2)), np.zeros((3, 2))]
In [206]: x
Out[206]:
array([array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]]),
       array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])], dtype=object)

A 1d object array like this, is, for most practical purposes a list.  Operations on the elements are performed with Python level iteration, implicit or explicit (as with your list comprehension).  Most of the computational power of a multidimensional numeric array is gone.

In [207]: x.shape
Out[207]: (2,)
In [208]: [xx.shape for xx in x]   # shape of the elements
Out[208]: [(3, 2), (3, 2)]
In [209]: [xx[:2,:] for xx in x]    # slice the elements
Out[209]:
[array([[ 0.,  0.],
        [ 0.,  0.]]), array([[ 0.,  0.],
        [ 0.,  0.]])]

You can reshape such an array, but you can't append as if it were a list.  Some math operations cross the 'object' boundary, but it is hit-and-miss.  In sum, don't use object arrays when a list would work just as well.

Understanding non-homogeneous numpy arrays


问:
Invalid Object name ##Temp Error when creating a global temporary table
I have data in a couple tables that I want to load into a temporary table in SQL Server.

I am creating a stored procedure that gets the data from the tables. Then I create the global temporary table and insert the results from the stored procedure into it.

However when trying to select the data from the temporary table I get this error
'Invalid object name ##Temp'

Why am I getting this error if it is a global temporary table?

```<code>DROP PROCEDURE usp_GetEmp
GO
CREATE PROCEDURE usp_GetEmp
AS
BEGIN
    SELECT table1.id AS Id
      , table2.data AS table2_value
  FROM table1 INNER JOIN table2
  ON table1.id = table2.table1_id
  WHERE table2.data = 1
END

  CREATE TABLE ##Temp
  ( Id Int
  , Value varchar(50))

  INSERT INTO ##Temp
  EXEC usp_GetEmp
  GO

  SELECT *
  FROM ##Temp
</code>```

答:
Try it's</p>

```<code>DROP PROCEDURE USP_GETEMP
GO
CREATE PROCEDURE USP_GETEMP
AS
BEGIN
SELECT
    TABLE1.ID AS ID
    ,TABLE2.DATA AS TABLE2_VALUE
FROM TABLE1 INNER JOIN TABLE2
ON TABLE1.ID = TABLE2.TABLE1_ID
WHERE TABLE2.DATA = 1
END
GO

IF OBJECT_ID('TEMPDB.DBO.##TEMP') IS NOT NULL
DROP TABLE ##TEMP
GO
CREATE TABLE ##TEMP
( ID INT
, VALUE VARCHAR(50))

INSERT INTO ##TEMP
EXEC USP_GETEMP
GO

SELECT *
FROM ##TEMP
</code>```

Body:
I have data in a couple tables that I want to load into a temporary table in SQL Server.

I am creating a stored procedure that gets the data from the tables. Then I create the global temporary table and insert the results from the stored procedure into it.

However when trying to select the data from the temporary table I get this error
'Invalid object name ##Temp'

Why am I getting this error if it is a global temporary table?

DROP PROCEDURE usp_GetEmp
GO
CREATE PROCEDURE usp_GetEmp
AS
BEGIN
    SELECT table1.id AS Id
      , table2.data AS table2_value
  FROM table1 INNER JOIN table2
  ON table1.id = table2.table1_id
  WHERE table2.data = 1
END

  CREATE TABLE ##Temp
  ( Id Int
  , Value varchar(50))

  INSERT INTO ##Temp
  EXEC usp_GetEmp
  GO

  SELECT *
  FROM ##Temp

Body:
Try it's

DROP PROCEDURE USP_GETEMP
GO
CREATE PROCEDURE USP_GETEMP
AS
BEGIN
SELECT
    TABLE1.ID AS ID
    ,TABLE2.DATA AS TABLE2_VALUE
FROM TABLE1 INNER JOIN TABLE2
ON TABLE1.ID = TABLE2.TABLE1_ID
WHERE TABLE2.DATA = 1
END
GO

IF OBJECT_ID('TEMPDB.DBO.##TEMP') IS NOT NULL
DROP TABLE ##TEMP
GO
CREATE TABLE ##TEMP
( ID INT
, VALUE VARCHAR(50))

INSERT INTO ##TEMP
EXEC USP_GETEMP
GO

SELECT *
FROM ##TEMP


问:
get process id and parent process in solaris kernel module
In solaris 11.0 kernel module driver, I need to get the parent process id and start time, and continue doing it - climb up the process tree this way.

in Linux kernel I have struct_task contains process id, start time.

What is equivelant to struct_task, and how I can get it within process context ?

Thanks

I saw something like what i need but for userspace. but "open" cannot be used in kernel space..

```<code>char psfile[64];
pid_t pid;
int fd;
psinfo_t psinfo;
pid = getpid();
sprintf(psfile, "/proc/%d/psinfo", pid);
if ((fd = open(psfile, O_RDONLY)) >= 0) {
if (read(fd, &psinfo, sizeof(psinfo_t)) != -1) {
printf("Pid: %ld\n", psinfo.pr_pid);
printf("Up Start: (%ld, %ld)\n", psinfo.pr_start.tv_sec,
psinfo.pr_start.tv_nsec);
printf("Command: %s\n", psinfo.pr_fname);
return 0;
}
} else {
perror("Open psfino");
}
</code>```

the whole concept of /proc/procid/psinfo is to allow userspace processes to read kernel data. Since im at kernel space, i need to get the data from /proc/procid/psinfo if im on kernel space, this is disk IO i avoid...

答:
If you look in /usr/include/sys/thread.h, you'll see the macro currproc defined:

```<code>#define curproc     (ttoproc(curthread))    /* current process pointer */
</code>```

That returns a struct proc * that if non-null refers to the current process.

The definition of struct proc can be found in /usr/include/sys/proc.h:

```<code>/*
 * One structure allocated per active process.  It contains all
 * data needed about the process while the process may be swapped
 * out.  Other per-process data (user.h) is also inside the proc structure.
 * Lightweight-process data (lwp.h) and the kernel stack may be swapped out.
 */
typedef struct  proc {
    /*
     * Fields requiring no explicit locking
     */
    struct  vnode *p_exec;      /* pointer to a.out vnode */
    struct  as *p_as;       /* process address space pointer */
    struct  plock *p_lockp;     /* ptr to proc struct's mutex lock */
    kmutex_t p_crlock;      /* lock for p_cred */
    struct  cred    *p_cred;    /* process credentials */
    /*
     * Fields protected by pidlock
     */
    int p_swapcnt;      /* number of swapped out lwps */
    char    p_stat;         /* status of process */
    char    p_wcode;        /* current wait code */
    ushort_t p_pidflag;     /* flags protected only by pidlock */
    int     p_wdata;        /* current wait return value */
    pid_t   p_ppid;         /* process id of parent */
    struct  proc    *p_link;    /* forward link */
    struct  proc    *p_parent;  /* ptr to parent process */
    struct  proc    *p_child;   /* ptr to first child process */
    struct  proc    *p_sibling; /* ptr to next sibling proc on chain */
    struct  proc    *p_psibling;    /* ptr to prev sibling proc on chain */
    struct  proc    *p_sibling_ns;  /* prt to siblings with new state */
    struct  proc    *p_child_ns;    /* prt to children with new state */
    struct  proc    *p_next;    /* active chain link next */
    struct  proc    *p_prev;    /* active chain link prev */
    struct  proc    *p_nextofkin;   /* gets accounting info at exit */
    struct  proc    *p_orphan;
    struct  proc    *p_nextorph;
    struct  proc    *p_pglink;  /* process group hash chain link next */
    struct  proc    *p_ppglink; /* process group hash chain link prev */
    struct  sess    *p_sessp;   /* session information */
    struct  pid     *p_pidp;    /* process ID info */
    struct  pid     *p_pgidp;   /* process group ID info */
    /*
     * Fields protected by p_lock
     */
    kcondvar_t p_cv;        /* proc struct's condition variable */
    kcondvar_t p_flag_cv;
    kcondvar_t p_lwpexit;       /* waiting for some lwp to exit */
    kcondvar_t p_holdlwps;      /* process is waiting for its lwps */
                    /* to to be held.  */
    uint_t  p_proc_flag;        /* /proc-related flags */
    uint_t  p_flag;         /* protected while set. */
                    /* flags defined below */
    clock_t p_utime;        /* user time, this process */
    clock_t p_stime;        /* system time, this process */
    clock_t p_cutime;       /* sum of children's user time */
    clock_t p_cstime;       /* sum of children's system time */
    avl_tree_t *p_segacct;      /* System V shared segment list */
    avl_tree_t *p_semacct;      /* System V semaphore undo list */
    caddr_t p_bssbase;      /* base addr of last bss below heap */
    caddr_t p_brkbase;      /* base addr of heap */
    size_t  p_brksize;      /* heap size in bytes */
    uint_t  p_brkpageszc;       /* preferred heap max page size code */
    /*
     * Per process signal stuff.
     */
    k_sigset_t p_sig;       /* signals pending to this process */
    k_sigset_t p_extsig;        /* signals sent from another contract */
    k_sigset_t p_ignore;        /* ignore when generated */
    k_sigset_t p_siginfo;       /* gets signal info with signal */
    void *p_sigfd;          /* signalfd support state */
    struct sigqueue *p_sigqueue;    /* queued siginfo structures */
    struct sigqhdr *p_sigqhdr;  /* hdr to sigqueue structure pool */
    struct sigqhdr *p_signhdr;  /* hdr to signotify structure pool */
    uchar_t p_stopsig;      /* jobcontrol stop signal */

    /*
     * Special per-process flag when set will fix misaligned memory
     * references.
     */
    char    p_fixalignment;

    /*
     * Per process lwp and kernel thread stuff
     */
    id_t    p_lwpid;        /* most recently allocated lwpid */
    int     p_lwpcnt;       /* number of lwps in this process */
    int p_lwprcnt;      /* number of not stopped lwps */
    int p_lwpdaemon;        /* number of TP_DAEMON lwps */
    int p_lwpwait;      /* number of lwps in lwp_wait() */
    int p_lwpdwait;     /* number of daemons in lwp_wait() */
    int p_zombcnt;      /* number of zombie lwps */
    kthread_t *p_tlist;     /* circular list of threads */
    lwpdir_t *p_lwpdir;     /* thread (lwp) directory */
    lwpdir_t *p_lwpfree;        /* p_lwpdir free list */
    tidhash_t *p_tidhash;       /* tid (lwpid) lookup hash table */
    uint_t  p_lwpdir_sz;        /* number of p_lwpdir[] entries */
    uint_t  p_tidhash_sz;       /* number of p_tidhash[] entries */
    ret_tidhash_t *p_ret_tidhash;   /* retired tidhash hash tables */
    uint64_t p_lgrpset;     /* unprotected hint of set of lgrps */
                    /* on which process has threads */
    volatile lgrp_id_t  p_t1_lgrpid; /* main's thread lgroup id */
    volatile lgrp_id_t  p_tr_lgrpid; /* text replica's lgroup id */
#if defined(_LP64)
    uintptr_t  p_lgrpres2;      /* reserved for lgrp migration */
#endif
    /*
     * /proc (process filesystem) debugger interface stuff.
     */
    k_sigset_t p_sigmask;       /* mask of traced signals (/proc) */
    k_fltset_t p_fltmask;       /* mask of traced faults (/proc) */
    struct vnode *p_trace;      /* pointer to primary /proc vnode */
    struct vnode *p_plist;      /* list of /proc vnodes for process */
    kthread_t *p_agenttp;       /* thread ptr for /proc agent lwp */
    avl_tree_t p_warea;     /* list of watched areas */
    avl_tree_t p_wpage;     /* remembered watched pages (vfork) */
    watched_page_t *p_wprot;    /* pages that need to have prot set */
    int p_mapcnt;       /* number of active pr_mappage()s */
    kmutex_t p_maplock;     /* lock for pr_mappage() */
    struct  proc  *p_rlink;     /* linked list for server */
    kcondvar_t p_srwchan_cv;
    size_t  p_stksize;      /* process stack size in bytes */
    uint_t  p_stkpageszc;       /* preferred stack max page size code */

    /*
     * Microstate accounting, resource usage, and real-time profiling
     */
    hrtime_t p_mstart;      /* hi-res process start time */
    hrtime_t p_mterm;       /* hi-res process termination time */
    hrtime_t p_mlreal;      /* elapsed time sum over defunct lwps */
    hrtime_t p_acct[NMSTATES];  /* microstate sum over defunct lwps */
    hrtime_t p_cacct[NMSTATES]; /* microstate sum over child procs */
    struct lrusage p_ru;        /* lrusage sum over defunct lwps */
    struct lrusage p_cru;       /* lrusage sum over child procs */
    struct itimerval p_rprof_timer; /* ITIMER_REALPROF interval timer */
    uintptr_t p_rprof_cyclic;   /* ITIMER_REALPROF cyclic */
    uint_t  p_defunct;      /* number of defunct lwps */
    /*
     * profiling. A lock is used in the event of multiple lwp's
     * using the same profiling base/size.
     */
    kmutex_t p_pflock;      /* protects user profile arguments */
    struct prof p_prof;     /* profile arguments */

    /*
     * Doors.
     */
    door_pool_t     p_server_threads; /* common thread pool */
    struct door_node    *p_door_list;   /* active doors */
    struct door_node    *p_unref_list;
    kcondvar_t      p_unref_cv;
    char            p_unref_thread; /* unref thread created */

    /*
     * Kernel probes
     */
    uchar_t         p_tnf_flags;

    /*
     * Solaris Audit
     */
    struct p_audit_data *p_audit_data; /* per process audit structure */

    pctxop_t    *p_pctx;

#if defined(__x86)
    /*
     * LDT support.
     */
    kmutex_t    p_ldtlock;  /* protects the following fields */
    user_desc_t *p_ldt;     /* Pointer to private LDT */
    system_desc_t   p_ldt_desc; /* segment descriptor for private LDT */
    ushort_t    p_ldtlimit; /* highest selector used */
#endif
    size_t p_swrss;         /* resident set size before last swap */
    struct aio  *p_aio;     /* pointer to async I/O struct */
    struct itimer   **p_itimer; /* interval timers */
    timeout_id_t    p_alarmid;  /* alarm's timeout id */
    caddr_t     p_usrstack; /* top of the process stack */
    uint_t      p_stkprot;  /* stack memory protection */
    uint_t      p_datprot;  /* data memory protection */
    model_t     p_model;    /* data model determined at exec time */
    struct lwpchan_data *p_lcp; /* lwpchan cache */
    kmutex_t    p_lcp_lock; /* protects assignments to p_lcp */
    utrap_handler_t *p_utraps;  /* pointer to user trap handlers */
    struct corectl_path *p_corefile;    /* pattern for core file */
    struct task *p_task;    /* our containing task */
    struct proc *p_taskprev;    /* ptr to previous process in task */
    struct proc *p_tasknext;    /* ptr to next process in task */
    kmutex_t    p_sc_lock;  /* protects p_pagep */
    struct sc_page_ctl *p_pagep;    /* list of process's shared pages */
    struct rctl_set *p_rctls;   /* resource controls for this process */
    rlim64_t    p_stk_ctl;  /* currently enforced stack size */
    rlim64_t    p_fsz_ctl;  /* currently enforced file size */
    rlim64_t    p_vmem_ctl; /* currently enforced addr-space size */
    rlim64_t    p_fno_ctl;  /* currently enforced file-desc limit */
    pid_t       p_ancpid;   /* ancestor pid, used by exacct */
    struct itimerval p_realitimer;  /* real interval timer */
    timeout_id_t    p_itimerid; /* real interval timer's timeout id */
    struct corectl_content *p_content;  /* content of core file */

    avl_tree_t  p_ct_held;  /* held contracts */
    struct ct_equeue **p_ct_equeue; /* process-type event queues */

    struct cont_process *p_ct_process; /* process contract */
    list_node_t p_ct_member;    /* process contract membership */
    sigqueue_t  *p_killsqp; /* sigqueue pointer for SIGKILL */

    int     p_dtrace_probes; /* are there probes for this proc? */
    uint64_t    p_dtrace_count; /* number of DTrace tracepoints */
                    /* (protected by P_PR_LOCK) */
    void        *p_dtrace_helpers; /* DTrace helpers, if any */
    struct pool *p_pool;    /* pointer to containing pool */
    kcondvar_t  p_poolcv;   /* synchronization with pools */
    uint_t      p_poolcnt;  /* # threads inside pool barrier */
    uint_t      p_poolflag; /* pool-related flags (see below) */
    uintptr_t   p_portcnt;  /* event ports counter */
    struct zone *p_zone;    /* zone in which process lives */
    struct vnode    *p_execdir; /* directory that p_exec came from */
    struct brand    *p_brand;   /* process's brand  */
    void        *p_brand_data;  /* per-process brand state */
    psecflags_t p_secflags; /* per-process security flags */

    /* additional lock to protect p_sessp (but not its contents) */
    kmutex_t p_splock;
    rctl_qty_t  p_locked_mem;   /* locked memory charged to proc */
                    /* protected by p_lock */
    rctl_qty_t  p_crypto_mem;   /* /dev/crypto memory charged to proc */
                    /* protected by p_lock */
    clock_t p_ttime;        /* buffered task time */

    /*
     * The user structure
     */
    struct user p_user;     /* (see sys/user.h) */
} proc_t;
</code>```

So your current process id is curproc->p_pidp->pid_id and the parent process id is curproc->p_ppid.

Body:
In solaris 11.0 kernel module driver, I need to get the parent process id and start time, and continue doing it - climb up the process tree this way.

in Linux kernel I have struct_task contains process id, start time.

What is equivelant to struct_task, and how I can get it within process context ?

Thanks

I saw something like what i need but for userspace. but "open" cannot be used in kernel space..

char psfile[64];
pid_t pid;
int fd;
psinfo_t psinfo;
pid = getpid();
sprintf(psfile, "/proc/%d/psinfo", pid);
if ((fd = open(psfile, O_RDONLY)) >= 0) {
if (read(fd, &psinfo, sizeof(psinfo_t)) != -1) {
printf("Pid: %ld\n", psinfo.pr_pid);
printf("Up Start: (%ld, %ld)\n", psinfo.pr_start.tv_sec,
psinfo.pr_start.tv_nsec);
printf("Command: %s\n", psinfo.pr_fname);
return 0;
}
} else {
perror("Open psfino");
}

the whole concept of /proc/procid/psinfo is to allow userspace processes to read kernel data. Since im at kernel space, i need to get the data from /proc/procid/psinfo if im on kernel space, this is disk IO i avoid...

Body:
If you look in /usr/include/sys/thread.h, you'll see the macro currproc defined:

#define curproc     (ttoproc(curthread))    /* current process pointer */

That returns a struct proc * that if non-null refers to the current process.

The definition of struct proc can be found in /usr/include/sys/proc.h:

/*
 * One structure allocated per active process.  It contains all
 * data needed about the process while the process may be swapped
 * out.  Other per-process data (user.h) is also inside the proc structure.
 * Lightweight-process data (lwp.h) and the kernel stack may be swapped out.
 */
typedef struct  proc {
    /*
     * Fields requiring no explicit locking
     */
    struct  vnode *p_exec;      /* pointer to a.out vnode */
    struct  as *p_as;       /* process address space pointer */
    struct  plock *p_lockp;     /* ptr to proc struct's mutex lock */
    kmutex_t p_crlock;      /* lock for p_cred */
    struct  cred    *p_cred;    /* process credentials */
    /*
     * Fields protected by pidlock
     */
    int p_swapcnt;      /* number of swapped out lwps */
    char    p_stat;         /* status of process */
    char    p_wcode;        /* current wait code */
    ushort_t p_pidflag;     /* flags protected only by pidlock */
    int     p_wdata;        /* current wait return value */
    pid_t   p_ppid;         /* process id of parent */
    struct  proc    *p_link;    /* forward link */
    struct  proc    *p_parent;  /* ptr to parent process */
    struct  proc    *p_child;   /* ptr to first child process */
    struct  proc    *p_sibling; /* ptr to next sibling proc on chain */
    struct  proc    *p_psibling;    /* ptr to prev sibling proc on chain */
    struct  proc    *p_sibling_ns;  /* prt to siblings with new state */
    struct  proc    *p_child_ns;    /* prt to children with new state */
    struct  proc    *p_next;    /* active chain link next */
    struct  proc    *p_prev;    /* active chain link prev */
    struct  proc    *p_nextofkin;   /* gets accounting info at exit */
    struct  proc    *p_orphan;
    struct  proc    *p_nextorph;
    struct  proc    *p_pglink;  /* process group hash chain link next */
    struct  proc    *p_ppglink; /* process group hash chain link prev */
    struct  sess    *p_sessp;   /* session information */
    struct  pid     *p_pidp;    /* process ID info */
    struct  pid     *p_pgidp;   /* process group ID info */
    /*
     * Fields protected by p_lock
     */
    kcondvar_t p_cv;        /* proc struct's condition variable */
    kcondvar_t p_flag_cv;
    kcondvar_t p_lwpexit;       /* waiting for some lwp to exit */
    kcondvar_t p_holdlwps;      /* process is waiting for its lwps */
                    /* to to be held.  */
    uint_t  p_proc_flag;        /* /proc-related flags */
    uint_t  p_flag;         /* protected while set. */
                    /* flags defined below */
    clock_t p_utime;        /* user time, this process */
    clock_t p_stime;        /* system time, this process */
    clock_t p_cutime;       /* sum of children's user time */
    clock_t p_cstime;       /* sum of children's system time */
    avl_tree_t *p_segacct;      /* System V shared segment list */
    avl_tree_t *p_semacct;      /* System V semaphore undo list */
    caddr_t p_bssbase;      /* base addr of last bss below heap */
    caddr_t p_brkbase;      /* base addr of heap */
    size_t  p_brksize;      /* heap size in bytes */
    uint_t  p_brkpageszc;       /* preferred heap max page size code */
    /*
     * Per process signal stuff.
     */
    k_sigset_t p_sig;       /* signals pending to this process */
    k_sigset_t p_extsig;        /* signals sent from another contract */
    k_sigset_t p_ignore;        /* ignore when generated */
    k_sigset_t p_siginfo;       /* gets signal info with signal */
    void *p_sigfd;          /* signalfd support state */
    struct sigqueue *p_sigqueue;    /* queued siginfo structures */
    struct sigqhdr *p_sigqhdr;  /* hdr to sigqueue structure pool */
    struct sigqhdr *p_signhdr;  /* hdr to signotify structure pool */
    uchar_t p_stopsig;      /* jobcontrol stop signal */

    /*
     * Special per-process flag when set will fix misaligned memory
     * references.
     */
    char    p_fixalignment;

    /*
     * Per process lwp and kernel thread stuff
     */
    id_t    p_lwpid;        /* most recently allocated lwpid */
    int     p_lwpcnt;       /* number of lwps in this process */
    int p_lwprcnt;      /* number of not stopped lwps */
    int p_lwpdaemon;        /* number of TP_DAEMON lwps */
    int p_lwpwait;      /* number of lwps in lwp_wait() */
    int p_lwpdwait;     /* number of daemons in lwp_wait() */
    int p_zombcnt;      /* number of zombie lwps */
    kthread_t *p_tlist;     /* circular list of threads */
    lwpdir_t *p_lwpdir;     /* thread (lwp) directory */
    lwpdir_t *p_lwpfree;        /* p_lwpdir free list */
    tidhash_t *p_tidhash;       /* tid (lwpid) lookup hash table */
    uint_t  p_lwpdir_sz;        /* number of p_lwpdir[] entries */
    uint_t  p_tidhash_sz;       /* number of p_tidhash[] entries */
    ret_tidhash_t *p_ret_tidhash;   /* retired tidhash hash tables */
    uint64_t p_lgrpset;     /* unprotected hint of set of lgrps */
                    /* on which process has threads */
    volatile lgrp_id_t  p_t1_lgrpid; /* main's thread lgroup id */
    volatile lgrp_id_t  p_tr_lgrpid; /* text replica's lgroup id */
#if defined(_LP64)
    uintptr_t  p_lgrpres2;      /* reserved for lgrp migration */
#endif
    /*
     * /proc (process filesystem) debugger interface stuff.
     */
    k_sigset_t p_sigmask;       /* mask of traced signals (/proc) */
    k_fltset_t p_fltmask;       /* mask of traced faults (/proc) */
    struct vnode *p_trace;      /* pointer to primary /proc vnode */
    struct vnode *p_plist;      /* list of /proc vnodes for process */
    kthread_t *p_agenttp;       /* thread ptr for /proc agent lwp */
    avl_tree_t p_warea;     /* list of watched areas */
    avl_tree_t p_wpage;     /* remembered watched pages (vfork) */
    watched_page_t *p_wprot;    /* pages that need to have prot set */
    int p_mapcnt;       /* number of active pr_mappage()s */
    kmutex_t p_maplock;     /* lock for pr_mappage() */
    struct  proc  *p_rlink;     /* linked list for server */
    kcondvar_t p_srwchan_cv;
    size_t  p_stksize;      /* process stack size in bytes */
    uint_t  p_stkpageszc;       /* preferred stack max page size code */

    /*
     * Microstate accounting, resource usage, and real-time profiling
     */
    hrtime_t p_mstart;      /* hi-res process start time */
    hrtime_t p_mterm;       /* hi-res process termination time */
    hrtime_t p_mlreal;      /* elapsed time sum over defunct lwps */
    hrtime_t p_acct[NMSTATES];  /* microstate sum over defunct lwps */
    hrtime_t p_cacct[NMSTATES]; /* microstate sum over child procs */
    struct lrusage p_ru;        /* lrusage sum over defunct lwps */
    struct lrusage p_cru;       /* lrusage sum over child procs */
    struct itimerval p_rprof_timer; /* ITIMER_REALPROF interval timer */
    uintptr_t p_rprof_cyclic;   /* ITIMER_REALPROF cyclic */
    uint_t  p_defunct;      /* number of defunct lwps */
    /*
     * profiling. A lock is used in the event of multiple lwp's
     * using the same profiling base/size.
     */
    kmutex_t p_pflock;      /* protects user profile arguments */
    struct prof p_prof;     /* profile arguments */

    /*
     * Doors.
     */
    door_pool_t     p_server_threads; /* common thread pool */
    struct door_node    *p_door_list;   /* active doors */
    struct door_node    *p_unref_list;
    kcondvar_t      p_unref_cv;
    char            p_unref_thread; /* unref thread created */

    /*
     * Kernel probes
     */
    uchar_t         p_tnf_flags;

    /*
     * Solaris Audit
     */
    struct p_audit_data *p_audit_data; /* per process audit structure */

    pctxop_t    *p_pctx;

#if defined(__x86)
    /*
     * LDT support.
     */
    kmutex_t    p_ldtlock;  /* protects the following fields */
    user_desc_t *p_ldt;     /* Pointer to private LDT */
    system_desc_t   p_ldt_desc; /* segment descriptor for private LDT */
    ushort_t    p_ldtlimit; /* highest selector used */
#endif
    size_t p_swrss;         /* resident set size before last swap */
    struct aio  *p_aio;     /* pointer to async I/O struct */
    struct itimer   **p_itimer; /* interval timers */
    timeout_id_t    p_alarmid;  /* alarm's timeout id */
    caddr_t     p_usrstack; /* top of the process stack */
    uint_t      p_stkprot;  /* stack memory protection */
    uint_t      p_datprot;  /* data memory protection */
    model_t     p_model;    /* data model determined at exec time */
    struct lwpchan_data *p_lcp; /* lwpchan cache */
    kmutex_t    p_lcp_lock; /* protects assignments to p_lcp */
    utrap_handler_t *p_utraps;  /* pointer to user trap handlers */
    struct corectl_path *p_corefile;    /* pattern for core file */
    struct task *p_task;    /* our containing task */
    struct proc *p_taskprev;    /* ptr to previous process in task */
    struct proc *p_tasknext;    /* ptr to next process in task */
    kmutex_t    p_sc_lock;  /* protects p_pagep */
    struct sc_page_ctl *p_pagep;    /* list of process's shared pages */
    struct rctl_set *p_rctls;   /* resource controls for this process */
    rlim64_t    p_stk_ctl;  /* currently enforced stack size */
    rlim64_t    p_fsz_ctl;  /* currently enforced file size */
    rlim64_t    p_vmem_ctl; /* currently enforced addr-space size */
    rlim64_t    p_fno_ctl;  /* currently enforced file-desc limit */
    pid_t       p_ancpid;   /* ancestor pid, used by exacct */
    struct itimerval p_realitimer;  /* real interval timer */
    timeout_id_t    p_itimerid; /* real interval timer's timeout id */
    struct corectl_content *p_content;  /* content of core file */

    avl_tree_t  p_ct_held;  /* held contracts */
    struct ct_equeue **p_ct_equeue; /* process-type event queues */

    struct cont_process *p_ct_process; /* process contract */
    list_node_t p_ct_member;    /* process contract membership */
    sigqueue_t  *p_killsqp; /* sigqueue pointer for SIGKILL */

    int     p_dtrace_probes; /* are there probes for this proc? */
    uint64_t    p_dtrace_count; /* number of DTrace tracepoints */
                    /* (protected by P_PR_LOCK) */
    void        *p_dtrace_helpers; /* DTrace helpers, if any */
    struct pool *p_pool;    /* pointer to containing pool */
    kcondvar_t  p_poolcv;   /* synchronization with pools */
    uint_t      p_poolcnt;  /* # threads inside pool barrier */
    uint_t      p_poolflag; /* pool-related flags (see below) */
    uintptr_t   p_portcnt;  /* event ports counter */
    struct zone *p_zone;    /* zone in which process lives */
    struct vnode    *p_execdir; /* directory that p_exec came from */
    struct brand    *p_brand;   /* process's brand  */
    void        *p_brand_data;  /* per-process brand state */
    psecflags_t p_secflags; /* per-process security flags */

    /* additional lock to protect p_sessp (but not its contents) */
    kmutex_t p_splock;
    rctl_qty_t  p_locked_mem;   /* locked memory charged to proc */
                    /* protected by p_lock */
    rctl_qty_t  p_crypto_mem;   /* /dev/crypto memory charged to proc */
                    /* protected by p_lock */
    clock_t p_ttime;        /* buffered task time */

    /*
     * The user structure
     */
    struct user p_user;     /* (see sys/user.h) */
} proc_t;

So your current process id is curproc->p_pidp->pid_id and the parent process id is curproc->p_ppid.


问:
Heap size discrepancies in VisualVM vs Eclipse MAT
I'm trying to analyze the memory usage of my Java app. In VisualVM I see the Heap size as ~733M:

But when I exported the heap dump to Eclipse MAT, it shows as 36.6MB:

Why is that?

答:
duplicate: Why is my Java heap dump size much smaller than used memory?

TLDR; heap dump triggered garbage collection and dump shows the "Used heap"


问:
Highlight "Cannot find name" / "any" in Vs Code
Using VS Code, when I make mistake in Typescript it highlights the error as "Cannot find name" / any, but in Javascript it is assigned "any" and therefore it is not an highlighted. Image attached:

Is it possible to highlight in JavaScript the errors in same way? JSlint extension did not help. It would be painful to see the errors only in build.

答:
TypeScript by default squelches these errors when you're in a .js file - however, if you add a // @ts-check comment to the top of your .js file, then you should get a similar form of checking as you would in TypeScript.

This is fairly new, but you can get details on it from the official blog post.

The summary is

Either add a // @ts-check comment to the top of your file, or

add the checkJs option to your jsconfig.json/tsconfig.json


问:
Getting actual value from react-native asyncStorage instead of promise
All morning I've been trying to get the AsyncStorage.getItem to return the value of the actual item, not a promise.

Here's what I have that according to everything I've read should work:

```<code>export async function getToken(){

    try{
        var value = await AsyncStorage.getItem('authToken');
        return value;
    }catch (error){
        console.log(error);
    }

}
</code>```

I have tried chaining together many .thens, tried accessing the actual value field of the promise, but for some reason that returns a promise also. I've tried pretty much every suggestion on this site and it will always return a promise.

答:
Quoting the AsyncStorage documentation

... Each method in the API returns a Promise object.

and also based on this post, there is no way for you to access the value without the use of promise or any other async patterns (generators, callback etc).

You can use Realm as a storage without using promises. This is how you query data in realm (quoting the documentation):

let token = realm.objects('authToken'); // retrieves all authTokens```

Body:
All morning I've been trying to get the AsyncStorage.getItem to return the value of the actual item, not a promise.

Here's what I have that according to everything I've read should work:

export async function getToken(){

    try{
        var value = await AsyncStorage.getItem('authToken');
        return value;
    }catch (error){
        console.log(error);
    }

}

I have tried chaining together many .thens, tried accessing the actual value field of the promise, but for some reason that returns a promise also. I've tried pretty much every suggestion on this site and it will always return a promise.


问:
BlackBerry non-wrapping LabelField
I have a label field and 3 edit fields.  I want characters entered in the label field to be on one line.  Can anybody tell me how to do this?</p>

答:
You can check the length of the string using Font.getDefaultFont and call the function stringWidth passing in your label string. If the text is wider then the screen (use Display.getWidth), either make the font smaller or trim it to the size.

Another option is to implement your own field but that seems far more work... :)

ContentLicense: CC BY-SA 2.5

Title: BlackBerry non-wrapping LabelField


问:
How to change port for jenkins window service when 8080 is being used
I installed Jenkins on a windows virtual server and want to run it as window service.

Since the port 8080 is being used by other service, I changed the http port to 8081 in jenkins.xml file. However, I am not able to launch localhost:8081/jenkins at all.  I need detail instruction/steps to configure port 8081 or something to run Jenkins.

答:
For jenkins in a docker container you can use port publish option in docker run command to map jenkins port in container to different outside port.

e.g. map docker container internal jenkins GUI port 8080 to port 9090 external

```<code>docker run -it -d --name jenkins42 --restart always \
   -p <ip>:9090:8080 <image>
</code>```

Body:
For jenkins in a docker container you can use port publish option in docker run command to map jenkins port in container to different outside port.

e.g. map docker container internal jenkins GUI port 8080 to port 9090 external

docker run -it -d --name jenkins42 --restart always \
   -p <ip>:9090:8080 <image>


问:
Enforcing custom enumeration in AWS LEX for slot values
I want to be able to specify a custom list of valid options for a slot that LEX will either attempt to approximate towards or, in the event that no valid option can be approximated, reject the invalid response.

At first I attempted to do this through custom slot types. And though their examples may lead you to believe these are enumerations, they are not. A user still has the capacity to input whatever value they like.

Their documentation has this to say: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/migrating-to-the-improved-built-in-and-custom-slot-types#literal

A custom slot type is not the equivalent of an enumeration. Values outside the list may still be returned if recognized by the spoken language understanding system. Although input to a custom slot type is weighted towards the values in the list, it is not constrained to just the items on the list. Your code still needs to include validation and error checking when using slot values.

I am aware that I can validate their submission through a lambda after they have completed their full submission, but by then it's too late. A user has submitted their full intent message. I'm unable to capture it midway and correct them.

Am I missing some way to input slot options or a configuration option for custom slot types? Is there any way to enforce a custom list of options for a slot? (Similar to utterances for intents, or the built in slot types, which will ask the same question again if there is no match.)

Thanks!

答:
I'm unable to capture it midway and correct them.

You can capture the error in lambda without fulfilling the intent and starting over. Here's how I validate input with Python.

If you detect a validation error in lambda, you can elicit the same slot and pass your error message. This allows you to set complex validation rules and have your bot return specific responses to the user.

```<code>   def validate(input):
       if input not in ['foo', 'bar']:
           return elicit_slot("Your response must be foo or bar")

   def elicit_slot(error_message):
        return {
            'dialogAction': {
                'type': 'ElicitSlot',
                'intentName': current_intent,
                'slots': current_slots,
                'slotToElicit': slot_with_validation_error,
                'message': {'contentType': 'PlainText', 'content': error_message }
        }
    }
</code>```

Body:
I'm unable to capture it midway and correct them.

You can capture the error in lambda without fulfilling the intent and starting over. Here's how I validate input with Python.

If you detect a validation error in lambda, you can elicit the same slot and pass your error message. This allows you to set complex validation rules and have your bot return specific responses to the user.

   def validate(input):
       if input not in ['foo', 'bar']:
           return elicit_slot("Your response must be foo or bar")

   def elicit_slot(error_message):
        return {
            'dialogAction': {
                'type': 'ElicitSlot',
                'intentName': current_intent,
                'slots': current_slots,
                'slotToElicit': slot_with_validation_error,
                'message': {'contentType': 'PlainText', 'content': error_message }
        }
    }


问:
Changing first item in nested list using list comprehension
Let's say I have the following list of lists:

```<code>[['Hello im an item', 1234], ['I enjoy python', 'hello'], ['I only have one item']]
</code>```

I want to replace the spaces with underscores in the first item in each inner list so it looks like this:

```<code>[['Hello_im_an_item', 1234], ['I_enjoy_python', 'hello'], ['I_only_have_one_item']]
</code>```

I have tried the following with no success:

```<code>formatted = [first[0].replace(' ', '_') for first in formatted]
</code>```

formatted returns a list of only the first items, but with the correct formatting.
Does anyone have any idea how this can be accomplished?

答:
Just use a for loop:

```<code>for a in formatted:
    a[0] = a[0].replace(' ', '_')
</code>```

This really isn't a use-case for list comprehensions.

Body:
Let's say I have the following list of lists:

[['Hello im an item', 1234], ['I enjoy python', 'hello'], ['I only have one item']]

I want to replace the spaces with underscores in the first item in each inner list so it looks like this:

[['Hello_im_an_item', 1234], ['I_enjoy_python', 'hello'], ['I_only_have_one_item']]

I have tried the following with no success:

formatted = [first[0].replace(' ', '_') for first in formatted]

formatted returns a list of only the first items, but with the correct formatting.
Does anyone have any idea how this can be accomplished?

Body:
Just use a for loop:

for a in formatted:
    a[0] = a[0].replace(' ', '_')

This really isn't a use-case for list comprehensions.


问:
Angular2 - Cross-Origin Request Blocked
I'm trying to use the forecast API with my angular2 app. However, when i try to access the API I get a Cross-Origin Error. Any idea how i can fix this error ?

```<code>search(latitude: any, longitude: any){
        console.log(latitude);
        console.log(longitude);
        let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude ;
        console.log(body);
        this.http.get(body)
            .map(
                response => response.json()
            ).subscribe(
                data =>  console.log("Data: "+data),
                err =>  console.log("Error: "+err),
                () => console.log('Get Complete')
            );
    }
</code>```

Error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.forecast.io/forecast/APIKEY/37.8267,-122.423. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Update
Now using JSONP

```<code>    let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude + '?callback=?' ;
    console.log(body);
    this.jsonp.get(body)
    .map(response => response.json())
    .subscribe(
            data =>  console.log("Data: "+data),
            err =>  console.log("Error: "+err),
            () => console.log('Get Complete')
    );
</code>```

Error

Error0.def29191127bbc3e0100.hot-update.js:59:10
Object { _body: "JSONP injected script did not invok…", status: 200, ok: true, statusText: "Ok", headers: Object, type: 3, url: "https://api.forecast.io/forecast/60…" }0.def29191127bbc3e0100.hot-update.js:61:10
SyntaxError: expected expression, got '==='

答:
You are getting this problem because the header you are sending does not match the headers in the backend.

Suppose you send the following headers:

```<code>contentHeaders = new Headers();
contentHeaders.append('Authorization', 'Your token used in app');
contentHeaders.append('Content-Type', 'application/json');
contentHeaders.append('Access-Control-Allow-Origin', '*');
</code>```

So those headers like Authorization, Content-type, and Access-Control-Allow-Origin should match the allowed headers in your backend.

So in the backend Access-Control-Allow-Headers should have all above headers:

```<code>res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization, content-type, Access-Control-Allow-Origin");
</code>```

So here in Access-Control-Allow-Headers you have to pass all headers which you send from frontend: 'Authorization', 'Content-type', and 'Access-Control-Allow-Origin'.

It will work perfectly when you use above concept.

Hope this post will helpful for you

Thanks

Title: Angular2 - Cross-Origin Request Blocked

Body:
I'm trying to use the forecast API with my angular2 app. However, when i try to access the API I get a Cross-Origin Error. Any idea how i can fix this error ?

search(latitude: any, longitude: any){
        console.log(latitude);
        console.log(longitude);
        let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude ;
        console.log(body);
        this.http.get(body)
            .map(
                response => response.json()
            ).subscribe(
                data =>  console.log("Data: "+data),
                err =>  console.log("Error: "+err),
                () => console.log('Get Complete')
            );
    }

Error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.forecast.io/forecast/APIKEY/37.8267,-122.423. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Update
Now using JSONP

    let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude + '?callback=?' ;
    console.log(body);
    this.jsonp.get(body)
    .map(response => response.json())
    .subscribe(
            data =>  console.log("Data: "+data),
            err =>  console.log("Error: "+err),
            () => console.log('Get Complete')
    );

Error

Error0.def29191127bbc3e0100.hot-update.js:59:10
Object { _body: "JSONP injected script did not invok…", status: 200, ok: true, statusText: "Ok", headers: Object, type: 3, url: "https://api.forecast.io/forecast/60…" }0.def29191127bbc3e0100.hot-update.js:61:10
SyntaxError: expected expression, got '==='

Body:
You are getting this problem because the header you are sending does not match the headers in the backend.

Suppose you send the following headers:

contentHeaders = new Headers();
contentHeaders.append('Authorization', 'Your token used in app');
contentHeaders.append('Content-Type', 'application/json');
contentHeaders.append('Access-Control-Allow-Origin', '*');

So those headers like Authorization, Content-type, and Access-Control-Allow-Origin should match the allowed headers in your backend.

So in the backend Access-Control-Allow-Headers should have all above headers:

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization, content-type, Access-Control-Allow-Origin");

So here in Access-Control-Allow-Headers you have to pass all headers which you send from frontend: 'Authorization', 'Content-type', and 'Access-Control-Allow-Origin'.

It will work perfectly when you use above concept.

Hope this post will helpful for you

Thanks


问:
In javascript, how to get timezone value in UTC format for new Date(2017,05,31).toISOString()?
How to get timezone value for new Date(2017,05,31).toISOString()? It always comes as 000Z for any Date when the date is passed to the Date constructor. But for new Date().toISOString(), it gives the the timezone value.

```<code>new Date(2017,05,31).toISOString() gives "2017-05-30T18:30:00.000Z"
</code>```

and new Date().toISOString() gives "2017-06-07T15:29:23.692Z". How to get timezone in UTC format for the past dates?

答:
In javascript, parsing, rendering and constructing dates will always assume local. It will convert to a timestamp, the number of milliseconds since 1-1-1970 00:00:00. JSON.stringify will convert to a UTC string, but legacy framworks use local dates. Always beware of this.

```<code>var myDate = new Date(); // this is now.
</code>```

you can get your timezoneoffset (in minutes) with myDate.getTimezoneOffset(), but this will return the same offset for every date (aside from daylight saving time)

You shouldn't do this:

```<code>var utcDate = new Date(+d+60000*d.getTimezoneOffset());
// +d convert the date to a timespan.
// getTimezoneOffset() is in minutes
// *60000 makes that in milliseconds, the scale timespans operate upon
</code>```

Date has a few methods to format dates, but always as local or UTC date. You need to do it manually if you want different time zones.

Note: the Date.UTC(...) function returns a timestamp. You sometimes see shifted dates, so they behave like UTC. But this causes problems later on.

```<code>var date = new Date(2000,1,1,12,0,0);
// DO NOT USE (breaks at start of daylight saving time)
// these are date/times that have the UTC-value,
// but Javascript treats them like local dates with this value.
utcDate1 = (+date-60000*d.getTimeZoneOffset()); // minus!!
utcDate2 = new Date(Date.UTC(2000,1,1,12,0,0));
// DO NOT USE (breaks at start of daylight saving time)
</code>```

BTW
Edge, Chrome and Firefox display dates differently in the console: Edge and Firefox always shows local date, Chrome shows UTC. Also, if you change your timezone, Edge will screw up.

Body:
How to get timezone value for new Date(2017,05,31).toISOString()? It always comes as 000Z for any Date when the date is passed to the Date constructor. But for new Date().toISOString(), it gives the the timezone value.

new Date(2017,05,31).toISOString() gives "2017-05-30T18:30:00.000Z"

and new Date().toISOString() gives "2017-06-07T15:29:23.692Z". How to get timezone in UTC format for the past dates?

Body:
In javascript, parsing, rendering and constructing dates will always assume local. It will convert to a timestamp, the number of milliseconds since 1-1-1970 00:00:00. JSON.stringify will convert to a UTC string, but legacy framworks use local dates. Always beware of this.

var myDate = new Date(); // this is now.

you can get your timezoneoffset (in minutes) with myDate.getTimezoneOffset(), but this will return the same offset for every date (aside from daylight saving time)

You shouldn't do this:

var utcDate = new Date(+d+60000*d.getTimezoneOffset());
// +d convert the date to a timespan.
// getTimezoneOffset() is in minutes
// *60000 makes that in milliseconds, the scale timespans operate upon

Date has a few methods to format dates, but always as local or UTC date. You need to do it manually if you want different time zones.

Note: the Date.UTC(...) function returns a timestamp. You sometimes see shifted dates, so they behave like UTC. But this causes problems later on.

var date = new Date(2000,1,1,12,0,0);
// DO NOT USE (breaks at start of daylight saving time)
// these are date/times that have the UTC-value,
// but Javascript treats them like local dates with this value.
utcDate1 = (+date-60000*d.getTimeZoneOffset()); // minus!!
utcDate2 = new Date(Date.UTC(2000,1,1,12,0,0));
// DO NOT USE (breaks at start of daylight saving time)

BTW
Edge, Chrome and Firefox display dates differently in the console: Edge and Firefox always shows local date, Chrome shows UTC. Also, if you change your timezone, Edge will screw up.


问:
Python for .NET: System.BadImageFormatException when embedding
I'm trying to embed Python in my .NET application.

I'm using Python 3.6.1 64-bit on Windows 10 and I have installed pythonnet 2.3.0 from PyPi using pip.

I've referenced Python.Runtime.dll from C:\Program Files\Python36\Lib\site-packages and have both Path and PYTHONHOME environment variables pointed to C:\Program Files\Python36\.

When I use .NET in Python everything is OK.

```<code>import clr
from System.Drawing import Point
p = Point(5, 5)
print(p)
</code>```

prints {X=5,Y=5} as expected.

But when I call Python from .NET I get System.BadImageFormatException. For example, when calling Python.Runtime.PythonEngine.Initialize(); :

System.BadImageFormatException: 'Could not load file or assembly
  'Python.Runtime, Version=2.3.0.0, Culture=neutral,
  PublicKeyToken=null' or one of its dependencies. An attempt was made
  to load a program with an incorrect format.'

Any thoughts?

Thanks in advance.

答: As denfromufa said, I was just calling from a 32-bit .NET process.</p>

Body:
I'm trying to embed Python in my .NET application.

I'm using Python 3.6.1 64-bit on Windows 10 and I have installed pythonnet 2.3.0 from PyPi using pip.

I've referenced Python.Runtime.dll from C:\Program Files\Python36\Lib\site-packages and have both Path and PYTHONHOME environment variables pointed to C:\Program Files\Python36\.

When I use .NET in Python everything is OK.

import clr
from System.Drawing import Point
p = Point(5, 5)
print(p)

prints {X=5,Y=5} as expected.

But when I call Python from .NET I get System.BadImageFormatException. For example, when calling Python.Runtime.PythonEngine.Initialize(); :

System.BadImageFormatException: 'Could not load file or assembly
  'Python.Runtime, Version=2.3.0.0, Culture=neutral,
  PublicKeyToken=null' or one of its dependencies. An attempt was made
  to load a program with an incorrect format.'

Any thoughts?

Thanks in advance.

ContentLicense: CC BY-SA 4.0


答:
It calculates m+1-1 as (m+1)-1 and m+1 is not sparse so from that point on you don't have a sparse matrix.

Try m+(1-1).

Title: R sparse matrix stores zeros after simple arithmetic (Matrix library)

Body:
I have the following [10 x 10] sparse matrix:

library(Matrix)
m = as(diag(10), 'sparseMatrix')
m
10 x 10 sparse Matrix of class "dgCMatrix"
[1,] 1 . . . . . . . . .
[2,] . 1 . . . . . . . .
[3,] . . 1 . . . . . . .
[4,] . . . 1 . . . . . .
[5,] . . . . 1 . . . . .
[6,] . . . . . 1 . . . .
[7,] . . . . . . 1 . . .
[8,] . . . . . . . 1 . .
[9,] . . . . . . . . 1 .
[10,] . . . . . . . . . 1

If I do simple arithmetic on this, it now stores all of the zeros.

M = m + 1 - 1
M
10 x 10 Matrix of class "dgeMatrix"
       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    0    0    0    0    0    0    0    0     0
 [2,]    0    1    0    0    0    0    0    0    0     0
 [3,]    0    0    1    0    0    0    0    0    0     0
 [4,]    0    0    0    1    0    0    0    0    0     0
 [5,]    0    0    0    0    1    0    0    0    0     0
 [6,]    0    0    0    0    0    1    0    0    0     0
 [7,]    0    0    0    0    0    0    1    0    0     0
 [8,]    0    0    0    0    0    0    0    1    0     0
 [9,]    0    0    0    0    0    0    0    0    1     0
[10,]    0    0    0    0    0    0    0    0    0     1

I know that I can make this new matrix sparse, but is there any way to make R do this automatically?

M = as(M, 'sparseMatrix')


问:
Amazon Echo trouble with Integers
I developed an AWS Lambda function for an Alexa Skill, some of the utterances are expecting an integer. Echo is most of the times confusing "two" as "to" and "four" as "for", eight as "ate". So far the only solution I could come up with is to say the word "number" before the actual number and the problem is fixed. However I was wondering if there is some other way to fix this without having to say the word "number" and adding it to my utterances. I could not find a solution online for this.</p>

Title: Amazon Echo trouble with Integers

Body:
AMAZON.NUMBER did not work. What worked for me was writing a method that changed words to integers it also handles the 'to', 'for', 'ate', etc... problem. A bit tedious to write but it worked at least. The following is the JavaScript code I used

 var Small=

{

 '1' : 1,
 '2' : 2,
 '3' : 3,
 '4' : 4,
 '5' : 5,
 '6' : 6,
 '7' : 7,
 '8' : 8,
 '9' : 9,
 '10' : 10,
 '11' : 11,
 '12' : 12,
 '13' : 13,
 '14' : 14,
 '15' : 15,
 '16' : 16,
 '17' : 17,
 '18' : 18,
 '19' : 19,
 '20' : 20,
 '21' : 21,
 '22' : 22,
 '23' : 23,
 '24' : 24,
 '25' : 25,
 '26' : 26,
 '27' : 27,
 '28' : 28,
 '29' : 29,
 '30' : 30,
 '31' : 31,
 '32' : 32,
 '33' : 33,
 '34' : 34,
 '35' : 35,
 '36' : 36,
 '37' : 37,
 '38' : 38,
 '39' : 39,
 '40' : 40,
 '41' : 41,
 '42' : 42,
 '43' : 43,
 '44' : 44,
 '45' : 45,
 '46' : 46,
 '47' : 47,
 '48' : 48,
 '49' : 49,
 '50' : 50,
 '51' : 51,
 '52' : 52,
 '53' : 53,
 '54' : 54,
 '55' : 55,
 '56' : 56,
 '57' : 57,
 '58' : 58,
 '59' : 59,
 '60' : 60,
 '61' : 61,
 '62' : 62,
 '63' : 63,
 '64' : 64,
 '65' : 65,
 '66' : 66,
 '67' : 67,
 '68' : 68,
 '69' : 69,
 '70' : 70,
 '71' : 71,
 '72' : 72,
 '73' : 73,
 '74' : 74,
 '75' : 75,
 '76' : 76,
 '77' : 77,
 '78' : 78,
 '79' : 79,
 '80' : 80,
 '81' : 81,
 '82' : 82,
 '83' : 83,
 '84' : 84,
 '85' : 85,
 '86' : 86,
 '87' : 87,
 '88' : 88,
 '89' : 89,
 '90' : 90,
 '91' : 91,
 '92' : 92,
 '93' : 93,
 '94' : 94,
 '95' : 95,
 '96' : 96,
 '97' : 97,
 '98' : 98,
 '99' : 99,
 '100' : 100,
 '101' : 101,
 '102' : 102,
 '103' : 103,
 '104' : 104,
 '105' : 105,
 '106' : 106,
 '107' : 107,
 '108' : 108,
 '109' : 109,
 '110' : 110,
 '111' : 111,
 '112' : 112,
 '113' : 113,
 '114' : 114,
 '115' : 115,
 '116' : 116,
 '117' : 117,
 '118' : 118,
 '119' : 119,
 '120' : 120,
 '121' : 121,
 '122' : 122,
 '123' : 123,
 '124' : 124,
 '125' : 125,
 '126' : 126,
 '127' : 127,
 '128' : 128,
 '129' : 129,
 '130' : 130,
 '131' : 131,
 '132' : 132,
 '133' : 133,
 '134' : 134,
 '135' : 135,
 '136' : 136,
 '137' : 137,
 '138' : 138,
 '139' : 139,
 '140' : 140,
 '141' : 141,
 '142' : 142,
 '143' : 143,
 '144' : 144,
 '145' : 145,
 '146' : 146,
 '147' : 147,
 '148' : 148,
 '149' : 149,
 '150' : 150,
 '151' : 151,
 '152' : 152,
 '153' : 153,
 '154' : 154,
 '155' : 155,
 '156' : 156,
 '157' : 157,
 '158' : 158,
 '159' : 159,
 '160' : 160,
 '161' : 161,
 '162' : 162,
 '163' : 163,
 '164' : 164,
 '165' : 165,
 '166' : 166,
 '167' : 167,
 '168' : 168,
 '169' : 169,
 '170' : 170,
 '171' : 171,
 '172' : 172,
 '173' : 173,
 '174' : 174,
 '175' : 175,
 '176' : 176,
 '177' : 177,
 '178' : 178,
 '179' : 179,
 '180' : 180,
 '181' : 181,
 '182' : 182,
 '183' : 183,
 '184' : 184,
 '185' : 185,
 '186' : 186,
 '187' : 187,
 '188' : 188,
 '189' : 189,
 '190' : 190,
 '191' : 191,
 '192' : 192,
 '193' : 193,
 '194' : 194,
 '195' : 195,
 '196' : 196,
 '197' : 197,
 '198' : 198,
 '199' : 199,
 '200' : 200,
 '201' : 201,
 '202' : 202,
 '203' : 203,
 '204' : 204,
 '205' : 205,
 '206' : 206,
 '207' : 207,
 '208' : 208,
 '209' : 209,
 '210' : 210,
 '211' : 211,
 '212' : 212,
 '213' : 213,
 '214' : 214,
 '215' : 215,
 '216' : 216,
 '217' : 217,
 '218' : 218,
 '219' : 219,
 '220' : 220,
 '221' : 221,
 '222' : 222,
 '223' : 223,
 '224' : 224,
 '225' : 225,
 '226' : 226,
 '227' : 227,
 '228' : 228,
 '229' : 229,
 '230' : 230,
 '231' : 231,
 '232' : 232,
 '233' : 233,
 '234' : 234,
 '235' : 235,
 '236' : 236,
 '237' : 237,
 '238' : 238,
 '239' : 239,
 '240' : 240,
 '241' : 241,
 '242' : 242,
 '243' : 243,
 '244' : 244,
 '245' : 245,
 '246' : 246,
 '247' : 247,
 '248' : 248,
 '249' : 249,
 '250' : 250,
 '251' : 251,
 '252' : 252,
 '253' : 253,
 '254' : 254,
 '255' : 255,
 '256' : 256,
 '257' : 257,
 '258' : 258,
 '259' : 259,
 '260' : 260,
 '261' : 261,
 '262' : 262,
 '263' : 263,
 '264' : 264,
 '265' : 265,
 '266' : 266,
 '267' : 267,
 '268' : 268,
 '269' : 269,
 '270' : 270,
 '271' : 271,
 '272' : 272,
 '273' : 273,
 '274' : 274,
 '275' : 275,
 '276' : 276,
 '277' : 277,
 '278' : 278,
 '279' : 279,
 '280' : 280,
 '281' : 281,
 '282' : 282,
 '283' : 283,
 '284' : 284,
 '285' : 285,
 '286' : 286,
 '287' : 287,
 '288' : 288,
 '289' : 289,
 '290' : 290,
 '291' : 291,
 '292' : 292,
 '293' : 293,
 '294' : 294,
 '295' : 295,
 '296' : 296,
 '297' : 297,
 '298' : 298,
 '299' : 299,
 '300' : 300,
 '301' : 301,
 '302' : 302,
 '303' : 303,
 '304' : 304,
 '305' : 305,
 '306' : 306,
 '307' : 307,
 '308' : 308,
 '309' : 309,
 '310' : 310,
 '311' : 311,
 '312' : 312,
 '313' : 313,
 '314' : 314,
 '315' : 315,
 '316' : 316,
 '317' : 317,
 '318' : 318,
 '319' : 319,
 '320' : 320,
 '321' : 321,
 '322' : 322,
 '323' : 323,
 '324' : 324,
 '325' : 325,
 '326' : 326,
 '327' : 327,
 '328' : 328,
 '329' : 329,
 '330' : 330,
 '331' : 331,
 '332' : 332,
 '333' : 333,
 '334' : 334,
 '335' : 335,
 '336' : 336,
 '337' : 337,
 '338' : 338,
 '339' : 339,
 '340' : 340,
 '341' : 341,
 '342' : 342,
 '343' : 343,
 '344' : 344,
 '345' : 345,
 '346' : 346,
 '347' : 347,
 '348' : 348,
 '349' : 349,
 '350' : 350,
 '351' : 351,
 '352' : 352,
 '353' : 353,
 '354' : 354,
 '355' : 355,
 '356' : 356,
 '357' : 357,
 '358' : 358,
 '359' : 359,
 '360' : 360,
 '361' : 361,
 '362' : 362,
 '363' : 363,
 '364' : 364,
 '365' : 365,
 '366' : 366,
 '367' : 367,
 '368' : 368,
 '369' : 369,
 '370' : 370,
 '371' : 371,
 '372' : 372,
 '373' : 373,
 '374' : 374,
 '375' : 375,
 '376' : 376,
 '377' : 377,
 '378' : 378,
 '379' : 379,
 '380' : 380,
 '381' : 381,
 '382' : 382,
 '383' : 383,
 '384' : 384,
 '385' : 385,
 '386' : 386,
 '387' : 387,
 '388' : 388,
 '389' : 389,
 '390' : 390,
 '391' : 391,
 '392' : 392,
 '393' : 393,
 '394' : 394,
 '395' : 395,
 '396' : 396,
 '397' : 397,
 '398' : 398,
 '399' : 399,
 '400' : 400,
 '401' : 401,
 '402' : 402,
 '403' : 403,
 '404' : 404,
 '405' : 405,
 '406' : 406,
 '407' : 407,
 '408' : 408,
 '409' : 409,
 '410' : 410,
 '411' : 411,
 '412' : 412,
 '413' : 413,
 '414' : 414,
 '415' : 415,
 '416' : 416,
 '417' : 417,
 '418' : 418,
 '419' : 419,
 '420' : 420,
 '421' : 421,
 '422' : 422,
 '423' : 423,
 '424' : 424,
 '425' : 425,
 '426' : 426,
 '427' : 427,
 '428' : 428,
 '429' : 429,
 '430' : 430,
 '431' : 431,
 '432' : 432,
 '433' : 433,
 '434' : 434,
 '435' : 435,
 '436' : 436,
 '437' : 437,
 '438' : 438,
 '439' : 439,
 '440' : 440,
 '441' : 441,
 '442' : 442,
 '443' : 443,
 '444' : 444,
 '445' : 445,
 '446' : 446,
 '447' : 447,
 '448' : 448,
 '449' : 449,
 '450' : 450,
 '451' : 451,
 '452' : 452,
 '453' : 453,
 '454' : 454,
 '455' : 455,
 '456' : 456,
 '457' : 457,
 '458' : 458,
 '459' : 459,
 '460' : 460,
 '461' : 461,
 '462' : 462,
 '463' : 463,
 '464' : 464,
 '465' : 465,
 '466' : 466,
 '467' : 467,
 '468' : 468,
 '469' : 469,
 '470' : 470,
 '471' : 471,
 '472' : 472,
 '473' : 473,
 '474' : 474,
 '475' : 475,
 '476' : 476,
 '477' : 477,
 '478' : 478,
 '479' : 479,
 '480' : 480,
 '481' : 481,
 '482' : 482,
 '483' : 483,
 '484' : 484,
 '485' : 485,
 '486' : 486,
 '487' : 487,
 '488' : 488,
 '489' : 489,
 '490' : 490,
 '491' : 491,
 '492' : 492,
 '493' : 493,
 '494' : 494,
 '495' : 495,
 '496' : 496,
 '497' : 497,
 '498' : 498,
 '499' : 499,
 '500' : 500,
 '501' : 501,
 '502' : 502,
 '503' : 503,
 '504' : 504,
 '505' : 505,
 '506' : 506,
 '507' : 507,
 '508' : 508,
 '509' : 509,
 '510' : 510,
 '511' : 511,
 '512' : 512,
 '513' : 513,
 '514' : 514,
 '515' : 515,
 '516' : 516,
 '517' : 517,
 '518' : 518,
 '519' : 519,
 '520' : 520,
 '521' : 521,
 '522' : 522,
 '523' : 523,
 '524' : 524,
 '525' : 525,
 '526' : 526,
 '527' : 527,
 '528' : 528,
 '529' : 529,
 '530' : 530,
 '531' : 531,
 '532' : 532,
 '533' : 533,
 '534' : 534,
 '535' : 535,
 '536' : 536,
 '537' : 537,
 '538' : 538,
 '539' : 539,
 '540' : 540,
 '541' : 541,
 '542' : 542,
 '543' : 543,
 '544' : 544,
 '545' : 545,
 '546' : 546,
 '547' : 547,
 '548' : 548,
 '549' : 549,
 '550' : 550,
 '551' : 551,
 '552' : 552,
 '553' : 553,
 '554' : 554,
 '555' : 555,
 '556' : 556,
 '557' : 557,
 '558' : 558,
 '559' : 559,
 '560' : 560,
 '561' : 561,
 '562' : 562,
 '563' : 563,
 '564' : 564,
 '565' : 565,
 '566' : 566,
 '567' : 567,
 '568' : 568,
 '569' : 569,
 '570' : 570,
 '571' : 571,
 '572' : 572,
 '573' : 573,
 '574' : 574,
 '575' : 575,
 '576' : 576,
 '577' : 577,
 '578' : 578,
 '579' : 579,
 '580' : 580,
 '581' : 581,
 '582' : 582,
 '583' : 583,
 '584' : 584,
 '585' : 585,
 '586' : 586,
 '587' : 587,
 '588' : 588,
 '589' : 589,
 '590' : 590,
 '591' : 591,
 '592' : 592,
 '593' : 593,
 '594' : 594,
 '595' : 595,
 '596' : 596,
 '597' : 597,
 '598' : 598,
 '599' : 599,
 '600' : 600,
 '601' : 601,
 '602' : 602,
 '603' : 603,
 '604' : 604,
 '605' : 605,
 '606' : 606,
 '607' : 607,
 '608' : 608,
 '609' : 609,
 '610' : 610,
 '611' : 611,
 '612' : 612,
 '613' : 613,
 '614' : 614,
 '615' : 615,
 '616' : 616,
 '617' : 617,
 '618' : 618,
 '619' : 619,
 '620' : 620,
 '621' : 621,
 '622' : 622,
 '623' : 623,
 '624' : 624,
 '625' : 625,
 '626' : 626,
 '627' : 627,
 '628' : 628,
 '629' : 629,
 '630' : 630,
 '631' : 631,
 '632' : 632,
 '633' : 633,
 '634' : 634,
 '635' : 635,
 '636' : 636,
 '637' : 637,
 '638' : 638,
 '639' : 639,
 '640' : 640,
 '641' : 641,
 '642' : 642,
 '643' : 643,
 '644' : 644,
 '645' : 645,
 '646' : 646,
 '647' : 647,
 '648' : 648,
 '649' : 649,
 '650' : 650,
 '651' : 651,
 '652' : 652,
 '653' : 653,
 '654' : 654,
 '655' : 655,
 '656' : 656,
 '657' : 657,
 '658' : 658,
 '659' : 659,
 '660' : 660,
 '661' : 661,
 '662' : 662,
 '663' : 663,
 '664' : 664,
 '665' : 665,
 '666' : 666,
 '667' : 667,
 '668' : 668,
 '669' : 669,
 '670' : 670,
 '671' : 671,
 '672' : 672,
 '673' : 673,
 '674' : 674,
 '675' : 675,
 '676' : 676,
 '677' : 677,
 '678' : 678,
 '679' : 679,
 '680' : 680,
 '681' : 681,
 '682' : 682,
 '683' : 683,
 '684' : 684,
 '685' : 685,
 '686' : 686,
 '687' : 687,
 '688' : 688,
 '689' : 689,
 '690' : 690,
 '691' : 691,
 '692' : 692,
 '693' : 693,
 '694' : 694,
 '695' : 695,
 '696' : 696,
 '697' : 697,
 '698' : 698,
 '699' : 699,
 '700' : 700,
 '701' : 701,
 '702' : 702,
 '703' : 703,
 '704' : 704,
 '705' : 705,
 '706' : 706,
 '707' : 707,
 '708' : 708,
 '709' : 709,
 '710' : 710,
 '711' : 711,
 '712' : 712,
 '713' : 713,
 '714' : 714,
 '715' : 715,
 '716' : 716,
 '717' : 717,
 '718' : 718,
 '719' : 719,
 '720' : 720,
 '721' : 721,
 '722' : 722,
 '723' : 723,
 '724' : 724,
 '725' : 725,
 '726' : 726,
 '727' : 727,
 '728' : 728,
 '729' : 729,
 '730' : 730,
 '731' : 731,
 '732' : 732,
 '733' : 733,
 '734' : 734,
 '735' : 735,
 '736' : 736,
 '737' : 737,
 '738' : 738,
 '739' : 739,
 '740' : 740,
 '741' : 741,
 '742' : 742,
 '743' : 743,
 '744' : 744,
 '745' : 745,
 '746' : 746,
 '747' : 747,
 '748' : 748,
 '749' : 749,
 '750' : 750,
 '751' : 751,
 '752' : 752,
 '753' : 753,
 '754' : 754,
 '755' : 755,
 '756' : 756,
 '757' : 757,
 '758' : 758,
 '759' : 759,
 '760' : 760,
 '761' : 761,
 '762' : 762,
 '763' : 763,
 '764' : 764,
 '765' : 765,
 '766' : 766,
 '767' : 767,
 '768' : 768,
 '769' : 769,
 '770' : 770,
 '771' : 771,
 '772' : 772,
 '773' : 773,
 '774' : 774,
 '775' : 775,
 '776' : 776,
 '777' : 777,
 '778' : 778,
 '779' : 779,
 '780' : 780,
 '781' : 781,
 '782' : 782,
 '783' : 783,
 '784' : 784,
 '785' : 785,
 '786' : 786,
 '787' : 787,
 '788' : 788,
 '789' : 789,
 '790' : 790,
 '791' : 791,
 '792' : 792,
 '793' : 793,
 '794' : 794,
 '795' : 795,
 '796' : 796,
 '797' : 797,
 '798' : 798,
 '799' : 799,
 '800' : 800,
 'zero': 0,
 'oh': 0,
 'o': 0,
    'one': 1,
    'two': 2,
    'to': 2,
    'three': 3,
    'four': 4,
    'for': 4,
    'five': 5,
    'six': 6,
    'sticks': 6,
    'seven': 7,
    'eight': 8,
    'ate': 8,
    'nine': 9,
    'ten': 10,
    'eleven': 11,
    'twelve': 12,
    'thirteen': 13,
    'fourteen': 14,
    'fifteen': 15,
    'sixteen': 16,
    'seventeen': 17,
    'eighteen': 18,
    'nineteen': 19,
    'twenty': 20,
    'thirty': 30,
    'forty': 40,
    'fifty': 50,
    'sixty': 60,
    'seventy': 70,
    'eighty': 80,
    'ninety': 90,
    'hundred': null,

};

I added the numbers just to be on the safe side and since the project I was working on only required 3 digit numbers (Course Numbers) I didn't have to go any further and thought it a good idea to just put those few hundred numbers. Clearly not a good idea for all numbers.

function text2num(s)

 {
  var array = s.toString().split(/[\s-]+/);
      var num=0;
       var a;
       var index=0;
        if(s.includes('hundred')){
        while(index<array.length){
        a=array[index];
        index++;
            if(a.includes('and')===false){
        num= feach(a, num, 0);
            }

    }
    return num;

    }else if(s.includes('ty') ){
        var d=100;
        while(index<array.length){
            a=array[index];

            index++;
                    if(a.includes('and')===false){
            num=feach(a, num, 0)*d;
            d=1;
                    }
        }
        return num;
    }else{
        var n='';

        while(index<array.length){
        a=array[index];
            if(a.includes('and')===false){
        n= n + feach(a, num, 0);
            }
        index++;
        }
        return n;
    }

    }
function feach(w, g, n ) {
        var x;
        var x = Small[w];
        if (x !== null) {
            g = g + x;
                return g;
        }
        else{
            g = g * 100;
                return g;
        }


问:
Django filter queryset __in for *every* item in list (2.0)
I've already read this and this, but they don't solve my problem because they make a final "count" with a comparison to a number that is hard-coded. I want to make a comparison of a number that is the sum of all ingredients of the recipe itself.

Let's imagine that I have some ingredients in my fridge, with their id's (= array of id's). I want to see what I can cook with that. I have my models like this:

```<code>class Ingredient(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    description = models.TextField(null=True, blank=True, default=None)

class Unit(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    abbr = models.CharField(max_length=20, null=True, blank=True,
                            default=None)

class IngredientUnit(models.Model):
    ingredient = models.ForeignKey(Ingredient, null=False, blank=True)
    unit = models.ForeignKey(Unit, null=False, blank=True)
    measurable = models.BooleanField(default=True, null=False, blank=True)
    is_int = models.BooleanField(default=True, null=False, blank=True)
    value = models.FloatField(null=True, blank=True, default=0.0)

class Recipe(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    description = models.TextField(null=True, blank=True, default=None)
    ingredients = models.ManyToManyField(IngredientUnit)
</code>```

I'd like to do this: 'select all recipe that have all' the ingredients of an array of ingredient's pk. For example: "Classic Vanilla Cake" has those ingredients: eggs, all-purpose flour, baking powder, baking soda, butter, sugar, vanilla, buttermilk. If one is missing, "Classic Vanilla Cake" shouldn't be in the resulting query. On the contrary, if there are more ingredients than those required, "Classic Vanilla Cake" should always be in the resulting query.

So far, I've done this, but it's not working.

```<code>    ingredient_ids = self.request.POST.getlist('ingredient[]', [])
    if len(ingredient_ids):
        recipes = Recipe.objects\
            .filter(ingredients__in=ingredient_ids)\
            .annotate(nb_ingredients=Count('ingredients'))\
            .filter(nb_ingredients=len(ingredient_ids))
        print([a for a in recipes])
</code>```

The problem is that nb_ingredients=len(ingredient_ids) should be nb_ingredients=the number of the ingredients of the current recipe

How can I do this?

答:
I found it! Can't avoid double query but it works like a charm. Here's the solution:

first, filter on Ingredients that are part of a recipe, for each recipe (= group by), count the total of ingredients found

then for all the existing recipes, if the total of ingredient == the total of ingredients founds before, then it's ok, keep it.

It feels like using a sledgehammer to crack a nut (even though the first query filters and eliminates a lot of recipes), but it works, if you have a better solution I'm your man!

```<code>recipes = Recipe.objects \
    .annotate(found=Count('*'))\
    .filter(ingredients__in=ingredient_ids)
for recipe in recipes:
    a = Recipe.objects.annotate(total=Count('ingredients')).filter(
        pk=recipe.pk, total=recipe.found)
    print("Recipe found:", str(a))
</code>```

And for example, if the ids of the ingredients are [1, 2, 3, 4, 5] you'll get those two queries:

```<code>SELECT "app_recipe"."id", "app_recipe"."label", "app_recipe"."description",
    COUNT(*) AS "found" FROM "app_recipe"
INNER JOIN "app_recipe_ingredients"
ON ("app_recipe"."id" = "app_recipe_ingredients"."recipe_id")
WHERE "app_recipe_ingredients"."ingredientunit_id" IN (1, 2, 3, 4, 5)
GROUP BY "app_recipe"."id", "app_recipe"."label", "app_recipe"."description";
</code>```

And the second loop will make queries based on the recipes found like this:

```<code>SELECT "app_recipe"."id", "app_recipe"."label", "app_recipe"."description",
    COUNT("app_recipe_ingredients"."ingredientunit_id") AS "total"
FROM "app_recipe"
LEFT OUTER JOIN "app_recipe_ingredients"
ON ("app_recipe"."id" = "app_recipe_ingredients"."recipe_id")
WHERE "app_recipe"."id" = 1
GROUP BY "app_recipe"."id", "app_recipe"."label", "app_recipe"."description"
HAVING COUNT("app_recipe_ingredients"."ingredientunit_id") = 5;
</code>```

Body:
I've already read this and this, but they don't solve my problem because they make a final "count" with a comparison to a number that is hard-coded. I want to make a comparison of a number that is the sum of all ingredients of the recipe itself.

Let's imagine that I have some ingredients in my fridge, with their id's (= array of id's). I want to see what I can cook with that. I have my models like this:

class Ingredient(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    description = models.TextField(null=True, blank=True, default=None)

class Unit(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    abbr = models.CharField(max_length=20, null=True, blank=True,
                            default=None)

class IngredientUnit(models.Model):
    ingredient = models.ForeignKey(Ingredient, null=False, blank=True)
    unit = models.ForeignKey(Unit, null=False, blank=True)
    measurable = models.BooleanField(default=True, null=False, blank=True)
    is_int = models.BooleanField(default=True, null=False, blank=True)
    value = models.FloatField(null=True, blank=True, default=0.0)

class Recipe(models.Model):
    label = models.CharField(max_length=200, null=True, blank=True,
                             default=None)
    description = models.TextField(null=True, blank=True, default=None)
    ingredients = models.ManyToManyField(IngredientUnit)

I'd like to do this: 'select all recipe that have all' the ingredients of an array of ingredient's pk. For example: "Classic Vanilla Cake" has those ingredients: eggs, all-purpose flour, baking powder, baking soda, butter, sugar, vanilla, buttermilk. If one is missing, "Classic Vanilla Cake" shouldn't be in the resulting query. On the contrary, if there are more ingredients than those required, "Classic Vanilla Cake" should always be in the resulting query.

So far, I've done this, but it's not working.

    ingredient_ids = self.request.POST.getlist('ingredient[]', [])
    if len(ingredient_ids):
        recipes = Recipe.objects\
            .filter(ingredients__in=ingredient_ids)\
            .annotate(nb_ingredients=Count('ingredients'))\
            .filter(nb_ingredients=len(ingredient_ids))
        print([a for a in recipes])

The problem is that nb_ingredients=len(ingredient_ids) should be nb_ingredients=the number of the ingredients of the current recipe

How can I do this?

Body:
I found it! Can't avoid double query but it works like a charm. Here's the solution:

first, filter on Ingredients that are part of a recipe, for each recipe (= group by), count the total of ingredients found

then for all the existing recipes, if the total of ingredient == the total of ingredients founds before, then it's ok, keep it.

It feels like using a sledgehammer to crack a nut (even though the first query filters and eliminates a lot of recipes), but it works, if you have a better solution I'm your man!

recipes = Recipe.objects \
    .annotate(found=Count('*'))\
    .filter(ingredients__in=ingredient_ids)
for recipe in recipes:
    a = Recipe.objects.annotate(total=Count('ingredients')).filter(
        pk=recipe.pk, total=recipe.found)
    print("Recipe found:", str(a))

And for example, if the ids of the ingredients are [1, 2, 3, 4, 5] you'll get those two queries:

SELECT "app_recipe"."id", "app_recipe"."label", "app_recipe"."description",
    COUNT(*) AS "found" FROM "app_recipe"
INNER JOIN "app_recipe_ingredients"
ON ("app_recipe"."id" = "app_recipe_ingredients"."recipe_id")
WHERE "app_recipe_ingredients"."ingredientunit_id" IN (1, 2, 3, 4, 5)
GROUP BY "app_recipe"."id", "app_recipe"."label", "app_recipe"."description";

And the second loop will make queries based on the recipes found like this:

SELECT "app_recipe"."id", "app_recipe"."label", "app_recipe"."description",
    COUNT("app_recipe_ingredients"."ingredientunit_id") AS "total"
FROM "app_recipe"
LEFT OUTER JOIN "app_recipe_ingredients"
ON ("app_recipe"."id" = "app_recipe_ingredients"."recipe_id")
WHERE "app_recipe"."id" = 1
GROUP BY "app_recipe"."id", "app_recipe"."label", "app_recipe"."description"
HAVING COUNT("app_recipe_ingredients"."ingredientunit_id") = 5;


答:
You're confused ISO date values do not show the "time zone" instead they show the UTC time. Z stand for Zulu (UTC time).

2017-06-07T15:29:23.692Z

The bold part is not the time zone. It is the milli-seconds, the full time is in UTC. The reason it shows a 000Z in the set Date is because you didnt' set the milli-seconds.

If you want to display the time zone use toUTCString(). However it will display GMT which is UTC/Greenwich Time. To display the local time zone in a the date format you can use date.toLocaleString('en-US',{timeZoneName:'short'}) for example will display the date plus the local US time zone. Or you can use toString() which will display the GMT offset + the long local time zone.

Title: In javascript, how to get timezone value in UTC format for new Date(2017,05,31).toISOString()?


问:
Real Memory VS. Private Memory
I have an Objective-C application that is designed to run for an extended period of time using WebKit views. After time the application builds up a fair amount of memory so I would like to accurately reveal the memory usage to the end user upon request. In Activity Monitor on OS X I see two memory values for my application Real Memory and Private Memory. From what I have read Private is everything that the process has and Real is an estimate. What should I trust? Is there a specific formula I can use to calculate the exact usage rather than what OS X reports?

Not my area of expertise.

答:
If you are worried about memory leaks, you should be using the various tools provided by Apple to debug it.

Real memory is the actual physical memory in use by the process.

Private memory is the physical memory that is used by just that process.

Virtual memory is the size of the entire virtual memory of the process including those pages that are not currently resident in physical RAM.

It's actually quite difficult to tell by looking at those numbers if you have a leak.  For example, a block that is malloced and then leaked will never be referenced again, so it'll eventually get swapped out.  It'll be part of the virtual memory but not part of the resident memory.  So if you have a leak, the virtual memory will gradually increase over time.

On the other hand, virtual memory will increase if malloc can't find an unused block of memory to allocate, but it won't decrease when free gives memory back.  So if you malloc a huge amount of RAM the VM will increase but even if you then free it correctly, it'll never decrease again.  If you also have a leak, it will take a long time for malloc to run out of the recycled VM which means that you might not notice it.

So, use the purpose built leak detection tools.

Title: Real Memory VS. Private Memory


问:
duplicate sourcemaps with Angular Cli - webpack
in the chrome developer tools I see multiple sourcemap to the same typescript file with GET. how can it be ? and what can I do to stay with only one ?

I'm using CLI-Webpack.

example for duplicate sourcemaps:

答: you need to promote the import of the module that holds this directive to app.module and it will solve this issue.</p>


问:
Convert list into a list of 2-tuples
I have a list:

```<code>list = [1, 2, 3]
</code>```

I want to get this list and add a tuple so this list becomes like this

```<code>T_list = [(1,x), (2, x), (3,x)]
</code>```

How do I do it?

答:
Here's my attempt, although I'm not an expert.</p>

```<code>lis = [1,2,3]
tup = (4, 5, 6)

new_tup = tuple(lis)
new_lis = []
for i in range(0,3):
    data = (new_tup[i],tup[i])
    new_lis.append(data)
print(new_lis)
</code>```

Title: Convert list into a list of 2-tuples

Body:
I have a list:

list = [1, 2, 3]

I want to get this list and add a tuple so this list becomes like this

T_list = [(1,x), (2, x), (3,x)]

How do I do it?

Body:
Here's my attempt, although I'm not an expert.

lis = [1,2,3]
tup = (4, 5, 6)

new_tup = tuple(lis)
new_lis = []
for i in range(0,3):
    data = (new_tup[i],tup[i])
    new_lis.append(data)
print(new_lis)


问:
Remove a page from Navigation Stack
I have this application schema :

```<code>[List Page] -> [Detail Page] -> [ShareOnFacebook Page]
                     ^__________________|
</code>```

The user select an Item in the [List Page]

The user may or may not click a Share button if he or she does, the application navigates to a [ShareOneFacebook page] which displays a Facebook Login Form, posts a message and navigates back

The user navigates back.

If the user shared on facebook, it will "repost" the message, because the application store the session so it will navigate back to ShareOnFacebook, and then back to my Detail page.

If the user didn't share, he goes back to the List Page.

How can I "ommit" the ShareOnFacebook page in my navigation stack ?

答:
Have a look at the new Nonlinear Navigation Service recipe

Download it from http://create.msdn.com/en-us/education/catalog/article/nln-serv-wp7

Title: Remove a page from Navigation Stack

Body:
I have this application schema :

[List Page] -> [Detail Page] -> [ShareOnFacebook Page]
                     ^__________________|

The user select an Item in the [List Page]

The user may or may not click a Share button if he or she does, the application navigates to a [ShareOneFacebook page] which displays a Facebook Login Form, posts a message and navigates back

The user navigates back.

If the user shared on facebook, it will "repost" the message, because the application store the session so it will navigate back to ShareOnFacebook, and then back to my Detail page.

If the user didn't share, he goes back to the List Page.

How can I "ommit" the ShareOnFacebook page in my navigation stack ?