问:
Match sequence at the very beginning of a string along with other sequences in the middle
I'm trying to find a way to match 2 patterns in the same regular expression, but I can't seem to be able to combine both. These are a few strings I'm trying to match against:

```<code>0 800-204-4000
0800-204 4000
0 800 -204 - 4000
800 204 4000
</code>```

What I'm trying to do is find a regular expression that matches a zero at the beginning of a string if it exists and all subsequent white spaces and dashes. So I was able to match the first zero if it exists using /^0?/ and match all empty spaces and dashes using /[\s-]*/g but how exactly can I combine both into the same expression?

Edit:

So I want to match the first 0 IF it exists and all following spaces and dashes. So in the examples above, what should be matched is in brackets:

```<code>[0 ]800[-]204[-]4000
[0]800[-]204[ ]4000
[0 ]800[ -]204[ - ]4000
800[ ]204[ ]4000
</code>```

The regex provided in the answers do not work. Check it out: https://regex101.com/r/dMN6xR/1

答:
You combine the regex by using the or operator:

```<code>/(^0?)|[\s-]*/g
</code>```

When simplified, it would be

```<code>/(^0)?[\s-]+/g
</code>```

Body:
I'm trying to find a way to match 2 patterns in the same regular expression, but I can't seem to be able to combine both. These are a few strings I'm trying to match against:

0 800-204-4000
0800-204 4000
0 800 -204 - 4000
800 204 4000

What I'm trying to do is find a regular expression that matches a zero at the beginning of a string if it exists and all subsequent white spaces and dashes. So I was able to match the first zero if it exists using /^0?/ and match all empty spaces and dashes using /[\s-]*/g but how exactly can I combine both into the same expression?

Edit:

So I want to match the first 0 IF it exists and all following spaces and dashes. So in the examples above, what should be matched is in brackets:

[0 ]800[-]204[-]4000
[0]800[-]204[ ]4000
[0 ]800[ -]204[ - ]4000
800[ ]204[ ]4000

The regex provided in the answers do not work. Check it out: https://regex101.com/r/dMN6xR/1

Body:
You combine the regex by using the or operator:

/(^0?)|[\s-]*/g

When simplified, it would be

/(^0)?[\s-]+/g


来源: stackexchange

问:
How do I create an MDI child window from a Delphi 5 ActiveX dll, and embed it in a Delphi XE MDI parent?
Is there a way to create an MDI child window from an ActiveX dll written in Delphi 5, and to embed it in a MDI parent window created from a Delphi XE windows client application? If not, is there a way to mimic the behavior?

Background

There is an application written entirely in Delphi 5. The main form of the application is an MDI parent window. All other forms in the application are MDI child forms, and every one of them is created from an ActiveX library. The parent application creates the ActiveX, after which is calls a method of the ActiveX interface. From this method a form is created and it's FormStyle is set to fsMDIChild. At this point the form is an MDI child of the MDI parent. This works because both the application and the ActiveX libraries are compiled using runtime packages. As a result, all forms share the same instance of TApplication.

The Problem

The application is very large, and needs to be migrated to Delphi 2010 or Delphi XE. It would be fantastic if the application could be migrated systematically, by first migrating the application, and then migrating the ActiveX libraries one at a time (there are about 50 of them).

The problem is that if the console application is compiled in XE, it will no longer be using the same TApplication instance as those libraries still compiled in Delphi 5.

Even if the forms in the ActiveX library cannot be true MDI child windows, it seems like I should be able to return the handle of the form that is created from the ActiveX and grab it from the main form and make the form appear to be an MDI child. I could then create my own layer for handling events.

Any ideas?

Update: The approach currently being taken with this application is that it is being migrated from MDI to an SDI interface. It is perfectly possible to instantiate TForms from a Delphi 5 ActiveX DLL from a Delphi XE application, so long as the first form from each DLL can take care of it's own data (loading, saving, displaying additional forms, etc). The problem was in keeping the original MDI design. If the SDI design proves acceptable, there will be no need for an MDI solution. Still, if someone knows how to accomplish the MDI solution, I'd like to know.

答:
Originally, I said that you cannot create do so.
I researched some more and found out that it's possible to do it.
You have to be very careful though.

Here's some source I created recently to test out the idea: http://cc.embarcadero.com/item/28168

The code spawns the Windows Calculator and Notepad app, then MDIize the external windows into the MDI Form.

Click Launch Notepad after starting the app, and see what happens.

You should be able to modify the work further so that you can achieve what you need.

Note that you need to ensure that your MDI Child in the ActiveX DLL is entirely self-contained.

ContentLicense: CC BY-SA 2.5


问:
protractor FOR loop using expectations
I made loop and now I want to use protractor expectation for every i.
Loop works ok, but expectations doesn't. If count is 4, there should be 4 expectations. If I run a test, I get pass, without any expectations(which should be false).

I found articles about that but I couldn't make it happen. I tried with Push, but there is only empty value.
Thanks for help.

```<code>myelement.count().then(function(count){
        console.log("whatever", count);
        for (var i=0; i<count; i++){
           var o = location.get(i);
            expect(o.getText()).toEqual("something");

        };

    });
</code>```

答:
Be aware. Almost all commands are promises. If you don't handle them correct it will never work. You will first need to resolve them before you can go to the next one.

Something like this can do the trick

let promise;
const promises = [];

myelement.count()
  .then(function(count) {
    console.log("whatever", count);

    for (var i = 0; i < count; i++) {
      var o = location.get(i);
      promises.push(expect(o.getText()).toEqual("something"));
    };

    return Promise.all(promises);
  });```

ContentLicense: CC BY-SA 3.0

Title: protractor FOR loop using expectations

Body:
I made loop and now I want to use protractor expectation for every i.
Loop works ok, but expectations doesn't. If count is 4, there should be 4 expectations. If I run a test, I get pass, without any expectations(which should be false).

I found articles about that but I couldn't make it happen. I tried with Push, but there is only empty value.
Thanks for help.

myelement.count().then(function(count){
        console.log("whatever", count);
        for (var i=0; i<count; i++){
           var o = location.get(i);
            expect(o.getText()).toEqual("something");

        };

    });


问:
HTTP POST not allowed in simple webpage in Visual Studio 2015 (405.0 error)
In Visual Studio 2015, I created a new ASP.NET empty website.  I wanted to try this sample shopping cart.  I added a very simple index.html:

```<code><!DOCTYPE html>
<html>
<head>
<title>Winery</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.shop.js"></script>
</head>
<body>
<div id="site">
    <header id="masthead">
        <h1>Winery <span class="tagline">Wines for web developers since 1999</h1>
    </header>
    <div id="content">
        <div id="products">
            <ul>
                <li>
                    <div class="product-image">
                        <img src="images/wine1.jpg" alt="" />
                    </div>
                    <div class="product-description" data-name="Wine #1" data-price="5">
                        <h3 class="product-name">Wine #1</h3>
                        <p class="product-price">€ 5</p>
                        <form class="add-to-cart" action="cart.html" method="post">
                            <div>
                                <label for="qty-1">Quantity</label>
                                <input type="text" name="qty-1" id="qty-1" class="qty" value="1" />
                            </div>
                            <p><input type="submit" value="Add to cart" class="btn" /></p>
                        </form>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div>
</body>
</html>
</code>```

When I click the button, I get this error:

```<code>HTTP Error 405.0 - Method Not Allowed
The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.
</code>```

This is supposed to POST an item in the cart.html page. (I can post code for the cart.html, but I think the error is happening before that page)  If I just open up Windows Explorer and find the index.html and just open that manually in Chrome and click the button the -POST WORKS FINE-, but for reason it doesn't in VS2015 (nor my Azure Web App Service).

When I test the site locally, in VS the process shows 'iisexpress.exe' is running, so I assume IIS Express is what serving up the pages by default.  My web.config for this project is the default and looks like this:

```<code><?xml version="1.0"?>
<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />
    </system.web>
</configuration>
</code>```

In looking online I've seen that POST could be disabled by default.. is that true?!  If so, I'd think many people would have this issue.  I can't believe I've had such a hard time finding an answer to this seemingly simple issue.

Also, as I mentioned I am publishing this to an AZURE Web App Service, so I don't think any local changes to IIS config files is going to change anything when I publish.  I think I need to change the web.config to make this work in Azure.

I've looked at this post and all of the links in the 'research efforts' section. Nothing.  I see all the 'similar questions' to the right as I'm typing this.. they seem related but no solutions work for me.

I appreciate the help.

答: Welp, it seems that I needed to change the file extension to .aspx for the POST to work.  Once I changed from .html to .aspx then the post worked as expected.  (Seems that the error messages could have SAID that so I didn't waste hours of my life trying to figure out why POST wasn't working)</p>

Body:
In Visual Studio 2015, I created a new ASP.NET empty website.  I wanted to try this sample shopping cart.  I added a very simple index.html:

<!DOCTYPE html>

<title>Winery</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="css/style.css" media="screen" type="text/css" />

Winery Wines for web developers since 1999

Wine #1

€ 5

                        <form class="add-to-cart" action="cart.html" method="post">

                                Quantity
                                <input type="text" name="qty-1" id="qty-1" class="qty" value="1" />

<input type="submit" value="Add to cart" class="btn" />

                        </form>

When I click the button, I get this error:

HTTP Error 405.0 - Method Not Allowed
The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.

This is supposed to POST an item in the cart.html page. (I can post code for the cart.html, but I think the error is happening before that page)  If I just open up Windows Explorer and find the index.html and just open that manually in Chrome and click the button the -POST WORKS FINE-, but for reason it doesn't in VS2015 (nor my Azure Web App Service).

When I test the site locally, in VS the process shows 'iisexpress.exe' is running, so I assume IIS Express is what serving up the pages by default.  My web.config for this project is the default and looks like this:

<?xml version="1.0"?>
<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />
    </system.web>
</configuration>

In looking online I've seen that POST could be disabled by default.. is that true?!  If so, I'd think many people would have this issue.  I can't believe I've had such a hard time finding an answer to this seemingly simple issue.

Also, as I mentioned I am publishing this to an AZURE Web App Service, so I don't think any local changes to IIS config files is going to change anything when I publish.  I think I need to change the web.config to make this work in Azure.

I've looked at this post and all of the links in the 'research efforts' section. Nothing.  I see all the 'similar questions' to the right as I'm typing this.. they seem related but no solutions work for me.

I appreciate the help.


问:
Firebase and Google Popup Authentication not fully authenticating
I have two Firebase projects that use the same front end web app and in my code when I paste in the Firebase web code snippet from Project1 into the code and I login with Google, Project 1 shows I am signed in and my my google profile pic and user name show:

when I paste into my same web app the Firebase code snippet from Project2, and I login with Google, Project 2 does not get my profile pic url and name, both are valued as null:

I've poured over my settings in Firebase Authentication and in the Google API Service Console, but I can't find where the hold up is. Any help to point me in the right direction would be appreciated!

答: Firebase-auth stores the auth session in web storage (localStorage/indexedDB) which is single host origin. I assume both projects are using different domains. If so, then the auth state (web storage) of one site will not be accessible from the other.</p>


问:
Classname Search in Nexus 3
The "Classname Search" seems to be not available in Nexus 3 and will not according to https://issues.sonatype.org/browse/NEXUS-6811, isn't it?
So I tried to search for a classname with maven-indexer and my local Nexus 3. However, it does not return a match. Does the Nexus 3 index by default contain any information about the classnames?
I was thinking about implementing classname search plugin/bundle for Nexus 3 but am not sure if the necessary data can be fetched in current Nexus 3 (3.3.1-01), can it?</p>

答: There is no support for class name search in Nexus 3.</p>

Title: Classname Search in Nexus 3


问:
jenkins selenium do not run test headlessly
I am running pytests selenium tests using jenkins. I ran test on my local machine it works. But when I run through jenkins, it runs on remote jenkins machine(creates workspace on remote jenkins machine) headlessly and it fails with test errors such as 'element not visible' or 'timeout exception due to element not clickable'.
After this I ran test on remote machine directly (windows server) in workspace. It launches chrome browser and runs test and passes.

Why is it running test headlessly when run through jenknis?

Can I make it to force open browser while running through jenkins?

Why tests are failing when ran through jenkins headlessly?

答:
I assume that your Jenkins is running as service on that machine under Windows, there are 2 things you may want to try at this point:

Specify local system account in service and check allow service to interact with desktop. More on how to do it in here. However, it could result in other issues.

Run your jenkins instance from WAR file, case you're running your tests on slave machine: start jenkins slave from command line.


问:
Why do we use volatile keyword?

Possible Duplicate:

Why does volatile exist?

I have never used it but I wonder why people use it? What does it exactly do? I searched the forum, I found it only C# or Java topics.

答:
Consider this code,

```<code>int some_int = 100;

while(some_int == 100)
{
   //your code
}
</code>```

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

```<code>volatile int some_int = 100; //note the 'volatile' qualifier now!
</code>```

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you
  know, I can be changed by some XYZ
  that you're not even aware of. That
  XYZ could be anything. Maybe some
  alien outside this planet called
  program. Maybe some lightning, some
  form of interrupt, volcanoes, etc can
  mutate me. Maybe. You never know who
  is going to change me! So O you
  ignorant, stop playing an all-knowing
  god, and don't dare touch the code
  where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.

Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the
  implementation to avoid aggressive
  optimization involving the object
  because the value of the object might
  be changed by means undetectable by an
  implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

ContentLicense: CC BY-SA 4.0

Title: Why do we use volatile keyword?

Body:
Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you
  know, I can be changed by some XYZ
  that you're not even aware of. That
  XYZ could be anything. Maybe some
  alien outside this planet called
  program. Maybe some lightning, some
  form of interrupt, volcanoes, etc can
  mutate me. Maybe. You never know who
  is going to change me! So O you
  ignorant, stop playing an all-knowing
  god, and don't dare touch the code
  where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.

Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the
  implementation to avoid aggressive
  optimization involving the object
  because the value of the object might
  be changed by means undetectable by an
  implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?


问:
Column names as variables
I want to pass column name as a parameter. Here I have written a query to select the column 'user_id' from table users, but it returns user_id as text.

```<code>EXECUTE format('SELECT $1 FROM users
WHERE name=''name''')
USING 'user_id';
</code>```

How can I do this?

答:
According to documentation...

Note that parameter symbols can only be used for data values — if you
  want to use dynamically determined table or column names, you must
  insert them into the command string textually. For example, if the
  preceding query needed to be done against a dynamically selected table...

So you need something like this

```<code>EXECUTE 'SELECT '
    || quote_ident(p_column)
    || ' FROM users '
    || ' WHERE name = $1'
   INTO v_result
   USING name;
</code>```

p_column is the column name received as a parameter in your function.

v_result is a variable for storing the result. This INTO part can be discarded if you don't care about the result.

name is the value supplied to the where condition. Must be somewhere in your function or get as a parameter too.

Title: Column names as variables

Body:
I want to pass column name as a parameter. Here I have written a query to select the column 'user_id' from table users, but it returns user_id as text.

EXECUTE format('SELECT $1 FROM users
WHERE name=''name''')
USING 'user_id';

How can I do this?

Body:
According to documentation...

Note that parameter symbols can only be used for data values — if you
  want to use dynamically determined table or column names, you must
  insert them into the command string textually. For example, if the
  preceding query needed to be done against a dynamically selected table...

So you need something like this

EXECUTE 'SELECT '
    || quote_ident(p_column)
    || ' FROM users '
    || ' WHERE name = $1'
   INTO v_result
   USING name;

p_column is the column name received as a parameter in your function.

v_result is a variable for storing the result. This INTO part can be discarded if you don't care about the result.

name is the value supplied to the where condition. Must be somewhere in your function or get as a parameter too.


问:
Batch limit of 5 on Microsoft Graph?
When trying to create a deamon application for mass updating users calendars, I stumbled upon the following documentation:

Issues with JSON batching

JSON batching new API

Batching Outlook REST API

As it seems you can batch (aka combine) up to 20 requests in the "don't use this API for new project API", but you can only combine up to 5 requests with the new Microsoft Graph API.

I found that without batching creating and deleting 100 calendar items takes around 40 seconds. Since application management got so much easier I want to use the new API, but is there any change the 5 request batch limit will be removed to let's say 20 like on the old API?

答: The batching feature is currently in beta. The limitation of 5 requests in the batch is a limitation I hope will be very short-lived. Customer asks will help me to advocate for that to happen. I've created a uservoice ask for this change here: https://officespdev.uservoice.com/forums/224641-feature-requests-and-feedback/suggestions/19505020-raise-or-remove-the-limit-on-number-of-requests-al. Voting on this ask will help demonstrate that the limitation should indeed be modified.</p>

Title: Batch limit of 5 on Microsoft Graph?


问:
Selective copying maven resources
I have a Java application build under maven. It contains two properties files - application.default.properties and application.properties. The second one suppose to supplement and/or overwrite some properties. I do have also logback.xml file in the same src/main/resources directory.
I want to keep logging and default properties in the jar file but move application.properies to the root of the tree. I put the following piece into the build section of my pom.xml

```<code>    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${user.dir}</targetPath>
            <filtering>false</filtering>
            <includes>
                <include>application.properties</include>
            </includes>
        </resource>
    </resources>
</code>```

It does copy the application.properties file as expected, but other two files disappeared from the jar file.
Can someone please tell me what I am doing wrong and how to alleviate the problem.
P.S. I did browse maven documentation but couldn't find the answer there, so please do not tell me RTFM, but if it is there provide a pointer to it.

答:
You will have to move that specific file you want at the root to another directory. </p>

<p>What you did with the include pattern is implicitly excluding the other files. If you include them, they will be moved as well. </p>

Title: Selective copying maven resources

Body:
I have a Java application build under maven. It contains two properties files - application.default.properties and application.properties. The second one suppose to supplement and/or overwrite some properties. I do have also logback.xml file in the same src/main/resources directory.
I want to keep logging and default properties in the jar file but move application.properies to the root of the tree. I put the following piece into the build section of my pom.xml

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${user.dir}</targetPath>
            <filtering>false</filtering>
            <includes>
                <include>application.properties</include>
            </includes>
        </resource>
    </resources>

It does copy the application.properties file as expected, but other two files disappeared from the jar file.
Can someone please tell me what I am doing wrong and how to alleviate the problem.
P.S. I did browse maven documentation but couldn't find the answer there, so please do not tell me RTFM, but if it is there provide a pointer to it.

Body:
You will have to move that specific file you want at the root to another directory.

What you did with the include pattern is implicitly excluding the other files. If you include them, they will be moved as well.


问:
Uncaught (in promise) DOMException: Quota exceeded
I am trying to see the demo of offline status  from the below link and I get DOMException: Quota exceeded.

https://serviceworke.rs/offline-status_demo.html

This error occurs only in chrome. It works fine in firefox without error in firefox.

The error occurs in the install event of the service worker.
Code from the service worker in posted below for reference.

// /serviceworker-cookbook/offline-status/

var CACHE_NAME = 'dependencies-cache';

// Files required to make this app work offline
var REQUIRED_FILES = [
  'random-1.png',
  'random-2.png',
  'random-3.png',
  'random-4.png',
  'random-5.png',
  'random-6.png',
  'style.css',
  'index.html',
  'index.js',
  'app.js'
];

self.addEventListener('install', function(event) {
  // Perform install step:  loading each required file into cache
  event.waitUntil(  // Error occurs here... Why???
    caches.open(CACHE_NAME)
      .then(function(cache) {
        // Add all offline dependencies to the cache
        console.log('[install] Caches opened, adding all core components' +
          'to cache');
        return cache.addAll(REQUIRED_FILES);
      })
      .then(function() {
        console.log('[install] All required resources have been cached, ' +
          'we\'re good!');
        return self.skipWaiting();
      })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return the response from the cached version
        if (response) {
          console.log(
            '[fetch] Returning from ServiceWorker cache: ',
            event.request.url
          );
          return response;
        }

        // Not in cache - return the result from the live server
        // `fetch` is essentially a "fallback"
        console.log('[fetch] Returning from server: ', event.request.url);
        return fetch(event.request);
      }
    )
  );
});

self.addEventListener('activate', function(event) {
  console.log('[activate] Activating ServiceWorker!');

  // Calling claim() to force a "controllerchange" event on navigator.serviceWorker
  console.log('[activate] Claiming this ServiceWorker!');
  event.waitUntil(self.clients.claim());
});```

How to rectify this error? Is there a way to increase the quota limit in chrome?

EDIT1:

This link says that the Chrome checks quota limit per origin whereas firefox has unlimited quota.

Is there a way to delete all the files cached from the origin (reset to original state) ?

答: I don't think there's a way to increase the quota limit. You just have to cache fewer files, or maybe use better compression.</p>

Body:
I am trying to see the demo of offline status  from the below link and I get DOMException: Quota exceeded.

https://serviceworke.rs/offline-status_demo.html

This error occurs only in chrome. It works fine in firefox without error in firefox.

The error occurs in the install event of the service worker.
Code from the service worker in posted below for reference.

// /serviceworker-cookbook/offline-status/

var CACHE_NAME = 'dependencies-cache';

// Files required to make this app work offline
var REQUIRED_FILES = [
  'random-1.png',
  'random-2.png',
  'random-3.png',
  'random-4.png',
  'random-5.png',
  'random-6.png',
  'style.css',
  'index.html',
  'index.js',
  'app.js'
];

self.addEventListener('install', function(event) {
  // Perform install step:  loading each required file into cache
  event.waitUntil(  // Error occurs here... Why???
    caches.open(CACHE_NAME)
      .then(function(cache) {
        // Add all offline dependencies to the cache
        console.log('[install] Caches opened, adding all core components' +
          'to cache');
        return cache.addAll(REQUIRED_FILES);
      })
      .then(function() {
        console.log('[install] All required resources have been cached, ' +
          'we\'re good!');
        return self.skipWaiting();
      })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return the response from the cached version
        if (response) {
          console.log(
            '[fetch] Returning from ServiceWorker cache: ',
            event.request.url
          );
          return response;
        }

        // Not in cache - return the result from the live server
        // `fetch` is essentially a "fallback"
        console.log('[fetch] Returning from server: ', event.request.url);
        return fetch(event.request);
      }
    )
  );
});

self.addEventListener('activate', function(event) {
  console.log('[activate] Activating ServiceWorker!');

  // Calling claim() to force a "controllerchange" event on navigator.serviceWorker
  console.log('[activate] Claiming this ServiceWorker!');
  event.waitUntil(self.clients.claim());
});

How to rectify this error? Is there a way to increase the quota limit in chrome?

EDIT1:

This link says that the Chrome checks quota limit per origin whereas firefox has unlimited quota.

Is there a way to delete all the files cached from the origin (reset to original state) ?


问:
Google Cloud vision demo behaving differently from actual API?
The same image leads to different text detection results in the google cloud vision API demo versus the actual API. In the demo, the accuracy is much higher. More importantly, the newline behavior is more correct in the demo; blocks of text are treated as together, whereas in the API I'm using with the free trial, the ordering of the text is treated as strictly "top to bottom" with no regard for horizontal proximity. Am I doing something wrong, or is this a bug? </p>

答: It's possible that you may get a better result from detect_document_text than from detect_text.  Try both APIs.</p>


问:
how to start observable after x sec
what's the best way to start observable after let's say 10 sec?

```<code>Single<Boolean> init();

public void onStart() {
    init().subscribe(getMySubscriber())
}
</code>```

I'd like to make the actual work in `init starts after 10 sec since subscribed.

答:
Observable.timer() is what you're looking for

```<code>Observable
            .timer(10L, TimeUnit.SECONDS)
            .subscribe(aLong -> init());
</code>```

Title: how to start observable after x sec

Body:
what's the best way to start observable after let's say 10 sec?

Single<Boolean> init();

public void onStart() {
    init().subscribe(getMySubscriber())
}

I'd like to make the actual work in `init starts after 10 sec since subscribed.

Body:
Observable.timer() is what you're looking for

Observable
            .timer(10L, TimeUnit.SECONDS)
            .subscribe(aLong -> init());


问:
Can e-mail (SMTP) be sent directly over RS-232
I'm in somewhat of an odd situation here. I'm looking to send SMTP e-mails from a remote embedded system which is directly connected to an iridium modem into a local server. The current system sends files in chunks of data and I don't know exactly how this would work with e-mail. I was thinking of using mutt to send attachments (.wav or .jpeg files), but again I don't know if this works without direct internet access. If anyone has any idea if this is possible, please let me know.

Edit: I'm using RUDICS communication, not a SBD modem

Thanks

答:
The Iridium Short Burst Data (SBD) service sends burst of less that 2Kb at a time and the revenue model for Iridium service might make sending audio and image data very expensive.

Nonetheless messages are converted by the Iridium network to be delivered in email format or over HTTP to a pre-configured address.  The address to which data is sent is assigned to your Iridium service subscription, not stored or configurable by the sender.  You can of course forward the received data to any desired destination.

You can get a direct Internet connection using an Iridium phone (https://www.iridium.com/services/details/iridium-direct-internet); but that is an expensive and bulky solution.


问:
How to avoid NPE when no values is specified for Spring JPA criteria
I have a Spring JPA search criteria like below. Where area is an Integer. </p>

```<code>cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())
</code>```

<p>The question is, when the user does not specify an upper bound or lower bound in the search, the value is null and this results in NPE. One thing comes to my mind is to make an if check for null values and set the value to Integer.MAX_VAL if it is null as a work around.This way I can avoid NPE, but it is also going to create a lot of if else checks. So I want to know if there is a better way.  </p>

答:
if getAreaMin and getAreaMax are NULL you can avoid/ignore to add this criteria .
if getAreaMin is NULL and getAreaMax is NOT NULL you can use le()  instead of between , and the same for getAreaMax with gt() method;
'if' code is ok.

something like this :

```<code> if(isNotNull(searchConstraint.getAreaMin()) && isNotNull(searchConstraint.getAreaMax())) {
         cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())
 }else{
     if(isNotNull(searchConstraint.getAreaMin()){
          cb.gt(root.get(Property_.area), searchConstraint.getAreaMin());
     }else{
          cb.le(root.get(Property_.area), searchConstraint.getAreaMax());
     }
 }
</code>```

Or you can create a util method like (but the prev variant is better dut to performance issue):

```<code>private Integer getValueOrDefault(Integer value , Integer defaultValue){
    return value==null ? defaultValue : value;
}
</code>```

execute :
cb.between(root.get(Property_.area), getValueOrDefault(searchConstraint.getAreaMin(), Integer.MIN_VALUE), getValueOrDefault(searchConstraint.getAreaMax(), Integer.MAX_VALUE))

Body:
I have a Spring JPA search criteria like below. Where area is an Integer.

cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())

The question is, when the user does not specify an upper bound or lower bound in the search, the value is null and this results in NPE. One thing comes to my mind is to make an if check for null values and set the value to Integer.MAX_VAL if it is null as a work around.This way I can avoid NPE, but it is also going to create a lot of if else checks. So I want to know if there is a better way.

Body:
if getAreaMin and getAreaMax are NULL you can avoid/ignore to add this criteria .
if getAreaMin is NULL and getAreaMax is NOT NULL you can use le()  instead of between , and the same for getAreaMax with gt() method;
'if' code is ok.

something like this :

 if(isNotNull(searchConstraint.getAreaMin()) && isNotNull(searchConstraint.getAreaMax())) {
         cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())
 }else{
     if(isNotNull(searchConstraint.getAreaMin()){
          cb.gt(root.get(Property_.area), searchConstraint.getAreaMin());
     }else{
          cb.le(root.get(Property_.area), searchConstraint.getAreaMax());
     }
 }

Or you can create a util method like (but the prev variant is better dut to performance issue):

private Integer getValueOrDefault(Integer value , Integer defaultValue){
    return value==null ? defaultValue : value;
}

execute :
cb.between(root.get(Property_.area), getValueOrDefault(searchConstraint.getAreaMin(), Integer.MIN_VALUE), getValueOrDefault(searchConstraint.getAreaMax(), Integer.MAX_VALUE))


问:
Oracle export: table doesn't exist
I am trying to export data in oracle 11g

```<code>exp user/password file=dump.dmp tables = (table1)
</code>```

via sqlplus.

And i get the following error:

About to export specified tables via Conventional Path ...

  EXP-00011: USER.TABLE1 does not exist
 Export terminated
  successfully with warnings.

But when i check who is the owner of this table:

```<code>SELECT owner, table_name from dba_tables where table_name = 'TABLE1';
</code>```

I get that the owner of TABLE1 is USER

What should i do to export this table?

UPDATE

Actually, i found a solution. I hope it will help someone else.
Since version 11g Oracle has introduced new feature that is called deferred segment creation. Thus oracle doesn't create table segment if there are now rows in it. So i recreated my table with option 'segment creation immediate'

答:
Change this:

```<code>exp user/password file=dump.dmp tables = (table1);
</code>```

to this:

```<code>exp user/password tables = (table1) file=dump.dmp;
</code>```

Title: Oracle export: table doesn't exist

Body:
I am trying to export data in oracle 11g

exp user/password file=dump.dmp tables = (table1)

via sqlplus.

And i get the following error:

About to export specified tables via Conventional Path ...

  EXP-00011: USER.TABLE1 does not exist
 Export terminated
  successfully with warnings.

But when i check who is the owner of this table:

SELECT owner, table_name from dba_tables where table_name = 'TABLE1';

I get that the owner of TABLE1 is USER

What should i do to export this table?

UPDATE

Actually, i found a solution. I hope it will help someone else.
Since version 11g Oracle has introduced new feature that is called deferred segment creation. Thus oracle doesn't create table segment if there are now rows in it. So i recreated my table with option 'segment creation immediate'

Body:
Change this:

exp user/password file=dump.dmp tables = (table1);

to this:

exp user/password tables = (table1) file=dump.dmp;


问:
Loading static files like CSS and JS to ejs
I am trying to load some static files to ejs (I was able to load in HTML file but not here in ejs file). Not just static files. I am not even able to load the CDN files! Can someone please help me to understand where I am going wrong?
Here is the directory structure:

This is my server.js:

const express=require('express');
var app=express();
const MongoClient = require('mongodb').MongoClient
app.set('view engine', 'ejs')
var path = require('path')
app.use('/static',express.static(__dirname + '/public'));

app.get('/',function(req,res){
 db.collection('testCollection').find().toArray((err, result) => {
    if (err) return console.log(err)
    console.log(result)
    res.render('index.ejs', {testCollection: result})
  })
});```
</div>
</div>
</p>

<p>This is my index.ejs:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/static/main.css"/>
</head>
<body>
<form>
<div id="container"></div>
<ul class="quotes">
 <% for(var i=0; i<testCollection.length; i++) {%>
    <li class="quote">
      <span><%= testCollection[i].name %></span>
    </li>
  <% } %>
</ul>
</form>
</body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="/static/main.js"></script>
</html></code>```

In the console I can see only index.ejs file loaded:

答:
I think that if you add :

```<code>app.set('views',__dirname);//---> before setting ejs as the View Engine ... (this is for the views folder that you have there but your view is in your current working directory hence __dirname)
var index = require('./index');
app.use('/', index);//---> after declaring static folder...
</code>```

to your code node might know where the files are ...

I suggest that you move your index.ejs to the views folder and then set:

```<code>app.set('views', path.join(__dirname, 'views'));
</code>```

instead of:

```<code>app.set('views',__dirname);
</code>```

Body:
I am trying to load some static files to ejs (I was able to load in HTML file but not here in ejs file). Not just static files. I am not even able to load the CDN files! Can someone please help me to understand where I am going wrong?
Here is the directory structure:

This is my server.js:

const express=require('express');
var app=express();
const MongoClient = require('mongodb').MongoClient
app.set('view engine', 'ejs')
var path = require('path')
app.use('/static',express.static(__dirname + '/public'));

app.get('/',function(req,res){
 db.collection('testCollection').find().toArray((err, result) => {
    if (err) return console.log(err)
    console.log(result)
    res.render('index.ejs', {testCollection: result})
  })
});

This is my index.ejs:

<!DOCTYPE html>

<link rel="stylesheet" href="/static/main.css"/>

<form>

 <% for(var i=0; i<testCollection.length; i++) {%>

      <%= testCollection[i].name %>

  <% } %>

</form>

In the console I can see only index.ejs file loaded:

Body:
I think that if you add :

app.set('views',__dirname);//---> before setting ejs as the View Engine ... (this is for the views folder that you have there but your view is in your current working directory hence __dirname)
var index = require('./index');
app.use('/', index);//---> after declaring static folder...

to your code node might know where the files are ...

I suggest that you move your index.ejs to the views folder and then set:

app.set('views', path.join(__dirname, 'views'));

instead of:

app.set('views',__dirname);


问:
Is it possible to find the url height and tab height in browser (JavaScript)?
I'm trying to find the maximum inner height of a browser no matter if it's in full screen or not. So I'm trying to subtract the height of URL and Tabs from windows.availHeight. Is this possible? </p>

<p>I would appreciate it if there is any better alternative solution. </p>

答: Have you tried document.documentElement.clientHeight, it changes when the browser enters fullscreen.</p>

Body:
I'm trying to find the maximum inner height of a browser no matter if it's in full screen or not. So I'm trying to subtract the height of URL and Tabs from windows.availHeight. Is this possible?

I would appreciate it if there is any better alternative solution.


问:
How to set Resource file path relative to the project file?
Let's say I have a directory A, and has a project file x.csproj and sln in that directory.
I also have resource file x.resources in it.

How can I set the resource file without the absolute path C:\A\x.resources, but relative path .\x.resources? I tried with x.resources but it doesn't work.

答: NOTE: Visual Studio sometimes puts the <PropertyGroup> <Win32Resource> too early in the .csproj, so you would need to manually edit the XML and move the <PropertyGroup> after the <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> element so the reference will be relative to the .csproj file.


问:
If we cant use 2D array of 10^9*10^9 then why are we able to instantiate it?
I can declare a 2D array of size 10^9*10^9 but when for a given test case which requires this size throws an exception of Exception in thread "main" java.lang.OutOfMemoryError: Java heap space and yes if it leads to complete memory usage then why are able to instantiate such arrays?

答:
One aspect worth mentioning: of course some level of checking takes place at compile time: you can only use int values when declaring the array size.

The compiler will prevent you from using a long value there, and of course will not allow when you go for a negative number (when using literals).

But as the other answer says: the compiler accepting your code isn't the same as reality at runtime accepting your input.


问:
Error handling with axios requests in reactjs
I have an SPA app built in React with many axios calls to an API. I can set up a redirect to the login page within axios when the error status returns 401, but with the large number of calls spread across a lot of components, is there a better way to handle this without repeating the:

```<code>if (error.status === 401) {
    //redirect to login page
}
</code>```

in every single request

答:
Avoid writing the api calls in all the components, create a separate file api.js or some abc.js, and write a generic method of making calls, and call that method from different component with proper parameters. In that case you need to handle all those kind of cases in every file, just put the logic only at one place inside api.js file.

api.js:

```<code>export function _callAPI(url, method, data, target){
     /*
         url: separate url for different component
         method: Get or Post or Put etc
         data: if required to pass
         target: callback method
     */
}
</code>```

Then import this in different component:

```<code>import * as Api from 'path to api.js file';
</code>```

call that by:

```<code>Api._callAPI(url, method, data, (data) => {
    console.log(data);
})
</code>```

Body:
I have an SPA app built in React with many axios calls to an API. I can set up a redirect to the login page within axios when the error status returns 401, but with the large number of calls spread across a lot of components, is there a better way to handle this without repeating the:

if (error.status === 401) {
    //redirect to login page
}

in every single request

Body:
Avoid writing the api calls in all the components, create a separate file api.js or some abc.js, and write a generic method of making calls, and call that method from different component with proper parameters. In that case you need to handle all those kind of cases in every file, just put the logic only at one place inside api.js file.

api.js:

export function _callAPI(url, method, data, target){
     /*
         url: separate url for different component
         method: Get or Post or Put etc
         data: if required to pass
         target: callback method
     */
}

Then import this in different component:

import * as Api from 'path to api.js file';

call that by:

Api._callAPI(url, method, data, (data) => {
    console.log(data);
})


问:
Connecting to Postgresql in a docker container from outside
I have Postgresql on a server in a docker container. How can I connect to it from the outside, that is, from my local computer? What setting should I apply to allow that?</p>

答:
I already had running postgres on host machine and didn't want to allow connections from network, so I did run temporary postgres instance in container and created database in just two lines:

# Run PostgreSQL
docker run --name postgres-container -e POSTGRES_PASSWORD=password -it -p 5433:5432 postgres

# Create database
docker exec -it postgres-container createdb -U postgres my-db
```


问:
Angular Json Parse. what am I doing wrong?
I'm trying to parse JSON by reference. I tried to do the examples, but the information is not output. The result of the get-query is a string that is not parsed. How do I get information?

Screenshots:

window

JSON

```<code><html ng-app="expeditionApp">
<head>
    <meta charset="utf-8">
    <title>Expedition</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>

    <script>
        var expeditionApp = angular.module('expeditionApp', []);
        expeditionApp.controller('expeditionCtrl', function ($scope, $http)
        {

            $http.get('http://localhost:3030/expedition/query?query=PREFIX exp: <http://sparql.sstu.ru:3030/expedition/> SELECT ?About ?RecDate ?LinkToVideo ?Duration WHERE {?video exp:hasVideoAbout ?About. ?video exp:hasRecDate ?RecDate. ?video exp:hasLinkToVideo ?LinkToVideo. ?video exp:hasDuration ?Duration.}')
            .success(function(response) {
                $scope.var = response;
                console.log(response)
            })
            .error(function(response) {
                alert(response);
                console.log('Error: ' + response);
            });

        });
    </script>

</head>
<body ng-controller="expeditionCtrl">
    <h2>Example</h2>

        ```{{var}}```

        <table class="table table-striped">
            <tr>
                <th>About</th>
                <th>RecDate</th>
                <th>LinkToVideo</th>
                <th>Duration</th>
            </tr>
            <tr ng-repeat="item in var.data  | orderBy: 'subject' ">
                <td>{{item.About}}</td>
                <td>{{item.RecDate}}</td>
                <td>{{item.LinkToVideo}}</td>
                <td>{{item.Duration}}</td>
            </tr>
      </table>
</body>
</code>```

答:
You cannot use $scope.var, var is a keyword therefore cannot be used, change the variable name and try again.

use  $scope.allData = response;

if the response is exactly what you have shared(screenshot) then line should be :

$scope.allData = response.data.results.bindings;

Body:
I'm trying to parse JSON by reference. I tried to do the examples, but the information is not output. The result of the get-query is a string that is not parsed. How do I get information?

Screenshots:

window

JSON

    <meta charset="utf-8">
    <title>Expedition</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

Example

{{var}}

                About
                RecDate
                LinkToVideo
                Duration

                {{item.About}}
                {{item.RecDate}}
                {{item.LinkToVideo}}
                {{item.Duration}}


问:
How to create c# mongodb pipeline that includes $redact
I am trying to create a a mongodb aggregate pipeline using the C# driver that includes redact followed by a project.  I have tried several ways shown below but in each case only the first stage of the pipeline is executed. The AppendStage does not appear to append the next stage.  So how does one have a redact followed by a project using the C# mongodb driver. Note that the fluent interface does not directly support redact but another post showed using the code below to do it which works for the first stage.

I am using 2.4.3 version of the C# driver and mongodb version 3.4.4

```<code>string redactJson = System.IO.File.ReadAllText(@"redactTest.json");
string projectJson = System.IO.File.ReadAllText(@"projectTest.json");

var collection = Database.GetCollection<BsonDocument>("Forecasts");

var redact = BsonDocument.Parse(redactJson);
var project = BsonDocument.Parse(projectJson);

var aggregatonPipeline = collection.Aggregate();
aggregatonPipeline.AppendStage<BsonDocument>(redact);
aggregatonPipeline.AppendStage<BsonDocument>(project);

var list = aggregatonPipeline.ToList();
</code>```

or similar code like this

```<code>var pipeline = collection.Aggregate().AppendStage<BsonDocument>(redact);
pipeline.AppendStage<BsonDocument>(project);
var list = pipeline.ToList();
</code>```

Where my aggregate json looks like these

redactTest.json:

```<code>{
    $redact: {
       $cond: {
         if: {
             $gt: [{ $size: { "$setIntersection": [ "$tags", ["STLW", "G"]]}}, 0]
         },
         then: "$$DESCEND",
         else: "$$PRUNE"
      }
   }
}
</code>```

projectTest.json

```<code>{
  "$project":
  {
    "_id": 0,
    "title": 1,
    "year": 1,
    "subsections.subtitle": 1,
    "subsections.content":  1
  }
}
</code>```

And the source document is

```<code>{
  _id: 1,
  title: "123 Department Report",
  tags: [ "G", "STLW" ],
  year: 2014,
  subsections: [
    {
      subtitle: "Section 1: Overview",
      tags: [ "SI", "G" ],
      content:  "Section 1: This is the content of section 1."
    },
    {
      subtitle: "Section 2: Analysis",
      tags: [ "STLW" ],
      content: "Section 2: This is the content of section 2."
    },
    {
      subtitle: "Section 3: Budgeting",
      tags: [ "TK" ],
      content: {
      text: "Section 3: This is the content of section3.",
       tags: [ "HCS" ]
     }
   }
 ]
}
</code>```

答:
collection.Aggregate() exposes the fluent aggregation interface and appends the stages to the pipeline via method chaining.

Something like

```<code>var pipeline= collection.Aggregate().AppendStage<BsonDocument>(redact).AppendStage<BsonDocument>(project);
var list = pipeline.ToList();
</code>```

Your usage overwrites the previous stages when add one stage at a time.

Body:
I am trying to create a a mongodb aggregate pipeline using the C# driver that includes redact followed by a project.  I have tried several ways shown below but in each case only the first stage of the pipeline is executed. The AppendStage does not appear to append the next stage.  So how does one have a redact followed by a project using the C# mongodb driver. Note that the fluent interface does not directly support redact but another post showed using the code below to do it which works for the first stage.

I am using 2.4.3 version of the C# driver and mongodb version 3.4.4

string redactJson = System.IO.File.ReadAllText(@"redactTest.json");
string projectJson = System.IO.File.ReadAllText(@"projectTest.json");

var collection = Database.GetCollection<BsonDocument>("Forecasts");

var redact = BsonDocument.Parse(redactJson);
var project = BsonDocument.Parse(projectJson);

var aggregatonPipeline = collection.Aggregate();
aggregatonPipeline.AppendStage<BsonDocument>(redact);
aggregatonPipeline.AppendStage<BsonDocument>(project);

var list = aggregatonPipeline.ToList();

or similar code like this

var pipeline = collection.Aggregate().AppendStage<BsonDocument>(redact);
pipeline.AppendStage<BsonDocument>(project);
var list = pipeline.ToList();

Where my aggregate json looks like these

redactTest.json:

{
    $redact: {
       $cond: {
         if: {
             $gt: [{ $size: { "$setIntersection": [ "$tags", ["STLW", "G"]]}}, 0]
         },
         then: "$$DESCEND",
         else: "$$PRUNE"
      }
   }
}

projectTest.json

{
  "$project":
  {
    "_id": 0,
    "title": 1,
    "year": 1,
    "subsections.subtitle": 1,
    "subsections.content":  1
  }
}

And the source document is

{
  _id: 1,
  title: "123 Department Report",
  tags: [ "G", "STLW" ],
  year: 2014,
  subsections: [
    {
      subtitle: "Section 1: Overview",
      tags: [ "SI", "G" ],
      content:  "Section 1: This is the content of section 1."
    },
    {
      subtitle: "Section 2: Analysis",
      tags: [ "STLW" ],
      content: "Section 2: This is the content of section 2."
    },
    {
      subtitle: "Section 3: Budgeting",
      tags: [ "TK" ],
      content: {
      text: "Section 3: This is the content of section3.",
       tags: [ "HCS" ]
     }
   }
 ]
}

Body:
collection.Aggregate() exposes the fluent aggregation interface and appends the stages to the pipeline via method chaining.

Something like

var pipeline= collection.Aggregate().AppendStage<BsonDocument>(redact).AppendStage<BsonDocument>(project);
var list = pipeline.ToList();

Your usage overwrites the previous stages when add one stage at a time.


问:
How to match URL with href in jQuery?
Using a list for navigation, I am looking for a clean way to apply the 'selected' class to a list item if the page URL (minus anything after the path) matches the href of the list item (minus anything after the path).

Example:

```<code><li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
</code>```

Apply class "selected" to the list item when the page URL includes the /p/clothing/dresses/N-10635 part of the href.

So far, I achieved partial results using:

```<code>$('.leftNav li a').each(function(){
    if(window.location.href == this.href){
        $(this).parents('li').addClass('selected');
    }
});

<ul class="leftNav">
<li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>
</code>```

This, however, only applied the 'selected' class when the URL matched the href exactly - meaning it had to include the link-tracking variable as in the href (ie: ?ab=leftNav:dresses). Thinking of ways to match the "base" URL's and href's, I tried adding a data attribute to the list items to match the path only:

```<code>$('.leftNav li').each(function(){
    if(window.location.href == (this).data('left-nav-href')){
        $(this).addClass('selected');
    }
});

<ul class="leftNav">
<li data-left-nav-href="/p/clothing/dresses/N-10635"><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
<li data-left-nav-href="/p/clothing/bottoms/capris/N-10764"><a href="/p/clothing/bottoms/capris/N-10764?ab=leftNav:capris">capris</a></li>
</ul>
</code>```

I attempted this with variations of window.location including: window.location.href, window.location.href.pathname, window.location.href.indexOf, window.location.href.startsWith. With this not working, I searched for a way to match the path of the URL and href regardless of additional parameters or variables, but all I can find are ways to match URL's and href's specifically with strings or parameters. All instances I could find of matching only part of a URL or href use "split" RegEx which introduces another level of complexity that I don't think my use requires. Am I missing a simpler solution?

答:
I guess if you keep your html like

```<code><li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
</code>```

but change the comparisson to:

```<code>$('.leftNav li a').each(function(){
    if (this.href.indexOf(location.pathname) > -1) {
        $(this).parents('li').addClass('selected');
    }
});
</code>```

you'll get what you need!

The "if" above will check if the given path is contained in item's href property.

So, if your URL is "http://www.yourhost.com/p/clothing/dresses/N-10635?param=value", it's path (/p/clothing/dresses/N-10635) should be found, and the output for the given example would be:

```<code><li class="selected"><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>
</code>```

I hope this helped! =)

Title: How to match URL with href in jQuery?

Body:
Using a list for navigation, I am looking for a clean way to apply the 'selected' class to a list item if the page URL (minus anything after the path) matches the href of the list item (minus anything after the path).

Example:

dresses

Apply class "selected" to the list item when the page URL includes the /p/clothing/dresses/N-10635 part of the href.

So far, I achieved partial results using:

$('.leftNav li a').each(function(){
    if(window.location.href == this.href){
        $(this).parents('li').addClass('selected');
    }
});

dresses

capris

This, however, only applied the 'selected' class when the URL matched the href exactly - meaning it had to include the link-tracking variable as in the href (ie: ?ab=leftNav:dresses). Thinking of ways to match the "base" URL's and href's, I tried adding a data attribute to the list items to match the path only:

$('.leftNav li').each(function(){
    if(window.location.href == (this).data('left-nav-href')){
        $(this).addClass('selected');
    }
});

dresses

capris

I attempted this with variations of window.location including: window.location.href, window.location.href.pathname, window.location.href.indexOf, window.location.href.startsWith. With this not working, I searched for a way to match the path of the URL and href regardless of additional parameters or variables, but all I can find are ways to match URL's and href's specifically with strings or parameters. All instances I could find of matching only part of a URL or href use "split" RegEx which introduces another level of complexity that I don't think my use requires. Am I missing a simpler solution?

Body:
I guess if you keep your html like

<li><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>

but change the comparisson to:

$('.leftNav li a').each(function(){
    if (this.href.indexOf(location.pathname) > -1) {
        $(this).parents('li').addClass('selected');
    }
});

you'll get what you need!

The "if" above will check if the given path is contained in item's href property.

So, if your URL is "http://www.yourhost.com/p/clothing/dresses/N-10635?param=value", it's path (/p/clothing/dresses/N-10635) should be found, and the output for the given example would be:

<li class="selected"><a href="/p/clothing/dresses/N-10635?ab=leftNav:dresses">dresses</a></li>

I hope this helped! =)


问:
How can I rename a file in code in Inno Setup?
I need to rename a file to zip, I try this code but doesn't works.

 Exec('cmd.exe', 'rename '+ExpandConstant('{app}\scripts\set.bat'+' set.zip'), '', SW_SHOW,
      ewWaitUntilTerminated, ResultCode);
```

I found a way to do it on [Run] section, but I need it to do in [Code] section.

答:
You need to quote the paths, as {app} typically contains spaces (Program Files).

You need /C command-line parameter before the command.

Exec('cmd.exe',
     '/C rename ' + AddQuotes(ExpandConstant('{app}\scripts\set.bat')) + ' set.zip',
     '', SW_SHOW, ewWaitUntilTerminated, ResultCode);
```

<hr>

<p>Though as @Alex correctly commented, use <code>RenameFile</code> instead:</p>

<pre class="lang-pascal prettyprint-override"><code>RenameFile(ExpandConstant('{app}\scripts\set.bat'), ExpandConstant('{app}\scripts\set.zip'));
</code>```

Body:
I need to rename a file to zip, I try this code but doesn't works.

 Exec('cmd.exe', 'rename '+ExpandConstant('{app}\scripts\set.bat'+' set.zip'), '', SW_SHOW,
      ewWaitUntilTerminated, ResultCode);

I found a way to do it on [Run] section, but I need it to do in [Code] section.

Body:
You need to quote the paths, as {app} typically contains spaces (Program Files).

You need /C command-line parameter before the command.

Exec('cmd.exe',
     '/C rename ' + AddQuotes(ExpandConstant('{app}\scripts\set.bat')) + ' set.zip',
     '', SW_SHOW, ewWaitUntilTerminated, ResultCode);

Though as @Alex correctly commented, use RenameFile instead:

RenameFile(ExpandConstant('{app}\scripts\set.bat'), ExpandConstant('{app}\scripts\set.zip'));


问:
What alternatives are there to +[LSApplicationWorkspace defaultWorkspace] and -allApplications?
I have an app that uses
LSApplicationWorkspace's +defaultWorkspace and -allApplications, but I can't use these on the App Store.

What alternatives do I have?

答:
What alternatives do I have?

If you are using LSApplicationWorkspace to detect what applications are installed? None.

Apple treats the list of installed applications as private, and have made deliberate changes to other APIs in the past to keep that information private. (For instance, iOS 9 applied limits to canOpenURL: to prevent it from being used to detect installed applications.)

If you need to detect other specific applications, and those applications implement custom URL schemes, you can still use canOpenURL: to check for those. However, you will need to declare these URL schemes ahead of time in your Info.plist, and you cannot detect applications which do not handle unique URL schemes.


问:
Javascript SVG Interaction Issue
I am trying to develop an interactive SVG map and I want to do stuff when the mouse enters rectangles within the SVG image. Currently, the code logs to the console when my mouse enters the SVG image, but not when I mouse over the rectangles. Any help would be much appreciated. Thanks!

<object onload="svgOnLoad()" id="activeSVG" data="SVGNAME.svg" type="image/svg+xml">
</object>

  ```

答:
After messing around with it for a bit I found what needed to be added. You need to get the content of the svg object and then play with it from there. I've included the new script code below.

```

Title: Javascript SVG Interaction Issue

Body:
After messing around with it for a bit I found what needed to be added. You need to get the content of the svg object and then play with it from there. I've included the new script code below.

<script>
            function svgOnLoad() {
              // Get SVG object
              var officeMapFloor = document.getElementById("activeSVG");

              // Get the content of the SVG object
              var svgDoc = officeMapFloor.contentDocument;

              // Access an ID within the content of the object
              var rect = svgDoc.getElementById("siesta");

              // Apply the event listener
              rect.onmouseover = function(){
                console.log("Finally in the rectangle");
              };

            }
 </script>


问:
how to run a service which updates the appwidget?
I am having a home screen widget and i want to run a background service which does all the fetching from url and should update all the widgets on the home screen corresponding to the provider i have created it.

how to do it? it seems that i unable to access appwidget or the context from the service.

any help?

答: my response here should be helpful to you android appwidget won't update from activity</p>


问:
CRM - sending email to contacts in sub grid
I work for a charity and we want to use our Dynamics 365 to support our fundraising team.  We have created a 'Fundraising Event' entity with an N:N relationship to the Contact entity (renamed to 'Individual' in our Org.  I have a sub grid on each entity so that we can add contacts to events either from the Contact record or from the event record.
We need to be able to send emails to everyone registered for an event to wish them good luck before the event.  I have created a workflow against the 'Fundraising Event' entity to run 7 days before an event start date however when I an testing this the System job shows "Error; Needs Attention" and when I look at the process it shows a message "The email must have at least one recipient before it can be sent."
Process error image
In the WF send email properties, I have tried using 'Contact' and 'Named Contact(Lookup)' from the list I have available (see screen shot below) in the TO field but I get the same result with both options.
To line option list image
My test event has 2 Individuals (Contacts) linked to it and I can see them both in the sub grid on the event record but I can't seem to be able to send emails to them.
Here are the details from a failed process:

```<code>Plugin Trace:
[Microsoft.Xrm.Sdk.Workflow: Microsoft.Xrm.Sdk.Workflow.Activities.SendEmail]
[SendEmailStep1]
Error Message:
Unhandled Exception:
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The e-mail must have at least one recipient before it can be sentDetail:

<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">

<ActivityId>9161cfb2-308e-4b19-af39-b859a78f132f</ActivityId>

<ErrorCode>-2147218684</ErrorCode>

<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />

<Message>The e-mail must have at least one recipient before it can be sent</Message>

<Timestamp>2017-03-31T11:07:27.6562583Z</Timestamp>

<ExceptionSource i:nil="true" />

<InnerFault>

<ActivityId>9161cfb2-308e-4b19-af39-b859a78f132f</ActivityId>

<ErrorCode>-2147218684</ErrorCode>

<ErrorDetails xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />

<Message>The e-mail must have at least one recipient before it can be sent</Message>

<Timestamp>2017-03-31T11:07:27.6562583Z</Timestamp>

<ExceptionSource i:nil="true" />

<InnerFault i:nil="true" />

<OriginalException i:nil="true" />

<TraceText i:nil="true" />

</InnerFault>

<OriginalException i:nil="true" />

<TraceText>[Microsoft.Xrm.Sdk.Workflow: Microsoft.Xrm.Sdk.Workflow.Activities.SendEmail]

[SendEmailStep1]

</TraceText>

</OrganizationServiceFault>

at Microsoft.Crm.Workflow.Services.SendEmailActivityService.Execute(ActivityContext executionContext, SendEmail sendEmail)

at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)

at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
</code>```

Is it possible to do what I'm attempting using out of the box functionality? If so, what am I missing?
Thanks,
Paul

答:
We did something like this.

Register a plugin in Pre-operation of Email Create message & have this logic in there.

This will add the recipients from N:N contact intersect entity in email To list.

```<code>    ConditionExpression frCondition1 = new ConditionExpression();
    ConditionExpression frCondition2 = new ConditionExpression();
    EntityCollection frResponse = new EntityCollection();
    EntityCollection toOwner = new EntityCollection();

    toOwner = targetEntity.GetAttributeValue<EntityCollection>("to");

    frCondition1 = CreateConditionExpression("parentIdcolummn", ConditionOperator.Equal, new string[] { parent.Id.ToString() });
    frCondition2 = CreateConditionExpression(statuscode, ConditionOperator.Equal, new object[] { 1 });

    ConditionExpression[] conditions = new ConditionExpression[] { frCondition1, frCondition2 };

    FilterExpression filterExpression = new FilterExpression();

filterExpression.Conditions.AddRange(conditions);
filterExpression.FilterOperator = LogicalOperator.And;

QueryExpression queryExpression = new QueryExpression();
queryExpression.ColumnSet = GenerateColumnSet("columnNames");
queryExpression.EntityName = "entityName";
queryExpression.Criteria = filterExpression;
queryExpression.NoLock = true;

    frResponse =  (EntityCollection)service.RetrieveMultiple(queryExpression);

    if(frResponse != null && frResponse.Entities.Count > 0)
    {
        //Adding all FRs in the email
        foreach (Entity FilingRep in frResponse.Entities)
        {
            Guid frGuid = ((EntityReference)FilingRep["contactLookupfieldname"]).Id;

            Entity toParty = new Entity("activityparty");

            toParty[ActivityParty.ActivityPartId] = new EntityReference("contact", frGuid);

            ToOwner.Entities.Add(toParty);
        }
    }

    targetEntity[EmailEntityAttributeName.To] = toOwner;
</code>```

Body:
I work for a charity and we want to use our Dynamics 365 to support our fundraising team.  We have created a 'Fundraising Event' entity with an N:N relationship to the Contact entity (renamed to 'Individual' in our Org.  I have a sub grid on each entity so that we can add contacts to events either from the Contact record or from the event record.
We need to be able to send emails to everyone registered for an event to wish them good luck before the event.  I have created a workflow against the 'Fundraising Event' entity to run 7 days before an event start date however when I an testing this the System job shows "Error; Needs Attention" and when I look at the process it shows a message "The email must have at least one recipient before it can be sent."
Process error image
In the WF send email properties, I have tried using 'Contact' and 'Named Contact(Lookup)' from the list I have available (see screen shot below) in the TO field but I get the same result with both options.
To line option list image
My test event has 2 Individuals (Contacts) linked to it and I can see them both in the sub grid on the event record but I can't seem to be able to send emails to them.
Here are the details from a failed process:

Plugin Trace:
[Microsoft.Xrm.Sdk.Workflow: Microsoft.Xrm.Sdk.Workflow.Activities.SendEmail]
[SendEmailStep1]
Error Message:
Unhandled Exception:
System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The e-mail must have at least one recipient before it can be sentDetail:

<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">

<ActivityId>9161cfb2-308e-4b19-af39-b859a78f132f</ActivityId>

<ErrorCode>-2147218684</ErrorCode>

<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />

<Message>The e-mail must have at least one recipient before it can be sent</Message>

<Timestamp>2017-03-31T11:07:27.6562583Z</Timestamp>

<ExceptionSource i:nil="true" />

<InnerFault>

<ActivityId>9161cfb2-308e-4b19-af39-b859a78f132f</ActivityId>

<ErrorCode>-2147218684</ErrorCode>

<ErrorDetails xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />

<Message>The e-mail must have at least one recipient before it can be sent</Message>

<Timestamp>2017-03-31T11:07:27.6562583Z</Timestamp>

<ExceptionSource i:nil="true" />

<InnerFault i:nil="true" />

<OriginalException i:nil="true" />

<TraceText i:nil="true" />

</InnerFault>

<OriginalException i:nil="true" />

<TraceText>[Microsoft.Xrm.Sdk.Workflow: Microsoft.Xrm.Sdk.Workflow.Activities.SendEmail]

[SendEmailStep1]

</TraceText>

</OrganizationServiceFault>

at Microsoft.Crm.Workflow.Services.SendEmailActivityService.Execute(ActivityContext executionContext, SendEmail sendEmail)

at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)

at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)

Is it possible to do what I'm attempting using out of the box functionality? If so, what am I missing?
Thanks,
Paul

Body:
We did something like this.

Register a plugin in Pre-operation of Email Create message & have this logic in there.

This will add the recipients from N:N contact intersect entity in email To list.

    ConditionExpression frCondition1 = new ConditionExpression();
    ConditionExpression frCondition2 = new ConditionExpression();
    EntityCollection frResponse = new EntityCollection();
    EntityCollection toOwner = new EntityCollection();

    toOwner = targetEntity.GetAttributeValue<EntityCollection>("to");

    frCondition1 = CreateConditionExpression("parentIdcolummn", ConditionOperator.Equal, new string[] { parent.Id.ToString() });
    frCondition2 = CreateConditionExpression(statuscode, ConditionOperator.Equal, new object[] { 1 });

    ConditionExpression[] conditions = new ConditionExpression[] { frCondition1, frCondition2 };

    FilterExpression filterExpression = new FilterExpression();

filterExpression.Conditions.AddRange(conditions);
filterExpression.FilterOperator = LogicalOperator.And;

QueryExpression queryExpression = new QueryExpression();
queryExpression.ColumnSet = GenerateColumnSet("columnNames");
queryExpression.EntityName = "entityName";
queryExpression.Criteria = filterExpression;
queryExpression.NoLock = true;

    frResponse =  (EntityCollection)service.RetrieveMultiple(queryExpression);

    if(frResponse != null && frResponse.Entities.Count > 0)
    {
        //Adding all FRs in the email
        foreach (Entity FilingRep in frResponse.Entities)
        {
            Guid frGuid = ((EntityReference)FilingRep["contactLookupfieldname"]).Id;

            Entity toParty = new Entity("activityparty");

            toParty[ActivityParty.ActivityPartId] = new EntityReference("contact", frGuid);

            ToOwner.Entities.Add(toParty);
        }
    }

    targetEntity[EmailEntityAttributeName.To] = toOwner;


问:
Google Cloud Vision API text detection google.gax.errors.RetryError: GaxError
I'm new in Google API.
Recently, I use the Google Vision API but I met the following problem:

```<code>google.gax.errors.RetryError: GaxError(Exception occurred in retry method that was not classified as transient, caused by <_Rendezvous of RPC that terminated with (StatusCode.RESOURCE_EXHAUSTED, Insufficient tokens for quota 'DefaultGroup' and limit 'USER-100s' of service 'vision.googleapis.com' for consumer 'project_number:XXX'.)>)
</code>```

And I tried the solution about "Create the service accout" to generate the service json key and invoke it in py.script,
it will work first in almost 3~4 url, but it will error in next url.
This is my detect code:

```<code>import argparse
import io
from google.cloud import vision
vision_client = vision.Client.from_service_account_json('/Users/bruce0621/Downloads/esun-bank-adc1897dba67.json')
...
def detect_text_uri(uri):
    """Detects text in the file located in Google Cloud Storage or on the Web.
    """
    vision_client = vision.Client()
    image = vision_client.image(source_uri=uri)

    texts = image.detect_text()
    print('Texts:')

    for text in texts:
        print('\n"{}"'.format(text.description))

        vertices = (['({},{})'.format(bound.x_coordinate, bound.y_coordinate)
                    for bound in text.bounds.vertices])

        print('bounds: {}'.format(','.join(vertices)))
</code>```

And I invoke the "detect.py" in another py.script:

```<code>detect.detect_text_uri('...')
</code>```

答:
Call:

```<code>export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials.json
</code>```

or

```<code>gcloud auth application-default login
</code>```

This will configure your environment to use the service account credential you downloaded.

Body:
I'm new in Google API.
Recently, I use the Google Vision API but I met the following problem:

google.gax.errors.RetryError: GaxError(Exception occurred in retry method that was not classified as transient, caused by <_Rendezvous of RPC that terminated with (StatusCode.RESOURCE_EXHAUSTED, Insufficient tokens for quota 'DefaultGroup' and limit 'USER-100s' of service 'vision.googleapis.com' for consumer 'project_number:XXX'.)>)

And I tried the solution about "Create the service accout" to generate the service json key and invoke it in py.script,
it will work first in almost 3~4 url, but it will error in next url.
This is my detect code:

import argparse
import io
from google.cloud import vision
vision_client = vision.Client.from_service_account_json('/Users/bruce0621/Downloads/esun-bank-adc1897dba67.json')
...
def detect_text_uri(uri):
    """Detects text in the file located in Google Cloud Storage or on the Web.
    """
    vision_client = vision.Client()
    image = vision_client.image(source_uri=uri)

    texts = image.detect_text()
    print('Texts:')

    for text in texts:
        print('\n"{}"'.format(text.description))

        vertices = (['({},{})'.format(bound.x_coordinate, bound.y_coordinate)
                    for bound in text.bounds.vertices])

        print('bounds: {}'.format(','.join(vertices)))

And I invoke the "detect.py" in another py.script:

detect.detect_text_uri('...')

Body:
Call:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials.json

or

gcloud auth application-default login

This will configure your environment to use the service account credential you downloaded.


问:
Message: Configured database connection is persistent. Aborting
Codeigniter 2 to 3 version after upgrading, I get this error..
Why would that be?

An uncaught Exception was encountered

Type: Exception

Message: Configured database connection is persistent. Aborting.

Filename: /var/www/vhosts/xxx.com/app/system/libraries/Session/drivers/Session_database_driver.php

Line Number: 94

Backtrace:

File: /var/www/vhosts/xxx.com/app/application/core/MY_Controller.php
Line: 11
Function: __construct

File: /var/www/vhosts/xxx.com/app/application/core/MY_Controller.php
Line: 52
Function: __construct

File: /var/www/vhosts/xxx.com/app/application/controllers/Dashboard.php
Line: 7
Function: __construct

File: /var/www/vhosts/xxx.com/application/index.php
Line: 293
Function: require_once

答:
You need to ensure that FALSE goes out without quotes.If you use 'FALSE', the database driver will take that as a true boolean. The system expects you to use FALSE directly, without quotes. So, unset pconnect instead of using 'FALSE' in order to default to FALSE, or use FALSE as a value if you like to keep things ordered :)</p>

```<code> * Persistent connection flag
 *
 * @var bool
 */
public $pconnect        = FALSE;
</code>```

Body:
You need to ensure that FALSE goes out without quotes.If you use 'FALSE', the database driver will take that as a true boolean. The system expects you to use FALSE directly, without quotes. So, unset pconnect instead of using 'FALSE' in order to default to FALSE, or use FALSE as a value if you like to keep things ordered :)

 * Persistent connection flag
 *
 * @var bool
 */
public $pconnect        = FALSE;


问:
How to handle error states with LiveData?
The new LiveData can be used as a replacement for RxJava's observables in some scenarios. However, unlike Observable, LiveData has no callback for errors.

My question is: How should I handle errors in LiveData, e.g. when it's backed by some network resource that can fail to be retrieved due to an IOException?

答:
In one of Google's sample apps for Android Architecture Components they wrap the LiveData emitted object in a class that can contain a status, data, and message for the emitted object.

https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/main/java/com/android/example/github/vo/Resource.kt

With this approach you can use the status to determine if there was an error.


问:
NZEC error in Python - SPOJ
```<code>def multiply(num1, num2):
    result = num1 * num2
    print(result)
    return result

tc = raw_input("") #testcases
tc = [int(tc)]
#count = [int(count)]
count = 0
while ( count < tc) :
    var1, var2 = raw_input("").split()
    var1, var2 = [int(var1), int(var2)]
    multiply (var1,var2)
    print '\n'`**enter code here**`
    count = count + 1
</code>```

I'm getting NZEC on SPOJ . I'm new to python programming .
Please help me. Thanks in advance . Link to the Question on SPOJ

答:
There are two issues in you code:

Line 7: tc = [int(tc)]

You shouldn't wrap variable tv into the list. You have created a singleton with the number of test cases as an element. Variable tc should be a number, therefore, the line should look like this:

tc = int(tc)

Line 14: print '\n'**enter code here**

You should remove the weird part "**enter code here**".

After mentioned changes your code should be a correct solution to the MUL problem on Spoj.

Title: NZEC error in Python - SPOJ

Body:
def multiply(num1, num2):
    result = num1 * num2
    print(result)
    return result

tc = raw_input("") #testcases
tc = [int(tc)]
#count = [int(count)]
count = 0
while ( count < tc) :
    var1, var2 = raw_input("").split()
    var1, var2 = [int(var1), int(var2)]
    multiply (var1,var2)
    print '\n'`**enter code here**`
    count = count + 1

I'm getting NZEC on SPOJ . I'm new to python programming .
Please help me. Thanks in advance . Link to the Question on SPOJ


问:
Not ordered parsers in Scala parser combinators
I need to parse the words in not ordered way. For now i can see that following

```<code>def first: Parser[String] = ???
def second: Parser[String] = ???
def unordered = (first ~ second) | (second ~ first)
</code>```

But i'm wondering if there's any native solution for that?

答:
The API isn't that big: https://static.javadoc.io/org.scala-lang.modules/scala-parser-combinators_2.12/1.0.6/scala/util/parsing/combinator/Parsers.html and https://static.javadoc.io/org.scala-lang.modules/scala-parser-combinators_2.12/1.0.6/scala/util/parsing/combinator/Parsers$Parser.html

Looking through this, it appears the answer is no, there is no way to do this more simply. This way doesn't seem bad at all, though.

Body:
I need to parse the words in not ordered way. For now i can see that following

def first: Parser[String] = ???
def second: Parser[String] = ???
def unordered = (first ~ second) | (second ~ first)

But i'm wondering if there's any native solution for that?


问:
Does Cython support the ternary style if statement (if ? then : else)?
I forget the technical term for the (if ? then : else) format in C/C++. Also, is this syntax supported in the Cython (a C variant of Python)?

I need to know the technical name so I can lookup if Cython supports this feature.

UPDATE: Does anyone know if Cython supports this?

Solution: In cython/python this is written as (b if a else c) compare to (a ? b : c)

答: ternary operator.</p>

Body: ternary operator.