问:
Is it possible to obtain index value from Singly linked list?
Suppose I have a singly linked list generated as:

```<code># Singly Linked List
class node:
  def __init__(self,data=None):
    self.data=data
    self.next=None

class linked_list:
  def __init__(self):
    self.head=node()

# Adds new node containing 'data' to the end of the linked list.
  def append(self,data):
    new_node=node(data)
    cur=self.head
    while cur.next!=None:
        cur=cur.next
    cur.next=new_node

# Returns the length (integer) of the linked list.
  def length(self):
    cur=self.head
    total=0
    while cur.next!=None:
        total+=1
        cur=cur.next
    return total

# Prints out the linked list in traditional Python list format.
  def display(self):
    elems=[]
    cur_node=self.head
    while cur_node.next!=None:
        cur_node=cur_node.next
        elems.append(cur_node.data)
    print elems

# Returns the value of the node at 'index'.
  def get(self,index):
    if index>=self.length():
        print "ERROR: 'Get' Index out of range!"
        return None
    cur_idx=0
    cur_node=self.head
    while True:
        cur_node=cur_node.next
        if cur_idx==index: return cur_node.data
        cur_idx+=1

# Deletes the node at index 'index'.
  def erase(self,index):
    if index>=self.length():
        print "ERROR: 'Erase' Index out of range!"
        return
    cur_idx=0
    cur_node=self.head
    while True:
        last_node=cur_node
        cur_node=cur_node.next
        if cur_idx==index:
            last_node.next=cur_node.next
            return
        cur_idx+=1

#Allows for bracket operator syntax (i.e. a[0] to return first item).
  def __getitem__(self,index):
    return self.get(index)

  def getindex(self,data):
    cur_node = self.data
    while True:
      cur_node = cur_node.next
        if cur_node == data:
            return cur_node.index
            break
        index +=1
</code>```

And suppose I create a singly linked list as:

```<code>new_list = linked_list()
new_list.append(5)
new_list.append(6)
new_list.append(8)
</code>```

Suppose I want to delete the 2nd value in the list (index 1) which happens to be the value 6 but I don't know what's the index for 6. How would I be able to find the index value of 6 and use it to delete 6? Or is there another way to delete a value from a singly linked list without knowing the index value?

EDIT: I've added a new module called getindex that should theoretically grab the index when a node is specified but I've gotten this error:

AttributeError: 'NoneType' object has no attribute 'next'. Its referring to the cur_node=cur_node.next line in the getindex module. How do I fix this error?

答:
This is the function which you need:

```<code>  def getIndex(self,data):
    cur_idx=0
    cur_node=self.head
    while cur_node.next:
        cur_node=cur_node.next
        if cur_node.data==data: return cur_idx
        cur_idx+=1
    return None
</code>```

And you use it like this:

```<code>new_list = linked_list()
new_list.append(5)
new_list.append(6)
new_list.append(8)
new_list.display()
idx = new_list.getIndex(6)
if idx != None:
    new_list.erase(idx)
new_list.display()
</code>```

Body:
Suppose I have a singly linked list generated as:

# Singly Linked List
class node:
  def __init__(self,data=None):
    self.data=data
    self.next=None

class linked_list:
  def __init__(self):
    self.head=node()

# Adds new node containing 'data' to the end of the linked list.
  def append(self,data):
    new_node=node(data)
    cur=self.head
    while cur.next!=None:
        cur=cur.next
    cur.next=new_node

# Returns the length (integer) of the linked list.
  def length(self):
    cur=self.head
    total=0
    while cur.next!=None:
        total+=1
        cur=cur.next
    return total

# Prints out the linked list in traditional Python list format.
  def display(self):
    elems=[]
    cur_node=self.head
    while cur_node.next!=None:
        cur_node=cur_node.next
        elems.append(cur_node.data)
    print elems

# Returns the value of the node at 'index'.
  def get(self,index):
    if index>=self.length():
        print "ERROR: 'Get' Index out of range!"
        return None
    cur_idx=0
    cur_node=self.head
    while True:
        cur_node=cur_node.next
        if cur_idx==index: return cur_node.data
        cur_idx+=1

# Deletes the node at index 'index'.
  def erase(self,index):
    if index>=self.length():
        print "ERROR: 'Erase' Index out of range!"
        return
    cur_idx=0
    cur_node=self.head
    while True:
        last_node=cur_node
        cur_node=cur_node.next
        if cur_idx==index:
            last_node.next=cur_node.next
            return
        cur_idx+=1

#Allows for bracket operator syntax (i.e. a[0] to return first item).
  def __getitem__(self,index):
    return self.get(index)

  def getindex(self,data):
    cur_node = self.data
    while True:
      cur_node = cur_node.next
        if cur_node == data:
            return cur_node.index
            break
        index +=1

And suppose I create a singly linked list as:

new_list = linked_list()
new_list.append(5)
new_list.append(6)
new_list.append(8)

Suppose I want to delete the 2nd value in the list (index 1) which happens to be the value 6 but I don't know what's the index for 6. How would I be able to find the index value of 6 and use it to delete 6? Or is there another way to delete a value from a singly linked list without knowing the index value?

EDIT: I've added a new module called getindex that should theoretically grab the index when a node is specified but I've gotten this error:

AttributeError: 'NoneType' object has no attribute 'next'. Its referring to the cur_node=cur_node.next line in the getindex module. How do I fix this error?

Body:
This is the function which you need:

  def getIndex(self,data):
    cur_idx=0
    cur_node=self.head
    while cur_node.next:
        cur_node=cur_node.next
        if cur_node.data==data: return cur_idx
        cur_idx+=1
    return None

And you use it like this:

new_list = linked_list()
new_list.append(5)
new_list.append(6)
new_list.append(8)
new_list.display()
idx = new_list.getIndex(6)
if idx != None:
    new_list.erase(idx)
new_list.display()


来源: stackexchange

问:
Why do I get this result in Python?
```<code>class A:
    def __init__ (self, an_int):
        self.g = an_int
        self.b = None

    def add (self, an_int):
        self.g += an_int + 1

class B:
    def __init__ (self, an_int):
        self.g = an_int
        self.a = None

    def subtract (self, an_int):
        self.g -= an_int-1

a = A(0)
b = B(1)

def show (an_a_obj, a_b_obj):
    print '%d %d' % (an_a_obj.g, a_b_obj.g)
</code>```

Now, I do this:

```<code>b.subtract(a.g)
show(a,b)
</code>```

What I am getting as a result, is 0 2, but I would think it should be:

```<code>0 0
</code>```

But that's definitely not true. What I don't understand is this part:

```<code>def subtract (self, an_int):
    self.g -= an_int-1
</code>```

So, a.g is being seen as "an_int" and then fetched, but as what? It's not global at all, so how can the interpreter know that a.g must be 0 or doesn't it know at all?

And what does self.g -= an_int - 1 do?

I would expect it's b.g (1) - 0 (a.g) - 1 = 0, but the interpreter says it's -1

Could someone help me in the right direction?

答: self.g -= an_int - 1 is equivalent to self.g = self.g - (an_int - 1), which is self.g = self.g + 1 - an_int. Since an_int is 0 in your example, self.g increases by 1.

ContentLicense: CC BY-SA 3.0

Title: Why do I get this result in Python?

Body:
class A:
    def __init__ (self, an_int):
        self.g = an_int
        self.b = None

    def add (self, an_int):
        self.g += an_int + 1

class B:
    def __init__ (self, an_int):
        self.g = an_int
        self.a = None

    def subtract (self, an_int):
        self.g -= an_int-1

a = A(0)
b = B(1)

def show (an_a_obj, a_b_obj):
    print '%d %d' % (an_a_obj.g, a_b_obj.g)

Now, I do this:

b.subtract(a.g)
show(a,b)

What I am getting as a result, is 0 2, but I would think it should be:

0 0

But that's definitely not true. What I don't understand is this part:

def subtract (self, an_int):
    self.g -= an_int-1

So, a.g is being seen as "an_int" and then fetched, but as what? It's not global at all, so how can the interpreter know that a.g must be 0 or doesn't it know at all?

And what does self.g -= an_int - 1 do?

I would expect it's b.g (1) - 0 (a.g) - 1 = 0, but the interpreter says it's -1

Could someone help me in the right direction?


问:
Get N Largest Date Pandas
I had posted this question and need to expand on the application. I now need to get the N max date for each Vendor:

```<code>#import pandas as pd
#df = pd.read_clipboard()
#df['Insert_Date'] = pd.to_datetime(df['Insert_Date'])

# used in example below
#df2 = df.sort_values(['Vendor','InsertDate']).drop_duplicates(['Vendor'],keep='last')

Vendor  Insert_Date Total
Steph   2017-10-25  2
Matt    2017-10-31  13
Chris   2017-11-03  3
Steve   2017-10-23  11
Chris   2017-10-27  3
Steve   2017-11-01  11
</code>```

If I needed to get the 2nd max date expected output would be:

```<code>Vendor  Insert_Date Total
Steph   2017-10-25  2
Steve   2017-10-23  11
Matt    2017-10-31  13
Chris   2017-10-27  3
</code>```

I can easily get the 2nd max date by using df2 in the example df.loc[~df.index.isin(df2.index)] but if i need to get the 50th max value, that is a lot of dataframe building to use isin()...

I have also tried df.groupby('Vendor')['Insert_Date'].nlargest(N_HERE) which gets me close, but i then need to get the N value for each Vendor.

I have also tried filtering out the df by Vendor:

df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)

but if I try to get the second record with df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)[2] it returns: Timestamp('2017-11-03 00:00:00'). Instead i need to use df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)[1:2]. Why must I use list slicing here and not simply[2]?

In summary? how do I return the N largest date by Vendor?

答:
I might've misunderstood your initial problem. You can sort on Insert_Date, and then use groupby + apply in this manner:

```<code>n = 9
df.sort_values('Insert_Date')\
          .groupby('Vendor', as_index=False).apply(lambda x: x.iloc[-n])
</code>```

For your example data, it seems n = 0 does the trick.

```<code>df.sort_values('Insert_Date')\
      .groupby('Vendor', as_index=False).apply(lambda x: x.iloc[0])

  Vendor Insert_Date  Total
0  Chris  2017-10-27      3
1   Matt  2017-10-31     13
2  Steph  2017-10-25      2
3  Steve  2017-10-23     11
</code>```

Beware, this code will throw errors if your Vendor groups are smaller in size than n.

Title: Get N Largest Date Pandas

Body:
I had posted this question and need to expand on the application. I now need to get the N max date for each Vendor:

#import pandas as pd
#df = pd.read_clipboard()
#df['Insert_Date'] = pd.to_datetime(df['Insert_Date'])

# used in example below
#df2 = df.sort_values(['Vendor','InsertDate']).drop_duplicates(['Vendor'],keep='last')

Vendor  Insert_Date Total
Steph   2017-10-25  2
Matt    2017-10-31  13
Chris   2017-11-03  3
Steve   2017-10-23  11
Chris   2017-10-27  3
Steve   2017-11-01  11

If I needed to get the 2nd max date expected output would be:

Vendor  Insert_Date Total
Steph   2017-10-25  2
Steve   2017-10-23  11
Matt    2017-10-31  13
Chris   2017-10-27  3

I can easily get the 2nd max date by using df2 in the example df.loc[~df.index.isin(df2.index)] but if i need to get the 50th max value, that is a lot of dataframe building to use isin()...

I have also tried df.groupby('Vendor')['Insert_Date'].nlargest(N_HERE) which gets me close, but i then need to get the N value for each Vendor.

I have also tried filtering out the df by Vendor:

df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)

but if I try to get the second record with df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)[2] it returns: Timestamp('2017-11-03 00:00:00'). Instead i need to use df.loc[df['Vendor']=='Chris', 'Insert_Date'].nlargest(2)[1:2]. Why must I use list slicing here and not simply[2]?

In summary? how do I return the N largest date by Vendor?

Body:
I might've misunderstood your initial problem. You can sort on Insert_Date, and then use groupby + apply in this manner:

n = 9
df.sort_values('Insert_Date')\
          .groupby('Vendor', as_index=False).apply(lambda x: x.iloc[-n])

For your example data, it seems n = 0 does the trick.

df.sort_values('Insert_Date')\
      .groupby('Vendor', as_index=False).apply(lambda x: x.iloc[0])

  Vendor Insert_Date  Total
0  Chris  2017-10-27      3
1   Matt  2017-10-31     13
2  Steph  2017-10-25      2
3  Steve  2017-10-23     11

Beware, this code will throw errors if your Vendor groups are smaller in size than n.


问:
How to use SQL Joins and Selects to get results from a third table that matches the first two?
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

```<code>Select * from 3rdTable where City='' AND State='';
</code>```

Result from Join is like

```<code> - City | State
 - A    | B
 - C    | D
 - E    | F
</code>```

Example Result if only 1 row of the 3rd table matches

```<code> - C    |  D
</code>```

How can this be done?

答:
You can use the joined table as a sub table in 3rdTable to create a where clause as follows;

```<code>select *
from 3rdTable
where City+'|'+State= (select a.City+'|'+b.State
                       from a
                       inner join b
                         on a.x=b.y)
</code>```

Buy concatenating the fields, you can create a single equality to the joined subquery

Body:
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

Select * from 3rdTable where City='' AND State='';

Result from Join is like

 - City | State
 - A    | B
 - C    | D
 - E    | F

Example Result if only 1 row of the 3rd table matches

 - C    |  D

How can this be done?

Body:
You can use the joined table as a sub table in 3rdTable to create a where clause as follows;

select *
from 3rdTable
where City+'|'+State= (select a.City+'|'+b.State
                       from a
                       inner join b
                         on a.x=b.y)

Buy concatenating the fields, you can create a single equality to the joined subquery


问:
Long to wide format with character value in r
I have a long data frame as below:

```<code>   Date        Time         Type
    1            1            A
    1            2            B
    1            3            C
    2            2            C
    2            3            D
    2            5            A
    2            7            E
</code>```

I want to change it to a wide format like the following:

```<code>   Date      Time1    Time2    Time3   Time4    Time5    Time6   Time7
     1         A        B        C
     2                  C        D                A                E
</code>```

I used the following code but it only gives me 0 and 1 values instead of 'Type' values:

```<code>   df_index = ddply(df, .(Date), mutate, index = paste0('Time', 1:length(Date)))
   df2 = dcast(df_index, Date ~ index, value.var = 'Type')
</code>```

Could you please help me here?

答:
You can use tidyr (part of the fantastic tidyverse you should look into) to do this fairly easily.

```<code>install.packages('tidyr')
install.packages('dplyr')

library(tidyr)
library(dplyr)

all_times <- data.frame(Time = c(1:6))
df <- data.frame(Date = c(1, 1, 1, 2, 2, 2, 2), Time = c(1, 2, 3, 2, 3, 5, 7),Type = c('A', 'B', 'C', 'C', 'D', 'A', 'E'))

spread_df <- df %>% right_join(all_times) %>% spread(Time, Type, sep = '.') %>% filter(!is.na(Date))
</code>```

Edited based on PoGibas's comment

Body:
I have a long data frame as below:

   Date        Time         Type
    1            1            A
    1            2            B
    1            3            C
    2            2            C
    2            3            D
    2            5            A
    2            7            E

I want to change it to a wide format like the following:

   Date      Time1    Time2    Time3   Time4    Time5    Time6   Time7
     1         A        B        C
     2                  C        D                A                E

I used the following code but it only gives me 0 and 1 values instead of 'Type' values:

   df_index = ddply(df, .(Date), mutate, index = paste0('Time', 1:length(Date)))
   df2 = dcast(df_index, Date ~ index, value.var = 'Type')

Could you please help me here?

Body:
You can use tidyr (part of the fantastic tidyverse you should look into) to do this fairly easily.

install.packages('tidyr')
install.packages('dplyr')

library(tidyr)
library(dplyr)

all_times <- data.frame(Time = c(1:6))
df <- data.frame(Date = c(1, 1, 1, 2, 2, 2, 2), Time = c(1, 2, 3, 2, 3, 5, 7),Type = c('A', 'B', 'C', 'C', 'D', 'A', 'E'))

spread_df <- df %>% right_join(all_times) %>% spread(Time, Type, sep = '.') %>% filter(!is.na(Date))

Edited based on PoGibas's comment


问:
Array formula to return an ARRAY without duplicates, without VBA
I would like to know whether it's possible to return an array from a single cell formula, which is filtered to remove duplicates, and which is built purely on Excel formulas.

I'm aware of approaches to return a list of values where the duplicates are removed (see this question), where the list is spread over multiple cells. However I specifically want to return an array intermediate.

E.g. For the list in A1:A5, I can get an array of values {0.1,0.2,0.2,0.7,0.3}, from which I want a second array {0.1,0.2,0.7,0.3}, as an intermediate in an array formula. Current approaches use single-end anchored ranges (like C$1:C1) to iterate through the items in the array geometrically (by dragging down column C). I would like to leave the array un-iterated, within the formula. I can then manipulate this as I would any other array.

All this should take place in a single cell if possible.

NB

Both MacroMarc's and Barry Houdini's answers are perfectly valid, and I ran a speed check on each - there was negligible difference (any difference was smaller than the variation between test runs). Both scored ~ 1.0±0.2 ms

答:
This formula will return a sorted array without duplicates, e.g. for your example

{0.1;0.2;0.3;0.7}

=SMALL(IF(MATCH(A1:A5,A1:A5,0)=ROW(A1:A5)-ROW(A1)+1,A1:A5),ROW(INDIRECT("1:"&SUM(0+(0<(FREQUENCY(A1:A5,A1:A5)))))))

confirmed with CTRL+SHIFT+ENTER

......or this version will keep the order

=INDEX(A1:A5,N(IF({1},SMALL(IF(MATCH(A1:A5,A1:A5,0)=ROW(A1:A5)-ROW(A1)+1,ROW(A1:A5)-ROW(A1)+1),ROW(INDIRECT("1:"&SUM(0+(0<(FREQUENCY(A1:A5,A1:A5))))))))))


问:
Is it possible to hide a page in a PDF document using javascript?
Is it possible to hide a page in a PDF document using javascript?</p>

答: You can also use Layers to hide content in PDF files.</p>

ContentLicense: CC BY-SA 2.5


问:
How to serve Video response without downloading the whole video on browser
I am using Pyramid with ZODB as Database storage. I want to return video response and I am able to but the only problem is browser downloads the whole video and then plays it and I don't want that to happen. I wanted to stream video but I am unable to find any proper solution.
Here's my code

Function which returns video response is:

```<code>@view_config(context=Content, name='getcontentplay')
def getContentImage(context,request):
    blob = context.blobdata
    resp = Response(content_disposition="inline; filename=\""+blob.filename.encode('utf-8')+"\"",content_type=blob.contentType,)
    resp.app_iter = blob.data
    resp.content_length = blob.size
    return resp
</code>```

And Blob Storage Class is:

```<code>from ZODB.blob import Blob
from persistent import Persistent

class BlobWrapper(Persistent):
    def __init__(self, filedata,contentType,filename):
        self.contentType = contentType
        self._blob = Blob(filedata)
        self.filename = filename

    def _getData(self):
        fp = self._blob.open('r')
        data = fp.read()
        fp.close()
        return data

    def retFile(self):
        return self._blob.open('r')

    data = property(_getData)

    @property
    def size(self):
        if 'size' in self.__dict__:
            return self.__dict__['size']
        reader = self._blob.open()
        reader.seek(0,2)
        size = int(reader.tell())
        reader.seek(0)
        reader.close()
        self.__dict__['size'] = size
        return size

    def getSize(self):
        return self.size
</code>```

And My HTML Template Code is

<video   poster="/static/images/kid.png" controls controlsList="nodownload" preload="none">
    <source src="${urltovideo}" />
</video>```

答: You are asking how to get a chunked/streaming response and the details of this are entirely dependent on your wsgi server and any other servers/proxies between the wsgi server and the client's browser. For example nginx will, by default, buffer the entire response from its upstream before sending the response to the client. Also many WSGI servers will do the same to a certain degree and you need to look at their settings for how to tune that buffering.</p>

Body:
I am using Pyramid with ZODB as Database storage. I want to return video response and I am able to but the only problem is browser downloads the whole video and then plays it and I don't want that to happen. I wanted to stream video but I am unable to find any proper solution.
Here's my code

Function which returns video response is:

@view_config(context=Content, name='getcontentplay')
def getContentImage(context,request):
    blob = context.blobdata
    resp = Response(content_disposition="inline; filename=\""+blob.filename.encode('utf-8')+"\"",content_type=blob.contentType,)
    resp.app_iter = blob.data
    resp.content_length = blob.size
    return resp

And Blob Storage Class is:

from ZODB.blob import Blob
from persistent import Persistent

class BlobWrapper(Persistent):
    def __init__(self, filedata,contentType,filename):
        self.contentType = contentType
        self._blob = Blob(filedata)
        self.filename = filename

    def _getData(self):
        fp = self._blob.open('r')
        data = fp.read()
        fp.close()
        return data

    def retFile(self):
        return self._blob.open('r')

    data = property(_getData)

    @property
    def size(self):
        if 'size' in self.__dict__:
            return self.__dict__['size']
        reader = self._blob.open()
        reader.seek(0,2)
        size = int(reader.tell())
        reader.seek(0)
        reader.close()
        self.__dict__['size'] = size
        return size

    def getSize(self):
        return self.size

And My HTML Template Code is

<video   poster="/static/images/kid.png" controls controlsList="nodownload" preload="none">
    <source src="${urltovideo}" />
</video>


问:
Possibility of connecting two django apps within a django project
I am about to build a django project for a web app I am developing. For structural purposes, I want to know if it is possible to have two different apps within a project that communicate with each other like two different things in a single app within a django project. For example:

have two different parts of a django project. users and groups.

I currently have a testing project that has both within the general app of the django project. within the general project I included all parts of project in a single app. I want to know if i can break apart different parts of this project into seperate apps that can communicate with each other (templates, redirects, renders), and how I can connect them or what I need to do to connect them together.

```<code>example
  -example
    -__init__.py
    -settings.py
    -urls.py
    -wsgi.py
  -general
    -__init__.py
    -admin.py
    -apps.py
    -models.py
    -test.py
    -urls.py
    -views.p
</code>```

THis is what I am thinking of doing

```<code>example
  -example
     -__init__.py
     -settings.py
     -urls.py
     -wsgi.py
   -users
     -__init__.py
     -admin.py
     -apps.py
     -models.py
     -test.py
     -urls.py
     -views.p
   -groups
     -__init__.py
     -admin.py
     -apps.py
     -models.py
     -test.py
     -urls.py
     -views.p
</code>```

How can i connect the two different projects inthe urls file so I can redirect url's between the two. if possible, what would a redirect look like if I want to go from a url in the users app to a url in a groups app... What would the main urls file look like... in the example folder...

Another question is... are queries going to stay the same or do i need to change how queries are made...

答:
Yes you certainly can have multiple apps communicate with each other in a django project.

example.urls:

```<code>from django.conf.urls import include, url

urlpatterns = [
    url(r'^users/', include('users.urls')),
    url(r'^groups/', include('groups.urls')),
]
</code>```

users.urls:

```<code>urlpatterns = [

    url(r'^myurl/$', users.views.myview, name='users_myview'),

]
</code>```

By using the name argument with an app identifier such as users_ you can ensure that your urls can be uniquely identified. In a view you can then refer to it as:

views.py:

```<code>from django.core.urlresolvers import reverse
reverse('users_myview',args=())
</code>```

Body:
I am about to build a django project for a web app I am developing. For structural purposes, I want to know if it is possible to have two different apps within a project that communicate with each other like two different things in a single app within a django project. For example:

have two different parts of a django project. users and groups.

I currently have a testing project that has both within the general app of the django project. within the general project I included all parts of project in a single app. I want to know if i can break apart different parts of this project into seperate apps that can communicate with each other (templates, redirects, renders), and how I can connect them or what I need to do to connect them together.

example
  -example
    -__init__.py
    -settings.py
    -urls.py
    -wsgi.py
  -general
    -__init__.py
    -admin.py
    -apps.py
    -models.py
    -test.py
    -urls.py
    -views.p

THis is what I am thinking of doing

example
  -example
     -__init__.py
     -settings.py
     -urls.py
     -wsgi.py
   -users
     -__init__.py
     -admin.py
     -apps.py
     -models.py
     -test.py
     -urls.py
     -views.p
   -groups
     -__init__.py
     -admin.py
     -apps.py
     -models.py
     -test.py
     -urls.py
     -views.p

How can i connect the two different projects inthe urls file so I can redirect url's between the two. if possible, what would a redirect look like if I want to go from a url in the users app to a url in a groups app... What would the main urls file look like... in the example folder...

Another question is... are queries going to stay the same or do i need to change how queries are made...

Body:
Yes you certainly can have multiple apps communicate with each other in a django project.

example.urls:

from django.conf.urls import include, url

urlpatterns = [
    url(r'^users/', include('users.urls')),
    url(r'^groups/', include('groups.urls')),
]

users.urls:

urlpatterns = [

    url(r'^myurl/$', users.views.myview, name='users_myview'),

]

By using the name argument with an app identifier such as users_ you can ensure that your urls can be uniquely identified. In a view you can then refer to it as:

views.py:

from django.core.urlresolvers import reverse
reverse('users_myview',args=())


问:
change radar image based on button click
I could do with some help. I have a radar which displays objects. I'm trying to introduce a radar scan feature so that when a button is clicked the image on the radar is updated based on the tag of the object. My code has no errors but I can't get it to work and was hoping someone here could spot what the problem is. Thanks!!!!

RadarScan Script

```<code>public class RadarScan : MonoBehaviour {

public Image RadarImageToChange;

public void ChangeImage(Image UpdateImage)
{
    if(gameObject.tag == "Enemy")
    {
        UpdateImage = RadarImageToChange;
    }

}
</code>```

Radar Script

```<code>public class RadarObject
{
    public Image icon { get; set; }
    public GameObject owner { get; set; }
}

public class Radar : MonoBehaviour {

public Transform playerPos; //position of player
float mapScale = 0.1f; //scale radar size

public static List<RadarObject> radObjects = new List<RadarObject>();

//Registers Object to the radar
public static void RegisterRadarObject(GameObject o, Image i)
{
    Image image = Instantiate(i);
    radObjects.Add(new RadarObject() { owner = o, icon = image }); //adds to List
}

//It loops through the list looking for the owner existing in the list, when it finds the owner is detroys the icon
public static void RemoveRadarObject(GameObject o)
{
    //New list for destroyed objects
    List<RadarObject> newList = new List<RadarObject>();
    for (int i = 0; i < radObjects.Count; i++)
    {
        if (radObjects[i].owner == o)
        {
            Destroy(radObjects[i].icon);
            continue;
        }
         else
            newList.Add(radObjects[i]);
        }
    radObjects.RemoveRange(0, radObjects.Count);
    radObjects.AddRange(newList);
}

void DrawRadarDots()
{
    //loops through the list and for each Object it gets the owners transform position and determins the difference between it's
    //position and the players position, does calculations on the angle and distance and position on a circle using polar equations.
    foreach (RadarObject ro in radObjects)
    {
        Vector3 radarPos = (ro.owner.transform.position - playerPos.position);
        float distToObject = Vector3.Distance(playerPos.position, ro.owner.transform.position) * mapScale;
        float deltay = Mathf.Atan2(radarPos.x, radarPos.z) * Mathf.Rad2Deg - 270 - playerPos.eulerAngles.y;
        radarPos.x = distToObject * Mathf.Cos(deltay * Mathf.Deg2Rad) * -1;
        radarPos.z = distToObject * Mathf.Sin(deltay * Mathf.Deg2Rad);

        //grabs icon of players objects and make it a child of panel and set it's postion based on radarPos.x and radarPos.z
        ro.icon.transform.SetParent(this.transform);
        ro.icon.transform.position = new Vector3(radarPos.x, radarPos.z, 0) + this.transform.position;
    }
}

    //Update is called once per frame
    void Update ()
    {
        DrawRadarDots();
    }
</code>```

}

MakeRadarObject Script

```<code>public class MakeRadarObject : MonoBehaviour {

public Image image;

// Use this for initialization
void Start () {
    Radar.RegisterRadarObject(this.gameObject, image);
}

void OnDestroy()
{
    Radar.RemoveRadarObject(this.gameObject);
}
</code>```

}

答:
You aren't applying the Image to your gameobject, only to a variable named UpdateImage. You need to get the image component of your gameobject and then assign the new image to it. You will also need to change the Image to the form of a Sprite for this to work.</p>

```<code>public Sprite RadarImageToChange;

public void ChangeImage(Sprite UpdateImage)
{
        if(gameObject.tag == "Enemy")
        {
            gameObject.GetComponent<Image>().sprite = RadarImageToChange;
        }
}
</code>```

Body:
I could do with some help. I have a radar which displays objects. I'm trying to introduce a radar scan feature so that when a button is clicked the image on the radar is updated based on the tag of the object. My code has no errors but I can't get it to work and was hoping someone here could spot what the problem is. Thanks!!!!

RadarScan Script

public class RadarScan : MonoBehaviour {

public Image RadarImageToChange;

public void ChangeImage(Image UpdateImage)
{
    if(gameObject.tag == "Enemy")
    {
        UpdateImage = RadarImageToChange;
    }

}

Radar Script

public class RadarObject
{
    public Image icon { get; set; }
    public GameObject owner { get; set; }
}

public class Radar : MonoBehaviour {

public Transform playerPos; //position of player
float mapScale = 0.1f; //scale radar size

public static List<RadarObject> radObjects = new List<RadarObject>();

//Registers Object to the radar
public static void RegisterRadarObject(GameObject o, Image i)
{
    Image image = Instantiate(i);
    radObjects.Add(new RadarObject() { owner = o, icon = image }); //adds to List
}

//It loops through the list looking for the owner existing in the list, when it finds the owner is detroys the icon
public static void RemoveRadarObject(GameObject o)
{
    //New list for destroyed objects
    List<RadarObject> newList = new List<RadarObject>();
    for (int i = 0; i < radObjects.Count; i++)
    {
        if (radObjects[i].owner == o)
        {
            Destroy(radObjects[i].icon);
            continue;
        }
         else
            newList.Add(radObjects[i]);
        }
    radObjects.RemoveRange(0, radObjects.Count);
    radObjects.AddRange(newList);
}

void DrawRadarDots()
{
    //loops through the list and for each Object it gets the owners transform position and determins the difference between it's
    //position and the players position, does calculations on the angle and distance and position on a circle using polar equations.
    foreach (RadarObject ro in radObjects)
    {
        Vector3 radarPos = (ro.owner.transform.position - playerPos.position);
        float distToObject = Vector3.Distance(playerPos.position, ro.owner.transform.position) * mapScale;
        float deltay = Mathf.Atan2(radarPos.x, radarPos.z) * Mathf.Rad2Deg - 270 - playerPos.eulerAngles.y;
        radarPos.x = distToObject * Mathf.Cos(deltay * Mathf.Deg2Rad) * -1;
        radarPos.z = distToObject * Mathf.Sin(deltay * Mathf.Deg2Rad);

        //grabs icon of players objects and make it a child of panel and set it's postion based on radarPos.x and radarPos.z
        ro.icon.transform.SetParent(this.transform);
        ro.icon.transform.position = new Vector3(radarPos.x, radarPos.z, 0) + this.transform.position;
    }
}

    //Update is called once per frame
    void Update ()
    {
        DrawRadarDots();
    }

}

MakeRadarObject Script

public class MakeRadarObject : MonoBehaviour {

public Image image;

// Use this for initialization
void Start () {
    Radar.RegisterRadarObject(this.gameObject, image);
}

void OnDestroy()
{
    Radar.RemoveRadarObject(this.gameObject);
}

}

Body:
You aren't applying the Image to your gameobject, only to a variable named UpdateImage. You need to get the image component of your gameobject and then assign the new image to it. You will also need to change the Image to the form of a Sprite for this to work.

public Sprite RadarImageToChange;

public void ChangeImage(Sprite UpdateImage)
{
        if(gameObject.tag == "Enemy")
        {
            gameObject.GetComponent<Image>().sprite = RadarImageToChange;
        }
}


问:
Try-catch block not executing at all
I'm trying to get some data out of Microsoft Acess and check it through MessageBoxes so the user can see if that is the data that he wants but the code its not executing at all. I can't see any of the message boxes and no exceptions are thrown.
Below its the code that I put in the Button event. (I've only done the first if, the CNPJ one).</p>

```<code>if (TipoConsulta.Text == "CNPJ")
{
    try
    {
        string comando = "SELECT razao_social FROM tblImobiliarias WHERE cnpj ='" + ValorConsulta.Text + "'";
        string conn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\\\\10.7.41.153\\Apoio\\Davi_Database\\Base_Imo.accdb";
        OleDbConnection Connection = new OleDbConnection(conn);
        OleDbCommand Command = new OleDbCommand(comando, Connection);
        Connection.Open();
        OleDbDataReader reader = Command.ExecuteReader();
        while (reader.Read())
        {
            foreach (OleDbDataReader resultado in reader)
            {
                DialogResult resultadoDialogo;
                resultadoDialogo = MessageBox.Show("Encontrada razão social '" + resultado.ToString() + "'.\n Está correto?", "Pesquisa", MessageBoxButtons.YesNo);
                if (resultadoDialogo == System.Windows.Forms.DialogResult.Yes)
                {

                    MessageBox.Show("Executado CarregaImobiliaria().");
                    break;
                }
                else if (resultadoDialogo == System.Windows.Forms.DialogResult.No)
                {
                    continue;
                }
            }
        }
    }
    catch (InvalidOperationException)
    {
        MessageBox.Show("Nada foi encontrado com o CNPJ " + ValorConsulta.Text + ".", "Pesquisa");
    }
}
else if (TipoConsulta.Text == "Razão Social")
{
    MessageBox.Show("Tipo: Razão Social");
    try
    {

    }
    catch (InvalidOperationException)
    {

    }
}
else if (TipoConsulta.Text == "RGI")
{
    MessageBox.Show("Tipo: Sub: RGI");
    try
    {

    }
    catch (InvalidOperationException)
    {

    }
}
</code>```

答:
The problem was probably was the lack of a matrix to acess the DataReader value, because of that the foreach block was never executed. I ended up using a while with a int.</p>

```<code>string _cmd = "SELECT razao_social FROM tblImobiliarias WHERE cnpj ='" + ValorConsulta.Text + "'";
                    string conn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\\\\10.7.41.153\\Apoio\\Davi_Database\\Base_Imo.accdb";
                    OleDbConnection Connection = new OleDbConnection(conn);
                    OleDbCommand Command = new OleDbCommand(_cmd, Connection);
                    Connection.Open();
                    OleDbDataReader reader = Command.ExecuteReader();
                    while (reader.Read())
                    {
                        int _resMatriz = 0;
                        DialogResult result;
                        result = MessageBox.Show("Encontrado imobiliária: " + reader[_resMatriz] + ".\nEstá correto?", "Pesquisa", MessageBoxButtons.YesNo);
                        _resMatriz++;
                        if (result == System.Windows.Forms.DialogResult.Yes)
                        {
                            MessageBox.Show("CarregaImo()");
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
</code>```

Title: Try-catch block not executing at all

Body:
I'm trying to get some data out of Microsoft Acess and check it through MessageBoxes so the user can see if that is the data that he wants but the code its not executing at all. I can't see any of the message boxes and no exceptions are thrown.
Below its the code that I put in the Button event. (I've only done the first if, the CNPJ one).

if (TipoConsulta.Text == "CNPJ")
{
    try
    {
        string comando = "SELECT razao_social FROM tblImobiliarias WHERE cnpj ='" + ValorConsulta.Text + "'";
        string conn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\\\\10.7.41.153\\Apoio\\Davi_Database\\Base_Imo.accdb";
        OleDbConnection Connection = new OleDbConnection(conn);
        OleDbCommand Command = new OleDbCommand(comando, Connection);
        Connection.Open();
        OleDbDataReader reader = Command.ExecuteReader();
        while (reader.Read())
        {
            foreach (OleDbDataReader resultado in reader)
            {
                DialogResult resultadoDialogo;
                resultadoDialogo = MessageBox.Show("Encontrada razão social '" + resultado.ToString() + "'.\n Está correto?", "Pesquisa", MessageBoxButtons.YesNo);
                if (resultadoDialogo == System.Windows.Forms.DialogResult.Yes)
                {

                    MessageBox.Show("Executado CarregaImobiliaria().");
                    break;
                }
                else if (resultadoDialogo == System.Windows.Forms.DialogResult.No)
                {
                    continue;
                }
            }
        }
    }
    catch (InvalidOperationException)
    {
        MessageBox.Show("Nada foi encontrado com o CNPJ " + ValorConsulta.Text + ".", "Pesquisa");
    }
}
else if (TipoConsulta.Text == "Razão Social")
{
    MessageBox.Show("Tipo: Razão Social");
    try
    {

    }
    catch (InvalidOperationException)
    {

    }
}
else if (TipoConsulta.Text == "RGI")
{
    MessageBox.Show("Tipo: Sub: RGI");
    try
    {

    }
    catch (InvalidOperationException)
    {

    }
}

Body:
The problem was probably was the lack of a matrix to acess the DataReader value, because of that the foreach block was never executed. I ended up using a while with a int.

string _cmd = "SELECT razao_social FROM tblImobiliarias WHERE cnpj ='" + ValorConsulta.Text + "'";
                    string conn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\\\\10.7.41.153\\Apoio\\Davi_Database\\Base_Imo.accdb";
                    OleDbConnection Connection = new OleDbConnection(conn);
                    OleDbCommand Command = new OleDbCommand(_cmd, Connection);
                    Connection.Open();
                    OleDbDataReader reader = Command.ExecuteReader();
                    while (reader.Read())
                    {
                        int _resMatriz = 0;
                        DialogResult result;
                        result = MessageBox.Show("Encontrado imobiliária: " + reader[_resMatriz] + ".\nEstá correto?", "Pesquisa", MessageBoxButtons.YesNo);
                        _resMatriz++;
                        if (result == System.Windows.Forms.DialogResult.Yes)
                        {
                            MessageBox.Show("CarregaImo()");
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }


问:
Optimizing subsetting with data.table in a loop
I have a basic question on how to optimize the following code. This is a very very abbreviated version of my code. Basically, I have a large data.table (> 50M rows) and I would like to subset the data very often (say 10000 times) and run some function on the subset (obviously more complicated than the one shown in the example below, i.e. I need all columns of the subset and the function returns a new data.table). I just picked the mean to make the example simple.

```<code>dt <- data.table(a=sample(letters, 1000000,replace=T),b=sample(1:100000))

mm <- list()

foo <- function(x) mean(x$b)

for(i in 1:1000)
{
  mm[[i]] <-  foo(dt[a %in% sample(letters,5)])
}
</code>```

It is obvious that this is not the fastest way to program even this minimal example (setting keys etc.).

I am interested, however, how to optimize the for loop. I had in mind to create indices for the subsets and then use data.table dt[,foo(.SD),by=subset_ID] , but I am not sure on how to this, since I am sampling with replacement (multiple group IDs). Any ideas based on data.table would be much appreciated (e.g. how to remove the loop?).

答:
I had in mind to create indices for the subsets and then use data.table dt[,foo(.SD),by=subset_ID], but I am not sure on how to this, since I am sampling with replacement (multiple group IDs).

With a join, you can have overlapping groups:

```<code># convert to numeric
dt[, b := as.numeric(b)]

# make samples
set.seed(1)
mDT = setDT(melt(replicate(1000, sample(letters,5))))
setnames(mDT, c("seqi", "g", "a"))

# compute function on each sample
dt[mDT, on=.(a), allow.cartesian=TRUE, .(g, b)][, .(res = mean(b)), by=g]
</code>```

which gives

```<code>         g      res
   1:    1 50017.85
   2:    2 49980.03
   3:    3 50093.80
   4:    4 50087.67
   5:    5 49990.83
  ---
 996:  996 50013.11
 997:  997 50095.43
 998:  998 49913.61
 999:  999 50058.44
1000: 1000 49909.36
</code>```

To confirm it's doing the right thing, you can check eg,

```<code>dt[a %in% mDT[g == 1, a], mean(b)]
# [1] 50017.85
</code>```

One downside of this approach is that it involves creating a very large table (containing the data for all the samples), which may put you in trouble, RAM-wise.

This approach is taking advantage of your function being mean, since passing it explicitly allows for certain optimizations; see ?GForce, which is also why I converted b to numeric.

I agree with Rob Jensen's suggestion to pass columns to the function instead of passing a table (with the function making assumptions about what columns appear in the table), both for efficiency and clarity.

In the specific case of taking the mean, you could speed this up further by adding up for each letter first, I think:

```<code>dtagg = dt[, .(.N, sumb = sum(b)), by=a]

dtagg[mDT, on=.(a), .(g, sumb, N)][, lapply(.SD, sum), by=g][, .(g, res = sumb/N)]

         g      res
   1:    1 50017.85
   2:    2 49980.03
   3:    3 50093.80
   4:    4 50087.67
   5:    5 49990.83
  ---
 996:  996 50013.11
 997:  997 50095.43
 998:  998 49913.61
 999:  999 50058.44
1000: 1000 49909.36
</code>```

allow.cartesian is not needed in this case, since each row of mDT finds only a single row in dtagg. On my computer, the speedup with the example data is pretty big, but most of the benefit comes from taking advantage of the form of the example function, I guess:

13.7 sec OP's approach

11.4 sec simple join

0.02 sec aggregate-first

Body:
I have a basic question on how to optimize the following code. This is a very very abbreviated version of my code. Basically, I have a large data.table (> 50M rows) and I would like to subset the data very often (say 10000 times) and run some function on the subset (obviously more complicated than the one shown in the example below, i.e. I need all columns of the subset and the function returns a new data.table). I just picked the mean to make the example simple.

dt <- data.table(a=sample(letters, 1000000,replace=T),b=sample(1:100000))

mm <- list()

foo <- function(x) mean(x$b)

for(i in 1:1000)
{
  mm[[i]] <-  foo(dt[a %in% sample(letters,5)])
}

It is obvious that this is not the fastest way to program even this minimal example (setting keys etc.).

I am interested, however, how to optimize the for loop. I had in mind to create indices for the subsets and then use data.table dt[,foo(.SD),by=subset_ID] , but I am not sure on how to this, since I am sampling with replacement (multiple group IDs). Any ideas based on data.table would be much appreciated (e.g. how to remove the loop?).

Body:
I had in mind to create indices for the subsets and then use data.table dt[,foo(.SD),by=subset_ID], but I am not sure on how to this, since I am sampling with replacement (multiple group IDs).

With a join, you can have overlapping groups:

# convert to numeric
dt[, b := as.numeric(b)]

# make samples
set.seed(1)
mDT = setDT(melt(replicate(1000, sample(letters,5))))
setnames(mDT, c("seqi", "g", "a"))

# compute function on each sample
dt[mDT, on=.(a), allow.cartesian=TRUE, .(g, b)][, .(res = mean(b)), by=g]

which gives

         g      res
   1:    1 50017.85
   2:    2 49980.03
   3:    3 50093.80
   4:    4 50087.67
   5:    5 49990.83
  ---
 996:  996 50013.11
 997:  997 50095.43
 998:  998 49913.61
 999:  999 50058.44
1000: 1000 49909.36

To confirm it's doing the right thing, you can check eg,

dt[a %in% mDT[g == 1, a], mean(b)]
# [1] 50017.85

One downside of this approach is that it involves creating a very large table (containing the data for all the samples), which may put you in trouble, RAM-wise.

This approach is taking advantage of your function being mean, since passing it explicitly allows for certain optimizations; see ?GForce, which is also why I converted b to numeric.

I agree with Rob Jensen's suggestion to pass columns to the function instead of passing a table (with the function making assumptions about what columns appear in the table), both for efficiency and clarity.

In the specific case of taking the mean, you could speed this up further by adding up for each letter first, I think:

dtagg = dt[, .(.N, sumb = sum(b)), by=a]

dtagg[mDT, on=.(a), .(g, sumb, N)][, lapply(.SD, sum), by=g][, .(g, res = sumb/N)]

         g      res
   1:    1 50017.85
   2:    2 49980.03
   3:    3 50093.80
   4:    4 50087.67
   5:    5 49990.83
  ---
 996:  996 50013.11
 997:  997 50095.43
 998:  998 49913.61
 999:  999 50058.44
1000: 1000 49909.36

allow.cartesian is not needed in this case, since each row of mDT finds only a single row in dtagg. On my computer, the speedup with the example data is pretty big, but most of the benefit comes from taking advantage of the form of the example function, I guess:

13.7 sec OP's approach

11.4 sec simple join

0.02 sec aggregate-first


问:
Partially Unshelve TFS Shelveset
A little while back, I shelved a bunch of changes from several unrelated features. Now, I want to grab just a few of those files. Is there a way to selectively unshelve files or directories (without checking out to a second place, unshelving there and copying things over)?</p>

答: You can do this directly from Visual Studio 2015.  After you browse to the shelvset, you can select the files you DON'T want to unshelve and then click Exclude.  Only the files remaining in the Include section will be unshelved when you click the Unshelve button.</p>

Title: Partially Unshelve TFS Shelveset

ContentLicense: CC BY-SA 4.0


问:
Angular 2 "Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE" Delete doesn't work
I'm trying to delete a record in angular 2, the API is working fine, but when I call the method who delete, the console says:

```<code>Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response.
</code>```

Of course I have been reading about the error, but the most popular solution doesn't work for me, here is the method:

```<code>deleteInventory(id){
    var headers = new Headers();
    headers.append('Authorization', `Bearer ${this.globalVar.getToken()}`);
    headers.append("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT,
    DELETE");
    var options = new RequestOptions({ headers: headers });
    var result = this.http.delete(this.globalVar.getHost() + "inventory/"+
    id, options);
   return result;
}
</code>```

Can anybody help me? Thank you :D

答:
The headers need to be added to the response by the server. Adding these headers on the request of the client is entirely pointless. There about 1k such questions. Try searching again and you surely will find something. You need to change the configuration on the server. If you don't control the server, use your own server and forward requests to the 3rd-party server and add the headers when you return the response to the browser.

Günter Zöchbauer

Body:
I'm trying to delete a record in angular 2, the API is working fine, but when I call the method who delete, the console says:

Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response.

Of course I have been reading about the error, but the most popular solution doesn't work for me, here is the method:

deleteInventory(id){
    var headers = new Headers();
    headers.append('Authorization', `Bearer ${this.globalVar.getToken()}`);
    headers.append("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT,
    DELETE");
    var options = new RequestOptions({ headers: headers });
    var result = this.http.delete(this.globalVar.getHost() + "inventory/"+
    id, options);
   return result;
}

Can anybody help me? Thank you :D


问:
C - makefile error undefined reference to main
```<code>    dealer: dealer.o readline.o car.o
        gcc -o dealer readline.o car.o

    dealer.o: dealer.c car.h readline.h
        gcc -c dealer.c

    readline.o: readline.c car.h readline.h
        gcc -c readline.c

    car.o: car.c car.h readline.h
        gcc -c car.c

make dealer
gcc -c dealer.c
gcc -c readline.c
gcc -c car.c
gcc -o dealer readline.o car.o
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
make: *** [dealer] Error 1
</code>```

I keep getting the error above. My dealer.c does indeed contain 'main'.

Does anybody have an idea on whats going on?

答:
your link line:

```<code>gcc -o dealer readline.o car.o
</code>```

doesn't contain dealer.o, which explains why main is missing. Should be:

```<code>gcc -o dealer dealer.o readline.o car.o
</code>```

(there's no automatic/guessed relation between the name of the final executable indicated by -o dealer and the object file dealer.o)

Body:
    dealer: dealer.o readline.o car.o
        gcc -o dealer readline.o car.o

    dealer.o: dealer.c car.h readline.h
        gcc -c dealer.c

    readline.o: readline.c car.h readline.h
        gcc -c readline.c

    car.o: car.c car.h readline.h
        gcc -c car.c

make dealer
gcc -c dealer.c
gcc -c readline.c
gcc -c car.c
gcc -o dealer readline.o car.o
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
make: *** [dealer] Error 1

I keep getting the error above. My dealer.c does indeed contain 'main'.

Does anybody have an idea on whats going on?

Body:
your link line:

gcc -o dealer readline.o car.o

doesn't contain dealer.o, which explains why main is missing. Should be:

gcc -o dealer dealer.o readline.o car.o

(there's no automatic/guessed relation between the name of the final executable indicated by -o dealer and the object file dealer.o)


问:
retrieving nested JSON objects when mapping from an api call
I am working on mapping JSON to Data driven rendering within react. To accomplish some of the things I need to do. I am going to require Nested JSON.
When attempting to map this data, I keep running into values that I cannot map. Specifically when trying (mapObject.object.value) where I am attempting to pass the nested values into an interpolated div.

JSON

```<code>{"PositionComponent": [
        {
            "key": 0,
            "Elevation": {
                "positionValue": "1.11566",
                "id": 0
            }
        },
        {
            "key": 1,
            "Azimuth": {
                "positionValue": "1.145657",
                "id": 1
            }
        }
    ]
}
</code>```

React Components:

```<code>import React, { Component } from 'react';
import '../HeaderBar/HeaderBar.css';
import 'whatwg-fetch';

type StatusBarProps = {};
type StatusBarState = {
    // tslint:disable-next-line:no-any
    positionStatus: any;
};

class StatusBar extends Component<StatusBarProps, StatusBarState> {
    constructor() {
        super();
        this.state = {
            positionStatus: []
        };
    }
    componentWillMount() {
        // maps azimuth and elevation for all objects
        fetch('http://localhost:5001/PositionComponent/').then(results => {
            return results.json();
        }).then(data => {
            let positionStatus = data.map((positioning) => {
                return (
                    <div className="temporary" key={positioning.key}>{positioning.Elevation.positionValue} : {positioning.Azimuth.positionValue}</div>
                );
            });
            this.setState({ positionStatus: positionStatus });
        });
    }
    render() {
        return (
            <div className="location">
                <div className="col-xs-12">
                    {this.state.positionStatus}
                </div>
            </div>
        );
    }
}

export default StatusBar;
</code>```

The relevant JSON has been provided for context of the issue, but is being served from JSON.server for sake of development speed. It seems that the issue is that I am receiving Object {key: 0, Elevation: Object }  Object { key: 1, Azimuth: Object } where I cannot go down a level into the object itself by calling {positioning.Elevation.positionValue}. My question is, how would I go about mapping this so that I can get those interior object values tied to Elevation, and Azimuth?

答:
Thought it might be a JSON error, but you are trying to access an undefined prop within your object.

This is your data:

```<code>[
  {
    "key": 0,
    "Elevation": {
      "positionValue": "1.11566",
      "id": 0
    }
  },
  {
    "key": 1,
    "Azimuth": {
      "positionValue": "1.145657",
      "id": 1
    }
  }
]
</code>```

Not all elements have Elevation nor Azimuth props. First one has only Elevation whereas second one has Azimuth.

Therefore, this line will always break:

```<code>{positioning.Elevation.positionValue} / {positioning.Azimuth.positionValue}
</code>```

Should you need to provide at least one of them:

```<code>let positionStatus = data.map((positioning) => {
  return (
    <div
      className="temporary"
      key={positioning.key}
    >
      {positioning.Elevation ? positioning.Elevation.positionValue : 0} :
      {positioning.Azimuth ? positioning.Azimuth.positionValue : 0}
    </div>
  )
})
</code>```

or

```<code>let positionStatus = data.map((positioning) => {
  return (
    <div
      className="temporary"
      key={positioning.key}
    >
      {positioning.Elevation
        ? positioning.Elevation.positionValue
        : positioning.Azimuth.positionValue
      }
    </div>
  )
})
</code>```

Body:
I am working on mapping JSON to Data driven rendering within react. To accomplish some of the things I need to do. I am going to require Nested JSON.
When attempting to map this data, I keep running into values that I cannot map. Specifically when trying (mapObject.object.value) where I am attempting to pass the nested values into an interpolated div.

JSON

{"PositionComponent": [
        {
            "key": 0,
            "Elevation": {
                "positionValue": "1.11566",
                "id": 0
            }
        },
        {
            "key": 1,
            "Azimuth": {
                "positionValue": "1.145657",
                "id": 1
            }
        }
    ]
}

React Components:

import React, { Component } from 'react';
import '../HeaderBar/HeaderBar.css';
import 'whatwg-fetch';

type StatusBarProps = {};
type StatusBarState = {
    // tslint:disable-next-line:no-any
    positionStatus: any;
};

class StatusBar extends Component<StatusBarProps, StatusBarState> {
    constructor() {
        super();
        this.state = {
            positionStatus: []
        };
    }
    componentWillMount() {
        // maps azimuth and elevation for all objects
        fetch('http://localhost:5001/PositionComponent/').then(results => {
            return results.json();
        }).then(data => {
            let positionStatus = data.map((positioning) => {
                return (

{positioning.Elevation.positionValue} : {positioning.Azimuth.positionValue}

                );
            });
            this.setState({ positionStatus: positionStatus });
        });
    }
    render() {
        return (

                    {this.state.positionStatus}

        );
    }
}

export default StatusBar;

The relevant JSON has been provided for context of the issue, but is being served from JSON.server for sake of development speed. It seems that the issue is that I am receiving Object {key: 0, Elevation: Object }  Object { key: 1, Azimuth: Object } where I cannot go down a level into the object itself by calling {positioning.Elevation.positionValue}. My question is, how would I go about mapping this so that I can get those interior object values tied to Elevation, and Azimuth?

Body:
Thought it might be a JSON error, but you are trying to access an undefined prop within your object.

This is your data:

[
  {
    "key": 0,
    "Elevation": {
      "positionValue": "1.11566",
      "id": 0
    }
  },
  {
    "key": 1,
    "Azimuth": {
      "positionValue": "1.145657",
      "id": 1
    }
  }
]

Not all elements have Elevation nor Azimuth props. First one has only Elevation whereas second one has Azimuth.

Therefore, this line will always break:

{positioning.Elevation.positionValue} / {positioning.Azimuth.positionValue}

Should you need to provide at least one of them:

let positionStatus = data.map((positioning) => {
  return (
    <div
      className="temporary"
      key={positioning.key}
    >
      {positioning.Elevation ? positioning.Elevation.positionValue : 0} :
      {positioning.Azimuth ? positioning.Azimuth.positionValue : 0}
    </div>
  )
})

or

let positionStatus = data.map((positioning) => {
  return (
    <div
      className="temporary"
      key={positioning.key}
    >
      {positioning.Elevation
        ? positioning.Elevation.positionValue
        : positioning.Azimuth.positionValue
      }
    </div>
  )
})


问:
Fill vector with sequence
Can you explain me, why, when i fill vector in R with sequence, i ve got this result:

```<code>sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
    test[j] = j
}
test
[1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19
</code>```

I want make a vector, which i can fill with some sequence and use it in loop, but only with values, not with NA values. Can somebody help me ?

答:
The actual issue is that whenever your are trying to assign value to test[j] it using value of j to change the size of the vector. The last value of j is 19 hence size of test is set to 19. But you have assigned value only to few indexes i.e. 1, 3, 5 etc. Rest of values are set to NA.

You can solve it by executing for loop only for number of items available in sekv.

```<code>sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in 1:length(sekv)) {
    test[j] = sekv[j]
}
print(test)
</code>```

Title: Fill vector with sequence

Body:
Can you explain me, why, when i fill vector in R with sequence, i ve got this result:

sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in sekv) {
    test[j] = j
}
test
[1]  1 NA  3 NA  5 NA  7 NA  9 NA 11 NA 13 NA 15 NA 17 NA 19

I want make a vector, which i can fill with some sequence and use it in loop, but only with values, not with NA values. Can somebody help me ?

Body:
The actual issue is that whenever your are trying to assign value to test[j] it using value of j to change the size of the vector. The last value of j is 19 hence size of test is set to 19. But you have assigned value only to few indexes i.e. 1, 3, 5 etc. Rest of values are set to NA.

You can solve it by executing for loop only for number of items available in sekv.

sekv <- seq(from = 1, to = 20, by = 2)
test <- c()
for (j in 1:length(sekv)) {
    test[j] = sekv[j]
}
print(test)


问:
Tencent International Cloud without PayPal
Is there a way to sign up for Tencent International Cloud without a PayPal account?</p>

答:
Our international service (https://intl.cloud.tencent.com) for customers with registered addresses outside Mainland China currently only accepts PayPal.

We are working to offer additional payment options in the future.


问:
Rails - Using true and false
I have the following in my controller:

```<code>if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end
</code>```

Then later in create.je.erb do:

```<code><% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>
</code>```

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

答:
Try this. I am taking it as @archived_new_status is a Boolean (true or false)</p>

```<code>params[:archive] ? @archived_new_status : !@archived_new_status
</code>```

Title: Rails - Using true and false

Body:
I have the following in my controller:

if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end

Then later in create.je.erb do:

<% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

Body:
Try this. I am taking it as @archived_new_status is a Boolean (true or false)

params[:archive] ? @archived_new_status : !@archived_new_status


问:
Aligning an image next to a table row
I want to display image next to each row in a table using Html and CSS.
Something like this image:

Images will be placed at the red cross position: on right side of each row and not created within extra column.

What would be the best way to do that.

答:
Another column with a blank table header should do it. </p>

```<code><table style="width:100%">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>  </th> -- This is the blank space
  </tr>
  <tr>
    <td>Peter</td>
    <td>Griffin</td>
    <td>Image goes here</td>
  </tr>
</table>
</code>```

<p>You can always style it up to appear like it is not apart of the table. </p>

Title: Aligning an image next to a table row

Body:
Another column with a blank table header should do it.

<table style="width:100%">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>  </th> -- This is the blank space
  </tr>
  <tr>
    <td>Peter</td>
    <td>Griffin</td>
    <td>Image goes here</td>
  </tr>
</table>

You can always style it up to appear like it is not apart of the table.


问:
sdk for morpho (safran) biometric scanner device
i have one safran device and its driver software. but i want to control it using c#. but i am unable to locate the SDK for this morpho biometric scanner. can anyone help me, so that i can make an home application with help of that.

i have tried with following code

```<code>using Morpho;
using MorphoAPI_1_0;
using MorphoSdkLiteDotNetWrapper;

Morpho.MorphoSmart.MorphoSmartDevice mSmtDev = new Morpho.MorphoSmart.MorphoSmartDevice();
</code>```

but this give following error
Could not load file or assembly 'Morpho.MorphoSmart.dll' or one of its dependencies. The specified module could not be found.

答: You have to copy all of the dll file located in dll folder into the folder where your application will be released, according to your target machine architecture.</p>

Body:
i have one safran device and its driver software. but i want to control it using c#. but i am unable to locate the SDK for this morpho biometric scanner. can anyone help me, so that i can make an home application with help of that.

i have tried with following code

using Morpho;
using MorphoAPI_1_0;
using MorphoSdkLiteDotNetWrapper;

Morpho.MorphoSmart.MorphoSmartDevice mSmtDev = new Morpho.MorphoSmart.MorphoSmartDevice();

but this give following error
Could not load file or assembly 'Morpho.MorphoSmart.dll' or one of its dependencies. The specified module could not be found.


问:
Assumed IAM Role is not authorized to perform: states:GetActivityTask on resource: arn:aws:states::012345678910:role/
I have a Cloudformation stack like,

```<code>---
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyFavoriteActivity:
     Type: "AWS::StepFunctions::Activity"
     Properties:
       Name: "my-special-name"

  ActivityAccessRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              AWS:
                Fn::Sub: "arn:aws:iam::${AWS::AccountId}:user/my-special-user"
            Action:
              - sts:AssumeRole
      Policies:
        - PolicyName: "Activity_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - states:GetActivityTask
                Resource: { Ref: "MyFavoriteActivity" }
</code>```

Using Boto3, I try to call get_activity_task using the keys from my ActivityAccessRole,

```<code>sfn_client = boto3.client('stepfunctions', **assumed_role_keys)
task = sfn_client.get_activity_task(
    activityArn='arn:aws:states:us-west-2:012345678910:activity:My-favorite-activity',
    workerName='my-worker'
)
</code>```

But I get an error,

```<code>An error occurred (AccessDeniedException) when calling the GetActivityTask operation:
User: arn:aws:sts::012345678910:assumed-role/some-prefix-ActivityAccessRole-some-hash/AssumeRoleSession1
is not authorized to perform: states:GetActivityTask on resource: arn:aws:states::012345678910:role/arn:aws:states:us-west-2:012345678910:activity:My-favorite-activity
</code>```

the problem I see is that I never created arn:aws:states::012345678910:role/arn:aws:states:us-west-2:012345678910:activity:My-favorite-activity (note the prefix)!

How do I fix my CF template to give the proper permissions?

答:
The problem is pretty dumb (or genius and poorly documented). I needed to change my role to,

```<code>  ActivityAccessRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              AWS:
                Fn::Sub: "arn:aws:iam::${AWS::AccountId}:user/frp-api-user"
            Action:
              - sts:AssumeRole
      Policies:
        - PolicyName: "Activity_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - states:GetActivityTask
                Resource:
                  - Fn::Sub: "arn:aws:states::${AWS::AccountId}:role/${MyFavoriteActivity}"
                  - { Ref: "MyFavoriteActivity" }
</code>```

Where you should note the last two lines. For some reason to need to add both resources. The real one and the one that popped out of the vacuum.

Body:
I have a Cloudformation stack like,

---
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyFavoriteActivity:
     Type: "AWS::StepFunctions::Activity"
     Properties:
       Name: "my-special-name"

  ActivityAccessRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              AWS:
                Fn::Sub: "arn:aws:iam::${AWS::AccountId}:user/my-special-user"
            Action:
              - sts:AssumeRole
      Policies:
        - PolicyName: "Activity_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - states:GetActivityTask
                Resource: { Ref: "MyFavoriteActivity" }

Using Boto3, I try to call get_activity_task using the keys from my ActivityAccessRole,

sfn_client = boto3.client('stepfunctions', **assumed_role_keys)
task = sfn_client.get_activity_task(
    activityArn='arn:aws:states:us-west-2:012345678910:activity:My-favorite-activity',
    workerName='my-worker'
)

But I get an error,

An error occurred (AccessDeniedException) when calling the GetActivityTask operation:
User: arn:aws:sts::012345678910:assumed-role/some-prefix-ActivityAccessRole-some-hash/AssumeRoleSession1
is not authorized to perform: states:GetActivityTask on resource: arn:aws:states::012345678910:role/arn:aws:states:us-west-2:012345678910:activity:My-favorite-activity

the problem I see is that I never created arn:aws:states::012345678910:role/arn:aws:states:us-west-2:012345678910:activity:My-favorite-activity (note the prefix)!

How do I fix my CF template to give the proper permissions?

Body:
The problem is pretty dumb (or genius and poorly documented). I needed to change my role to,

  ActivityAccessRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              AWS:
                Fn::Sub: "arn:aws:iam::${AWS::AccountId}:user/frp-api-user"
            Action:
              - sts:AssumeRole
      Policies:
        - PolicyName: "Activity_Role_Policy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - states:GetActivityTask
                Resource:
                  - Fn::Sub: "arn:aws:states::${AWS::AccountId}:role/${MyFavoriteActivity}"
                  - { Ref: "MyFavoriteActivity" }

Where you should note the last two lines. For some reason to need to add both resources. The real one and the one that popped out of the vacuum.


答:
The main issue here is that you got different keys on each object that holds the nested key you want to grab.

You may try to access it conditionally and check the existing of Elevation OR  Azimuth and access respectively.

The downside for this approach that when you add a new key, another condition should be added. So you may want a more generic approach.

You can use Object.entries and .map through the keys and return the for each positionValue. if a certain key doesnt hold it then undefined will be evaluated which map will ignore and wont return it.

Something like this:

```<code>Object.entries(positioning).map(([key, value]) => {
  return positioning[key].positionValue;
})
</code>```

I would take out the rendering logic out to another method and wont store a markup in state.

Another thing you will want to change is to avoid the use of fetching or side effects in componentWillMount

Here is a running example of your code (i didn't use fetch as i don't have your data in a server)

const dataFromServer = [
  {
    key: 0,
    Elevation: {
      positionValue: "1.11566",
      id: 0
    }
  },
  {
    key: 1,
    Azimuth: {
      positionValue: "1.145657",
      id: 1
    }
  }
];

class StatusBar extends React.Component {
  constructor() {
    super();
    this.state = {
      positionStatus: []
    };
  }

  componentDidMount() {
    let positionStatus = dataFromServer;
    this.setState({ positionStatus: positionStatus });
  }

  renderPositionstatus = () => {
    const { positionStatus } = this.state;
    return (

        {positionStatus.map(positioning => {
          return (

              {Object.entries(positioning).map(([key, value]) => {
                return positioning[key].positionValue;
              })}

          );
        })}

    );
  };

  render() {
    return (

{this.renderPositionstatus()}

    );
  }
}

ReactDOM.render(<StatusBar />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Title: retrieving nested JSON objects when mapping from an api call

Body:
The main issue here is that you got different keys on each object that holds the nested key you want to grab.

You may try to access it conditionally and check the existing of Elevation OR  Azimuth and access respectively.

The downside for this approach that when you add a new key, another condition should be added. So you may want a more generic approach.

You can use Object.entries and .map through the keys and return the for each positionValue. if a certain key doesnt hold it then undefined will be evaluated which map will ignore and wont return it.

Something like this:

Object.entries(positioning).map(([key, value]) => {
  return positioning[key].positionValue;
})

I would take out the rendering logic out to another method and wont store a markup in state.

Another thing you will want to change is to avoid the use of fetching or side effects in componentWillMount

Here is a running example of your code (i didn't use fetch as i don't have your data in a server)

const dataFromServer = [
  {
    key: 0,
    Elevation: {
      positionValue: "1.11566",
      id: 0
    }
  },
  {
    key: 1,
    Azimuth: {
      positionValue: "1.145657",
      id: 1
    }
  }
];

class StatusBar extends React.Component {
  constructor() {
    super();
    this.state = {
      positionStatus: []
    };
  }

  componentDidMount() {
    let positionStatus = dataFromServer;
    this.setState({ positionStatus: positionStatus });
  }

  renderPositionstatus = () => {
    const { positionStatus } = this.state;
    return (
      <div>
        {positionStatus.map(positioning => {
          return (
            <div className="temporary" key={positioning.key}>
              {Object.entries(positioning).map(([key, value]) => {
                return positioning[key].positionValue;
              })}
            </div>
          );
        })}
      </div>
    );
  };

  render() {
    return (
      <div className="location">
        <div className="col-xs-12">{this.renderPositionstatus()}</div>
      </div>
    );
  }
}

ReactDOM.render(<StatusBar />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


问:
Sequelize Eager Loading not working at all
First of all, I already searched every single question about this topic here in StackOverflow and in almost everywhere, so I'm asking if you can help me.

I'm making a web app using ExpressJS(v4.15.5) and Sequelize(v4.22.6). I defined the models, migrations, associations and inclusively add an alias to all associations so I'll use this alias when making the eager loading. If I try to eager load a specific association tells me that X is not associated to Y and of course, if I try to eager load all associations using {include: [{all: true}]} it doesn't return any association.

I already verified if the sync was being done and it is, in file bin/www:

```<code>models.sequelize.sync().then(function() {
    /**
     * Listen on provided port, on all network interfaces.
     */
    server.listen(port, function() {
        debug('Express server listening on port ' + server.address().port);
    });
    server.on('error', onError);
    server.on('listening', onListening);
});
</code>```

Above are my models MessageGroup and Message and my routes/index.js file.

MessageGroup Model

```<code>'use strict';

module.exports = (sequelize, DataTypes) => {
    var MessageGroup = sequelize.define('MessageGroup', {
        slug: DataTypes.STRING,
        name: DataTypes.STRING
    }, {
        classMethods: {
            associate: function (models) {
                // associations can be defined here
                MessageGroup.hasMany(models.Message, { as:'messages', foreignKey: "messageGroupId" });
            }
        }
    });

    return MessageGroup;
};
</code>```

Message model

```<code>'use strict';

module.exports = (sequelize, DataTypes) => {
    var Message = sequelize.define('Message', {
        slug: DataTypes.STRING,
        name: DataTypes.STRING,
        description: DataTypes.TEXT
    }, {
        classMethods: {
            associate: function (models) {
                // associations can be defined here
                Message.belongsTo(models.MessageGroup, { as:'messageGroup', foreignKey: "messageGroupId" });
                Message.hasMany(models.MessageParameter, { as:'messageParameters', foreignKey: "messageId" });
            }
        }
    });

    return Message;
};
</code>```

routes/index.js file

```<code><!-- language: javascript -->
const express = require('express');
const router = express.Router();
const models = require('../models');

router.get('/data', function (req, res, next) {
    models.MessageGroup.findAll({include: [{all: true}]}).then(result => {
        res.json({data: result});
    });
});

module.exports = router;
</code>```

Thanks in advance.

答:
Problem solved. I was using sequelize v3 syntax. In the v4 syntax models classMethods dissapear and associations are made like this:

```<code> ...
     Message.associate = function (models) {
            // associations can be defined here
            Message.belongsTo(models.MessageGroup, { as:'messageGroup', foreignKey: "messageGroupId" });
            Message.hasMany(models.MessageParameter, { as:'messageParameters', foreignKey: "messageId" });
        };
    ...
</code>```

More info here http://docs.sequelizejs.com/manual/tutorial/upgrade-to-v4.html

Body:
First of all, I already searched every single question about this topic here in StackOverflow and in almost everywhere, so I'm asking if you can help me.

I'm making a web app using ExpressJS(v4.15.5) and Sequelize(v4.22.6). I defined the models, migrations, associations and inclusively add an alias to all associations so I'll use this alias when making the eager loading. If I try to eager load a specific association tells me that X is not associated to Y and of course, if I try to eager load all associations using {include: [{all: true}]} it doesn't return any association.

I already verified if the sync was being done and it is, in file bin/www:

models.sequelize.sync().then(function() {
    /**
     * Listen on provided port, on all network interfaces.
     */
    server.listen(port, function() {
        debug('Express server listening on port ' + server.address().port);
    });
    server.on('error', onError);
    server.on('listening', onListening);
});

Above are my models MessageGroup and Message and my routes/index.js file.

MessageGroup Model

'use strict';

module.exports = (sequelize, DataTypes) => {
    var MessageGroup = sequelize.define('MessageGroup', {
        slug: DataTypes.STRING,
        name: DataTypes.STRING
    }, {
        classMethods: {
            associate: function (models) {
                // associations can be defined here
                MessageGroup.hasMany(models.Message, { as:'messages', foreignKey: "messageGroupId" });
            }
        }
    });

    return MessageGroup;
};

Message model

'use strict';

module.exports = (sequelize, DataTypes) => {
    var Message = sequelize.define('Message', {
        slug: DataTypes.STRING,
        name: DataTypes.STRING,
        description: DataTypes.TEXT
    }, {
        classMethods: {
            associate: function (models) {
                // associations can be defined here
                Message.belongsTo(models.MessageGroup, { as:'messageGroup', foreignKey: "messageGroupId" });
                Message.hasMany(models.MessageParameter, { as:'messageParameters', foreignKey: "messageId" });
            }
        }
    });

    return Message;
};

routes/index.js file

const express = require('express');
const router = express.Router();
const models = require('../models');

router.get('/data', function (req, res, next) {
    models.MessageGroup.findAll({include: [{all: true}]}).then(result => {
        res.json({data: result});
    });
});

module.exports = router;

Thanks in advance.

Body:
Problem solved. I was using sequelize v3 syntax. In the v4 syntax models classMethods dissapear and associations are made like this:

 ...
     Message.associate = function (models) {
            // associations can be defined here
            Message.belongsTo(models.MessageGroup, { as:'messageGroup', foreignKey: "messageGroupId" });
            Message.hasMany(models.MessageParameter, { as:'messageParameters', foreignKey: "messageId" });
        };
    ...

More info here http://docs.sequelizejs.com/manual/tutorial/upgrade-to-v4.html


问:
Distinguishing between objects fetched from the in-memory Managed Object Context and the Persistent Store
In an iOS app, I am creating NSManagedObject subclass objects using a framework that parses JSON objects and then inserts them into an NSManagedObjectContext. However, I want to distinguish between those newly created objects and ones that have already been saved into the persistent store. That's because I may need to update or overwrite some of the objects in the store. When I execute an NSFetchRequest, it simply returns all of the registered objects, both objects fetched from the store, and the ones I've created locally, in-memory. How would I be able to distinguish between the two types of objects?

答:
You can tell if a managed object has been saved by looking at its object ID. Check myObject.objectID.isTemporaryID, which will be true until you first save the object and false from then on.

However as @Paulw11 alludes to in a comment, in this case it's generally better to find out if you already have a local object before creating a new one. That avoids the issue of having duplicates. You can either update values on the existing object or delete it and replace it.


问:
Jasper Reports with C++ possible or painful?
I've briefly looked at using Jasper Reports as a reporting engine.  However it's all in Java and everything else we have including our server/client architecture, in memory data model, etc is all in C++.  Does anyone have any experience with wrapping JasperReports and calling it from C++ or do they have an interface which provides some sort of API to do this?

Alternately does anyone know a good reporting package designed in or for C++?

As side note we don't use SQL syntax or traditional data sources as the data model is accessed through a generic query interface and is capable of being persisted to any database technology Oracle, SQL Server, Sysbase, etc, or any combination thereof so the emphasis is more on the ability to dynamically format and generate "sexy looking" reports and although the web support would be nice that is not a necessity either.

答: From how you describe your environment, I'd not go into Jasper Reports, unless some corner somewhere in your company has already used it.</p>


问:
Override default Auth routes in Laravel >= 5.4
I want to override /login route to /admin/login. In web.php I tried

```<code>//Auth::routes();
Route::get('login', ['as' => 'auth.login', 'uses' => 'App\Modules\Admin\Controllers\AdminUserController@loginAdminUser'])->name('login');
</code>```

But it is still showing Laravel default login form. How can I do this?

答:
As I was struggling with the same problem I managed to find a good way to override laravel 5.5 routes:

The static function Auth::routes(); :

```<code>public static function routes()
{
    static::$app->make('router')->auth();
}
</code>```

The auth() function is called here which creates auth routes:

laravel/framework/src/Illuminate/Routing/Router.php

```<code>public function auth()
{
    // Authentication Routes...
    $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
    $this->post('login', 'Auth\LoginController@login');
    $this->post('logout', 'Auth\LoginController@logout')->name('logout');

    // Registration Routes...
    $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
    $this->post('register', 'Auth\RegisterController@register');

    // Password Reset Routes...
    $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
    $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
    $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
    $this->post('password/reset', 'Auth\ResetPasswordController@reset');
}
</code>```

You can copy&paste the body of the function right into your web.php and modify them as you wish.

Body:
I want to override /login route to /admin/login. In web.php I tried

//Auth::routes();
Route::get('login', ['as' => 'auth.login', 'uses' => 'App\Modules\Admin\Controllers\AdminUserController@loginAdminUser'])->name('login');

But it is still showing Laravel default login form. How can I do this?

Body:
As I was struggling with the same problem I managed to find a good way to override laravel 5.5 routes:

The static function Auth::routes(); :

public static function routes()
{
    static::$app->make('router')->auth();
}

The auth() function is called here which creates auth routes:

laravel/framework/src/Illuminate/Routing/Router.php

public function auth()
{
    // Authentication Routes...
    $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
    $this->post('login', 'Auth\LoginController@login');
    $this->post('logout', 'Auth\LoginController@logout')->name('logout');

    // Registration Routes...
    $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
    $this->post('register', 'Auth\RegisterController@register');

    // Password Reset Routes...
    $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
    $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
    $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
    $this->post('password/reset', 'Auth\ResetPasswordController@reset');
}

You can copy&paste the body of the function right into your web.php and modify them as you wish.


问:
troubles with powershell where clause
i am trying to parse a website for specific data.

```<code>$strings = $body.split(";")
$strings2 = $strings.Where({$_ -like ("*recordData[`"key`"]*")})
</code>```

i figured out that the square brackets are to blame, i use

```<code>$strings2 = $strings.Where({$_ -like ("*recordData*")})
</code>```

and it works fine, albeit returning way more results then i need.
is there a way i can just search for "recordData[key]"

$body is just the entirety of a returned webpage

thanks.

EDIT:
as requested the input data is like this

```<code>rs.currentColumn = 0;
recordData["dataGridExtraRow"] = 0;
recordData["rownum"] = "0";

recordData["key"] = '3354087';

recordData["factory"] = "cr";
</code>```

in the end i need the 3354087 number, but just picking out the lines i needed was the issue, after that i can pick apart the string fine.

however, i ended up using the .contains, thanks for the suggestion.
sort of facepalmed after i saw it though.

答:
If you are using the like operator then you are going to be having an issue with the open square bracket which is a wildcard character in PowerShell. See About_Wildcards

```<code>...
[] - Matches range of characters
...
</code>```

A use case would be something like this which would return true.

```<code>"recordFata" -like "record[DF]ata"
</code>```

So if you are going to be using -like you need to escape the brackets using backticks in a single quoted sting. You can avoid that by using other methods that function in the same way you intended.

Other options

String .Contains() Method

```<code>"sdfafdrecordData[key]asdfasdfas".Contains("recordData[key]")
</code>```

Fairly basic and no need to worry about special characters for the most part.

Regex

```<code>"sdfafdrecordData[key]asdfasdfas" -match "recordData\[key]"
</code>```

Note that the square braces are also regex metacharacters that need to be escaped as well.

Title: troubles with powershell where clause

Body:
i am trying to parse a website for specific data.

$strings = $body.split(";")
$strings2 = $strings.Where({$_ -like ("*recordData[`"key`"]*")})

i figured out that the square brackets are to blame, i use

$strings2 = $strings.Where({$_ -like ("*recordData*")})

and it works fine, albeit returning way more results then i need.
is there a way i can just search for "recordData[key]"

$body is just the entirety of a returned webpage

thanks.

EDIT:
as requested the input data is like this

rs.currentColumn = 0;
recordData["dataGridExtraRow"] = 0;
recordData["rownum"] = "0";

recordData["key"] = '3354087';

recordData["factory"] = "cr";

in the end i need the 3354087 number, but just picking out the lines i needed was the issue, after that i can pick apart the string fine.

however, i ended up using the .contains, thanks for the suggestion.
sort of facepalmed after i saw it though.

Body:
If you are using the like operator then you are going to be having an issue with the open square bracket which is a wildcard character in PowerShell. See About_Wildcards

...
[] - Matches range of characters
...

A use case would be something like this which would return true.

"recordFata" -like "record[DF]ata"

So if you are going to be using -like you need to escape the brackets using backticks in a single quoted sting. You can avoid that by using other methods that function in the same way you intended.

Other options

String .Contains() Method

"sdfafdrecordData[key]asdfasdfas".Contains("recordData[key]")

Fairly basic and no need to worry about special characters for the most part.

Regex

"sdfafdrecordData[key]asdfasdfas" -match "recordData\[key]"

Note that the square braces are also regex metacharacters that need to be escaped as well.


问:
Prolog "append_dl/3" wrapper
I am just learning Prolog and the concept of difference-lists in Prolog, so bear with me please.

I have following code:

```<code>:- op(400, xfx, \).

append(Xs, Ys, Zs) :-
  append_dl( [Xs|T1]\T1, [Ys|T2]\T2, Zs\[]).

append_dl( Xs\Ys, Ys\Zs, Xs\Zs).
</code>```

Now if i append Lists [1,2,3] and [a,b,c] in the SWI-interpreter it yields lists of lists

```<code>?- append([1,2,3],[a,b,c],Zs).
Zs = [[1, 2, 3], [a, b, c]].
</code>```

Whereas if i do call append_dl direktly like so:

```<code>?- append_dl([1,2,3|T1]\T1,[a,b,c|T2]\T2,Zs\[]).
T1 = [a, b, c],
T2 = [],
Zs = [1, 2, 3, a, b, c].
</code>```

it works...

What am i doing wrong and how should one wrap these functions using difference lists correctly?

Thank you guys for the Help :D

答:
While this programming technique is key to Prolog, this append_dl/3  is an highly artificial example that nobody uses in this precise way. There is a Prolog textbook (Art of Prolog) which uses this as the first "motivating" example and some courses still follow such textbooks literally...

(Let's keep the common definition of append/3 as it is usually defined)

Difference-lists are not lists. Rather, they are differences between lists. So list difference would be a more appropriate name for them. In most situations you do not have such differences ready, rather, you would have to convert an actual list to such a difference or (more commonly) construct the difference while you go along.

So take the list [1,2,3] which can be represented by the difference [1,2,3|Xs]\Xs. Another way to represent it would be [1,2,3]\[]. But you  can use append_dl/3 only if the differences are represented in their most general form which you have not. Thus you first need to convert regular lists into that representation.

```<code>mappend(XsL, YsL, ZsL) :-
   append(XsL, Xs,Xs0),       % convert XsL to a difference Xs0\Xs
   append(YsL, Ys,Ys0),       % convert YsL to a difference Ys0\Ys
   append_dl( Xs0\Xs, Ys0\Ys, ZsL\[]).
</code>```

In this concrete example, the conversion was just overhead. You needed the built-in append/3 twice.  Also, mappend(XsL, YsL, [1,2]) does not terminate, whereas append(XsL, YsL, [1,2]) does.  For that case you would have change the order of the goals.

After you have given in that assignment, I would recommend you study Prolog's dcg notation.

Title: Prolog "append_dl/3" wrapper

Body:
I am just learning Prolog and the concept of difference-lists in Prolog, so bear with me please.

I have following code:

:- op(400, xfx, \).

append(Xs, Ys, Zs) :-
  append_dl( [Xs|T1]\T1, [Ys|T2]\T2, Zs\[]).

append_dl( Xs\Ys, Ys\Zs, Xs\Zs).

Now if i append Lists [1,2,3] and [a,b,c] in the SWI-interpreter it yields lists of lists

?- append([1,2,3],[a,b,c],Zs).
Zs = [[1, 2, 3], [a, b, c]].

Whereas if i do call append_dl direktly like so:

?- append_dl([1,2,3|T1]\T1,[a,b,c|T2]\T2,Zs\[]).
T1 = [a, b, c],
T2 = [],
Zs = [1, 2, 3, a, b, c].

it works...

What am i doing wrong and how should one wrap these functions using difference lists correctly?

Thank you guys for the Help :D

Body:
While this programming technique is key to Prolog, this append_dl/3  is an highly artificial example that nobody uses in this precise way. There is a Prolog textbook (Art of Prolog) which uses this as the first "motivating" example and some courses still follow such textbooks literally...

(Let's keep the common definition of append/3 as it is usually defined)

Difference-lists are not lists. Rather, they are differences between lists. So list difference would be a more appropriate name for them. In most situations you do not have such differences ready, rather, you would have to convert an actual list to such a difference or (more commonly) construct the difference while you go along.

So take the list [1,2,3] which can be represented by the difference [1,2,3|Xs]\Xs. Another way to represent it would be [1,2,3]\[]. But you  can use append_dl/3 only if the differences are represented in their most general form which you have not. Thus you first need to convert regular lists into that representation.

mappend(XsL, YsL, ZsL) :-
   append(XsL, Xs,Xs0),       % convert XsL to a difference Xs0\Xs
   append(YsL, Ys,Ys0),       % convert YsL to a difference Ys0\Ys
   append_dl( Xs0\Xs, Ys0\Ys, ZsL\[]).

In this concrete example, the conversion was just overhead. You needed the built-in append/3 twice.  Also, mappend(XsL, YsL, [1,2]) does not terminate, whereas append(XsL, YsL, [1,2]) does.  For that case you would have change the order of the goals.

After you have given in that assignment, I would recommend you study Prolog's dcg notation.