问:
TypeError: _get_valid_digit() takes exactly 2 arguments (1 given) - Odoo v8 to Odoo v10 community
Consider this function:

```<code>@api.multi
def _validate_rif(self, vat): #, cr, uid, vat, context=None
    '''validates if the VE VAT NUMBER is right
    @param vat: string: Vat number to Check
    returns vat when right otherwise returns False

    '''
    if not vat:
        return False

    if 'VE' in vat:
        vat = vat[2:]

    if re.search(r'^[VJEGP][0-9]{9}$', vat):
        valid_digit = self._get_valid_digit()
        if valid_digit is None:
            return False
        if int(vat[9]) == valid_digit:
            return vat
        else:
            self._print_error(_('Vat Error !'), _('Invalid VAT!'))
    elif re.search(r'^([VE][0-9]{1,8})$', vat):
        vat = vat[0] + vat[1:].rjust(8, '0')
        valid_digit = self._get_valid_digit()
        vat += str(valid_digit)
        return vat
    return False
</code>```

This is from a migration I'm doing from v8 to v10 community.

The error comes on this line: valid_digit = self._get_valid_digit()

This calls for this function:

```<code>@api.multi
def _get_valid_digit(self, vat): #, cr, uid, vat, context=None
    '''
    @param vat: string
    returns validating digit
    '''
    #vat = ''
    divisor = 11
    vat_type = {'V': 1, 'E': 2, 'J': 3, 'P': 4, 'G': 5}
    mapper = {1: 3, 2: 2, 3: 7, 4: 6, 5: 5, 6: 4, 7: 3, 8: 2}
    valid_digit = None

    vat_type = vat_type.get(vat[0].upper())
    if vat_type:
        sum_vat = vat_type * 4
        for i in range(8):
            sum_vat += int(vat[i + 1]) * mapper[i + 1]

        valid_digit = divisor - sum_vat % divisor
        if valid_digit >= 10:
            valid_digit = 0
    return valid_digit
</code>```

Every time I click on this button it throws me this:

```<code>Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 675, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 331, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/service/model.py", line 119, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 324, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 933, in __call__
return self.method(*args, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 504, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 866, in call_button
action = self._call_kw(model, method, args, {})
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 854, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 681, in call_kw
return call_kw_multi(method, model, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 672, in call_kw_multi
result = method(recs, *args, **kwargs)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/search_info_partner_seniat.py", line 64, in search_partner_seniat
res = self.env['seniat.url']._dom_giver(vat)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/model/seniat_url.py", line 226, in _dom_giver
vat = self._validate_rif(vat)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/model/seniat_url.py", line 98, in _validate_rif
valid_digit = self._get_valid_digit()
TypeError: _get_valid_digit() takes exactly 2 arguments (1 given)
</code>```

These methods originally looked like this:

```<code>def _get_valid_digit(self, cr, uid, vat, context=None):
    '''
    @param vat: string
    returns validating digit
    '''
    divisor = 11
    vat_type = {'V': 1, 'E': 2, 'J': 3, 'P': 4, 'G': 5}
    mapper = {1: 3, 2: 2, 3: 7, 4: 6, 5: 5, 6: 4, 7: 3, 8: 2}
    valid_digit = None

    vat_type = vat_type.get(vat[0].upper())
    if vat_type:
        sum_vat = vat_type * 4
        for i in range(8):
            sum_vat += int(vat[i + 1]) * mapper[i + 1]

        valid_digit = divisor - sum_vat % divisor
        if valid_digit >= 10:
            valid_digit = 0
    return valid_digit

def _validate_rif(self, cr, uid, vat, context=None):
    '''validates if the VE VAT NUMBER is right
    @param vat: string: Vat number to Check
    returns vat when right otherwise returns False

    '''
    if not vat:
        return False

    if 'VE' in vat:
        vat = vat[2:]

    if re.search(r'^[VJEGP][0-9]{9}$', vat):
        valid_digit = self._get_valid_digit(cr, uid, vat, context=context)
        if valid_digit is None:
            return False
        if int(vat[9]) == valid_digit:
            return vat
        else:
            self._print_error(_('Vat Error !'), _('Invalid VAT!'))
    elif re.search(r'^([VE][0-9]{1,8})$', vat):
        vat = vat[0] + vat[1:].rjust(8, '0')
        valid_digit = self._get_valid_digit(cr, uid, vat, context=context)
        vat += str(valid_digit)
        return vat
    return False
</code>```

Any ideas?

答:
Replace with this

```<code>valid_digit = self._get_valid_digit(vat)
</code>```

In your original function you were passing the vat argument. You correctly removed the other cr,uid,and context arguments which are passed automatically in the new api however this particular function seems to have a requirement for the vat argument.

Body:
Consider this function:

@api.multi
def _validate_rif(self, vat): #, cr, uid, vat, context=None
    '''validates if the VE VAT NUMBER is right
    @param vat: string: Vat number to Check
    returns vat when right otherwise returns False

    '''
    if not vat:
        return False

    if 'VE' in vat:
        vat = vat[2:]

    if re.search(r'^[VJEGP][0-9]{9}$', vat):
        valid_digit = self._get_valid_digit()
        if valid_digit is None:
            return False
        if int(vat[9]) == valid_digit:
            return vat
        else:
            self._print_error(_('Vat Error !'), _('Invalid VAT!'))
    elif re.search(r'^([VE][0-9]{1,8})$', vat):
        vat = vat[0] + vat[1:].rjust(8, '0')
        valid_digit = self._get_valid_digit()
        vat += str(valid_digit)
        return vat
    return False

This is from a migration I'm doing from v8 to v10 community.

The error comes on this line: valid_digit = self._get_valid_digit()

This calls for this function:

@api.multi
def _get_valid_digit(self, vat): #, cr, uid, vat, context=None
    '''
    @param vat: string
    returns validating digit
    '''
    #vat = ''
    divisor = 11
    vat_type = {'V': 1, 'E': 2, 'J': 3, 'P': 4, 'G': 5}
    mapper = {1: 3, 2: 2, 3: 7, 4: 6, 5: 5, 6: 4, 7: 3, 8: 2}
    valid_digit = None

    vat_type = vat_type.get(vat[0].upper())
    if vat_type:
        sum_vat = vat_type * 4
        for i in range(8):
            sum_vat += int(vat[i + 1]) * mapper[i + 1]

        valid_digit = divisor - sum_vat % divisor
        if valid_digit >= 10:
            valid_digit = 0
    return valid_digit

Every time I click on this button it throws me this:

Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 675, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 331, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/service/model.py", line 119, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 324, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 933, in __call__
return self.method(*args, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 504, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 866, in call_button
action = self._call_kw(model, method, args, {})
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 854, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 681, in call_kw
return call_kw_multi(method, model, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 672, in call_kw_multi
result = method(recs, *args, **kwargs)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/search_info_partner_seniat.py", line 64, in search_partner_seniat
res = self.env['seniat.url']._dom_giver(vat)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/model/seniat_url.py", line 226, in _dom_giver
vat = self._validate_rif(vat)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/model/seniat_url.py", line 98, in _validate_rif
valid_digit = self._get_valid_digit()
TypeError: _get_valid_digit() takes exactly 2 arguments (1 given)

These methods originally looked like this:

def _get_valid_digit(self, cr, uid, vat, context=None):
    '''
    @param vat: string
    returns validating digit
    '''
    divisor = 11
    vat_type = {'V': 1, 'E': 2, 'J': 3, 'P': 4, 'G': 5}
    mapper = {1: 3, 2: 2, 3: 7, 4: 6, 5: 5, 6: 4, 7: 3, 8: 2}
    valid_digit = None

    vat_type = vat_type.get(vat[0].upper())
    if vat_type:
        sum_vat = vat_type * 4
        for i in range(8):
            sum_vat += int(vat[i + 1]) * mapper[i + 1]

        valid_digit = divisor - sum_vat % divisor
        if valid_digit >= 10:
            valid_digit = 0
    return valid_digit

def _validate_rif(self, cr, uid, vat, context=None):
    '''validates if the VE VAT NUMBER is right
    @param vat: string: Vat number to Check
    returns vat when right otherwise returns False

    '''
    if not vat:
        return False

    if 'VE' in vat:
        vat = vat[2:]

    if re.search(r'^[VJEGP][0-9]{9}$', vat):
        valid_digit = self._get_valid_digit(cr, uid, vat, context=context)
        if valid_digit is None:
            return False
        if int(vat[9]) == valid_digit:
            return vat
        else:
            self._print_error(_('Vat Error !'), _('Invalid VAT!'))
    elif re.search(r'^([VE][0-9]{1,8})$', vat):
        vat = vat[0] + vat[1:].rjust(8, '0')
        valid_digit = self._get_valid_digit(cr, uid, vat, context=context)
        vat += str(valid_digit)
        return vat
    return False

Any ideas?

Body:
Replace with this

valid_digit = self._get_valid_digit(vat)

In your original function you were passing the vat argument. You correctly removed the other cr,uid,and context arguments which are passed automatically in the new api however this particular function seems to have a requirement for the vat argument.


来源: stackexchange

问:
Translate java object to soap
I have this (not so cool) web service:

```<code>import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService()
public class WMCWeb {
}
</code>```

And would like to do something like

```<code>@WebMethod(operationName = "getMyObject")
public MyObject getMyObject(@WebParam(name = "id") String id) {
        ...
        return new myObject;
}
</code>```

But I can't just return an object. I don't really know what I should do to be able to do so. I read something about writing a org.apache.soap.util.Serializer, but it seems like an old solution. How can I make the WebService know how to translate the object to a Soap response?

答: look at CXF or axis2. They actually do expose methods as web service and you can easily call these methods by using something like a skeleton (just like how EJB works). also, if you have the web service already(meaning the WSDL is published), you can do a WSDLtojava and it will create those objects for you.</p>

ContentLicense: CC BY-SA 2.5

Title: Translate java object to soap

Body:
I have this (not so cool) web service:

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService()
public class WMCWeb {
}

And would like to do something like

@WebMethod(operationName = "getMyObject")
public MyObject getMyObject(@WebParam(name = "id") String id) {
        ...
        return new myObject;
}

But I can't just return an object. I don't really know what I should do to be able to do so. I read something about writing a org.apache.soap.util.Serializer, but it seems like an old solution. How can I make the WebService know how to translate the object to a Soap response?


问:
I want to remove part of string from a string
Thank you in advance.

I want to remove string after . including ., but length is variable and string can be of any length.

1)Example:

 Input:- SCC0204.X  and FRK0005.X  and RF0023.X and ADF1010.A and HGT9010.V

Output:  SCC0204 and FRK0005 and RF0023 and ADF1010.A and HGT9010.V

I tried using the charindex but as the length keeps on changing i wasn't able to do it. I want to trim the values with ending with only X

Any help will be greatly appreciated.

答:
Update: I just missed one of the comments where the OP clarifies the requirement. What I put together below is how you would deal with a requirement to remove everything after the first dot on strings ending with X. I leave this here for reference.

```<code>;WITH cte_TestData(Code) AS
(
  SELECT 'SCC0204.X'  UNION ALL -- ends with '.X'
  SELECT 'FRK.000.X'  UNION ALL -- ends with '.X', contains multiple dots
  SELECT 'RF0023.AX'  UNION ALL -- ends with '.AX'
  SELECT 'ADF1010.A'  UNION ALL -- ends with '.A'
  SELECT 'HGT9010.V'  UNION ALL -- ends with '.V'
  SELECT 'SCC0204.XF' UNION ALL -- ends with '.XF'
  SELECT 'FRK0005'    UNION ALL -- totally clean
  SELECT 'ABCX'                 -- ends with 'X', not dots
)
SELECT
  orig_string = code,
  newstring   =
  SUBSTRING
  (
    code, 1,
    CASE
      WHEN code LIKE '%X'
      THEN ISNULL(NULLIF(CHARINDEX('.',code)-1, -1), LEN(code))
      ELSE LEN(code)
    END
  )
FROM cte_TestData;
</code>```

FYI - SQL Server 2012+ you could simplify this code like this:

```<code>SELECT
  orig_string = code,
  newstring   =
  SUBSTRING(code, 1,IIF(code LIKE '%X', ISNULL(NULLIF(CHARINDEX('.',code)-1, -1), LEN(code)), LEN(code)))
FROM cte_TestData;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Update: I just missed one of the comments where the OP clarifies the requirement. What I put together below is how you would deal with a requirement to remove everything after the first dot on strings ending with X. I leave this here for reference.

;WITH cte_TestData(Code) AS
(
  SELECT 'SCC0204.X'  UNION ALL -- ends with '.X'
  SELECT 'FRK.000.X'  UNION ALL -- ends with '.X', contains multiple dots
  SELECT 'RF0023.AX'  UNION ALL -- ends with '.AX'
  SELECT 'ADF1010.A'  UNION ALL -- ends with '.A'
  SELECT 'HGT9010.V'  UNION ALL -- ends with '.V'
  SELECT 'SCC0204.XF' UNION ALL -- ends with '.XF'
  SELECT 'FRK0005'    UNION ALL -- totally clean
  SELECT 'ABCX'                 -- ends with 'X', not dots
)
SELECT
  orig_string = code,
  newstring   =
  SUBSTRING
  (
    code, 1,
    CASE
      WHEN code LIKE '%X'
      THEN ISNULL(NULLIF(CHARINDEX('.',code)-1, -1), LEN(code))
      ELSE LEN(code)
    END
  )
FROM cte_TestData;

FYI - SQL Server 2012+ you could simplify this code like this:

SELECT
  orig_string = code,
  newstring   =
  SUBSTRING(code, 1,IIF(code LIKE '%X', ISNULL(NULLIF(CHARINDEX('.',code)-1, -1), LEN(code)), LEN(code)))
FROM cte_TestData;


问:
Error deploying endpoint containing parameter of type "file"
I'm trying to deploy a simple endpoint which contains a parameter of type file .

I'm using the gcloud service-management deploy command with the following openapi compliant yaml:

```<code>swagger: "2.0"

info:
  description: "Image API"
  title: "Image API"
  version: "v1"

host: "image-api.endpoints.myproject.cloud.goog"
basePath: "/v1"

schemes:
- "https"

paths:
  "/images":
    post:
      description: "Adds an image"
      operationId: "add"
      consumes:
      - "multipart/form-data"
      produces:
      - "application/json"
      responses:
        201:
          description: "An image create response"
          schema:
            $ref: "#/definitions/ImageResponse"
      parameters:
      - name: filepath
        in: formData
        required: true
        type: string
      - name: image
        in: formData
        required: false
        type: file

definitions:
  ImageResponse:
    type: object
    properties:
      id:
        type: string
      url:
        type: string
      thumbnail_url:
        type: string
</code>```

But getting the following error:

 ERROR: unknown location: http: repeated message field 'google.protobuf.Struct.fields' referred to by message 'AddRequest' cann
ot be mapped as an HTTP parameter.
 ERROR: unknown location: http: cyclic message field 'google.protobuf.Struct.FieldsEntry.value' referred to by message 'AddRequ
est' cannot be mapped as an HTTP parameter.
 ERROR: unknown location: http: cyclic message field 'google.protobuf.ListValue.values' referred to by message 'AddRequest' can
not be mapped as an HTTP parameter.'
```

If I take the file parameter out the endpoint is successfully deployed.
Is that a Google Cloud Endpoint limitation or is there another way to define it ?

答:
Google Cloud Endpoints does not currently support uploading of images.

You could upload to Google Cloud Storage first:
https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload
https://cloud.google.com/storage/docs/object-basics

And then pass the URL to your Google Cloud Endpoints, which could then retrieve the image from Google Cloud Storage and perform processing.

Body:
I'm trying to deploy a simple endpoint which contains a parameter of type file .

I'm using the gcloud service-management deploy command with the following openapi compliant yaml:

swagger: "2.0"

info:
  description: "Image API"
  title: "Image API"
  version: "v1"

host: "image-api.endpoints.myproject.cloud.goog"
basePath: "/v1"

schemes:
- "https"

paths:
  "/images":
    post:
      description: "Adds an image"
      operationId: "add"
      consumes:
      - "multipart/form-data"
      produces:
      - "application/json"
      responses:
        201:
          description: "An image create response"
          schema:
            $ref: "#/definitions/ImageResponse"
      parameters:
      - name: filepath
        in: formData
        required: true
        type: string
      - name: image
        in: formData
        required: false
        type: file

definitions:
  ImageResponse:
    type: object
    properties:
      id:
        type: string
      url:
        type: string
      thumbnail_url:
        type: string

But getting the following error:

 ERROR: unknown location: http: repeated message field 'google.protobuf.Struct.fields' referred to by message 'AddRequest' cann
ot be mapped as an HTTP parameter.
 ERROR: unknown location: http: cyclic message field 'google.protobuf.Struct.FieldsEntry.value' referred to by message 'AddRequ
est' cannot be mapped as an HTTP parameter.
 ERROR: unknown location: http: cyclic message field 'google.protobuf.ListValue.values' referred to by message 'AddRequest' can
not be mapped as an HTTP parameter.'

If I take the file parameter out the endpoint is successfully deployed.
Is that a Google Cloud Endpoint limitation or is there another way to define it ?


问:
How to read files recursively in awk
I have a bunch of latex files witch use the \input{filename.tex} macro (it works like an #include from C), and I want to resolve them so I can output all of them to a single .tex file (the file must be pasted at the place of the \input{} macro, it is safe to assume that each file is referenced only once).

Example:

tesis.tex:

```<code>My thesis.
\input{chapter1.tex}
More things
\input{chapter2.tex}
</code>```

chapter1.tex:

```<code>Chapter 1 content.
</code>```

chapter2.tex:

```<code>Chapter 2 content.
\include{section2-2.tex}
</code>```

section2-2.tex:

```<code>Section 1.
</code>```

The desired result should be:

```<code>My thesis.
Chapter 1 content.
More things
Chapter 2 content.
Section 1.
</code>```

If there was only a \input{foo.tex} level I would be able to solve this with this AWK program:

```<code>/\\input\{.*\}/{
    sub(/^[^{]*{/,"",$0)
    sub(/}[^}]*$/,"",$0)
    system("cat " $0)
    next
}

{
    print $0
}
</code>```

Is there any way to read files recursively in AWK?

(I am open to do it with any other language, but the posixest the better)

Thanks!

答:
Here's a solution in awk using getline in a recursive function for the job. I assumed chapter2.tex:

```<code>Chapter 2 content.
\input{section2-2.tex}
</code>```

Code:

```<code>$ cat program.awk
function recurse(file) {              # the recursive function definition
    while((getline line<file) >0) {   # read parameter given file line by line
        if(line~/^\\input/) {         # if line starts with \input
            gsub(/^.*{|}.*$/,"",line) # read the filename from inside {}
#           print "FILE: " line       # debug
            recurse(line)             # make the recursive function call
        }
        else print line               # print records without \input
    }
    close(file)                       # after file processed close it
}
{                                     # main program used to just call recurse()
    recurse(FILENAME)                 # called
    exit                              # once called, exit
}
</code>```

Run it:

```<code>$ awk -f program.awk tesis.tex
My thesis.
Chapter 1 content.
More things
Chapter 2 content.
Section 1.
</code>```

Solution expects \input to be in the beginning of the record without any other data on it.

Title: How to read files recursively in awk

Body:
I have a bunch of latex files witch use the \input{filename.tex} macro (it works like an #include from C), and I want to resolve them so I can output all of them to a single .tex file (the file must be pasted at the place of the \input{} macro, it is safe to assume that each file is referenced only once).

Example:

tesis.tex:

My thesis.
\input{chapter1.tex}
More things
\input{chapter2.tex}

chapter1.tex:

Chapter 1 content.

chapter2.tex:

Chapter 2 content.
\include{section2-2.tex}

section2-2.tex:

Section 1.

The desired result should be:

My thesis.
Chapter 1 content.
More things
Chapter 2 content.
Section 1.

If there was only a \input{foo.tex} level I would be able to solve this with this AWK program:

/\\input\{.*\}/{
    sub(/^[^{]*{/,"",$0)
    sub(/}[^}]*$/,"",$0)
    system("cat " $0)
    next
}

{
    print $0
}

Is there any way to read files recursively in AWK?

(I am open to do it with any other language, but the posixest the better)

Thanks!

Body:
Here's a solution in awk using getline in a recursive function for the job. I assumed chapter2.tex:

Chapter 2 content.
\input{section2-2.tex}

Code:

$ cat program.awk
function recurse(file) {              # the recursive function definition
    while((getline line<file) >0) {   # read parameter given file line by line
        if(line~/^\\input/) {         # if line starts with \input
            gsub(/^.*{|}.*$/,"",line) # read the filename from inside {}
#           print "FILE: " line       # debug
            recurse(line)             # make the recursive function call
        }
        else print line               # print records without \input
    }
    close(file)                       # after file processed close it
}
{                                     # main program used to just call recurse()
    recurse(FILENAME)                 # called
    exit                              # once called, exit
}

Run it:

$ awk -f program.awk tesis.tex
My thesis.
Chapter 1 content.
More things
Chapter 2 content.
Section 1.

Solution expects \input to be in the beginning of the record without any other data on it.


问:
Open list of files using a with statement
I'm trying to open several files from sys.argv inputs using a with statement.

I know I can do it by manually typing out each one:

```<code>with open(sys.argv[1], 'r') as test1, open(sys.argv[2], 'r') as test2, \
     open(sys.argv[3], 'r') as test3, open(sys.argv[4], 'r') as test4:
    do_something()
</code>```

But is there a way to do this without doing so, like the following pseudocode:

```<code>with open(sys.argv[1:4], 'r') as test1, test2, test3:
    do_something()
</code>```

答:
You can do this in Python 3.3+ with contextlib.ExitStack:

```<code>from contextlib import ExitStack

with ExitStack() as stack:
    files = [stack.enter_context(open(arg, 'r')) for arg in sys.arv[1:4]]
</code>```

Amusingly, the example in the documentation is exactly what you want.

This correctly closes any open files upon exiting the with statement - even if something went wrong before they were all open

For earlier version of python, there is a backport in the contextlib2 package, which you can get through pip

Body:
I'm trying to open several files from sys.argv inputs using a with statement.

I know I can do it by manually typing out each one:

with open(sys.argv[1], 'r') as test1, open(sys.argv[2], 'r') as test2, \
     open(sys.argv[3], 'r') as test3, open(sys.argv[4], 'r') as test4:
    do_something()

But is there a way to do this without doing so, like the following pseudocode:

with open(sys.argv[1:4], 'r') as test1, test2, test3:
    do_something()

Body:
You can do this in Python 3.3+ with contextlib.ExitStack:

from contextlib import ExitStack

with ExitStack() as stack:
    files = [stack.enter_context(open(arg, 'r')) for arg in sys.arv[1:4]]

Amusingly, the example in the documentation is exactly what you want.

This correctly closes any open files upon exiting the with statement - even if something went wrong before they were all open

For earlier version of python, there is a backport in the contextlib2 package, which you can get through pip


问:
Change a single Firebase value based on the query of another value
My Firebase Database looks like this

I wish to change the event_user_image value by querying the data and comparing the value of event_username.
My code looks like this

```<code>final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dr = database.getReference().child("ApprovedEvents");
        dr.orderByChild("event_user_name").equalTo("username");
        dr.child("event_user_image").setValue("https://lh4.googleusercontent.com/aaaaaaaaaaaaaaaa/photo.jpg");
</code>```

Instead it makes a separate value  under Approved Events.
Please help !

答:
Your DatabaseReference is referring to ApprovedEvents and when you set the value for event_user_image, it would have it like this:

```<code>ApprovedEvents
---Record 1
---Record 2
.
.
.
---event_user_image
</code>```

What you want to do is change the event_user_image for a specific record.

To do that, you first have to query the record with the specific username like this:

```<code>final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference dr = database.getReference().child("ApprovedEvents");
Query query = dr.orderByChild("username").equalTo("yourUsername");
</code>```

Then you could use a listener to see if there would be objects queried with that specific username then get their keys so you could add it in the path for updating:

```<code>query.addChildEventListener(
        new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                //dr would refer to path                  : ApprovedEvents
                //adding the key as a child would make it : ApprovedEvents/Record1
                dr.child(dataSnapshot.getKey()).child("event_user_image").setValue("yourDesiredValue");
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            }
        });
</code>```

Body:
My Firebase Database looks like this

I wish to change the event_user_image value by querying the data and comparing the value of event_username.
My code looks like this

final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference dr = database.getReference().child("ApprovedEvents");
        dr.orderByChild("event_user_name").equalTo("username");
        dr.child("event_user_image").setValue("https://lh4.googleusercontent.com/aaaaaaaaaaaaaaaa/photo.jpg");

Instead it makes a separate value  under Approved Events.
Please help !

Body:
Your DatabaseReference is referring to ApprovedEvents and when you set the value for event_user_image, it would have it like this:

ApprovedEvents
---Record 1
---Record 2
.
.
.
---event_user_image

What you want to do is change the event_user_image for a specific record.

To do that, you first have to query the record with the specific username like this:

final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference dr = database.getReference().child("ApprovedEvents");
Query query = dr.orderByChild("username").equalTo("yourUsername");

Then you could use a listener to see if there would be objects queried with that specific username then get their keys so you could add it in the path for updating:

query.addChildEventListener(
        new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                //dr would refer to path                  : ApprovedEvents
                //adding the key as a child would make it : ApprovedEvents/Record1
                dr.child(dataSnapshot.getKey()).child("event_user_image").setValue("yourDesiredValue");
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            }
        });


问:
How can I organize the content of my controllers in Laravel if i have reports?
I'm creating a Laravel app and I have controllers with the CRUD methods, but I need to show reports and I'm not sure if I have to create a controller called 'Reports' or I have to put each report function inside the controller:

First Option:

Controllers/ProductController.php

Functions (Create, Read, Edit, Update, Delete)

Controllers/CategoryController.php

Functions (Create, Read, Edit, Update, Delete)

Controllers/ReportController.php

Functions (TopProducts, TopCategories)

Second Option:

Controllers/ProductController.php

Functions (Create, Read, Edit, Update, Delete, TopProducts)

Controllers/CategoryController.php

Functions (Create, Read, Edit, Update, Delete, TopCategories)

I hope you can tell me a which is the best option or your own alternative.
Thanks.

答:
I think you should do the first option because your code will be clearer and more separated.

This way, if you want to create more reports from different tables, you will have everything in one controller.

I would advise against option 1 if you are using queries that are already defined in the other controllers, following DRY principles.


问:
PrintWriter not writing to seatingChart.txt file
I need to make a movie ticket program. I've written the majority of the class. The last thing to do is create a text file with PrintWriter by sending the info to the text file.

I haven't gotten started on the second part yet. For now I'm just trying to get the first two lines of the seating chart to print. This doesn't require info from the class.

The problem is that nothing is being added to the text file at all. This is what I have so far:

```<code>public void createSeatingChart() throws FileNotFoundException
{
    File seatingChart = new File("C:/Users/Chris/Documents/NetBeansProjects/Auditorium/seatingChart.txt");
    PrintWriter pw = new PrintWriter(seatingChart);

    pw.println("\t\tSeats");
    pw.println("\t123456789012345678901234567890");

    pw.close();
}
</code>```

I'm pretty sure it's something small that I'm missing but I'm not sure what it is. Any ideas?

答:
Here is a Simple Solution That Worked For me Without any Errors.

As Declared in the JavaDoc for the PrintWriter Class:

FileNotFoundException - If the given file object does not denote an
  existing, writable regular file and a new regular file of that name
  cannot be created, or if some other error occurs while opening or
  creating the file

I Think The Problem of the FileNotFoundException is because you are trying to Create a File inside a directory not existed.

So to Solve the problem you have to check firstly the Parent Directory of the file you want to create is it already existed or not, if it's not exist you have to create it first then you can try to write to the file using the PrintWriter

Note: the Second if Statement is optionnelle You can Remove it
  because the PrintWriter will create the file if not exist (Just for
  Demonstration Purpose).

```<code>public void createSeatingChart() throws IOException
    {

        File seatingChart = new File("C:/Users/Chris/Documents/NetBeansProjects/Auditorium/seatingChart.txt");

        // Check The parent Directory is Exist or Create it.
        if (!seatingChart.getParentFile().exists()) seatingChart.getParentFile().mkdirs();

        // create a new file if not exist
        if (!seatingChart.exists()) seatingChart.createNewFile();

        PrintWriter pw = new PrintWriter(seatingChart);

        pw.println("\t\tSeats");
        pw.println("\t123456789012345678901234567890");

        pw.close();

    }
</code>```

Body:
I need to make a movie ticket program. I've written the majority of the class. The last thing to do is create a text file with PrintWriter by sending the info to the text file.

I haven't gotten started on the second part yet. For now I'm just trying to get the first two lines of the seating chart to print. This doesn't require info from the class.

The problem is that nothing is being added to the text file at all. This is what I have so far:

public void createSeatingChart() throws FileNotFoundException
{
    File seatingChart = new File("C:/Users/Chris/Documents/NetBeansProjects/Auditorium/seatingChart.txt");
    PrintWriter pw = new PrintWriter(seatingChart);

    pw.println("\t\tSeats");
    pw.println("\t123456789012345678901234567890");

    pw.close();
}

I'm pretty sure it's something small that I'm missing but I'm not sure what it is. Any ideas?

Body:
Here is a Simple Solution That Worked For me Without any Errors.

As Declared in the JavaDoc for the PrintWriter Class:

FileNotFoundException - If the given file object does not denote an
  existing, writable regular file and a new regular file of that name
  cannot be created, or if some other error occurs while opening or
  creating the file

I Think The Problem of the FileNotFoundException is because you are trying to Create a File inside a directory not existed.

So to Solve the problem you have to check firstly the Parent Directory of the file you want to create is it already existed or not, if it's not exist you have to create it first then you can try to write to the file using the PrintWriter

Note: the Second if Statement is optionnelle You can Remove it
  because the PrintWriter will create the file if not exist (Just for
  Demonstration Purpose).

public void createSeatingChart() throws IOException
    {

        File seatingChart = new File("C:/Users/Chris/Documents/NetBeansProjects/Auditorium/seatingChart.txt");

        // Check The parent Directory is Exist or Create it.
        if (!seatingChart.getParentFile().exists()) seatingChart.getParentFile().mkdirs();

        // create a new file if not exist
        if (!seatingChart.exists()) seatingChart.createNewFile();

        PrintWriter pw = new PrintWriter(seatingChart);

        pw.println("\t\tSeats");
        pw.println("\t123456789012345678901234567890");

        pw.close();

    }


问:
html/javascript page that files can be loaded to
I want to write a html file that can access files on my computer with gui like this one:

https://smallpdf.com/pdf-to-jpg

In the yellow box it says "choose file". you can click that and choose a file from your computers file system. I would like to do something similar and then be able to use the files in the html.

In particular I want the user to be able to choose a png and then convert it to a html canvas and then do stuff with that canvas. I want everything to be local, so nothing should be uploaded like the website i linked to does.

How does one do this?

Thanks

Sorry this wasn't clear, I want to have all the file processing handled by the html page not by some php on a server. I don't want there to be a server side component to this. If that is not possible please let me know, thanks again.

I want everything to be able to work off line so you could just have the html page, open it, and use it.

答: You're going to want to learn a server-side language like PHP to accomplish this task.  W3schools has tutorials you can learn from. https://www.w3schools.com/php/php_file_upload.asp</p>


问:
view Inline Pages by typing page id in address bar in framework7
how to view Inline Pages by typing page id in address bar
example: index.html#register ?
i tried to make it but i failed</p>

答:
You should use anchors</p>

```<code><ul>
    <li><a href="#title1">title1</a></li>
    <li><a href="#title2">title2</a></li>
    <li><a href="#title3">title3</a></li>
</ul>
<h2 id="title1">title1</h2>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<h2 id="title2">title2</h2>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<h2 id="title3">title3</h2>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
</code>```

Body:
You should use anchors

<ul>
    <li><a href="#title1">title1</a></li>
    <li><a href="#title2">title2</a></li>
    <li><a href="#title3">title3</a></li>
</ul>
<h2 id="title1">title1</h2>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<h2 id="title2">title2</h2>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<h2 id="title3">title3</h2>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>
<p>bla bla bla</p>


问:
Magento - Checking if a module is installed?
I have a small piece of code in a template file that I ONLY want to run if a certain module is installed. I found the below code, which you can use to find if a module is active, but I want to know if a module is installed.

```<code>$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;

if($modulesArray['Mage_Paypal']->is('active')) {
    echo "Paypal module is active.";
} else {
    echo "Paypal module is not active.";
}
</code>```

I'm thinking I could maybe get a list of names of all the modules that are installed, and then use

```<code>if (stristr($modulelist, 'Name_Extension'))
</code>```

to show my code only if the referenced extension is installed.

Anyone any ideas how to do that? Or any better solutions?

答:
Try this:</p>

```<code>$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;

if(isset($modulesArray['Mage_Paypal'])) {
    echo "Paypal module exists.";
} else {
    echo "Paypal module doesn't exist.";
}
</code>```

Body:
I have a small piece of code in a template file that I ONLY want to run if a certain module is installed. I found the below code, which you can use to find if a module is active, but I want to know if a module is installed.

$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;

if($modulesArray['Mage_Paypal']->is('active')) {
    echo "Paypal module is active.";
} else {
    echo "Paypal module is not active.";
}

I'm thinking I could maybe get a list of names of all the modules that are installed, and then use

if (stristr($modulelist, 'Name_Extension'))

to show my code only if the referenced extension is installed.

Anyone any ideas how to do that? Or any better solutions?

Body:
Try this:

$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;

if(isset($modulesArray['Mage_Paypal'])) {
    echo "Paypal module exists.";
} else {
    echo "Paypal module doesn't exist.";
}


问:
Controlling the location of multiple pop-up windows
I have 3 pop-up windows in this code.  I would like to be able to control the position of each of the 3 pop-up windows, however they all go in exactly the same place.  How can I control the positioning of each one?  Can anyone help?  Thanks so much!!

https://jsfiddle.net/vibajajo64/v8prq87x/1/

```<code><!DOCTYPE html>
<html>
<head>
    <style>
        .popup {
  position: fixed;
  top: 0px;
  left: 0px;
  bottom:0px;
  right: 0px;
  margin: auto;
  width: 200px;
  height: 150px;
  font-family: verdana;
  font-size: 13px;
  padding: 10px;
  background-color: rgb(240, 240, 240);
  border: 2px solid grey;
  z-index: 100000000000000000;
}

.blur {
  filter: blur(5px);
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
}

.cancel {
  display: relative;
  cursor: pointer;
  margin: 0;
  float: right;
  height: 10px;
  width: 14px;
  padding: 0 0 5px 0;
  background-color: red;
  text-align: center;
  font-weight: bold;
  font-size: 11px;
  color: white;
  border-radius: 3px;
  z-index: 100000000000000000;
}

.cancel:hover {
  background: rgb(255, 50, 50);
}

#overlay1,
#overlay2,
#overlay3 {
  position: fixed;
  display: none;
  left: 0px;
  top: 0px;
  right: 0px;
  bottom: 0px;
  background: rgba(255, 255, 255, .8);
  z-index: 999;
}

#popup {
  position: absolute;
  width: 400px;
  height: 200px;
  background: rgb(255, 255, 255);
  border: 5px solid rgb(90, 90, 90);
  left: 0px;
  right: 0px;
  top: 0px;
  bottom: 0px;
  margin: auto;
}
    </style>

    </head>

    <body>
  <div id="overlay1">
    <div id="popup">
      <h3>POPUP 1</h3> http://www.google.com <a href="javascript:myBlurFunction(0, 'popup1');"> hide</a></div>
  </div>
  <div id="main_container1">
    <a href="javascript:myBlurFunction(1, 'popup1');">OPEN POPUP 1</a><br/>
  </div>
  <br/>

<div id="overlay2">
    <div id="popup">
      <h3>POPUP 2</h3> http://www.cnn.com <a href="javascript:myBlurFunction(0, 'popup2');"> hide</a></div>
  </div>
  <div id="main_container2">
    <a href="javascript:myBlurFunction(1, 'popup2');">OPEN POPUP 2</a><br/>
  </div>
  <br/>

  <div id="overlay3">
    <div id="popup">
      <h3>POPUP 3</h3> http://www.yahoo.com<a href="javascript:myBlurFunction(0, 'popup3');"> hide</a></div>
  </div>
  <div id="main_container3">
    <a href="javascript:myBlurFunction(1, 'popup3');">OPEN POPUP 3</a><br/>
  </div>

<script type="text/javascript">
  var myBlurFunction = function(state, popup_type) {
    if (state == 1) {
      if (popup_type == "popup1") {
        var containerElement = document.getElementById('main_container1');
        var overlayEle = document.getElementById('overlay1');
        overlayEle.style.display = 'block';
        containerElement.setAttribute('class', 'blur');
      } else {
        if (popup_type == "popup2") {
        var containerElement = document.getElementById('main_container2');
        var overlayEle = document.getElementById('overlay2');
        overlayEle.style.display = 'block';
        containerElement.setAttribute('class', 'blur');
      } else {
        var containerElement = document.getElementById('main_container3');
        var overlayEle = document.getElementById('overlay3');
        overlayEle.style.display = 'block';
        containerElement.setAttribute('class', 'blur');
      }}}

      else {
      if (popup_type == "popup1") {
        var containerElement = document.getElementById('main_container1');
        var overlayEle = document.getElementById('overlay1');
        overlayEle.style.display = 'none';
        containerElement.setAttribute('class', 'null');}

      else {
      if (popup_type == "popup2") {
        var containerElement = document.getElementById('main_container2');
        var overlayEle = document.getElementById('overlay2');
        overlayEle.style.display = 'none';
        containerElement.setAttribute('class', 'null');}

      else {
        var containerElement = document.getElementById('main_container3');
        var overlayEle = document.getElementById('overlay3');
        overlayEle.style.display = 'none';
        containerElement.setAttribute('class', 'null');
      }}
    }
  };
</script>

<Center>All good men try to do their level best.</Center>
</body>
</html>
</code>```

答:
popup is absolutely positioned.you can change left,right,top,bottom to change location of popup.here is a example https://jsfiddle.net/v8prq87x/2/

```<code>document.getElementById("popup").style.left="200px";//
//you can use  left ,right ,top ,bottom css properties to change location of absolutely positioned popup
</code>```

update

please check updated version
https://jsfiddle.net/v8prq87x/3/
on closer inspection, the code only changes pop-up1 - yes problem was you have 3 element with same id so only first one get called.id is a unique name only one element can have a popup id.so what you need is a class.see my updated code.in there i have added class popup for 3 popup divs.so we can access 1st one as document.getElementsByClassName("popup")[0]

Body:
I have 3 pop-up windows in this code.  I would like to be able to control the position of each of the 3 pop-up windows, however they all go in exactly the same place.  How can I control the positioning of each one?  Can anyone help?  Thanks so much!!

https://jsfiddle.net/vibajajo64/v8prq87x/1/

<!DOCTYPE html>

POPUP 1
 http://www.google.com  hide

    OPEN POPUP 1

POPUP 2
 http://www.cnn.com  hide

    OPEN POPUP 2

POPUP 3
 http://www.yahoo.com hide

    OPEN POPUP 3

All good men try to do their level best.

Body:
popup is absolutely positioned.you can change left,right,top,bottom to change location of popup.here is a example https://jsfiddle.net/v8prq87x/2/

document.getElementById("popup").style.left="200px";//
//you can use  left ,right ,top ,bottom css properties to change location of absolutely positioned popup

update

please check updated version
https://jsfiddle.net/v8prq87x/3/
on closer inspection, the code only changes pop-up1 - yes problem was you have 3 element with same id so only first one get called.id is a unique name only one element can have a popup id.so what you need is a class.see my updated code.in there i have added class popup for 3 popup divs.so we can access 1st one as document.getElementsByClassName("popup")[0]


问:
What are the obstacles in today's object detection?
I am new to computer vision, and now I am do some research on object detection. I have read papers about faster RCNN and RFCN, also read YOLO. It seems the biggest problem is the speed? And all of them use image data data only. Are there any models that combines text and image data? Which means we can use the information from text to help detection when the training data is small. For example, when the training data is small, the model cannot tell dogs and cats clearly, but the model could tell there is a bone near that object, and the model gets some information from text that the object near a bone is most likely a dog, thus the model now could tell what the object is. Does this kind of algorithm exist? I haven't found them, hope you could help me. Thanks a lot. </p>

答:
It seems you have mostly referred to research on Deep Networks for Object Detection. Prior to the success of deep networks, researchers were looking to to the possibility of using text with image features to implement ideas similar to yours. You might want to refer to papers from ACM Multimedia and IEEE TMM, especially those before 2014.

The problem was that those approaches could not perform as well as the simplest of the deep networks that use only images. There is some work on combining both images and text, such as this paper. I am sure at least some researchers are already working on this.


问:
Selecting rows until a column value isn't the same
```<code>SELECT product.productID
    , product.Name
    , product.date
    , product.status
FROM product
    INNER JOIN shelf ON product.sheldID=shelf.shelfID
WHERE product.weekID = $ID
    AND product.date < '$day'
    OR (product.date = '$day' AND shelf.expire <= '$time' )
ORDER BY concat(product.date,shelf.expire)
</code>```

I am trying to stop the SQL statement at a specific value e.g. bad.

I have tried using max-date, but am finding it hard as am making the time stamp in the query. (Combining date/time)

This example table shows that 3 results should be returned and if the status "bad" was the first result than no results should be returned. (They are ordered by date and time).

```<code>ProductID   Date     status
1        2017-03-27  Good
2        2017-03-27  Good
3        2017-03-26  Good
4        2017-03-25  Bad
5        2017-03-25  Good
</code>```

Think I may have fixed it, I added this to my while loop.

The query gives the results in order by present to past using date and time, this while loop checks if the column of that row is equal to 'bad' if it is does something (might be able to use an array to fill it up with data). If not than the loop is broken.

I know it doesn't seem ideal but it works lol

```<code>   while ($row = mysqli_fetch_assoc($result)) {
    if ($row['status'] == "bad") {
    $counter += 1;
    }
    else{
break;}
</code>```

答:
I will provide an answer just with your output as if it was just one table. It will give you the main ideia in how to solve your problem.

Basically I created a column called ord that will work as a row_number (MySql doesn't support it yet AFAIK). Then I got the minimum ord value for a bad status then I get everything from the data where ord is less than that.

```<code>select y.*
  from (select ProductID, dt, status, @rw:=@rw+1 ord
          from product, (select @rw:=0) a
         order by dt desc) y
 where y.ord < (select min(ord) ord
                  from (select ProductID, status, @rin:=@rin+1 ord
                          from product, (select @rin:=0) a
                         order by dt desc) x
                 where status = 'Bad');
</code>```

Result will be:

```<code>ProductID        dt     status  ord
-------------------------------------
1           2017-03-27   Good    1
2           2017-03-27   Good    2
3           2017-03-26   Good    3
</code>```

Also tested with the use case where the Bad status is the first result, no results will be returned.

See it working here: http://sqlfiddle.com/#!9/28dda/1

ContentLicense: CC BY-SA 4.0

Body:
SELECT product.productID
    , product.Name
    , product.date
    , product.status
FROM product
    INNER JOIN shelf ON product.sheldID=shelf.shelfID
WHERE product.weekID = $ID
    AND product.date < '$day'
    OR (product.date = '$day' AND shelf.expire <= '$time' )
ORDER BY concat(product.date,shelf.expire)

I am trying to stop the SQL statement at a specific value e.g. bad.

I have tried using max-date, but am finding it hard as am making the time stamp in the query. (Combining date/time)

This example table shows that 3 results should be returned and if the status "bad" was the first result than no results should be returned. (They are ordered by date and time).

ProductID   Date     status
1        2017-03-27  Good
2        2017-03-27  Good
3        2017-03-26  Good
4        2017-03-25  Bad
5        2017-03-25  Good

Think I may have fixed it, I added this to my while loop.

The query gives the results in order by present to past using date and time, this while loop checks if the column of that row is equal to 'bad' if it is does something (might be able to use an array to fill it up with data). If not than the loop is broken.

I know it doesn't seem ideal but it works lol

   while ($row = mysqli_fetch_assoc($result)) {
    if ($row['status'] == "bad") {
    $counter += 1;
    }
    else{
break;}

Body:
I will provide an answer just with your output as if it was just one table. It will give you the main ideia in how to solve your problem.

Basically I created a column called ord that will work as a row_number (MySql doesn't support it yet AFAIK). Then I got the minimum ord value for a bad status then I get everything from the data where ord is less than that.

select y.*
  from (select ProductID, dt, status, @rw:=@rw+1 ord
          from product, (select @rw:=0) a
         order by dt desc) y
 where y.ord < (select min(ord) ord
                  from (select ProductID, status, @rin:=@rin+1 ord
                          from product, (select @rin:=0) a
                         order by dt desc) x
                 where status = 'Bad');

Result will be:

ProductID        dt     status  ord
-------------------------------------
1           2017-03-27   Good    1
2           2017-03-27   Good    2
3           2017-03-26   Good    3

Also tested with the use case where the Bad status is the first result, no results will be returned.

See it working here: http://sqlfiddle.com/#!9/28dda/1


问:
Try Catch Errors many script components - JavaScript
I have a page that contains many script components (50+) and I am getting an error when using IE at some random instance (doesn't happen in Chrome or Firefox).

"Out of Memory at line: 1"

I've done some google search too and that reveals issues with IE handling things differently to Chrome and FF. I would like to catch this error and know exactly what the cause of that script error is.

What would be the best way to use a global try-catch block on that many script components? All these script components are on the same page. Looking forward to your suggestions.

Body:
You might want to try window.onerror as a starting point. It will need to be added before the <script> tags that load the components.

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror

If that fails, you might try reducing the components loaded by half until the error no longer occurs. Then, profile the page (you may have to reduce further due to the demand of profiling). Look for a memory leak as @Bergi suggested. If there is in fact a leak, it will likely occur in all browsers, so you can trouble-shoot in Chrome, as well.

If that still fails to yield anything interesting, the issue may be in one particular component that was not in the set of components you were loading. Ideally, anytime that component is included you see the issue. You could repeatedly bisect the loaded components until you isolate the culprit.

Finally, forgot to mention, your home-base for all of this should be the browser's developer tools, e.g. Chrome dev tools, or if it is unique to Edge, Edge debugger.

And FYI, Edge is the browser that crashes, but that does not mean the issue is not present in Chrome or FF.


问:
How to handle multiple events at once, where one rules over the other
I'm trying to handle multiple states of a Counter-Strike events. I basically need to overrule some of the rules. Here are some examples of functions that could be triggered:

If I shoot someone

If I shoot someone, but I win the round, the round won should overrule my shot someone

If I shoot someone in the head, it should overrule shot someone, but round won should overrule headshot

Other than that, I need to be able to cancel some events that are occuring at the moment. Basically say STOP EVERYTHING AND DO THIS INSTEAD. Let's imagine the code is hosted on my Raspberry Pi and I can control LEDs using my NodeJS code (basically what I am doing). I need to be able to stop current events, so the LED doesn't keep blinking a color, if something else happens instead. Here is a mockup of what I am trying to accomplish:

```<code>var t_won = false;
var ct_won = false;
var bomb_planted = false;
var kills = 0;

server.on("update", function(data) {
    if(data.round.win_team == "T" && t_won == false) {
        t_won = true;
        blinkLED("red", 5);
    } else if(data.round.win_team == "CT" && ct_won == false) {
        ct_won = true;
        blinkLED("blue", 5);
    } else if(data.round.bomb == "planted" && bomb_planted == false) {
        bomb_planted = true;
        blinkLED("red", 40);
    } else if(data.round.bomb == "defused" && bomb_planted == true) {
        LED.stop();
        //ct_won(); or whatever
    }
});

function blinkLED(color, time) {
    //time = time in seconds
    LED.blink(color, time);
}
</code>```

Does that make sense? It's basically pseudo code, but it works the same way. If the LED is blinking for 40 seconds (because the bomb has been planted), I need to be able to stop it, so I can trigger ct_won instead. I don't want to make all these variables hardcoded into the app, because that seems very bad.

Many of these can appear at the same time. The data.round.bomb == "defused" and data.round.win_team == "CT" are basically both true at the same time, so a big if-else-if chunk of code doesn't seem very wise now that I think about it.

Is something like this possible? It would be fine to have some kind of order system, so I can give the most important one order: 1, the second most important one order: 2 and so on.

答:
It sounds like you are thinking about implementing a rules engine like this one https://www.npmjs.com/package/json-rules-engine.  This would be fun to play with, but from your example I do not believe it would be beneficial.  Best would be to just try to simplify your code a bit if possible and stick with plain JavaScript code.

If you notice I have done a few things to clean up the ifs. One is to separate detecting new state, another using the same property names, also breaking winner and bomb indications into their own function, also getting led color from team object, and return instead of else if.  This is is equivalent to the ifs but more readable.

```<code>let state = { won: null, bomb: null };
let team = { terrorist: 'red', counterTerrorist: 'blue' }

function detectNewState(data) {
  let newState = {};
  for (key in state)
    if (state[key] != data[key]) {
      newState[key] = data[key];
      state[key] = data[key];
    }
  return newState;
}

function indicateWinner(won) {
  blinkLED(team[won], 5);
}

function indicateBomb(bomb) {
  blinkLed(team[bomb], 40);
}

function update(data) {
  const {won, bomb} = detectNewState(data);
  if (won) return indicateWinner(won);
  if (bomb) return indicateBomb(bomb);
});

server.on('update', update);
</code>```

Body:
I'm trying to handle multiple states of a Counter-Strike events. I basically need to overrule some of the rules. Here are some examples of functions that could be triggered:

If I shoot someone

If I shoot someone, but I win the round, the round won should overrule my shot someone

If I shoot someone in the head, it should overrule shot someone, but round won should overrule headshot

Other than that, I need to be able to cancel some events that are occuring at the moment. Basically say STOP EVERYTHING AND DO THIS INSTEAD. Let's imagine the code is hosted on my Raspberry Pi and I can control LEDs using my NodeJS code (basically what I am doing). I need to be able to stop current events, so the LED doesn't keep blinking a color, if something else happens instead. Here is a mockup of what I am trying to accomplish:

var t_won = false;
var ct_won = false;
var bomb_planted = false;
var kills = 0;

server.on("update", function(data) {
    if(data.round.win_team == "T" && t_won == false) {
        t_won = true;
        blinkLED("red", 5);
    } else if(data.round.win_team == "CT" && ct_won == false) {
        ct_won = true;
        blinkLED("blue", 5);
    } else if(data.round.bomb == "planted" && bomb_planted == false) {
        bomb_planted = true;
        blinkLED("red", 40);
    } else if(data.round.bomb == "defused" && bomb_planted == true) {
        LED.stop();
        //ct_won(); or whatever
    }
});

function blinkLED(color, time) {
    //time = time in seconds
    LED.blink(color, time);
}

Does that make sense? It's basically pseudo code, but it works the same way. If the LED is blinking for 40 seconds (because the bomb has been planted), I need to be able to stop it, so I can trigger ct_won instead. I don't want to make all these variables hardcoded into the app, because that seems very bad.

Many of these can appear at the same time. The data.round.bomb == "defused" and data.round.win_team == "CT" are basically both true at the same time, so a big if-else-if chunk of code doesn't seem very wise now that I think about it.

Is something like this possible? It would be fine to have some kind of order system, so I can give the most important one order: 1, the second most important one order: 2 and so on.

Body:
It sounds like you are thinking about implementing a rules engine like this one https://www.npmjs.com/package/json-rules-engine.  This would be fun to play with, but from your example I do not believe it would be beneficial.  Best would be to just try to simplify your code a bit if possible and stick with plain JavaScript code.

If you notice I have done a few things to clean up the ifs. One is to separate detecting new state, another using the same property names, also breaking winner and bomb indications into their own function, also getting led color from team object, and return instead of else if.  This is is equivalent to the ifs but more readable.

let state = { won: null, bomb: null };
let team = { terrorist: 'red', counterTerrorist: 'blue' }

function detectNewState(data) {
  let newState = {};
  for (key in state)
    if (state[key] != data[key]) {
      newState[key] = data[key];
      state[key] = data[key];
    }
  return newState;
}

function indicateWinner(won) {
  blinkLED(team[won], 5);
}

function indicateBomb(bomb) {
  blinkLed(team[bomb], 40);
}

function update(data) {
  const {won, bomb} = detectNewState(data);
  if (won) return indicateWinner(won);
  if (bomb) return indicateBomb(bomb);
});

server.on('update', update);


问:
Is neo4j suitable for searching for paths of specific length
I am a total newcommer in the world of graph databases. But let's put that on a side.

I have a task to find a cicular path of certain length (or of any other measure) from start point and back.

So for example, I need to find a path from one node and back which is 10 "nodes" long and at the same time has around 15 weights of some kind. This is just an example.

Is this somehow possible with neo4j, or is it even the right thing to use?

Hope I clarified it enough, and thank you for your answers.

Regards

答:
Since you did not provide a data model, I will just assume that your starting/ending nodes all have the Foo label, that the relevant relationships all have the BAR type, and that your circular path relationships all point in the same direction (which should be faster to process, in general). Also, I gather that you only want circular paths of a specific length (10). Finally, I am guessing that you prefer circular paths with lower total weight, and that you want to ignore paths whose total weight exceed a bounding value (15). This query accomplishes the above, returning the matching paths and their path weights, in ascending order:

```<code>MATCH p=(f:Foo)-[rels:BAR*10]->(f)
WITH p, REDUCE(s = 0, r IN rels | s + r.weight) AS pathWeight
WHERE pathWeight <= 15
RETURN p, pathWeight
ORDER BY pathWeight;
</code>```

Body:
Since you did not provide a data model, I will just assume that your starting/ending nodes all have the Foo label, that the relevant relationships all have the BAR type, and that your circular path relationships all point in the same direction (which should be faster to process, in general). Also, I gather that you only want circular paths of a specific length (10). Finally, I am guessing that you prefer circular paths with lower total weight, and that you want to ignore paths whose total weight exceed a bounding value (15). This query accomplishes the above, returning the matching paths and their path weights, in ascending order:

MATCH p=(f:Foo)-[rels:BAR*10]->(f)
WITH p, REDUCE(s = 0, r IN rels | s + r.weight) AS pathWeight
WHERE pathWeight <= 15
RETURN p, pathWeight
ORDER BY pathWeight;


问:
Testing route navigation without an outlet in Angular
I am writing a spec for an Angular component that displays a button that will navigate to another page. The component makes use of Router::navigate() but does not itself have a router outlet. A parent component has the outlet. In my spec, the test should confirm that clicking on the button routes to the correct path.

My current (broken) spec tries to use RouterTestingModule to provide a route to a DummyComponent. When the button is clicked in the spec I get the following error:

'Unhandled Promise rejection:', 'Cannot find primary outlet to load 'DummyComponent'', '; Zone:', 'angular', '; Task:', 'Promise.then', '; Value:', Error{__zone_symbol__error: Error{originalStack: 'Error: Cannot find primary outlet to load 'DummyComponent'

Obviously I am approaching this problem in the wrong manner. What is the correct way to test router navigation when the component does not have a router outlet?

The component (pseudo-code):

```<code>@Component({
    template: `
        Go to the <button (click)="nextPage">next page</button>
    `
})
export class ExampleComponent {
    public myId = 5;

    constructor(private _router: Router);

    public nextPage(): void {
        this._router.navigate(['/example', this.myId]);
    }
}
</code>```

The spec. This does not work:

```<code>const FAKE_ID = 999;

describe('ExampleComponent Test', () => {
    let exampleComponent: ExampleComponent;
    let fixture: ComponentFixture<ExampleComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ DummyComponent ],
            imports: [
                RouterTestingModule.withRoutes([
                    { path: 'example/:id', component: DummyComponent }
                ]);
            ]
        });

        fixture = TestBed.createComponent(exampleComponent);
        exampleComponent = fixture.componentInstance;
    });

    it('should route to example/:id', inject([Router, Location], (router: Router, location: Location) => {
        fixture.detectChanges();
        exampleComponent.myId = FAKE_ID;

        const LINK_BUTTON = fixture.debugElement.query(By.css('button'));
        LINK_BUTTON.nativeElement.dispatchEvent(new Event('click'));
        expect(location.path()).toEqual('/example/' + FAKE_ID);
    });
});
</code>```

答:
There needs to be an outlet (<router-outlet>) for the DummyComponent. If the DummyComponent is a route being navigated to from the ExampleComponent, then the ExampleComponent should have the outlet. You also also need to add the ExampleComponent to the declarations`

```<code>@Component({
  tempalte: `
    <router-outlet></router-outlet>
    <button (click)="nextPage">next page</button>
  `
})
class ExampleComponent{}

declarations: [ ExampleComponent, DummyComponent ]
</code>```

If you want to avoid having to set up this infrastructure just to test the route being navigated to, the better option might be to just mock the Router, and just check that the navigate method is called with the correct path.

```<code>beforeEach(()=>{
  TestBed.configureTestingModule({
    providers: [
      {
        provide: Router,
        useValue: { navigate: jasmine.createSpy('navigate') }
      }
    ]
  })
})
</code>```

With this, you don't need to configure an routing at all, as you're using a fake Router. Then in your test

```<code>it('should route to example/:id', inject([Router], (router: Router) => {
  expect(router.navigate).toHaveBeenCalledWith(['/example', FAKE_ID]);
});
</code>```

Body:
I am writing a spec for an Angular component that displays a button that will navigate to another page. The component makes use of Router::navigate() but does not itself have a router outlet. A parent component has the outlet. In my spec, the test should confirm that clicking on the button routes to the correct path.

My current (broken) spec tries to use RouterTestingModule to provide a route to a DummyComponent. When the button is clicked in the spec I get the following error:

'Unhandled Promise rejection:', 'Cannot find primary outlet to load 'DummyComponent'', '; Zone:', 'angular', '; Task:', 'Promise.then', '; Value:', Error{__zone_symbol__error: Error{originalStack: 'Error: Cannot find primary outlet to load 'DummyComponent'

Obviously I am approaching this problem in the wrong manner. What is the correct way to test router navigation when the component does not have a router outlet?

The component (pseudo-code):

@Component({
    template: `
        Go to the <button (click)="nextPage">next page</button>
    `
})
export class ExampleComponent {
    public myId = 5;

    constructor(private _router: Router);

    public nextPage(): void {
        this._router.navigate(['/example', this.myId]);
    }
}

The spec. This does not work:

const FAKE_ID = 999;

describe('ExampleComponent Test', () => {
    let exampleComponent: ExampleComponent;
    let fixture: ComponentFixture<ExampleComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ DummyComponent ],
            imports: [
                RouterTestingModule.withRoutes([
                    { path: 'example/:id', component: DummyComponent }
                ]);
            ]
        });

        fixture = TestBed.createComponent(exampleComponent);
        exampleComponent = fixture.componentInstance;
    });

    it('should route to example/:id', inject([Router, Location], (router: Router, location: Location) => {
        fixture.detectChanges();
        exampleComponent.myId = FAKE_ID;

        const LINK_BUTTON = fixture.debugElement.query(By.css('button'));
        LINK_BUTTON.nativeElement.dispatchEvent(new Event('click'));
        expect(location.path()).toEqual('/example/' + FAKE_ID);
    });
});

Body:
There needs to be an outlet (<router-outlet>) for the DummyComponent. If the DummyComponent is a route being navigated to from the ExampleComponent, then the ExampleComponent should have the outlet. You also also need to add the ExampleComponent to the declarations`

@Component({
  tempalte: `
    <router-outlet></router-outlet>
    <button (click)="nextPage">next page</button>
  `
})
class ExampleComponent{}

declarations: [ ExampleComponent, DummyComponent ]

If you want to avoid having to set up this infrastructure just to test the route being navigated to, the better option might be to just mock the Router, and just check that the navigate method is called with the correct path.

beforeEach(()=>{
  TestBed.configureTestingModule({
    providers: [
      {
        provide: Router,
        useValue: { navigate: jasmine.createSpy('navigate') }
      }
    ]
  })
})

With this, you don't need to configure an routing at all, as you're using a fake Router. Then in your test

it('should route to example/:id', inject([Router], (router: Router) => {
  expect(router.navigate).toHaveBeenCalledWith(['/example', FAKE_ID]);
});


问:
Index was outside the bounds of the array
At the line `If aryTemp(1) < aryTemp2(1) Then the

Index was outside the bounds of the
  array.

error appears. Can't identify why would it be outside array's bounds.
Basically trying to compare Last Names to sort the records and place em back into list box.

A student record looks like this:
FirstName[space]LastName[space]Major[space]Telephone[space]Email[space]GPA

Example: Johny Cake E201 6666666666 me@me.com 1.0

```<code> Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
        ''#load all students into array
        Dim arySort(numberOfRecords) As String
        Dim aryTemp(6) As String
        Dim aryTemp2(6) As String
        For i = 0 To numberOfRecords - 1
            arySort(i) = lstListBox.Items(i)
        Next
        Dim temp As String ''#holds temporary record
        Dim k As Integer
        For i = 0 To arySort.Length - 2
            aryTemp = Split(arySort(i), " ")
            For k = i + 1 To arySort.Length - 1
                aryTemp2 = Split(arySort(k), " ")
                If aryTemp(1) < aryTemp2(1) Then ''# index of 1 refers to last name of a split string
                    temp = arySort(k)
                    arySort(k) = arySort(i)
                    arySort(i) = temp
                End If
            Next
        Next
        lstListBox.Items.Clear()
        numberOfRecords = 0
        isLoaded = False
        For i = 0 To arySort.Length - 1
            lstListBox.Items.Add(arySort(i))
            numberOfRecords += 1
        Next
        currentRecord = 0
        isLoaded = True
    End Sub
</code>```

答:
If you're using Visual Studio 2008 or later, you can make this much simpler:

```<code>Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
    Dim arySort = lstListBox.Items.OrderBy(Function(s) s.Split(" "c)(1)).ToArray()
    lstListBox.Clear()
    lstListBox.AddRange(arySort)
    currentRecord = 0
    isLoaded = True
End Sub
</code>```

I wouldn't suggest turning it in, because it's way outside of what your professor expects of this assignment.  Also, it has the same issue as your original code of not checking to make sure there really is a space in the string to split on. But think of it as what you should be shooting for.

Body:
At the line `If aryTemp(1) < aryTemp2(1) Then the

Index was outside the bounds of the
  array.

error appears. Can't identify why would it be outside array's bounds.
Basically trying to compare Last Names to sort the records and place em back into list box.

A student record looks like this:
FirstName[space]LastName[space]Major[space]Telephone[space]Email[space]GPA

Example: Johny Cake E201 6666666666 me@me.com 1.0

 Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
        ''#load all students into array
        Dim arySort(numberOfRecords) As String
        Dim aryTemp(6) As String
        Dim aryTemp2(6) As String
        For i = 0 To numberOfRecords - 1
            arySort(i) = lstListBox.Items(i)
        Next
        Dim temp As String ''#holds temporary record
        Dim k As Integer
        For i = 0 To arySort.Length - 2
            aryTemp = Split(arySort(i), " ")
            For k = i + 1 To arySort.Length - 1
                aryTemp2 = Split(arySort(k), " ")
                If aryTemp(1) < aryTemp2(1) Then ''# index of 1 refers to last name of a split string
                    temp = arySort(k)
                    arySort(k) = arySort(i)
                    arySort(i) = temp
                End If
            Next
        Next
        lstListBox.Items.Clear()
        numberOfRecords = 0
        isLoaded = False
        For i = 0 To arySort.Length - 1
            lstListBox.Items.Add(arySort(i))
            numberOfRecords += 1
        Next
        currentRecord = 0
        isLoaded = True
    End Sub

Body:
If you're using Visual Studio 2008 or later, you can make this much simpler:

Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
    Dim arySort = lstListBox.Items.OrderBy(Function(s) s.Split(" "c)(1)).ToArray()
    lstListBox.Clear()
    lstListBox.AddRange(arySort)
    currentRecord = 0
    isLoaded = True
End Sub

I wouldn't suggest turning it in, because it's way outside of what your professor expects of this assignment.  Also, it has the same issue as your original code of not checking to make sure there really is a space in the string to split on. But think of it as what you should be shooting for.


问:
Google Apps Script Fails to Load Tempate html Files
I have created a sidebar with custom functionality for my spreadsheet. It used to work as expected, but when I opened the file recently it fails to load correctly.

I have an html file called Page that contains the html code. I have another file Stylesheet to store the css and have added it to Page like this:

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <?!= include('Stylesheet'); ?>
  </head>
  <body>
    My Content
  </body>
</html>
</code>```

This used to correctly load the stylesheet when I opened the file. However, now I see this instead:

From what I can tell, I am following the proper methods and process from here:
https://developers.google.com/apps-script/guides/html/best-practices

I fear that I am missing something obvious, but I would appreciate any help you can provide to get this to work.

UPDATE

Here is my Stylesheet code:

```<code><style>
    .width-100 {
      width: 98%;
      height: 100%
    }
    .red{ color:red; }
    i.material-icons,input[type='Submit']{
      cursor:pointer;
    }
    i.material-icons.active{
      border-bottom: 2px solid red;
      padding-bottom: 3px;
    }
    .sidebar.branding-below {
      top: 0;
    }
    .sidebar.bottom {
      border-top: 1px solid #ddd;
    }
    img.logo{
      position: relative;
      vertical-align: middle;
    }
    #topBar {
      border-bottom: 1px solid #bbb;
      margin-bottom: 10px;
      padding-bottom: 5px;
    }
    #settingForm {
      position: absolute;
      background: white;
      margin: 10px;
      width: 260px;
      top: 36px;
      box-shadow: 2px 2px 1px #bbb;
      border: 1px solid grey;
      padding: 10px;
      position: relative;
    }
    #settingForm hr {
      margin-top: 0;
    }
    #proserWorkSecurity{
    }
    #proserWorkSettings h3 {
      margin: 0 0 10px 0;
      line-height: 20px;
    }
    i#settingsClose {
      position: absolute;
      top: 10px;
      right: 10px;
      font-size: 20px;
    }
    #processingWindow {
      position: absolute;
      padding: 200px 30px 30px 30px;
      width: 78%;
      height: 69%;
      background-color: rgba(256,256,256,0.9);
    }
    .formButton{
      cursor: pointer !important;
    }
    .formButton:hover{
      background: -webkit-linear-gradient(top, #4d90fe, #4787ed) !important;
      color: white !important;
      border: 1px transparent !important;
    }
    .Loader {
      text-align: center;
      padding: 80px 0;
    }
    .Loader_label {
      color: #363636;
      font-size: 13px;
      font-weight: 700;
      margin: 15px 0;
    }
    .CircleSpinner {
      -webkit-animation: spin 0.6s infinite linear;
      animation: spin 0.6s infinite linear;
      fill: #2196f3;
      height: 30px;
      width: 30px;
    }
    svg {
      overflow: hidden;
    }
  </style>
</code>```

Here is my include:

```<code>function include(File) {
  return HtmlService.createHtmlOutputFromFile(File).getContent();
};
</code>```

UPDATE 2

I have created a test instance to make it easier to see what is happening. I have added a custom menu Campaign Manager with one menu item to open the sidebar.

https://docs.google.com/spreadsheets/d/10gsWSkaSvf7oi45SBluJm3Y-GsIteMrOP7uzP-26ewU/edit?usp=sharing

答: Redeploy it with a new project version.</p>

Body:
I have created a sidebar with custom functionality for my spreadsheet. It used to work as expected, but when I opened the file recently it fails to load correctly.

I have an html file called Page that contains the html code. I have another file Stylesheet to store the css and have added it to Page like this:

<!DOCTYPE html>

    <base target="_top">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <?!= include('Stylesheet'); ?>

    My Content

This used to correctly load the stylesheet when I opened the file. However, now I see this instead:

From what I can tell, I am following the proper methods and process from here:
https://developers.google.com/apps-script/guides/html/best-practices

I fear that I am missing something obvious, but I would appreciate any help you can provide to get this to work.

UPDATE

Here is my Stylesheet code:

Here is my include:

function include(File) {
  return HtmlService.createHtmlOutputFromFile(File).getContent();
};

UPDATE 2

I have created a test instance to make it easier to see what is happening. I have added a custom menu Campaign Manager with one menu item to open the sidebar.

https://docs.google.com/spreadsheets/d/10gsWSkaSvf7oi45SBluJm3Y-GsIteMrOP7uzP-26ewU/edit?usp=sharing

Body: Redeploy it with a new project version.


问:
Are there tools like boosts bcp for Eigen?
in a project I use a very small portion of Eigen. I want to offer the user of my code two options:

download eigen and link to it

use built-in eigen shipped with my code

For option 2) I do not want to ship the whole of Eigen, but only the subpart I need. Boost offers for such occasions the tool bcp, that finds all dependencies and separates all the necessary headers. Is there something like this available for Eigen, too? And is this conform with the license?

答:
Eigen is a header only library. You should not need to redistribute it; there is nothing to link to.

From their website:

Eigen is only a compile-time dependency for your project. No need to redistribute, or ask your user to install, any library.

If you are distributing source code, I'm not exactly sure how the license applies. You could have your build tool try to locally find Eigen first, then pull the headers from the Eigen repo if it doesn't succeed.


问:
nothing is stored as the result of fscanf
```<code>#define TERMMAX 100
typedef struct{
    int coef;
    int expon;
} poly;
poly term[TERMMAX];
int avail = 0;

#define TERMMAX 100
enter code here
int main()
{
    int i;
    FILE *fp = fopen("a.txt", "r");

    while(fscanf(fp, "%d\t%d", &term[avail].coef, &term[avail].expon) != EOF)
        avail++;
</code>```

the fscanf part above works just fine but the following fscanf doesn't.

```<code>    while(fscanf(fp, "%d\t%d", &term[avail].coef, &term[avail++].expon) != EOF)
        ;
</code>```

Nothing is stored in term[].expon. Why?

答: IIRC, the order of evaluation of function parameters is unspecified by the Standard. Any side effects of function parameters are indeterminately sequenced. </p>

Body:
#define TERMMAX 100
typedef struct{
    int coef;
    int expon;
} poly;
poly term[TERMMAX];
int avail = 0;

#define TERMMAX 100
enter code here
int main()
{
    int i;
    FILE *fp = fopen("a.txt", "r");

    while(fscanf(fp, "%d\t%d", &term[avail].coef, &term[avail].expon) != EOF)
        avail++;

the fscanf part above works just fine but the following fscanf doesn't.

    while(fscanf(fp, "%d\t%d", &term[avail].coef, &term[avail++].expon) != EOF)
        ;

Nothing is stored in term[].expon. Why?


问:
Git extension does not work in Visual Studio 2017; Is it a known issue?
Before trying the official release of Visual Studio 2017, I installed Visual Studio 2017 RC and found that my existing Git Repository is not recognized. Even though I made sure that the Source Control plugin is set to Git as shown in the following picture.

Then, I thought, maybe it is just because of RC edition.
Anyway, today official version of Visual Studio 2017 released and I have installed again. I see the same problem. Did anyone face the same issue? What is the solution to this problem? I do not think I need to install Git Extension separately as looks like Visual studio already has that extension preinstalled.

答:
Check out Easy Git Integration Tools. Much better tools than Team Explorer, and integrates with GitExtensions, works with VS2017 https://marketplace.visualstudio.com/items?itemName=jzoss.GitSourceControlProvider2015

New Feature Highlights

Added option to auto-add projects and to the git repository when you
add them to the project!

Switch and create branches, switch git
repositories, and open the pending changes window all from the status
bar!

Initialize new projects from the status bar.

Features

Display file status in solution explorer and solution navigator

Multiple repository support.

Display repository status e.g. in the middle of merging, patching, rebase and bisecting

Enable/disable plug-in through visual studio's source control plug-in selection

No source code control information stored in solution or project file

Initialize new git repository and generate .gitignore

Integrates with Git for Windows

Integrates with Git Extensions

Integrates with TortoiseGit

Git - Pending Changes Tool Window

Git - View History Tool Window

Options page


问:
Copyright Key and Value Not in info.plist
I am preparing my first app for submission to the App Store, in Apple's documentation they say to:

Make sure that your information property list file contains a valid value for the Copyright key.

And then show in a picture what they are talking about which can be found here: http://i.imgur.com/V3ZAgUX.png

However, my info.plist does not contain a copyright Key or Value.  How do I get one in there, is it even really necessary to have this? Is there a chance apple will reject my app without this?

答:
Apple Documentation indicates this is needed for Mac apps, but implies thereby that it's not needed for iOS apps.

See: Setting the Copyright Key (Mac) section in:
https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/ConfiguringYourApp/ConfiguringYourApp.html

...

NSHumanReadableCopyright (String - macOS). This key contains a string with the copyright notice for the bundle; for example, © 2016, My Company. You can load this string and display it in an About dialog box. The system uses this string in the app’s Info window in Finder.


问:
How to output multiple numbers at once in a for loop using Java
I'm very new to Java programming (2 weeks in) and currently am practicing arrays.

My code is as follows:

```<code>import java.util.Scanner;

public class LA2_2_1 {
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int x;
        double avg;
        double num = 0;

        System.out.print("Enter the number of items: ");
        x = scan.nextInt();

        int [] numbers = new int [x];
        double sum = 0;
        sum = sum + num;

        for (int index = 0; index < numbers.length; index++)
        {
            System.out.print("Enter the numbers: ");
            num = scan.nextDouble();
            sum = sum + num;
            System.out.println(sum);
        }
        avg = sum/x;
        System.out.println("The average is " + avg);
    }
}
</code>```

Output:

```<code>Enter the number of items: 10

Enter the numbers: 3.4 5 6 1 6.5 7.8 3.5 8.5 6.3 9.5

3.4

Enter the numbers: 8.4

Enter the numbers: 14.4

Enter the numbers: 15.4

Enter the numbers: 21.9

Enter the numbers: 29.7

Enter the numbers: 33.2

Enter the numbers: 41.7

Enter the numbers: 48.0

Enter the numbers: 57.5

The average is 5.75
</code>```

My question is, how can I format the code so that I get "Enter the numbers" to appear only once? I just want the program to ask the user for the series of numbers they want to input. I do not want it to output multiple "Enter the numbers".

I think this may have to do with the output being within a for loop, but I am not too positive. I tried taking it out, and both the average and output for "Enter the numbers" turned to 0.0.

Any input would be helpful.

Thank you

答:
consider my answer if your really learning an array because in your code you didn't use your array</p>

```<code>public static void main(String args[])
    {
        //sb object for getting the actual int
        StringBuilder sb = new StringBuilder("");
        Scanner scan = new Scanner(System.in);
        int x;
        //this is for the array element of numbers e.g. numbers[y]
        int y=0;

        double sum=0;
        double avg;
        System.out.print("Enter the number of items: ");
        x = scan.nextInt();
        //please add the scan.nextLine that is why you are getting
        scan.nextLine();
        double[] numbers=new double[x];
        System.out.print("Enter the numbers followed by space:");
        String numberEntered=scan.nextLine();

        for(int i=0;i<numberEntered.length();++i)
        {
            //everytime loop iterate new sb with empty value is created
            sb=new StringBuilder("");
                while(i<numberEntered.length()&&numberEntered.charAt(i)!=' ')
                {
                    //get the actual String integer not containing space
                    sb.append(numberEntered.charAt(i));
                    ++i;
                }
                //convert the String actual integers to integer
            numbers[y]=Double.parseDouble(sb.toString());
            //increment y for the array element of numbers
                ++y;
        }
        //get the sum using foreach loop containing the array of numbers
        for(double myNumbers:numbers)
        {
            sum+=myNumbers;
        }

        avg=sum/x;
        System.out.println("The average is " + avg);

    }
</code>```

Body:
I'm very new to Java programming (2 weeks in) and currently am practicing arrays.

My code is as follows:

import java.util.Scanner;

public class LA2_2_1 {
    public static void main (String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int x;
        double avg;
        double num = 0;

        System.out.print("Enter the number of items: ");
        x = scan.nextInt();

        int [] numbers = new int [x];
        double sum = 0;
        sum = sum + num;

        for (int index = 0; index < numbers.length; index++)
        {
            System.out.print("Enter the numbers: ");
            num = scan.nextDouble();
            sum = sum + num;
            System.out.println(sum);
        }
        avg = sum/x;
        System.out.println("The average is " + avg);
    }
}

Output:

Enter the number of items: 10

Enter the numbers: 3.4 5 6 1 6.5 7.8 3.5 8.5 6.3 9.5

3.4

Enter the numbers: 8.4

Enter the numbers: 14.4

Enter the numbers: 15.4

Enter the numbers: 21.9

Enter the numbers: 29.7

Enter the numbers: 33.2

Enter the numbers: 41.7

Enter the numbers: 48.0

Enter the numbers: 57.5

The average is 5.75

My question is, how can I format the code so that I get "Enter the numbers" to appear only once? I just want the program to ask the user for the series of numbers they want to input. I do not want it to output multiple "Enter the numbers".

I think this may have to do with the output being within a for loop, but I am not too positive. I tried taking it out, and both the average and output for "Enter the numbers" turned to 0.0.

Any input would be helpful.

Thank you

Body:
consider my answer if your really learning an array because in your code you didn't use your array

public static void main(String args[])
    {
        //sb object for getting the actual int
        StringBuilder sb = new StringBuilder("");
        Scanner scan = new Scanner(System.in);
        int x;
        //this is for the array element of numbers e.g. numbers[y]
        int y=0;

        double sum=0;
        double avg;
        System.out.print("Enter the number of items: ");
        x = scan.nextInt();
        //please add the scan.nextLine that is why you are getting
        scan.nextLine();
        double[] numbers=new double[x];
        System.out.print("Enter the numbers followed by space:");
        String numberEntered=scan.nextLine();

        for(int i=0;i<numberEntered.length();++i)
        {
            //everytime loop iterate new sb with empty value is created
            sb=new StringBuilder("");
                while(i<numberEntered.length()&&numberEntered.charAt(i)!=' ')
                {
                    //get the actual String integer not containing space
                    sb.append(numberEntered.charAt(i));
                    ++i;
                }
                //convert the String actual integers to integer
            numbers[y]=Double.parseDouble(sb.toString());
            //increment y for the array element of numbers
                ++y;
        }
        //get the sum using foreach loop containing the array of numbers
        for(double myNumbers:numbers)
        {
            sum+=myNumbers;
        }

        avg=sum/x;
        System.out.println("The average is " + avg);

    }


问:
PHP Remove empty value from array with unset not working correctly
I have a string containing sentences. I wish to break these sentences into an array, then modify each array item, including removing any array items that are empty.

Here's what I have:

```<code>//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array
foreach ($items_array as $i => $item) {

  //Remove any whitespace at front of item
  $item= ltrim($item);

  //Check if array item is empty and unset
  if($item === NULL){
    unset($items_array[$i]);
  }

  //Reinstate the dot
  $item .= '.';
}
</code>```

However, this does not work. I see extra '.' and if I put a print(strlen($item)); within the loop (after the unset) I see a few 0 results.

I know the if condition is being met because if I put a print in there it will trigger the same amount of times a 0 appears, eg:

```<code> if($item === NULL){
      print("no value");
      unset($raw_inclusions[$i]);
    }
</code>```

Have I done something wrong here?

Example $raw_data string. Assume I have no control over what is placed here.

```<code>$raw_data = "Brown fox. Lazy dog."
</code>```

Expected/desired result:

```<code>$items_array = array("Brown fox.", "Lazy dog.");
</code>```

Current result:

```<code>$items_array = array("Brown fox.", "Lazy dog.", ".");
</code>```

答:
I would do this:

```<code>$items_array = array_map(function($v) { return ltrim($v).'.'; },
                         array_filter(explode('.', $raw_data)));
</code>```

explode on .

filter empty items

map each item to trim and add .

Body:
I have a string containing sentences. I wish to break these sentences into an array, then modify each array item, including removing any array items that are empty.

Here's what I have:

//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array
foreach ($items_array as $i => $item) {

  //Remove any whitespace at front of item
  $item= ltrim($item);

  //Check if array item is empty and unset
  if($item === NULL){
    unset($items_array[$i]);
  }

  //Reinstate the dot
  $item .= '.';
}

However, this does not work. I see extra '.' and if I put a print(strlen($item)); within the loop (after the unset) I see a few 0 results.

I know the if condition is being met because if I put a print in there it will trigger the same amount of times a 0 appears, eg:

 if($item === NULL){
      print("no value");
      unset($raw_inclusions[$i]);
    }

Have I done something wrong here?

Example $raw_data string. Assume I have no control over what is placed here.

$raw_data = "Brown fox. Lazy dog."

Expected/desired result:

$items_array = array("Brown fox.", "Lazy dog.");

Current result:

$items_array = array("Brown fox.", "Lazy dog.", ".");

Body:
I would do this:

$items_array = array_map(function($v) { return ltrim($v).'.'; },
                         array_filter(explode('.', $raw_data)));

explode on .

filter empty items

map each item to trim and add .


问:
html/javascript page that files can be loaded to
I want to write a html file that can access files on my computer with gui like this one:

https://smallpdf.com/pdf-to-jpg

In the yellow box it says "choose file". you can click that and choose a file from your computers file system. I would like to do something similar and then be able to use the files in the html.

In particular I want the user to be able to choose a png and then convert it to a html canvas and then do stuff with that canvas. I want everything to be local, so nothing should be uploaded like the website i linked to does.

How does one do this?

Thanks

Sorry this wasn't clear, I want to have all the file processing handled by the html page not by some php on a server. I don't want there to be a server side component to this. If that is not possible please let me know, thanks again.

I want everything to be able to work off line so you could just have the html page, open it, and use it.

答: Maybe you can try the File Api from Html5 so you could load it on the local and made the changes you need. </p>


问:
how to create an array of list of pair in C++
I want to use an array of list of pairs to represent a directed weighted graph using adjacent list

```<code>class Graph{
int n_v;
list<pair<int, int> > *adj;
public:
Graph(int _n_v){
    n_v = _n_v;
    adj = new list<pair<int, int> >[n_v];
}
</code>```

but the compiler raised an error:

```<code>class list<pair<int, int>> is not compatible with list<int, int>>
</code>```

how to solve with this problem?

答:
Use std::vector especially if you use standard containers already:

```<code>std::vector<std::list<std::pair<int, int>>> arr( size );
</code>```

Body:
I want to use an array of list of pairs to represent a directed weighted graph using adjacent list

class Graph{
int n_v;
list<pair<int, int> > *adj;
public:
Graph(int _n_v){
    n_v = _n_v;
    adj = new list<pair<int, int> >[n_v];
}

but the compiler raised an error:

class list<pair<int, int>> is not compatible with list<int, int>>

how to solve with this problem?

Body:
Use std::vector especially if you use standard containers already:

std::vector<std::list<std::pair<int, int>>> arr( size );