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

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

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

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

THis is what I am thinking of doing

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

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

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

答:
You should read the Django documentation on URL dispatcher. Here is the part referencing inclusion of other URLconfs.

Include urls from apps in the urlpatterns in example.urls. I also suggest you use namespace argument to avoid confusion.

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

You then use url syntax namespace:urlname in views and templates.

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

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

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

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

THis is what I am thinking of doing

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

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

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

Body:
You should read the Django documentation on URL dispatcher. Here is the part referencing inclusion of other URLconfs.

Include urls from apps in the urlpatterns in example.urls. I also suggest you use namespace argument to avoid confusion.

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

You then use url syntax namespace:urlname in views and templates.


来源: stackexchange

问:
Sync 2 MySQL databases
I have 2 MySql databases and I want keep them in sync. The problem is that I dont have access to the machine that runs the "master" database, I only have rights to read.

So I created a secondary database and I want to create a cron job to sync with the master one every day at 12:00 (for example).

What is the best way to do this ?

答: My solution was to create a python script to re-import all the data. I needed to change the table names anyway for the django-app.</p>

ContentLicense: CC BY-SA 2.5

Title: Sync 2 MySQL databases


问:
Highlight search result string case issue
I am using a cfscript that takes in a string, search terms, and optional highlight option and return the string with search terms highlighted:

```<code><cfscript>
string function highlightKeywords(required string str, required string keywords, struct highlight){
    var keyword     = "";
    var replacement = "";

    param name="highlight.tag"          default="span";
    param name="highlight.attributes"   default="style='color:rgb(255,102,0);'";

    for (var index=1; index <= listLen( arguments.keywords, " " ); index++){
        keyword = ReReplace(listGetAt(arguments.keywords, index, " "), "\(|\)", "", "all" );
        replacement = "<#highlight.tag#";
        if (len(highlight.attributes)){
            replacement &= " #highlight.attributes#";
        }
        replacement &= ">" & keyword & "</#highlight.tag#>";

        arguments.str = reReplaceNoCase( arguments.str, "\b#keyword#\b", replacement, "all" );
    }
    return arguments.str;
}
</cfscript>
</code>```

Everything seems to be working fine, except one issue.  It changes the case of the original string.

For example, when a user search for the term "highlight search" and the original string is stored as "This is a Highlight Search Testing".  One would expect that it will return "This is a Highlight Search Testing".  Instead it returned "This is a highlight search Testing".  It replaced the case with whatever the user typed instead of keeping original case.  Can someone assist me in this?  Thanks in advance.

Additional Note:
CF works differently for backreferences.

答:
You may capture the keyword with "\b(#keyword#)\b" (note the capturing parentheses) and replace with the \1 backreference to this Group 1 value to actually replace with the matched variant of the keyword.

Use

```<code>replacement &= ">\1</#highlight.tag#>"
</code>```

and then

```<code> arguments.str = reReplaceNoCase( arguments.str, "\b(#keyword#)\b", replacement, "all" )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using a cfscript that takes in a string, search terms, and optional highlight option and return the string with search terms highlighted:

<cfscript>
string function highlightKeywords(required string str, required string keywords, struct highlight){
    var keyword     = "";
    var replacement = "";

    param name="highlight.tag"          default="span";
    param name="highlight.attributes"   default="style='color:rgb(255,102,0);'";

    for (var index=1; index <= listLen( arguments.keywords, " " ); index++){
        keyword = ReReplace(listGetAt(arguments.keywords, index, " "), "\(|\)", "", "all" );
        replacement = "<#highlight.tag#";
        if (len(highlight.attributes)){
            replacement &= " #highlight.attributes#";
        }
        replacement &= ">" & keyword & "</#highlight.tag#>";

        arguments.str = reReplaceNoCase( arguments.str, "\b#keyword#\b", replacement, "all" );
    }
    return arguments.str;
}
</cfscript>

Everything seems to be working fine, except one issue.  It changes the case of the original string.

For example, when a user search for the term "highlight search" and the original string is stored as "This is a Highlight Search Testing".  One would expect that it will return "This is a Highlight Search Testing".  Instead it returned "This is a highlight search Testing".  It replaced the case with whatever the user typed instead of keeping original case.  Can someone assist me in this?  Thanks in advance.

Additional Note:
CF works differently for backreferences.

Body:
You may capture the keyword with "\b(#keyword#)\b" (note the capturing parentheses) and replace with the \1 backreference to this Group 1 value to actually replace with the matched variant of the keyword.

Use

replacement &= ">\1</#highlight.tag#>"

and then

 arguments.str = reReplaceNoCase( arguments.str, "\b(#keyword#)\b", replacement, "all" )


问:
TypeError: Cannot find function hasNext in object
I'm trying to save an email in to a particular drive folder however getting error message

```<code>TypeError: Cannot find function hasNext in object
</code>```

Any idea how I can overcome this.

```<code>function saveGmailToDrive() {
    var gmailLabels  = "SaveToDrivetest";
    var driveFolder  = "Emails saved by " + Session.getActiveUser().getEmail()

    /* Gmail Label that contains the queue */
    var label = GmailApp.getUserLabelByName(gmailLabels) ?
                    GmailApp.getUserLabelByName(gmailLabels) :
                    GmailApp.createLabel(gmailLabels);

    var threads = GmailApp.search("in:" + gmailLabels, 0, 5);

    if (threads.length > 0) {
        /* Google Drive folder where the Files would be saved */
        var folders = DriveApp.getFolderById("0B9Ug3fXvrl5HeGRddddMcE93bkE3Q1k");
        var folder = folders.hasNext() ?
                         folders.next() :
                         DriveApp.createFolder(driveFolder);
    }
</code>```

答:
In general: if the noun after "get" is in plural form, you get an iterator to be used with hasNext and next methods. If that noun is in singular form, you get a single object. Examples:

getFileById returns one File

getFiles returns an iterator

getFilesByName returns an iterator

getFilesByType returns an iterator

getFolderById returns one Folder

getFolders returns an iterator

getFoldersByName returns an iterator

Body:
I'm trying to save an email in to a particular drive folder however getting error message

TypeError: Cannot find function hasNext in object

Any idea how I can overcome this.

function saveGmailToDrive() {
    var gmailLabels  = "SaveToDrivetest";
    var driveFolder  = "Emails saved by " + Session.getActiveUser().getEmail()

    /* Gmail Label that contains the queue */
    var label = GmailApp.getUserLabelByName(gmailLabels) ?
                    GmailApp.getUserLabelByName(gmailLabels) :
                    GmailApp.createLabel(gmailLabels);

    var threads = GmailApp.search("in:" + gmailLabels, 0, 5);

    if (threads.length > 0) {
        /* Google Drive folder where the Files would be saved */
        var folders = DriveApp.getFolderById("0B9Ug3fXvrl5HeGRddddMcE93bkE3Q1k");
        var folder = folders.hasNext() ?
                         folders.next() :
                         DriveApp.createFolder(driveFolder);
    }


问:
I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular
I'm using Angular 4 HttpClient to send requests to external service. It is a very standard setup:

```<code>this.httpClient.get(url).subscribe(response => {
  //do something with response
}, err => {
  console.log(err.message);
}, () => {
  console.log('completed');
}
</code>```

The problem is, when the request fails I see a generic
Http failure response for (unknown url): 0 Unknown Error message in console. Meanwhile, when I inspect the failed request in chrome I can see the response status is 422, and in the "preview" tab I see the actual message desribing failure cause.

How do I access the actual response message I can see in chrome dev tools?

Here's a screenshot demonstrating the problem:

答:
The problem was related to CORS. I noticed that there was another error in Chrome console:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 422.`

This means the response from backend server was missing Access-Control-Allow-Origin header even though backend nginx was configured to add those headers to the responses with add_header directive.

However, this directive only adds headers when response code is 20X or 30X. On error responses the headers were missing. I needed to use always parameter to make sure header is added regardless of the response code:

add_header 'Access-Control-Allow-Origin' 'http://localhost:4200' always;

Once the backend was correctly configured I could access actual error message in Angular code.

Body:
I'm using Angular 4 HttpClient to send requests to external service. It is a very standard setup:

this.httpClient.get(url).subscribe(response => {
  //do something with response
}, err => {
  console.log(err.message);
}, () => {
  console.log('completed');
}

The problem is, when the request fails I see a generic
Http failure response for (unknown url): 0 Unknown Error message in console. Meanwhile, when I inspect the failed request in chrome I can see the response status is 422, and in the "preview" tab I see the actual message desribing failure cause.

How do I access the actual response message I can see in chrome dev tools?

Here's a screenshot demonstrating the problem:


问:
How can I open a new document without saving the current document by using a single command in Vim
In Vim

:w saves the document document1

:wq or :x quits the document document1 after saving

wq! quits the document document1 without saving

:sav document2 or :w + :e document2 saves the document document1 and opens the document document2

What I want is that I want to open a a new document document2 without saving the document document1, and I want to do so using a single command.

Is it possible?

答:
You want

```<code>:e! document2
</code>```

to edit document2, discarding all changes to the current buffer.

Body:
You want

:e! document2

to edit document2, discarding all changes to the current buffer.


问:
What should I consider when determining JWT expiration time?
Isn't it effective to never let the JWT expire so that user automatically logs in? Is there  a security problem with it?

I don't want to use session and or cookie. They are ineffective.

答:
IMO, it is effective in case the token gets stolen. If you have an infinite expiration time, the intruder has access to the protected resource for the lifetime. Think of it this as your password for personal mail. It is often a good idea to change it periodically so that if someone has obtained your password without your knowledge, he won't be able to access your email again after that.
Having said that, it is not compulsory to have the expiration time.
according to this

The "exp" (expiration time) claim identifies the expiration time on
or after which the JWT MUST NOT be accepted for processing.  The
processing of the "exp" claim requires that the current date/time
MUST be before the expiration date/time listed in the "exp" claim. Implementers MAY provide for some small leeway, usually no more than
a few minutes, to account for clock skew.  Its value MUST be a number
containing a NumericDate value.  Use of this claim is OPTIONAL.


问:
ANT & MSBUILD - build process won't fail if errors
When running msbuild.exe with ANT's exec task, errors in the .net code do not result in the build process failing.

Why would this be?

答: I use Nant to run some MSBuild tasks.  Every time I use the failonbuild attribute of that task, it fails for me.  Looking at Apache's documentation for Ant, it would appear the same attribute is there as well. Are you using this attribute?

OwnerDisplayName: Bert Vandamme

OwnerDisplayName: JamesEggers


问:
Not recognized non existant file
im getting a weird error using this code (part of a class):

```<code>from sys import path as workingDIR
from os import system, path

image = '' # some jpeg image data
keep = 0

DIR = workingDIR[0] + '\\image'
if path.isfile(DIR + '.jpeg'):                # adding numbers to end of file name like how windows prevents multiple files having the same name
    x = 2
    while path.isfile(DIR + ' (' + str(x) + ').jpeg'):
        x += 1
    DIR += ' (' + str(x) + ')'
DIR += '.jpeg'
f = open(DIR, 'w+b')
f.write(image)
f.close()
system(DIR)
system('pause')
if not(keep):
    remove(DIR)
</code>```

cmd is telling me '...\image' is not recognized as an internal or external command, operable program or batch file. (ignore the ...), which doesnt make sense, because DIR has already been changed to ...\image.jpeg and yet it is getting image. what am i doing wrong here?

答:
You have an extra white space in the image filename - "..\image (1).jpeg"<br>
so when you call system(DIR), "..\image" becomes the command and "(1).jpeg" is the first argument.  </p>

Title: Not recognized non existant file

Body:
im getting a weird error using this code (part of a class):

from sys import path as workingDIR
from os import system, path

image = '' # some jpeg image data
keep = 0

DIR = workingDIR[0] + '\\image'
if path.isfile(DIR + '.jpeg'):                # adding numbers to end of file name like how windows prevents multiple files having the same name
    x = 2
    while path.isfile(DIR + ' (' + str(x) + ').jpeg'):
        x += 1
    DIR += ' (' + str(x) + ')'
DIR += '.jpeg'
f = open(DIR, 'w+b')
f.write(image)
f.close()
system(DIR)
system('pause')
if not(keep):
    remove(DIR)

cmd is telling me '...\image' is not recognized as an internal or external command, operable program or batch file. (ignore the ...), which doesnt make sense, because DIR has already been changed to ...\image.jpeg and yet it is getting image. what am i doing wrong here?

Body:
You have an extra white space in the image filename - "..\image (1).jpeg"

so when you call system(DIR), "..\image" becomes the command and "(1).jpeg" is the first argument.


问:
Why is Angular Material Dialog component not showing in Google Chrome?
The dialog box works fine in Firefox. In Chrome, the click event just displays a small empty dialog box with no content or buttons. I was working through this example when I had the issue.

DialogComponent:

@Component({
selector: 'dialog',
template: `

hey title

        <md-dialog-content class="accent-color">
          hey this is the content of the dialog
        </md-dialog-content>
        <md-dialog-actions>
          <button md-raised-button color="primary" md-dialog-close>
            close button
          </button>
        </md-dialog-actions>
`
})
```

<p>AppComponent html:</p>

<pre class="lang-html prettyprint-override"><code><div>
  <button md-raised-button color="primary" (click)="openDialog()">
    Example Dialog - Click Me!
  </button>
</div>
</code>```

AppComponent function:

constructor(public dialog: MdDialog) {}

openDialog() {
  this.dialog.open(DialogComponent);}
```

Is there something specific I have to do to make it work in Google Chrome browser?

答: Had a very similar problem, which was fixed after changing my selector name from 'dialog' to 'dialog-box.' Not sure of the specifics, but I assume Chrome contains some 'dialog' selector that will be reference if you use 'dialog' as a selector name.</p>

Body:
The dialog box works fine in Firefox. In Chrome, the click event just displays a small empty dialog box with no content or buttons. I was working through this example when I had the issue.

DialogComponent:

@Component({
selector: 'dialog',
template: `

hey title

        <md-dialog-content class="accent-color">
          hey this is the content of the dialog
        </md-dialog-content>
        <md-dialog-actions>
          <button md-raised-button color="primary" md-dialog-close>
            close button
          </button>
        </md-dialog-actions>
`
})

AppComponent html:

  <button md-raised-button color="primary" (click)="openDialog()">
    Example Dialog - Click Me!
  </button>

AppComponent function:

constructor(public dialog: MdDialog) {}

openDialog() {
  this.dialog.open(DialogComponent);}

Is there something specific I have to do to make it work in Google Chrome browser?


问:
Oracle distinct listagg with count
I need to display a comma-separated description per table row but I need the list to be distinct and have counts for some of the descriptions available.

```<code>every_description     needs_count
---------------------------------
Bred                          yes
From Vendor                   yes
Grouped                        no
Removed                       yes
Separated                      no
Weaned                        yes
</code>```

So in a day, the description could be something like Bred, Grouped, Weaned and I have this working now using LISTAGG and removing the duplicates using the solution mentioned here but I need to add counts for some of the descriptions like 5 Bred, Grouped, 2 Weaned.

Here's my current query where I'm stuck:

```<code>WITH cages AS (
        SELECT 1234 AS id FROM DUAL
  UNION SELECT 5678 AS id FROM DUAL
  UNION SELECT 9012 AS id FROM DUAL
  UNION SELECT 3456 AS id FROM DUAL
), cage_comments AS (
        SELECT 1234 AS cage_id, 'Bred' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 5678 AS cage_id, 'Grouped' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 9012 AS cage_id, 'Weaned' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Weaned' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Bred' AS description, TO_DATE('11/02/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Grouped' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
), calendar AS (
  SELECT dt
  FROM (
    SELECT TRUNC(LAST_DAY(TO_DATE(&month || '/01/' || &year, 'MM/DD/YYYY')) - ROWNUM + 1) dt
    FROM DUAL CONNECT BY ROWNUM <= 31
  )
  WHERE dt >= TRUNC(TO_DATE(&month || '/01/' || &year, 'MM/DD/YYYY'), 'MM')
  ORDER BY dt ASC
)

SELECT
  cal.dt,
  (
    SELECT
      CASE
        WHEN COUNT(cc.cage_id) > 0 THEN RTRIM(
          REGEXP_REPLACE(
            (LISTAGG(cc.description, ',') WITHIN GROUP (ORDER BY cc.description)),
            '([^,]*)(,\1)+($|,)',
            '\1\3'
          ),
          ','
        )
        ELSE NULL
      END
    FROM cages c
    LEFT JOIN cage_comments cc ON cc.cage_id = c.id
    WHERE cc.event_date = cal.dt
  ) AS description
FROM calendar cal
ORDER BY cal.dt
</code>```

In short - I'm just having difficulties adding the COUNT for some of the descriptions for that day. In the case above I would like to say 1 Bred for November 2, 2017 and 1 Bred, Grouped, 2 Weaned for November 14, 2017.

答:
You could use:

```<code>SELECT
  cal.dt,
  (
      SELECT LISTAGG(CASE WHEN COUNT(*)=1 THEN ''
            ELSE CAST(COUNT(*) AS VARCHAR2(10)) || ' ' END  || description, ', ')
            WITHIN GROUP (ORDER BY description)
      FROM cages c
      LEFT JOIN cage_comments cc ON cc.cage_id = c.id
      WHERE cc.event_date = cal.dt
      GROUP BY cc.event_date, cc.description
  ) AS description
FROM calendar cal
ORDER BY cal.dt;
</code>```

DBFiddle Demo

Title: Oracle distinct listagg with count

Body:
I need to display a comma-separated description per table row but I need the list to be distinct and have counts for some of the descriptions available.

every_description     needs_count
---------------------------------
Bred                          yes
From Vendor                   yes
Grouped                        no
Removed                       yes
Separated                      no
Weaned                        yes

So in a day, the description could be something like Bred, Grouped, Weaned and I have this working now using LISTAGG and removing the duplicates using the solution mentioned here but I need to add counts for some of the descriptions like 5 Bred, Grouped, 2 Weaned.

Here's my current query where I'm stuck:

WITH cages AS (
        SELECT 1234 AS id FROM DUAL
  UNION SELECT 5678 AS id FROM DUAL
  UNION SELECT 9012 AS id FROM DUAL
  UNION SELECT 3456 AS id FROM DUAL
), cage_comments AS (
        SELECT 1234 AS cage_id, 'Bred' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 5678 AS cage_id, 'Grouped' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 9012 AS cage_id, 'Weaned' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Weaned' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Bred' AS description, TO_DATE('11/02/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
  UNION SELECT 3456 AS cage_id, 'Grouped' AS description, TO_DATE('11/14/2017', 'MM/DD/YYYY') AS event_date FROM DUAL
), calendar AS (
  SELECT dt
  FROM (
    SELECT TRUNC(LAST_DAY(TO_DATE(&month || '/01/' || &year, 'MM/DD/YYYY')) - ROWNUM + 1) dt
    FROM DUAL CONNECT BY ROWNUM <= 31
  )
  WHERE dt >= TRUNC(TO_DATE(&month || '/01/' || &year, 'MM/DD/YYYY'), 'MM')
  ORDER BY dt ASC
)

SELECT
  cal.dt,
  (
    SELECT
      CASE
        WHEN COUNT(cc.cage_id) > 0 THEN RTRIM(
          REGEXP_REPLACE(
            (LISTAGG(cc.description, ',') WITHIN GROUP (ORDER BY cc.description)),
            '([^,]*)(,\1)+($|,)',
            '\1\3'
          ),
          ','
        )
        ELSE NULL
      END
    FROM cages c
    LEFT JOIN cage_comments cc ON cc.cage_id = c.id
    WHERE cc.event_date = cal.dt
  ) AS description
FROM calendar cal
ORDER BY cal.dt

In short - I'm just having difficulties adding the COUNT for some of the descriptions for that day. In the case above I would like to say 1 Bred for November 2, 2017 and 1 Bred, Grouped, 2 Weaned for November 14, 2017.

Body:
You could use:

SELECT
  cal.dt,
  (
      SELECT LISTAGG(CASE WHEN COUNT(*)=1 THEN ''
            ELSE CAST(COUNT(*) AS VARCHAR2(10)) || ' ' END  || description, ', ')
            WITHIN GROUP (ORDER BY description)
      FROM cages c
      LEFT JOIN cage_comments cc ON cc.cage_id = c.id
      WHERE cc.event_date = cal.dt
      GROUP BY cc.event_date, cc.description
  ) AS description
FROM calendar cal
ORDER BY cal.dt;

DBFiddle Demo


问:
OpenSSL Blocking Sockets SSL_read blocks
I am using blocking sockets in OpenSSL connection. SSL_read blocks sometimes for few seconds. In server - BIO_write is used to send data in variable buffer size. In client - first SSL_read to get buffer size succeeds but following SSL_read to get buffer data blocks for few seconds(this issue is simulated after 2 to 3mins) even though data sent successfully. I wait on poll() to invoke client read function. How to correct these problem in blocking sockets?

Server Code

```<code>void process_and_send() {
     // sending variable size buffer each time
     // sbuf - first 4 bytes contains sbuf size information
     send_data(sbuf, sbufSize);
}

void send_data(void *sbuf, int pending_len) {
        while(pending_len > 0) {
                result = BIO_write(bio, sbuf, pending_len);
                if(result == 0) {
                        attempts = 0;
                        LOG_D("%s", log_str(SSL_CONN_CLOSE));
                        SSL_FN_TRACE("connection closed\n");
                        break;
                }
                else if(result < 0) {
                        LOG_I("%s", log_str(SSL_WRITE_FAIL));
                        SSL_FN_TRACE("BIO_write fail\n");
                        if(errno == EINTR) {
                                continue;
                        }
                        if(errno == EAGAIN) {
                                attempts++;
                                continue;
                        }
                        if(errno == EWOULDBLOCK) {
                                attempts++;
                                continue;
                        }
                        break;
                }
                else {
                        BIO_flush(bio);
                        pending_len -= result;
                        sbuf += result;
                }
        }
 }
</code>```

Client Code

```<code>// wait on poll() and call receive_and_process
void receive_and_process() {
     int rbufSize = 0;
     // get the size of data to read
     receive_data((void *)&rbufSize, sizeof(Int));
     // this call blocks for few seconds
     receive_data(rbuf, rbufSize);
}

void receive_data(void *rbuf, int pending_len) {
    while(pending_len > 0) {
                    result = SSL_read(ssl, rbuf, pending_len);
            if(result == 0) {
                    LOG_D("%s", log_str(SSL_CONN_CLOSE));
                    SSL_FN_TRACE("connection closed\n");
                    return NULL;
            }
            else if(result < 0) {
                    if(errno == ETIMEDOUT) {
                            SSL_FN_ERROR("SSL read timeout:  \n");
                            continue;
                    }
                    if(errno == EINTR) {
                            continue;
                    }
                    if(errno == EAGAIN) {
                            continue;
                    }
                    if(errno == EWOULDBLOCK) {
                            continue;
                    }

                    SSL_FN_ERROR("SSL read fail error no:  %s\n",
                                    ERR_reason_error_string(ERR_get_error()));
                    LOG_I("%s", log_str(SSL_READ_FAIL));
                    return NULL;
            }
            pending_len -= result;
            rbuf += result;
            FN_ERROR("after read full data pending len %d\n", pending_len);
    }
}
</code>```

答:
Well, for starters, your client code can't compile as shown, because receive_data() has a void return type, so return NULL is a compiler error.  Also, you can't use the += operator on a void* pointer, that is also a compiler error.

Beside that, if SSL_read() returns < 0, you need to use SSL_get_error() instead of errno to find out why it failed.  Don't use errno unless SSL_get_error() returns SSL_ERROR_SYSCALL.  If SSL_get_error() returns SSL_ERROR_SSL, use ERR_get_error() and related functions instead.  And, make sure you are handling the SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE errors.

Also, when sending multi-byte integers, you have to deal with endian issues if you are sending across machine boundaries.  Best to use functions like htonl() and ntohl() to send integers over the connection in network byte order.

Try something more like this:

Server:

```<code>void process_and_send() {
     // sending variable size buffer each time
     // sbuf - DO NOT store the size information in the first 4 bytes!
     //        handle the size separately...
     int32_t size = htonl(sbufSize);
     if (send_data(&size, sizeof(size)))
         send_data(sbuf, sbufSize);
}

bool send_data(void *sbuf, int pending_len) {
    unsigned char *pbuf = (unsigned char *) sbuf;
    while (pending_len > 0) {
        result = BIO_write(bio, pbuf, pending_len);
        if (result > 0) {
            BIO_flush(bio);
            pbuf += result;
            pending_len -= result;
        }
        else if (result == 0) {
            attempts = 0;
            LOG_D("%s", log_str(SSL_CONN_CLOSE));
            SSL_FN_TRACE("connection closed\n");
            return false;
        }
        else if (!BIO_should_retry(bio)) {
            LOG_I("%s", log_str(SSL_WRITE_FAIL));
            SSL_FN_TRACE("BIO_write fail\n");
            return false;
        }
        else {
            ++attempts;
        }
    }
    return true;
}
</code>```

Client:

```<code>// wait on poll() and call receive_and_process
void receive_and_process() {
     int32_t rbufSize = 0;
     // get the size of data to read
     if (receive_data(&rbufSize, sizeof(rbufSize))) {
         rbufSize = ntohl(rbufSize);
         // TODO: make sure rbuf is at least rbufSize in size...
         receive_data(rbuf, rbufSize);
     }
}

bool receive_data(void *rbuf, int pending_len) {
    unsigned char *pbuf = (unsigned char *) rbuf;
    while (pending_len > 0) {
        result = SSL_read(ssl, pbuf, pending_len);
        if (result > 0) {
            pbuf += result;
            pending_len -= result;
            FN_ERROR("after read full data pending len %d\n", pending_len);
        }
        else {
            result = SSL_get_error();
            if (result == SSL_ERROR_ZERO_RETURN) {
                LOG_D("%s", log_str(SSL_CONN_CLOSE));
                SSL_FN_TRACE("connection closed\n");
            }
            else {
                if (result == SSL_ERROR_WANT_READ) {
                    // TODO: use select() to wait for the socket to be readable before trying again...
                    continue;
                }
                else if (result == SSL_ERROR_WANT_WRITE) {
                    // TODO: use select() to wait for the socket to be writable before trying again...
                    continue;
                }
                else if (result == SSL_ERROR_SYSCALL) {
                    if ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK)) {
                        continue;
                    }

                    if (errno == ETIMEDOUT) {
                        SSL_FN_ERROR("SSL read timeout:  \n");
                        continue;
                    }

                    SSL_FN_ERROR("SSL read fail error no:  %d\n", errno);
                }
                else if (result == SSL_ERROR_SSL) {
                    SSL_FN_ERROR("SSL read fail error no:  %s\n",
                        ERR_reason_error_string(ERR_get_error()));
                }
                else {
                    SSL_FN_ERROR("SSL read fail error no:  %d\n", result);
                }
                LOG_I("%s", log_str(SSL_READ_FAIL));
            }
            return false;
        }
    }
    return true;
}
</code>```

Body:
I am using blocking sockets in OpenSSL connection. SSL_read blocks sometimes for few seconds. In server - BIO_write is used to send data in variable buffer size. In client - first SSL_read to get buffer size succeeds but following SSL_read to get buffer data blocks for few seconds(this issue is simulated after 2 to 3mins) even though data sent successfully. I wait on poll() to invoke client read function. How to correct these problem in blocking sockets?

Server Code

void process_and_send() {
     // sending variable size buffer each time
     // sbuf - first 4 bytes contains sbuf size information
     send_data(sbuf, sbufSize);
}

void send_data(void *sbuf, int pending_len) {
        while(pending_len > 0) {
                result = BIO_write(bio, sbuf, pending_len);
                if(result == 0) {
                        attempts = 0;
                        LOG_D("%s", log_str(SSL_CONN_CLOSE));
                        SSL_FN_TRACE("connection closed\n");
                        break;
                }
                else if(result < 0) {
                        LOG_I("%s", log_str(SSL_WRITE_FAIL));
                        SSL_FN_TRACE("BIO_write fail\n");
                        if(errno == EINTR) {
                                continue;
                        }
                        if(errno == EAGAIN) {
                                attempts++;
                                continue;
                        }
                        if(errno == EWOULDBLOCK) {
                                attempts++;
                                continue;
                        }
                        break;
                }
                else {
                        BIO_flush(bio);
                        pending_len -= result;
                        sbuf += result;
                }
        }
 }

Client Code

// wait on poll() and call receive_and_process
void receive_and_process() {
     int rbufSize = 0;
     // get the size of data to read
     receive_data((void *)&rbufSize, sizeof(Int));
     // this call blocks for few seconds
     receive_data(rbuf, rbufSize);
}

void receive_data(void *rbuf, int pending_len) {
    while(pending_len > 0) {
                    result = SSL_read(ssl, rbuf, pending_len);
            if(result == 0) {
                    LOG_D("%s", log_str(SSL_CONN_CLOSE));
                    SSL_FN_TRACE("connection closed\n");
                    return NULL;
            }
            else if(result < 0) {
                    if(errno == ETIMEDOUT) {
                            SSL_FN_ERROR("SSL read timeout:  \n");
                            continue;
                    }
                    if(errno == EINTR) {
                            continue;
                    }
                    if(errno == EAGAIN) {
                            continue;
                    }
                    if(errno == EWOULDBLOCK) {
                            continue;
                    }

                    SSL_FN_ERROR("SSL read fail error no:  %s\n",
                                    ERR_reason_error_string(ERR_get_error()));
                    LOG_I("%s", log_str(SSL_READ_FAIL));
                    return NULL;
            }
            pending_len -= result;
            rbuf += result;
            FN_ERROR("after read full data pending len %d\n", pending_len);
    }
}

Body:
Well, for starters, your client code can't compile as shown, because receive_data() has a void return type, so return NULL is a compiler error.  Also, you can't use the += operator on a void* pointer, that is also a compiler error.

Beside that, if SSL_read() returns < 0, you need to use SSL_get_error() instead of errno to find out why it failed.  Don't use errno unless SSL_get_error() returns SSL_ERROR_SYSCALL.  If SSL_get_error() returns SSL_ERROR_SSL, use ERR_get_error() and related functions instead.  And, make sure you are handling the SSL_ERROR_WANT_READ and SSL_ERROR_WANT_WRITE errors.

Also, when sending multi-byte integers, you have to deal with endian issues if you are sending across machine boundaries.  Best to use functions like htonl() and ntohl() to send integers over the connection in network byte order.

Try something more like this:

Server:

void process_and_send() {
     // sending variable size buffer each time
     // sbuf - DO NOT store the size information in the first 4 bytes!
     //        handle the size separately...
     int32_t size = htonl(sbufSize);
     if (send_data(&size, sizeof(size)))
         send_data(sbuf, sbufSize);
}

bool send_data(void *sbuf, int pending_len) {
    unsigned char *pbuf = (unsigned char *) sbuf;
    while (pending_len > 0) {
        result = BIO_write(bio, pbuf, pending_len);
        if (result > 0) {
            BIO_flush(bio);
            pbuf += result;
            pending_len -= result;
        }
        else if (result == 0) {
            attempts = 0;
            LOG_D("%s", log_str(SSL_CONN_CLOSE));
            SSL_FN_TRACE("connection closed\n");
            return false;
        }
        else if (!BIO_should_retry(bio)) {
            LOG_I("%s", log_str(SSL_WRITE_FAIL));
            SSL_FN_TRACE("BIO_write fail\n");
            return false;
        }
        else {
            ++attempts;
        }
    }
    return true;
}

Client:

// wait on poll() and call receive_and_process
void receive_and_process() {
     int32_t rbufSize = 0;
     // get the size of data to read
     if (receive_data(&rbufSize, sizeof(rbufSize))) {
         rbufSize = ntohl(rbufSize);
         // TODO: make sure rbuf is at least rbufSize in size...
         receive_data(rbuf, rbufSize);
     }
}

bool receive_data(void *rbuf, int pending_len) {
    unsigned char *pbuf = (unsigned char *) rbuf;
    while (pending_len > 0) {
        result = SSL_read(ssl, pbuf, pending_len);
        if (result > 0) {
            pbuf += result;
            pending_len -= result;
            FN_ERROR("after read full data pending len %d\n", pending_len);
        }
        else {
            result = SSL_get_error();
            if (result == SSL_ERROR_ZERO_RETURN) {
                LOG_D("%s", log_str(SSL_CONN_CLOSE));
                SSL_FN_TRACE("connection closed\n");
            }
            else {
                if (result == SSL_ERROR_WANT_READ) {
                    // TODO: use select() to wait for the socket to be readable before trying again...
                    continue;
                }
                else if (result == SSL_ERROR_WANT_WRITE) {
                    // TODO: use select() to wait for the socket to be writable before trying again...
                    continue;
                }
                else if (result == SSL_ERROR_SYSCALL) {
                    if ((errno == EINTR) || (errno == EAGAIN) || (errno == EWOULDBLOCK)) {
                        continue;
                    }

                    if (errno == ETIMEDOUT) {
                        SSL_FN_ERROR("SSL read timeout:  \n");
                        continue;
                    }

                    SSL_FN_ERROR("SSL read fail error no:  %d\n", errno);
                }
                else if (result == SSL_ERROR_SSL) {
                    SSL_FN_ERROR("SSL read fail error no:  %s\n",
                        ERR_reason_error_string(ERR_get_error()));
                }
                else {
                    SSL_FN_ERROR("SSL read fail error no:  %d\n", result);
                }
                LOG_I("%s", log_str(SSL_READ_FAIL));
            }
            return false;
        }
    }
    return true;
}


问:
Getting the values of textboxes in Javascript
I have this html code:

```<code><table border="" cellpadding="3" cellspacing="0" id="mytable">

<tbody><tr><td>Song:</td> <td><input type="text" name="song" maxlength="64" size="48" /> </td></tr>
<tr><td>Artist:</td> <td><input type="text" name="artist" maxlength="16" size="48" /> </td></tr>
</code>```

How do I get the values of "song" and "artist"? I have tried:

```<code>var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);
</code>```

but I keep getting "undefined" even when there is text inside the textbox

答:
The tagName that is relevant here is "input", not td. That will get you what you're looking for.

It's almost a cliche on StackOverflow, but I suggest you take a look at JQuery. JQuery allows you to treat your html as a database and query it to get this kind of stuff. If your markup was like this:

```<code><input type="text" id="song" maxlength="64" size="48" />
</code>```

You could get the value like this:

```<code>$("#id").value();
</code>```

If you wanted to get the value of the maxlength attribute on it, you could do this:

```<code>$("#id").attr("maxlength");
</code>```

Much more fun than digging through element arrays.

Body:
I have this html code:

Song:	 <input type="text" name="song" maxlength="64" size="48" />

Artist:	 <input type="text" name="artist" maxlength="16" size="48" />

How do I get the values of "song" and "artist"? I have tried:

var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);

but I keep getting "undefined" even when there is text inside the textbox

Body:
The tagName that is relevant here is "input", not td. That will get you what you're looking for.

It's almost a cliche on StackOverflow, but I suggest you take a look at JQuery. JQuery allows you to treat your html as a database and query it to get this kind of stuff. If your markup was like this:

<input type="text" id="song" maxlength="64" size="48" />

You could get the value like this:

$("#id").value();

If you wanted to get the value of the maxlength attribute on it, you could do this:

$("#id").attr("maxlength");

Much more fun than digging through element arrays.


问:
Internal server error when set cookie in Django
In URL can additional parameters for example like utm_campaign

In view I get this parameters:

```<code>utm_campaign = request.GET.get('utm_campaign',None)
</code>```

But when i wanna set this information in cookie I get Internal Server Error without traceback or another information

I was trying several solution:

```<code>response.set_cookie('utm_campaign',utm_campaign )
response.set_cookie('utm_campaign',utm_campaign .encode('utf-8'))
response.set_cookie('utm_campaign',utm_campaign .encode())
response.set_cookie('utm_campaign',request.GET.get('utm_campaign '))
</code>```

What is the problem?

The problem is that if I write English text or numbers - everything works.
If I try write cyrillic text - there is an error without details.

Python3

CentOs7 (default "utf-8")

Django 1.11 (default "utf-8")

答:
Solution

```<code>from urllib import parse
response.set_cookie('utm_campaign', parse.quote(utm_campaign))
</code>```

Body:
In URL can additional parameters for example like utm_campaign

In view I get this parameters:

utm_campaign = request.GET.get('utm_campaign',None)

But when i wanna set this information in cookie I get Internal Server Error without traceback or another information

I was trying several solution:

response.set_cookie('utm_campaign',utm_campaign )
response.set_cookie('utm_campaign',utm_campaign .encode('utf-8'))
response.set_cookie('utm_campaign',utm_campaign .encode())
response.set_cookie('utm_campaign',request.GET.get('utm_campaign '))

What is the problem?

The problem is that if I write English text or numbers - everything works.
If I try write cyrillic text - there is an error without details.

Python3

CentOs7 (default "utf-8")

Django 1.11 (default "utf-8")

Body:
Solution

from urllib import parse
response.set_cookie('utm_campaign', parse.quote(utm_campaign))


问:
Best way to handle dynamic css in a rails app
I'm researching a problem for handling dynamic css in a rails app.  Within the app, individual users and/or groups of users can have customized look and feel that is accomplished via CSS.  There will not be any fixed number of "look and feels" or css files, the number will grow as the number of users and groups grows and the look and feel is defined by the users via the  application's admin interface.  Throughout the course of a typical day thousands (it not tens of thousands) of different variations of the css will be served up.  The app will store the pre-built css in mongodb, so there it will not have to pay the price of constructing the css for every request, the question is more about how is the best way to serve up this dynamic css content.  I've seen other questions like [this one][1] that speak to using erb or sass, but some of these answers are dated by several years so I wanted to make sure there wasn't a better answer with Rails 3.</p>

答:
You can treat your CSS files as resources, store them on the database, and serve them with page caching, so that you only need to hit the db once when the CSS is modified. All later requests will be served directly by the web server from the cache, without ever touching your app or db.

```<code># stylesheet.rb
class Stylesheet < ActiveRecord::Base
  validates_presence_of :contents
end

# stylesheets_controller.rb
class StylesheetsController < ApplicationController
  caches_page :show # magic happens here

  def show
    @stylesheet = Stylesheet.find(params[:id])
    respond_to do |format|
      format.html # regular ERB template
      format.css { render :text => @stylesheet.contents, :content_type => "text/css" }
    end
  end
  # the rest is your typical RESTful controller,
  # just remember to expire the cache when the stylesheet changes
end

# routes.rb
resources :stylesheets

# layouts/application.html.erb
…
<link href="<%= stylesheet_path(@current_user.stylesheet) %>" rel="stylesheet" type="text/css" />
</code>```

Body:
You can treat your CSS files as resources, store them on the database, and serve them with page caching, so that you only need to hit the db once when the CSS is modified. All later requests will be served directly by the web server from the cache, without ever touching your app or db.

# stylesheet.rb
class Stylesheet < ActiveRecord::Base
  validates_presence_of :contents
end

# stylesheets_controller.rb
class StylesheetsController < ApplicationController
  caches_page :show # magic happens here

  def show
    @stylesheet = Stylesheet.find(params[:id])
    respond_to do |format|
      format.html # regular ERB template
      format.css { render :text => @stylesheet.contents, :content_type => "text/css" }
    end
  end
  # the rest is your typical RESTful controller,
  # just remember to expire the cache when the stylesheet changes
end

# routes.rb
resources :stylesheets

# layouts/application.html.erb
…
<link href="<%= stylesheet_path(@current_user.stylesheet) %>" rel="stylesheet" type="text/css" />


问:
ServiceNow Client Script asynchronous query to stop submission onSubmit in new Service Portal
I have a Client Script that performs a GlideRecord query to check if a record already exists with the same name.

If a matching record is found, we need to STOP the form from being submitted.

We have this working fine on the CMS portal.

However, the new Service Portal does not support synchronous GlideRecord query.

So I can't use gr.query() I need to use a callback such as gr.query(callback).

The issue is that since the callback is asynchronous, it does not actually stop the form from being submitted!

g_form.submitted = false; DOES NOT work. That's because the script proceeds along to submit the form before the callback has a chance to retrieve the value.

How can we stop the submission of a form based on the value returned by an asynchronous callback? We can't use GlideAjax for the same reason, getXMLWait() is no longer supported.

Here is the client script that I am trying to get working in the new Service Portal.

```<code>function onSubmit() {

    var group_name = g_form.getValue('u_group_name');
    g_form.hideAllFieldMsgs('error');

    /*Check if group already exists*/
    var rec = new GlideRecord('u_auth_group');
    rec.addQuery('u_group_name', u_group_name);
    rec.query(getAccountResponse);
    }

function getAccountResponse(rec) {
    while (rec.next()) {
        g_form.showFieldMsg('u_group_name', " Group Name exists already, please select another group name",'error');
        g_form.submitted = false; //DOES NOT STOP THE FORM FROM BEING SUBMITTED
        return false;
    }
}
</code>```

Here is the existing script that works in the CMS portal.

```<code>function onSubmit() {

    var group_name = g_form.getValue('u_group_name');
    g_form.hideAllFieldMsgs('error');

    /*Check if group already exists*/
    var rec = new GlideRecord('u_auth_group');
    rec.addQuery('u_group_name', u_group_name);
    rec.query(getAccountResponse);
    while (rec.next()) {
        g_form.showFieldMsg('u_group_name', " Group Name exists already, please select another group name",'error');
        g_form.submitted = false; //Stops the form from being submitted if a result is returned
        return false;
    }
}
</code>```

答:
I was able to solve this by using an asyc callback with the glide record query.</p>

```<code>function onSubmit() {
//If ServicePortal
if (!window) {
    if (g_scratchpad.isFormValid) {
        return true;
    }

    g_form.hideAllFieldMsgs("error");

    var actionName = g_form.getActionName();

    //Group Name contain letters numbers and dashes only
    var group_name = g_form.getValue("u_group_name");

    //Group name regular expression
    var regGrpName = /^([A-Za-z0-9\-]+)$/;

    //Check name against regular expression
    validGroupName = regGrpName.test(group_name);

    //Check if google group already exists
    var gg = new GlideRecord("u_system_group");
    gg.addQuery("u_group_name", group_name);

    //Callback function to control stop submit asynchronously
    gg.query(function() {
        while (gg.next()) {
            g_form.showFieldMsg("u_group_name","Group Name " + gg.u_group_name + " already exists! Please enter a different group name.", "error", true);
            return false;
        }
        g_scratchpad.isFormValid = true;
        g_form.submit(actionName);
    });

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

Body:
I have a Client Script that performs a GlideRecord query to check if a record already exists with the same name.

If a matching record is found, we need to STOP the form from being submitted.

We have this working fine on the CMS portal.

However, the new Service Portal does not support synchronous GlideRecord query.

So I can't use gr.query() I need to use a callback such as gr.query(callback).

The issue is that since the callback is asynchronous, it does not actually stop the form from being submitted!

g_form.submitted = false; DOES NOT work. That's because the script proceeds along to submit the form before the callback has a chance to retrieve the value.

How can we stop the submission of a form based on the value returned by an asynchronous callback? We can't use GlideAjax for the same reason, getXMLWait() is no longer supported.

Here is the client script that I am trying to get working in the new Service Portal.

function onSubmit() {

    var group_name = g_form.getValue('u_group_name');
    g_form.hideAllFieldMsgs('error');

    /*Check if group already exists*/
    var rec = new GlideRecord('u_auth_group');
    rec.addQuery('u_group_name', u_group_name);
    rec.query(getAccountResponse);
    }

function getAccountResponse(rec) {
    while (rec.next()) {
        g_form.showFieldMsg('u_group_name', " Group Name exists already, please select another group name",'error');
        g_form.submitted = false; //DOES NOT STOP THE FORM FROM BEING SUBMITTED
        return false;
    }
}

Here is the existing script that works in the CMS portal.

function onSubmit() {

    var group_name = g_form.getValue('u_group_name');
    g_form.hideAllFieldMsgs('error');

    /*Check if group already exists*/
    var rec = new GlideRecord('u_auth_group');
    rec.addQuery('u_group_name', u_group_name);
    rec.query(getAccountResponse);
    while (rec.next()) {
        g_form.showFieldMsg('u_group_name', " Group Name exists already, please select another group name",'error');
        g_form.submitted = false; //Stops the form from being submitted if a result is returned
        return false;
    }
}

Body:
I was able to solve this by using an asyc callback with the glide record query.

function onSubmit() {
//If ServicePortal
if (!window) {
    if (g_scratchpad.isFormValid) {
        return true;
    }

    g_form.hideAllFieldMsgs("error");

    var actionName = g_form.getActionName();

    //Group Name contain letters numbers and dashes only
    var group_name = g_form.getValue("u_group_name");

    //Group name regular expression
    var regGrpName = /^([A-Za-z0-9\-]+)$/;

    //Check name against regular expression
    validGroupName = regGrpName.test(group_name);

    //Check if google group already exists
    var gg = new GlideRecord("u_system_group");
    gg.addQuery("u_group_name", group_name);

    //Callback function to control stop submit asynchronously
    gg.query(function() {
        while (gg.next()) {
            g_form.showFieldMsg("u_group_name","Group Name " + gg.u_group_name + " already exists! Please enter a different group name.", "error", true);
            return false;
        }
        g_scratchpad.isFormValid = true;
        g_form.submit(actionName);
    });

    return false;
  }
}


答:
groups: urls.py

```<code>urlpatterns = [
    url(r'^add-groups/$', view_1),
    url(r'^fetch-groups/group_id(?P<num>[0-9]+)/$', view_2),
]
</code>```

users: urls.py

```<code>urlpatterns = [
    url(r'^add-users/$', group_add_view),
    url(r'^fetch-users/user_id(?P<num>[0-9]+)/$', group_fetch_view),
]
</code>```

example: url.py (main url)

```<code>from django.conf.urls import include, url
from groups.urls import urlpatterns as group_patterns
from users.urls import urlpatterns as user_patterns
    urlpatterns = [
        url(r'^groups/', include(group_patterns)),
        url(r'^users/', include(user_patterns)),
    ]
</code>```

/groups/add-groups/ will go to group_add_view

Title: Possibility of connecting two django apps within a django project

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

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

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

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

THis is what I am thinking of doing

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

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

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

Body:
groups: urls.py

urlpatterns = [
    url(r'^add-groups/$', view_1),
    url(r'^fetch-groups/group_id(?P<num>[0-9]+)/$', view_2),
]

users: urls.py

urlpatterns = [
    url(r'^add-users/$', group_add_view),
    url(r'^fetch-users/user_id(?P<num>[0-9]+)/$', group_fetch_view),
]

example: url.py (main url)

from django.conf.urls import include, url
from groups.urls import urlpatterns as group_patterns
from users.urls import urlpatterns as user_patterns
    urlpatterns = [
        url(r'^groups/', include(group_patterns)),
        url(r'^users/', include(user_patterns)),
    ]

/groups/add-groups/ will go to group_add_view


问:
Difference between X-Cache and X-Cache-Remote Akamai Headers
I searched a lot but couldn't find a single page on the internet which explained the difference between X-Cache and X-Cache-Remote Akamai header.
Every time I receive two different values for these headers which indicates that they are not the same. Any information regarding the different between the two will be of great help.

答:
There is a single page that explains all of the various x-akamai-* headers (if you're logged in to the Akamai Customer Community) that you can use with Akamai.

The possible values of those two specific headers (x-akamai-cache and x-akamai-cache-remote) are available in a separate Customer Community document.

In short, the x-akamai-cache header tells you how the initially responding Edge server handled the object. The x-akamai-cache-remote header tells you how the Parent Tier handled the object.

In many circumstances, your configuration may have something called "Tiered Distribution" (or "Cache Hierarchy") enabled which uses a multi-layered caching system. There's a good video created by Akamai employees that talks about Tiered Distribution and other caching behaviors available to you through the Akamai platform. There's also a little more on this multi-tiered caching system on Akamai's Developer site.


问:
Python loop through text and set numpy array index
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

```<code>temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]
</code>```

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?

答: So, the problem here was that the dual brackets in rA[[rowIndex, colIndex]] caused every cell in the row to be set. This should be rA[rowIndex, colIndex]</p>

Body:
Given a block of text with matrix rows and columns separated by commas and semicolons, I want to parse the text and set the indices of numpy arrays. Here is the code with the variable 'matrixText' representing the base text.

I first create the matrices and then split the text by semicolons and then by commas. I loop through the split text and set each index. However with the text ...

1,2,3;4,5,6;7,8,9

I get the result

7,7,7;8,8,8;9,9,9

temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]

I thought that by setting each index, I would avoid any copy by reference issues.

To provide more info, in the first iteration, the 0,0 index is set to 1 and the output of that is then 1,1,1;0,0,0;0,0,0 which I can't figure out since setting one index in the numpy array sets three.

In the second iteration, the index 0-1 is set to 2 and the result is then 2,2,2;2,2,2;0,0,0

The third iteration sets 0-2 to 3 but the result is 3,3,3;2,2,2;3,3,3

Any suggestions?


问:
Special characters replace using regex in python
Just for learning I am trying to replace all the special characters present in the keyboard to replace with underscore'_'

```<code>List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./
</code>```

string I created:

```<code>table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""

import re

table1= re.sub(r'!~@#$%^&*()-+={}[]:;<.>?/\'"', '_', table)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib64/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression
</code>```

Unable to do so I am getting the above error.

How can I replace the special characters in the string using regex

答:
You could use re.escape to escape all the special regex characters in the string, and then enclose the escaped string into [...] so it matches any of them.

```<code>>>> re.sub("[%s]" % re.escape('!~@#$%^&*()-+={}[]:;<.>?/\''), '_', table)
'123____________|___"_______\\__,__'
</code>```

However, as you are not really using that regex as a regex, you might instead just check whether each character is in that string:

```<code>>>>''.join("_" if c in '!~@#$%^&*()-+={}[]:;<.>?/\'' else c for c in table)
'123____________|___"_______\\__,__'
</code>```

Or to make the lookup a bit faster, create a set from the chars in that string first:

```<code>>>> bad_chars = set('!~@#$%^&*()-+={}[]:;<.>?/\'')
>>> ''.join("_" if c in bad_chars else c for c in table)
</code>```

Body:
Just for learning I am trying to replace all the special characters present in the keyboard to replace with underscore'_'

List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./

string I created:

table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""

import re

table1= re.sub(r'!~@#$%^&*()-+={}[]:;<.>?/\'"', '_', table)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib64/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression

Unable to do so I am getting the above error.

How can I replace the special characters in the string using regex

Body:
You could use re.escape to escape all the special regex characters in the string, and then enclose the escaped string into [...] so it matches any of them.

>>> re.sub("[%s]" % re.escape('!~@#$%^&*()-+={}[]:;<.>?/\''), '_', table)
'123____________|___"_______\\__,__'

However, as you are not really using that regex as a regex, you might instead just check whether each character is in that string:

>>>''.join("_" if c in '!~@#$%^&*()-+={}[]:;<.>?/\'' else c for c in table)
'123____________|___"_______\\__,__'

Or to make the lookup a bit faster, create a set from the chars in that string first:

>>> bad_chars = set('!~@#$%^&*()-+={}[]:;<.>?/\'')
>>> ''.join("_" if c in bad_chars else c for c in table)


问:
When should you use a class vs a struct in C++?
In what scenarios is it better to use a struct vs a class in C++?

答:
An advantage of struct over class is that it save one line of code, if adhering to "first public members, then private". In this light, I find the keyword class useless.

Here is another reason for using only struct and never class. Some code style guidelines for C++ suggest using small letters for function macros, the rationale being that when the macro is converted to an inline function, the name shouldn't need to be changed. Same here. You have your nice C-style struct and one day, you find out you need to add a constructor, or some convenience method. Do you change it to a class? Everywhere?

Distinguishing between structs and classes is just too much hassle getting into the way of doing what we should be doing - programming. Like so many of C++'s problems it arises out of the strong desire for backwards compatibility.

OwnerDisplayName: ZeroSignal

LastEditorDisplayName: Don Kirkby

ContentLicense: CC BY-SA 4.0


问:
ng-repeat with ng-selected
I am trying to figure out how to generate list of option elements using ng-repeat, but one of them to be marked as the selected option on load.

After googling, what I found is this base, which I modified by adding the selected property to the data objects
https://plnkr.co/edit/7g4MeAQnG4PzpnrebBGc?p=preview
However, it seems that ng-selected="option.selected == true" has no effect :(

Why? I also have the more complex example here: http://jsfiddle.net/ej5fx3kr/14/ which works, although I am not sure what is the difference, or what is the model here used for (note: changing the model name from "program" to anything, it still works... so not sure what is the purpose).

Bonus points: How do I debug code in AngularJS in directives? Like experiment in debug mode line by line to actually see what are the variable values in that particular scope, what is available to use, etc...

My ultimate goal in this question, is to load list of values via ajax on page load in the controller, IF there is a routeParam in the URL, find it in the list of loaded values, and add selected attribute, then set selected=true in the generated HTML on page load, otherwise not pre-select anything in the populated select box on the page load, so this is why its important for me to understand this on the simplest example before trying to plug this in.

Thanks!

答:
Using ng-selected = true  inside ng-repeat would solve this .
However be sure of the data that you call in ng-repeat.For additional debugging and experiment line by line use chrome debugger .go to source tab and set break points on the js lines that you need to debug.This will let you debug line by line by pause and play . Hope this helps.Thanks

Title: ng-repeat with ng-selected


问:
Failed to load ad (Error 1)
Have been searching for hours on google, but still without success.
I always get the Error Message and the adBanner doesnt load:

```<code>There was a problem getting an ad response. ErrorCode: 1
Failed to load ad: 1
</code>```

build.gradle

```<code>compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.google.android.gms:play-services-ads:9.4.0'
</code>```

Android Manifest

```<code><activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@android:style/Theme.Translucent"
        />
</code>```

layout

```<code><com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ads:adSize="BANNER"
    android:layout_marginTop="20dip"
    ads:adUnitId="pub-*****************"
    android:layout_below="@+id/middle"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
</code>```

activity (imports)

```<code>import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
</code>```

activity

```<code>AdView adView = (AdView)findViewById(R.id.adView);

    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
</code>```

permissions are also added

ty for your help in advance

答:
Error 1 means the ID is wrong.

Admob gives you a number like this and is the general ID, with ~ :

```<code>ca-app-pub-9611919736642270~3440171884
</code>```

And the ads id with / is to the request;

```<code>ca-app-pub-9611919736642270/3440171834
</code>```

Title: Failed to load ad (Error 1)

Body:
Have been searching for hours on google, but still without success.
I always get the Error Message and the adBanner doesnt load:

There was a problem getting an ad response. ErrorCode: 1
Failed to load ad: 1

build.gradle

compile 'com.android.support:appcompat-v7:24.0.0'
compile 'com.google.android.gms:play-services-ads:9.4.0'

Android Manifest

<activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
        android:theme="@android:style/Theme.Translucent"
        />

layout

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    ads:adSize="BANNER"
    android:layout_marginTop="20dip"
    ads:adUnitId="pub-*****************"
    android:layout_below="@+id/middle"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

activity (imports)

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

activity

AdView adView = (AdView)findViewById(R.id.adView);

    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);

permissions are also added

ty for your help in advance

Body:
Error 1 means the ID is wrong.

Admob gives you a number like this and is the general ID, with ~ :

ca-app-pub-9611919736642270~3440171884

And the ads id with / is to the request;

ca-app-pub-9611919736642270/3440171834


问:
Tensorflow, proper way to define a loss function with element-wise operations
I have a batch of n training examples. Each training example yields me with a vector a (of length k) and a vector c (also of length k).

In tensorflow my output is p.

I would like to define the following loss function:

\sum_(i = 0)^(i=n) c_i ( (a_i - p)^2 )

I have read about various tf operations available to me but cannot seem to find out a proper implementation for this. I tried to use tf.tile to replicate p into a k-length tensor and do a tf.subtract, but this seems excessive.

Any help would be much appreciated.

答:
What is the shape of p? TensorFlow natively supports subtraction of tensors with different shapes:

```<code>import tensorflow as tf

a = tf.Variable([[1, 2, 3], [2, 3, 4], [3, 4, 5]])

x_1 = a - tf.Variable([1, 1, 1])
x_2 = a - tf.Variable([1])
x_3 = a - tf.Variable(1)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(x_1))  # [[0, 1, 2], [1, 2, 3] [2, 3, 4]]
    print(sess.run(x_2))  # [[0, 1, 2], [1, 2, 3] [2, 3, 4]]
    print(sess.run(x_3))  # [[0, 1, 2], [1, 2, 3] [2, 3, 4]]
</code>```

You can define your loss function as follows:

```<code>a = tf.Variable([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
c = tf.Variable([[4, 5, 6], [5, 6, 7], [6, 7, 8]])

p = tf.Variable(1)

loss_1 = tf.reduce_mean(tf.reduce_sum(tf.multiply(c, tf.pow(tf.subtract(a, p), 2)), axis=1))  # 112
loss_2 = tf.reduce_mean(tf.reduce_sum(c * (a-p)**2, axis=1))  # 112
</code>```

Body:
What is the shape of p? TensorFlow natively supports subtraction of tensors with different shapes:

import tensorflow as tf

a = tf.Variable([[1, 2, 3], [2, 3, 4], [3, 4, 5]])

x_1 = a - tf.Variable([1, 1, 1])
x_2 = a - tf.Variable([1])
x_3 = a - tf.Variable(1)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(x_1))  # [[0, 1, 2], [1, 2, 3] [2, 3, 4]]
    print(sess.run(x_2))  # [[0, 1, 2], [1, 2, 3] [2, 3, 4]]
    print(sess.run(x_3))  # [[0, 1, 2], [1, 2, 3] [2, 3, 4]]

You can define your loss function as follows:

a = tf.Variable([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
c = tf.Variable([[4, 5, 6], [5, 6, 7], [6, 7, 8]])

p = tf.Variable(1)

loss_1 = tf.reduce_mean(tf.reduce_sum(tf.multiply(c, tf.pow(tf.subtract(a, p), 2)), axis=1))  # 112
loss_2 = tf.reduce_mean(tf.reduce_sum(c * (a-p)**2, axis=1))  # 112


问:
On Raspbian run multiple python Versions simultaniously
I have some old programs from back in the times when python 3.1 came out.
In the program I often used the Callable() to pass a function and it's parameters like this to my TKinter application:

```<code>tvf.mi(datei_bu, text=datei_opt, command=Callable(exec_datei_opts, datei_opt))
</code>```

Now I wanted to use my programs again but the callable- Object was gone. In the web I found that this functionality was removed in python 3.2, and none of the alternatives worked for me.

Finally I decided to reinstall python 3.1. However, I have no idea if it is possible to have multiple python 3 versions installed at the same time or how to 'create' a shell command for this version when I want to use this special version.

My questions are:

Is there a replacement for the Callable- Object that was removed?

How can I use multiple python versions at the same time?

How can I create a matching shell command?

答:
From the terminal, run with:

```<code>python3.1 your_program.py
</code>```

Body:
I have some old programs from back in the times when python 3.1 came out.
In the program I often used the Callable() to pass a function and it's parameters like this to my TKinter application:

tvf.mi(datei_bu, text=datei_opt, command=Callable(exec_datei_opts, datei_opt))

Now I wanted to use my programs again but the callable- Object was gone. In the web I found that this functionality was removed in python 3.2, and none of the alternatives worked for me.

Finally I decided to reinstall python 3.1. However, I have no idea if it is possible to have multiple python 3 versions installed at the same time or how to 'create' a shell command for this version when I want to use this special version.

My questions are:

Is there a replacement for the Callable- Object that was removed?

How can I use multiple python versions at the same time?

How can I create a matching shell command?

Body:
From the terminal, run with:

python3.1 your_program.py


问:
mySQL Returning the top 5 of each category
I want to be able to return 5 menuitem per menu. I've tried this several script but had no luck. here are the tables

```<code>menus
-------
menuid int()
profileName varchar(35)

menuitems
-----------
itemid int()
name varchar(40)
</code>```

Here what I have now. I'm getting the error message with the script below. Error: Subquery returns more then 1 row.

```<code>SELECT m.profilename, name
FROM menus m
WHERE (SELECT name
        from menuitems s
        where m.menuid = s.menuid
        limit 5)
</code>```

Any suggestion is great appreciated.

答:
You have to use side effecting variables for this</p>

```<code>SELECT profilename, name
FROM
(
    SELECT m.profilename, s.name,
        @r:=case when @g=m.profilename then @r+1 else 1 end r,
        @g:=m.profilename
    FROM (select @g:=null,@r:=0) n
    cross join menus m
    left join menuitems s on m.menuid = s.menuid
) X
WHERE r <= 5
</code>```

Body:
I want to be able to return 5 menuitem per menu. I've tried this several script but had no luck. here are the tables

menus
-------
menuid int()
profileName varchar(35)

menuitems
-----------
itemid int()
name varchar(40)

Here what I have now. I'm getting the error message with the script below. Error: Subquery returns more then 1 row.

SELECT m.profilename, name
FROM menus m
WHERE (SELECT name
        from menuitems s
        where m.menuid = s.menuid
        limit 5)

Any suggestion is great appreciated.

Body:
You have to use side effecting variables for this

SELECT profilename, name
FROM
(
    SELECT m.profilename, s.name,
        @r:=case when @g=m.profilename then @r+1 else 1 end r,
        @g:=m.profilename
    FROM (select @g:=null,@r:=0) n
    cross join menus m
    left join menuitems s on m.menuid = s.menuid
) X
WHERE r <= 5


问:
SAS protect Excel worksheet with DDE
I want to manipulate an existing Excel sheet with DDE using SAS:

I have the following code (be careful! I use z for r(ows) and s for c(columns) because of German language settings in Excel):

```<code>option noxwait noxsync;
x call "C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE";

%let delay=5;

data _null_;
rc=sleep(&delay);
run;

filename sas2xl dde 'excel|system';

data _null_;
rc=sleep(&delay);
run;

%let mapwkbk=H:\odstest.xlsx;

data _null_;
file sas2xl;
rc=sleep(&delay);
put '[open("' "&mapwkbk" '")]';
run;

filename random dde 'excel|Daten!z2s1:z100s3';
data _null_;
    set sashelp.class;
    file random;
    put name sex age;
run;

data _null_;
file sas2xl;
/*rc=sleep(&delay);*/
put '[workbook.select("Pivot")]';
put '[select("Z2S1")]';
put "[pivot.refresh()]";

put '[workbook.select("Daten")]';
put '[select("z1S2:z1s5")]';
put '[filter]';
put '[select("z1S10")]';
put '[filter]';

put '[column.width(0,"s1",false,1)]';
put '[column.width(0,"s6:s9",false,1)]';

put '[ActiveSheet.Protect("***")]';

put '[workbook.delete("Dim")]';

/*put "[save()]";*/
/*put "[quit()]";*/
run;
</code>```

Now I would like to password protect the sheet Daten and set option use autofilter active. Any ideas how to reach this?

答:
My recommendation here is to write a macro to do what you're trying to do (both questions here really), and then call that macro using DDE if you must use DDE.  That's far easier to do than to use DDE to do every little thing, and far easier to maintain (plus more portable when you eventually move away from DDE).

If you do that, then your macro code doesn't have all the extra SAS language bits around it, and can be more easily read/maintained (even by a VBA developer rather than a SAS developer), and SAS just calls the macro which is easy to do.

DDE is an old technology not well supported anymore, and new development should move away from it where possible.

Title: SAS protect Excel worksheet with DDE

Body:
I want to manipulate an existing Excel sheet with DDE using SAS:

I have the following code (be careful! I use z for r(ows) and s for c(columns) because of German language settings in Excel):

option noxwait noxsync;
x call "C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE";

%let delay=5;

data _null_;
rc=sleep(&delay);
run;

filename sas2xl dde 'excel|system';

data _null_;
rc=sleep(&delay);
run;

%let mapwkbk=H:\odstest.xlsx;

data _null_;
file sas2xl;
rc=sleep(&delay);
put '[open("' "&mapwkbk" '")]';
run;

filename random dde 'excel|Daten!z2s1:z100s3';
data _null_;
    set sashelp.class;
    file random;
    put name sex age;
run;

data _null_;
file sas2xl;
/*rc=sleep(&delay);*/
put '[workbook.select("Pivot")]';
put '[select("Z2S1")]';
put "[pivot.refresh()]";

put '[workbook.select("Daten")]';
put '[select("z1S2:z1s5")]';
put '[filter]';
put '[select("z1S10")]';
put '[filter]';

put '[column.width(0,"s1",false,1)]';
put '[column.width(0,"s6:s9",false,1)]';

put '[ActiveSheet.Protect("***")]';

put '[workbook.delete("Dim")]';

/*put "[save()]";*/
/*put "[quit()]";*/
run;

Now I would like to password protect the sheet Daten and set option use autofilter active. Any ideas how to reach this?


问:
Persistence of data in Logger
How long does data stay in Logger.log before it is flushed? What is the persistence time of data in Logger.log?

I have a number of scripts that feed data into Logger which is then emailed to me.  I would like the log file sent once a day with all my script results rather than individually as each script runs.

NOTE:

答: As Brian said, the log file is written over every time the script runs. That is, the output of Logger.log will persist until the script runs again.

Title: Persistence of data in Logger


问:
Iteration controlled loop not working correctly
The following should generate 2 random numbers between 0 and 100, that follow certain rules.

Those rules being:

*Neither can be 0

*Num1 must be larger than Num2

*And Num1 must be divisible by Num2 (The num1 % num2 bit)

Currently the loop works correctly for the first two points, but not the last one. It is still generating numbers where num1 is not divisible by num2. Whats gone wrong?

```<code>do {
        if (num1 == 0) {
            num1 = rand()%100;
        }
        else if(num2 == 0) {
            num2 = rand()%100;
        }
        else if (num1 < num2) {
            num2 = rand()%100;
        }
        else if(num1 % num2 != 0) {
            num2 = rand()%100;
        }
        a++;
        printf("Loop no.:%d %d mod %d = %d %d / %d \n",a,num1,num2,num1%num2,num1,num2);
    } while(num1 < num2 && (num1%num2 != 0) && num1 != 0 && num2 != 0);
</code>```

答:
This can be done more efficiently.

Start with one number,

```<code>num2 = rand()%50 + 1;
</code>```

This will be the lower number. If it is bigger that 50, there is no possible second number.

Then, calculate how many numbers are possible for num1. Since num1 must be a multiple of num2, and less than or equal to 100, and it may not be the same as num2:

```<code>int nnum1 = 100/num2 - 1;
</code>```

The, just pick one:

```<code>num1 = (rand()%nnum1 + 2)*num2;
</code>```

Live demo here

Body:
The following should generate 2 random numbers between 0 and 100, that follow certain rules.

Those rules being:

*Neither can be 0

*Num1 must be larger than Num2

*And Num1 must be divisible by Num2 (The num1 % num2 bit)

Currently the loop works correctly for the first two points, but not the last one. It is still generating numbers where num1 is not divisible by num2. Whats gone wrong?

do {
        if (num1 == 0) {
            num1 = rand()%100;
        }
        else if(num2 == 0) {
            num2 = rand()%100;
        }
        else if (num1 < num2) {
            num2 = rand()%100;
        }
        else if(num1 % num2 != 0) {
            num2 = rand()%100;
        }
        a++;
        printf("Loop no.:%d %d mod %d = %d %d / %d \n",a,num1,num2,num1%num2,num1,num2);
    } while(num1 < num2 && (num1%num2 != 0) && num1 != 0 && num2 != 0);

Body:
This can be done more efficiently.

Start with one number,

num2 = rand()%50 + 1;

This will be the lower number. If it is bigger that 50, there is no possible second number.

Then, calculate how many numbers are possible for num1. Since num1 must be a multiple of num2, and less than or equal to 100, and it may not be the same as num2:

int nnum1 = 100/num2 - 1;

The, just pick one:

num1 = (rand()%nnum1 + 2)*num2;

Live demo here


问:
Js compress by uglify-js give error Unexpected token: name ($)
I am compress my js files by uglify-js
   I want to compress Bootstrap 4 js file but it give me Error like this.
   Can I compress all js files by only uglify-js Or how can i do it.

```<code>    Parse error at src\bootstrap\alert.js:1,7
    import $ from 'jquery'
           ^
    ERROR: Unexpected token: name ($)
</code>```

my package.json

```<code>"devDependencies": {
    "node-sass": "^4.6.1",
    "nodemon": "^1.12.1"
  },
  "dependencies": {
    "autoprefixer": "^7.1.6",
    "jquery": "^3.2.1",
    "postcss-cli": "^4.1.1",
    "uglify-js": "^3.1.9"
  }
</code>```

答:
Try using the ES6 version of uglify-js. Replace with this in your package.json

"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"

or via command line:

npm install --save uglify-js@github:mishoo/UglifyJS2#harmony

Body:
I am compress my js files by uglify-js
   I want to compress Bootstrap 4 js file but it give me Error like this.
   Can I compress all js files by only uglify-js Or how can i do it.

    Parse error at src\bootstrap\alert.js:1,7
    import $ from 'jquery'
           ^
    ERROR: Unexpected token: name ($)

my package.json

"devDependencies": {
    "node-sass": "^4.6.1",
    "nodemon": "^1.12.1"
  },
  "dependencies": {
    "autoprefixer": "^7.1.6",
    "jquery": "^3.2.1",
    "postcss-cli": "^4.1.1",
    "uglify-js": "^3.1.9"
  }


问:
Assign same value to ties in ranking
I have some data that looks like this:

```<code>Value <- c(-0.07, -0.07, -0.0003, 0.45, 0.45, 1.2, 1.4, 1.4, 1.4)
</code>```

I need to convert it to "ranked" data but I would like all ties to be given the same value AND the rankings to be sequential, such that:

```<code># new.value
1 1 2 3 3 4 5 5 5
</code>```

I've tried the rank() function in R but I'm having trouble with the ties.

答:
You can turn the ranks into a factor, and then convert the factor into integers.  Consider:  </p>

```<code>rank(Value)
# [1] 1.5 1.5 3.0 4.5 4.5 6.0 8.0 8.0 8.0
as.numeric(factor(rank(Value)))
# [1] 1 1 2 3 3 4 5 5 5
</code>```

Title: Assign same value to ties in ranking

Body:
I have some data that looks like this:

Value <- c(-0.07, -0.07, -0.0003, 0.45, 0.45, 1.2, 1.4, 1.4, 1.4)

I need to convert it to "ranked" data but I would like all ties to be given the same value AND the rankings to be sequential, such that:

# new.value
1 1 2 3 3 4 5 5 5

I've tried the rank() function in R but I'm having trouble with the ties.

Body:
You can turn the ranks into a factor, and then convert the factor into integers.  Consider:

rank(Value)
# [1] 1.5 1.5 3.0 4.5 4.5 6.0 8.0 8.0 8.0
as.numeric(factor(rank(Value)))
# [1] 1 1 2 3 3 4 5 5 5


问:
Log viewer for blackberry device like DDMS
I am new to Blackberry device. I need to see device logs for the running apps like DDMS in case of Android while connecting the device through USB. Any solution?</p>

答:
You need momentics and link your device to momentics,then:

On  momentics IDE

Window --> Show perspective -->QNX system information--> click your device -->launch ssh --> then the  Terminal showing ssh

if you want to show all log real time,input:
$ slog2info -w

if you want to the log for certain app real time,input:
$ slog2info -w -s theNameOfYourApp


问:
How to map RestTemplate with multiple response content?
I must consume a REST API with RestTemplate which doesn't follows good patterns, like using HTTP status codes, for example.

I have both below response contents.

Success response:

```<code>{
    "435": {
        "Codigo": "435",
        "Tipo": "",
        "Corretor": "62",
        "Cliente": "48304",
        "DataHora": "2016-04-27 14:18:24",
        "DataHoraAtualizacao": "",
        "Assunto": "Visita - Imóvel 2",
        "Local": "",
        "Texto": "",
        "DataHoraInicio": "2016-04-28 12:00:00",
        "DataHoraFinal": "2016-04-28 12:20:00"
    },
    "687": {
        "Codigo": "687",
        "Tipo": "",
        "Corretor": "20",
        "Cliente": "33040",
        "DataHora": "2016-07-18 17:09:28",
        "DataHoraAtualizacao": "",
        "Assunto": "Visita - Imóvel 2",
        "Local": "",
        "Texto": "teste",
        "DataHoraInicio": "2016-07-28 08:00:00",
        "DataHoraFinal": "2016-07-28 09:00:00"
    }}
</code>```

We can note a map structure, as follows::

```<code>Map<String, MyObject> myObjects;
</code>```

MyObject Class

```<code>public class MyObject {

    @JsonProperty("Codigo")
    private String codigo;

    @JsonProperty("Tipo")
    private String tipo;

    @JsonProperty("Corretor")
    private String corretor;

    @JsonProperty("Cliente")
    private String cliente;

    @JsonProperty("DataHora")
    private String dataHora;

    @JsonProperty("DataHoraAtualizacao")
    private String dataHoraAtualizacao;

    @JsonProperty("Assunto")
    private String assunto;

    @JsonProperty("Local")
    private String local;

    @JsonProperty("Texto")
    private String texto;

    @JsonProperty("DataHoraInicio")
    private String dataHoraInicio;

    @JsonProperty("DataHoraFinal")
    private String dataHoraFinal;

}
</code>```

Error response (with no objects to return):

```<code>{
    "status": "200",
    "message": "A pesquisa não retornou resultados."
}
</code>```

How I should map a Java class in order to solve both cases?

答:
You can create a new Response class with a property Map<String, MyObject> myObjects and add status and message to the Response class, don't forget to annotate with @JsonIgnoreProperties(ignoreUnknown = true).
However the json you get back from RestTemplate "might"not automatically serialize to myObjects, you might need to do a little formatting with the response to fit your Response Class below.

```<code>@JsonIgnoreProperties(
    ignoreUnknown = true
)
public class Response{
  Map<String, MyObject> myObjects;
  String status;
  String message;
}
</code>```

Body:
I must consume a REST API with RestTemplate which doesn't follows good patterns, like using HTTP status codes, for example.

I have both below response contents.

Success response:

{
    "435": {
        "Codigo": "435",
        "Tipo": "",
        "Corretor": "62",
        "Cliente": "48304",
        "DataHora": "2016-04-27 14:18:24",
        "DataHoraAtualizacao": "",
        "Assunto": "Visita - Imóvel 2",
        "Local": "",
        "Texto": "",
        "DataHoraInicio": "2016-04-28 12:00:00",
        "DataHoraFinal": "2016-04-28 12:20:00"
    },
    "687": {
        "Codigo": "687",
        "Tipo": "",
        "Corretor": "20",
        "Cliente": "33040",
        "DataHora": "2016-07-18 17:09:28",
        "DataHoraAtualizacao": "",
        "Assunto": "Visita - Imóvel 2",
        "Local": "",
        "Texto": "teste",
        "DataHoraInicio": "2016-07-28 08:00:00",
        "DataHoraFinal": "2016-07-28 09:00:00"
    }}

We can note a map structure, as follows::

Map<String, MyObject> myObjects;

MyObject Class

public class MyObject {

    @JsonProperty("Codigo")
    private String codigo;

    @JsonProperty("Tipo")
    private String tipo;

    @JsonProperty("Corretor")
    private String corretor;

    @JsonProperty("Cliente")
    private String cliente;

    @JsonProperty("DataHora")
    private String dataHora;

    @JsonProperty("DataHoraAtualizacao")
    private String dataHoraAtualizacao;

    @JsonProperty("Assunto")
    private String assunto;

    @JsonProperty("Local")
    private String local;

    @JsonProperty("Texto")
    private String texto;

    @JsonProperty("DataHoraInicio")
    private String dataHoraInicio;

    @JsonProperty("DataHoraFinal")
    private String dataHoraFinal;

}

Error response (with no objects to return):

{
    "status": "200",
    "message": "A pesquisa não retornou resultados."
}

How I should map a Java class in order to solve both cases?

Body:
You can create a new Response class with a property Map<String, MyObject> myObjects and add status and message to the Response class, don't forget to annotate with @JsonIgnoreProperties(ignoreUnknown = true).
However the json you get back from RestTemplate "might"not automatically serialize to myObjects, you might need to do a little formatting with the response to fit your Response Class below.

@JsonIgnoreProperties(
    ignoreUnknown = true
)
public class Response{
  Map<String, MyObject> myObjects;
  String status;
  String message;
}


问:
Extracting all text from a powerpoint file in VBA
I have a huge set of powerpoint files from which I want to extract all the text and just lump it all into one big text file.  Each source (PPT) file has multiple pages (slides).  I do not care about formatting - only the words.

I could do this manually with a file by just ^A ^C in PPT, followed by ^V in notepad; then page down in the PPT, and repeat for each slide in the powerpoint.  (Too bad I can't just do a ^A that would grab EVERYTHING ... then I could use sendkey to copy / paste)

But there are many hundreds of these PPTs with different numbers of slides.

It seems like this would be a common thing to want to do, but I can't find an example anywhere.

Does anyone have sample code to do this?

答:
The following example shows code to loop through a list of files based on Otaku's code given above:</p>

```<code>Sub test_click2()

Dim thePath As String
Dim src As String
Dim dst As String
Dim PPT As PowerPoint.Application
Dim p As PowerPoint.Presentation
Dim s As Slide
Dim sh As PowerPoint.Shape
Dim i As Integer
Dim f(10) As String

f(1) = "abc.pptx"
f(2) = "def.pptx"
f(3) = "ghi.pptx"

thePath = "C:\Work\Text parsing PPT\"

For i = 1 To 3
  src = thePath & f(i)
  dst = thePath & f(i) & ".txt"

  On Error Resume Next
  Kill dst
  Open dst For Output As #1
    Set PPT = CreateObject("PowerPoint.Application")
    PPT.Activate
    PPT.Visible = True
    'PPT.WindowState = ppWindowMinimized
    PPT.Presentations.Open filename:=src, ReadOnly:=True
    For Each s In PPT.ActivePresentation.Slides
        For Each sh In s.Shapes
            If sh.HasTextFrame Then
                If sh.TextFrame.HasText Then
                    Debug.Print sh.TextFrame.TextRange.Text
                End If
            End If
        Next
    Next
    PPT.ActivePresentation.Close
  Close #1
Next i
Set PPT = Nothing

End Sub
</code>```

Body:
The following example shows code to loop through a list of files based on Otaku's code given above:

Sub test_click2()

Dim thePath As String
Dim src As String
Dim dst As String
Dim PPT As PowerPoint.Application
Dim p As PowerPoint.Presentation
Dim s As Slide
Dim sh As PowerPoint.Shape
Dim i As Integer
Dim f(10) As String

f(1) = "abc.pptx"
f(2) = "def.pptx"
f(3) = "ghi.pptx"

thePath = "C:\Work\Text parsing PPT\"

For i = 1 To 3
  src = thePath & f(i)
  dst = thePath & f(i) & ".txt"

  On Error Resume Next
  Kill dst
  Open dst For Output As #1
    Set PPT = CreateObject("PowerPoint.Application")
    PPT.Activate
    PPT.Visible = True
    'PPT.WindowState = ppWindowMinimized
    PPT.Presentations.Open filename:=src, ReadOnly:=True
    For Each s In PPT.ActivePresentation.Slides
        For Each sh In s.Shapes
            If sh.HasTextFrame Then
                If sh.TextFrame.HasText Then
                    Debug.Print sh.TextFrame.TextRange.Text
                End If
            End If
        Next
    Next
    PPT.ActivePresentation.Close
  Close #1
Next i
Set PPT = Nothing

End Sub