问:
How to stop insert in a transaction in SQL Server?
Create query using BEGIN TRAN statement to insert two rows within BEGIN TRY if transaction count is greater than 1, catch error and rollback the transaction, otherwise print “transaction committed” (this is my teacher question the idea is that it should not insert more than 1 row by using the @@trancount is greater than one the transaction is rolled back)

This is the code that I wrote

```<code>BEGIN TRY
    BEGIN TRAN;

        INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
        PRINT @@TRANCOUNT

        BEGIN TRAN
            INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
            PRINT @@TRANCOUNT

            IF @@TRANCOUNT > 1
                PRINT 'Rollback the transaction...';
            ELSE
                PRINT 'transaction succeeded';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH;
</code>```

It keeps inserting the two rows even though the trans count is greater than 1

How can I fix this?!!

This is the result

答:
```<code>BEGIN TRY
BEGIN TRAN;
INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
print @@TRANCOUNT
Begin tran
INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
print @@TRANCOUNT
if @@TRANCOUNT>1

PRINT 'Rollback the transaction...';
else
print 'transaction successes';
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH;
GO
</code>```

<p>You are not actually doing a rollback, you're just printing 'Rollback the transaction' change to </p>

```<code>BEGIN TRY
BEGIN TRAN;
INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
print @@TRANCOUNT
Begin tran
INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
print @@TRANCOUNT
if @@TRANCOUNT>1
 begin
  PRINT 'Rollback the transaction...';
  ROLLBACK TRANSACTION
 end
else
print 'transaction successes';
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH;
GO
</code>```

Body:
Create query using BEGIN TRAN statement to insert two rows within BEGIN TRY if transaction count is greater than 1, catch error and rollback the transaction, otherwise print “transaction committed” (this is my teacher question the idea is that it should not insert more than 1 row by using the @@trancount is greater than one the transaction is rolled back)

This is the code that I wrote

BEGIN TRY
    BEGIN TRAN;

        INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
        PRINT @@TRANCOUNT

        BEGIN TRAN
            INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
            PRINT @@TRANCOUNT

            IF @@TRANCOUNT > 1
                PRINT 'Rollback the transaction...';
            ELSE
                PRINT 'transaction succeeded';
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH;

It keeps inserting the two rows even though the trans count is greater than 1

How can I fix this?!!

This is the result

Body:
BEGIN TRY
BEGIN TRAN;
INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
print @@TRANCOUNT
Begin tran
INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
print @@TRANCOUNT
if @@TRANCOUNT>1

PRINT 'Rollback the transaction...';
else
print 'transaction successes';
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH;
GO

You are not actually doing a rollback, you're just printing 'Rollback the transaction' change to

BEGIN TRY
BEGIN TRAN;
INSERT INTO [Info].[Country]([name]) VALUES ('Italy');
print @@TRANCOUNT
Begin tran
INSERT INTO [Info].[Country]([name]) VALUES ('Jorden');
print @@TRANCOUNT
if @@TRANCOUNT>1
 begin
  PRINT 'Rollback the transaction...';
  ROLLBACK TRANSACTION
 end
else
print 'transaction successes';
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH;
GO


来源: stackexchange

问:
Improve regex for capturing files in a directory, excluding dotfiles
I am looking to get all non dot-files in a folder with a particular extension. So far my regex is:

(?<=\/|^)(?<!\.)(\w+(?:\.mov|\.py|))$

Is there a way to improve the above regex? What might be some examples where this regex might not work?

答:
Here's how I would do it:

```<code>(?<=\/|^)[^\/\\:*?"<>|\n]+\.(?:mov|py)$
</code>```

(?<=\/|^) Lookbehind just like you had it

[^\/\\:*?"<>|\n]+ One or more of any character that is not disallowed in filenames

\. A literal dot

(?:mov|py) Either "mov" or "py" in a non-capturing group (similar to yours, but I moved the dot out and excluded the redundant "|")

$ Anchors the search to the end of the line, so only files will match, no folders

ContentLicense: CC BY-SA 4.0

Body:
Here's how I would do it:

(?<=\/|^)[^\/\\:*?"<>|\n]+\.(?:mov|py)$

(?<=\/|^) Lookbehind just like you had it

[^\/\\:*?"<>|\n]+ One or more of any character that is not disallowed in filenames

\. A literal dot

(?:mov|py) Either "mov" or "py" in a non-capturing group (similar to yours, but I moved the dot out and excluded the redundant "|")

$ Anchors the search to the end of the line, so only files will match, no folders


问:
tput cup in python on the commandline
Is there an elegant solution to do this shell script in Python without importing os ?

```<code>    tput cup 14 15; echo -ne "\033[1;32mtest\033[0m" ; tput cup 50 0
</code>```

This just has been gnawing in my mind for some time now :)

Thanks

答:
Given that

you assume ANSI escape sequences

tput cup 14 15 | cat -v displays ^[[15;16H

the whole suggested script results in the following Python script:

```<code>import sys
sys.stdout.write("\033[15;16H\033[1;32mtest\033[m\033[51;1H")
# and a possible sys.stdout.flush() here, depending on your needs
</code>```

ContentLicense: CC BY-SA 3.0

Title: tput cup in python on the commandline

Body:
Is there an elegant solution to do this shell script in Python without importing os ?

    tput cup 14 15; echo -ne "\033[1;32mtest\033[0m" ; tput cup 50 0

This just has been gnawing in my mind for some time now :)

Thanks

Body:
Given that

you assume ANSI escape sequences

tput cup 14 15 | cat -v displays ^[[15;16H

the whole suggested script results in the following Python script:

import sys
sys.stdout.write("\033[15;16H\033[1;32mtest\033[m\033[51;1H")
# and a possible sys.stdout.flush() here, depending on your needs


问:
Group by all columns in a data.table
I'm working with iris data.table in R.

To remind how it looks I paste six five rows here

```<code>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1:          5.1         3.5          1.4         0.2  setosa
2:          4.9         3.0          1.4         0.2  setosa
3:          4.7         3.2          1.3         0.2  setosa
4:          4.6         3.1          1.5         0.2  setosa
5:          5.0         3.6          1.4         0.2  setosa
6:          5.4         3.9          1.7         0.4  setosa
</code>```

I would like to calculate the number of rows, grouped by all columns. Of course we may write all variables in by, like this:

```<code>iris[, .(Freq = .N), by = .(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)]

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species Freq
1:          5.1         3.5          1.4         0.2  setosa    1
2:          4.9         3.0          1.4         0.2  setosa    1
3:          4.7         3.2          1.3         0.2  setosa    1
4:          4.6         3.1          1.5         0.2  setosa    1
5:          5.0         3.6          1.4         0.2  setosa    1
6:          5.4         3.9          1.7         0.4  setosa    1
</code>```

However, I wonder if there is a method to group by all variables without needing to type all the columns names?

答:
We can use

```<code>library(data.table)
out1 <- as.data.table(iris)[, .N, by = names(iris)]
</code>```

-checking with OP's approach

```<code>out2 <-  as.data.table(iris)[,  .N, by = .(Sepal.Length,
      Sepal.Width, Petal.Length, Petal.Width, Species)]
identical(out1, out2)
#[1] TRUE
</code>```

Title: Group by all columns in a data.table

Body:
I'm working with iris data.table in R.

To remind how it looks I paste six five rows here

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1:          5.1         3.5          1.4         0.2  setosa
2:          4.9         3.0          1.4         0.2  setosa
3:          4.7         3.2          1.3         0.2  setosa
4:          4.6         3.1          1.5         0.2  setosa
5:          5.0         3.6          1.4         0.2  setosa
6:          5.4         3.9          1.7         0.4  setosa

I would like to calculate the number of rows, grouped by all columns. Of course we may write all variables in by, like this:

iris[, .(Freq = .N), by = .(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width, Species)]

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species Freq
1:          5.1         3.5          1.4         0.2  setosa    1
2:          4.9         3.0          1.4         0.2  setosa    1
3:          4.7         3.2          1.3         0.2  setosa    1
4:          4.6         3.1          1.5         0.2  setosa    1
5:          5.0         3.6          1.4         0.2  setosa    1
6:          5.4         3.9          1.7         0.4  setosa    1

However, I wonder if there is a method to group by all variables without needing to type all the columns names?

Body:
We can use

library(data.table)
out1 <- as.data.table(iris)[, .N, by = names(iris)]

-checking with OP's approach

out2 <-  as.data.table(iris)[,  .N, by = .(Sepal.Length,
      Sepal.Width, Petal.Length, Petal.Width, Species)]
identical(out1, out2)
#[1] TRUE


问:
What is the best way to work with another repository in my repository?
I have a repository that I'm working on, let's call it Super. I need code from an open-source repository, let's call it Dep, in Super's repository. I need to be able to pull from Dep's original repository in case there are any changes, and I need to be able to make additions to Dep's code and push them to Super's repository. What is the best way to do this?

I've tried looking at sub-modules but I can't make changes to the module and push them onto Super's repository. I also tried just cloning Dep into Super's repository, but then I can't pull from Dep's repository.

答: I'd suggest you fork Dep, so that you can make changes into it, make pull requests, etc.


问:
How to limit DBA_AUDIT_TRAIL activity visibility by schema or other possibilities to see activity for targeted schemas
I am asking the DBA to turn on DBA_AUDIT_TRAIL logging and I am getting push back.  In some environments, I see change activity logged when I query this table, in other environments, I do not.

I am only interested in a handful of schemas. In my opinion, if my visibility of this table could be limited to the schemas that I have an interest in tracking, then there might potentially be less resistance to granting me access. What is the best way to grant me access to only the objects in a target schema list? Is there an alternate view that I could be granted access to?

Is there an existing Oracle view that limits row activity to only those objects that a user otherwise has visibility to or do we have to create our own view or more primitively, say, create a view like this

```<code>SELECT * FROM DBA_AUDIT_TRAIL WHERE OWNER IN ('schema1','schema2')
</code>```

and limit SELECT access to the view? I'm not sure if this query is returning no rows in some envs because logging isn't turned on or whether I just don't have the proper access.

答:
I have not found an alternative view based on DBA_AUDIT_TRAIL ou UNIFIED_AUDIT_TRAIL.

I think that the solution is to create your own views with limited privileges.

Your DBA should be able to tell you if auditing is enabled or not, with or without unified audit trail and what is audited: actually he/she is very likely the only one being able to check this (unless there is some kind of separate role for database security administration).

Body:
I am asking the DBA to turn on DBA_AUDIT_TRAIL logging and I am getting push back.  In some environments, I see change activity logged when I query this table, in other environments, I do not.

I am only interested in a handful of schemas. In my opinion, if my visibility of this table could be limited to the schemas that I have an interest in tracking, then there might potentially be less resistance to granting me access. What is the best way to grant me access to only the objects in a target schema list? Is there an alternate view that I could be granted access to?

Is there an existing Oracle view that limits row activity to only those objects that a user otherwise has visibility to or do we have to create our own view or more primitively, say, create a view like this

SELECT * FROM DBA_AUDIT_TRAIL WHERE OWNER IN ('schema1','schema2')

and limit SELECT access to the view? I'm not sure if this query is returning no rows in some envs because logging isn't turned on or whether I just don't have the proper access.


问:
Any way to create the unmemo-monad?
Suppose someone makes a program to play chess, or solve sudoku. In this kind of program it makes sense to have a tree structure representing game states.

This tree would be very large, "practically infinite". Which isn't by itself a problem as Haskell supports infinite data structures.

An familiar example of an infinite data structure:

```<code>fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
</code>```

Nodes are only allocated when first used, so the list takes finite memory. One may also iterate over an infinite list if they don't keep references to its head, allowing the garbage collector to collect its parts which are not needed anymore.

Back to the tree example - suppose one does some iteration over the tree, the tree nodes iterated over may not be freed if the root of the tree is still needed (for example in an iterative deepening search, the tree would be iterated over several times and so the root needs to be kept).

One possible solution for this problem that I thought of is using an "unmemo-monad".

I'll try to demonstrate what this monad is supposed to do using monadic lists:

```<code>import Control.Monad.ListT (ListT)  -- cabal install List
import Data.Copointed  -- cabal install pointed
import Data.List.Class
import Prelude hiding (enumFromTo)

nums :: ListT Unmemo Int  -- What is Unmemo?
nums = enumFromTo 0 1000000

main = print $ div (copoint (foldlL (+) 0 nums)) (copoint (lengthL nums))
</code>```

Using nums :: [Int], the program would take a lot of memory as a reference to nums is needed by lengthL nums while it is being iterated over foldlL (+) 0 nums.

The purpose of Unmemo is to make the runtime not keep the nodes iterated over.

I attempted using ((->) ()) as Unmemo, but it yields the same results as nums :: [Int] does - the program uses a lot of memory, as evident by running it with +RTS -s.

Is there anyway to implement Unmemo that does what I want?

答:
Same trick as with a stream -- don't capture the remainder directly, but instead capture a value and a function which yields a remainder. You can add memoization on top of this as necessary.

```<code>data UTree a = Leaf a | Branch a (a -> [UTree a])
</code>```

I'm not in the mood to figure it out precisely at the moment, but this structure arises, I'm sure, naturally as the cofree comonad over a fairly straightforward functor.

Edit

Found it: http://hackage.haskell.org/packages/archive/comonad-transformers/1.6.3/doc/html/Control-Comonad-Trans-Stream.html

Or this is perhaps simpler to understand: http://hackage.haskell.org/packages/archive/streams/0.7.2/doc/html/Data-Stream-Branching.html

In either case, the trick is that your f can be chosen to be something like data N s a = N (s -> (s,[a])) for an appropriate s (s being the type of your state parameter of the stream -- the seed of your unfold, if you will). That might not be exactly correct, but something close should do...

But of course for real work, you can scrap all this and just write the datatype directly as above.

Edit 2

The below code illustrates how this can prevent sharing. Note that even in the version without sharing, there are humps in the profile indicating that the sum and length calls aren't running in constant space. I'd imagine that we'd need an explicit strict accumulation to knock those down.

```<code>{-# LANGUAGE DeriveFunctor #-}
import Data.Stream.Branching(Stream(..))
import qualified Data.Stream.Branching as S
import Control.Arrow
import Control.Applicative
import Data.List

data UM s a = UM (s -> Maybe a) deriving Functor
type UStream s a = Stream (UM s) a

runUM s (UM f) = f s
liftUM x = UM $ const (Just x)
nullUM = UM $ const Nothing

buildUStream :: Int -> Int -> Stream (UM ()) Int
buildUStream start end = S.unfold (\x -> (x, go x)) start
    where go x
           | x < end = liftUM (x + 1)
           | otherwise = nullUM

sumUS :: Stream (UM ()) Int -> Int
sumUS x = S.head $ S.scanr (\x us -> maybe 0 id (runUM () us) + x) x

lengthUS :: Stream (UM ()) Int -> Int
lengthUS x = S.head $ S.scanr (\x us -> maybe 0 id (runUM () us) + 1) x

sumUS' :: Stream (UM ()) Int -> Int
sumUS' x = last $ usToList $ liftUM $ S.scanl (+) 0  x

lengthUS' :: Stream (UM ()) Int -> Int
lengthUS' x = last $ usToList $ liftUM $ S.scanl (\acc _ -> acc + 1) 0 x

usToList x = unfoldr (\um -> (S.head &&& S.tail) <$> runUM () um) x

maxNum = 1000000
nums = buildUStream 0 maxNum

numsL :: [Int]
numsL = [0..maxNum]

-- All these need to be run with increased stack to avoid an overflow.

-- This generates an hp file with two humps (i.e. the list is not shared)
main = print $ div (fromIntegral $ sumUS' nums) (fromIntegral $ lengthUS' nums)

-- This generates an hp file as above, and uses somewhat less memory, at the cost of
-- an increased number of GCs. -H helps a lot with that.
-- main = print $ div (fromIntegral $ sumUS nums) (fromIntegral $ lengthUS nums)

-- This generates an hp file with one hump (i.e. the list is shared)
-- main = print $ div (fromIntegral $ sum $ numsL) (fromIntegral $ length $ numsL)
</code>```

Title: Any way to create the unmemo-monad?

Body:
Suppose someone makes a program to play chess, or solve sudoku. In this kind of program it makes sense to have a tree structure representing game states.

This tree would be very large, "practically infinite". Which isn't by itself a problem as Haskell supports infinite data structures.

An familiar example of an infinite data structure:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

Nodes are only allocated when first used, so the list takes finite memory. One may also iterate over an infinite list if they don't keep references to its head, allowing the garbage collector to collect its parts which are not needed anymore.

Back to the tree example - suppose one does some iteration over the tree, the tree nodes iterated over may not be freed if the root of the tree is still needed (for example in an iterative deepening search, the tree would be iterated over several times and so the root needs to be kept).

One possible solution for this problem that I thought of is using an "unmemo-monad".

I'll try to demonstrate what this monad is supposed to do using monadic lists:

import Control.Monad.ListT (ListT)  -- cabal install List
import Data.Copointed  -- cabal install pointed
import Data.List.Class
import Prelude hiding (enumFromTo)

nums :: ListT Unmemo Int  -- What is Unmemo?
nums = enumFromTo 0 1000000

main = print $ div (copoint (foldlL (+) 0 nums)) (copoint (lengthL nums))

Using nums :: [Int], the program would take a lot of memory as a reference to nums is needed by lengthL nums while it is being iterated over foldlL (+) 0 nums.

The purpose of Unmemo is to make the runtime not keep the nodes iterated over.

I attempted using ((->) ()) as Unmemo, but it yields the same results as nums :: [Int] does - the program uses a lot of memory, as evident by running it with +RTS -s.

Is there anyway to implement Unmemo that does what I want?

Body:
Same trick as with a stream -- don't capture the remainder directly, but instead capture a value and a function which yields a remainder. You can add memoization on top of this as necessary.

data UTree a = Leaf a | Branch a (a -> [UTree a])

I'm not in the mood to figure it out precisely at the moment, but this structure arises, I'm sure, naturally as the cofree comonad over a fairly straightforward functor.

Edit

Found it: http://hackage.haskell.org/packages/archive/comonad-transformers/1.6.3/doc/html/Control-Comonad-Trans-Stream.html

Or this is perhaps simpler to understand: http://hackage.haskell.org/packages/archive/streams/0.7.2/doc/html/Data-Stream-Branching.html

In either case, the trick is that your f can be chosen to be something like data N s a = N (s -> (s,[a])) for an appropriate s (s being the type of your state parameter of the stream -- the seed of your unfold, if you will). That might not be exactly correct, but something close should do...

But of course for real work, you can scrap all this and just write the datatype directly as above.

Edit 2

The below code illustrates how this can prevent sharing. Note that even in the version without sharing, there are humps in the profile indicating that the sum and length calls aren't running in constant space. I'd imagine that we'd need an explicit strict accumulation to knock those down.

{-# LANGUAGE DeriveFunctor #-}
import Data.Stream.Branching(Stream(..))
import qualified Data.Stream.Branching as S
import Control.Arrow
import Control.Applicative
import Data.List

data UM s a = UM (s -> Maybe a) deriving Functor
type UStream s a = Stream (UM s) a

runUM s (UM f) = f s
liftUM x = UM $ const (Just x)
nullUM = UM $ const Nothing

buildUStream :: Int -> Int -> Stream (UM ()) Int
buildUStream start end = S.unfold (\x -> (x, go x)) start
    where go x
           | x < end = liftUM (x + 1)
           | otherwise = nullUM

sumUS :: Stream (UM ()) Int -> Int
sumUS x = S.head $ S.scanr (\x us -> maybe 0 id (runUM () us) + x) x

lengthUS :: Stream (UM ()) Int -> Int
lengthUS x = S.head $ S.scanr (\x us -> maybe 0 id (runUM () us) + 1) x

sumUS' :: Stream (UM ()) Int -> Int
sumUS' x = last $ usToList $ liftUM $ S.scanl (+) 0  x

lengthUS' :: Stream (UM ()) Int -> Int
lengthUS' x = last $ usToList $ liftUM $ S.scanl (\acc _ -> acc + 1) 0 x

usToList x = unfoldr (\um -> (S.head &&& S.tail) <$> runUM () um) x

maxNum = 1000000
nums = buildUStream 0 maxNum

numsL :: [Int]
numsL = [0..maxNum]

-- All these need to be run with increased stack to avoid an overflow.

-- This generates an hp file with two humps (i.e. the list is not shared)
main = print $ div (fromIntegral $ sumUS' nums) (fromIntegral $ lengthUS' nums)

-- This generates an hp file as above, and uses somewhat less memory, at the cost of
-- an increased number of GCs. -H helps a lot with that.
-- main = print $ div (fromIntegral $ sumUS nums) (fromIntegral $ lengthUS nums)

-- This generates an hp file with one hump (i.e. the list is shared)
-- main = print $ div (fromIntegral $ sum $ numsL) (fromIntegral $ length $ numsL)


问:
nodejs session variable undefined
I have created a session variable in the login request but unable to access it in logout request(it is undefined).
I want users only that have logged in to request a logout ,if someone who has not logged on requests a logout then ill redirect them to login page.I am using express-session as middleware in the code below.
Here is the session code

```<code>var app = express();
app.set('trust proxy', 1); // trust first proxy
app.use(session({
  secret: 'nikhilsingh',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));
</code>```

Here is the login function

```<code> app.post('/login',bodyparserencoder,function(req,res){

        console.log('login requested');
        let query=require('../'+'dbconnect/'+'login.js');
        let exists=query.login({username:req.body.Username,password:req.body.Password},res,req);
        console.log('everything done, exists= ' + exists);
        req.session.loggedin=true;
});
</code>```

here is the logout

```<code>app.get('/logout',function(req,res){
    console.log(req.session.loggedin);
    if(req.session.loggedin){
    console.log('logout requested');
    res.render('Addmie.ejs');}
    else{
        console.log('login to continue');
    }
});
</code>```

I am new to nodejs ,please ellaborate and explain if I am doing something wrong.Thanks.

答: I solver this problem by removing the secure attribute from cookie object,anyways I did not understand what actually was causing the problem.</p>

Title: nodejs session variable undefined

Body:
I have created a session variable in the login request but unable to access it in logout request(it is undefined).
I want users only that have logged in to request a logout ,if someone who has not logged on requests a logout then ill redirect them to login page.I am using express-session as middleware in the code below.
Here is the session code

var app = express();
app.set('trust proxy', 1); // trust first proxy
app.use(session({
  secret: 'nikhilsingh',
  resave: false,
  saveUninitialized: true,
  cookie: { secure: true }
}));

Here is the login function

 app.post('/login',bodyparserencoder,function(req,res){

        console.log('login requested');
        let query=require('../'+'dbconnect/'+'login.js');
        let exists=query.login({username:req.body.Username,password:req.body.Password},res,req);
        console.log('everything done, exists= ' + exists);
        req.session.loggedin=true;
});

here is the logout

app.get('/logout',function(req,res){
    console.log(req.session.loggedin);
    if(req.session.loggedin){
    console.log('logout requested');
    res.render('Addmie.ejs');}
    else{
        console.log('login to continue');
    }
});

I am new to nodejs ,please ellaborate and explain if I am doing something wrong.Thanks.


问:
Issue with HomeController showing undefined method
I am trying to pass stored_products from shopify into a Rails app but keep getting a home controller error at https://f588240c.ngrok.io/ i have made updates, with no luck and restarted the server a number of times with no luck.

Any help would be welcomed. Heres the code

```<code>class Api::V1::HomeController < ShopifyApp::AuthenticatedController
def index
@products = ShopifyAPI::Product.find(:all, params: { limit: 10 })

@products.each do |product|
      StoredProduct.where(shopify_id: product.id)
      .first_or_create do |stored_product|
        stored_product.shopify_id = product.id
        stored_product.shopify_title = product.title
        stored_product.shopify_handle = product.handle
        stored_product.shopify_image_url = product.image.src
        stored_product.shop_id = @shop.id
        stored_product.save

        product.images.each do |image|
          ProductImage.where(shopify_id: image.id)
            .first_or_create do |product_image|
              product_image.image_url = image.src
              product_image.stored_product_id = stored_product_id
              product_image.shopify_id = image.id
          end
        end

      end
    end
  @stored_products = StoredProduct.belongs_to_shop(@shop.id)
  end
end
</code>```

From the authenticated controller

```<code>    private
      def set_shop
        @shop = Shop.find_by(id: session[:shopify])
        set_locale
      end
</code>```

from the store_products.rb file

```<code>class StoredProduct < ApplicationRecord
  belongs_to :shop
  has_many :product_images

  scope :belongs_to_shop, -> shop_id { where(shop_id: shop_id) }
end
</code>```

答:
For this specific issue/code tutorial, the private set_shop method should be set like follows:

```<code>def set_shop
  @shop = Shop.find_by(id: session[:shop_id])
  set_locale
end
</code>```

The other answer has params instead of session

Body:
I am trying to pass stored_products from shopify into a Rails app but keep getting a home controller error at https://f588240c.ngrok.io/ i have made updates, with no luck and restarted the server a number of times with no luck.

Any help would be welcomed. Heres the code

class Api::V1::HomeController < ShopifyApp::AuthenticatedController
def index
@products = ShopifyAPI::Product.find(:all, params: { limit: 10 })

@products.each do |product|
      StoredProduct.where(shopify_id: product.id)
      .first_or_create do |stored_product|
        stored_product.shopify_id = product.id
        stored_product.shopify_title = product.title
        stored_product.shopify_handle = product.handle
        stored_product.shopify_image_url = product.image.src
        stored_product.shop_id = @shop.id
        stored_product.save

        product.images.each do |image|
          ProductImage.where(shopify_id: image.id)
            .first_or_create do |product_image|
              product_image.image_url = image.src
              product_image.stored_product_id = stored_product_id
              product_image.shopify_id = image.id
          end
        end

      end
    end
  @stored_products = StoredProduct.belongs_to_shop(@shop.id)
  end
end

From the authenticated controller

    private
      def set_shop
        @shop = Shop.find_by(id: session[:shopify])
        set_locale
      end

from the store_products.rb file

class StoredProduct < ApplicationRecord
  belongs_to :shop
  has_many :product_images

  scope :belongs_to_shop, -> shop_id { where(shop_id: shop_id) }
end

Body:
For this specific issue/code tutorial, the private set_shop method should be set like follows:

def set_shop
  @shop = Shop.find_by(id: session[:shop_id])
  set_locale
end

The other answer has params instead of session


问:
Is it possible to generate random numbers through physical process simulation?
Is it possible to generate random numbers through physical process simulation?

If I simulate the physical roll of a dice (i.e. you picking it up, shaking it in your hand, releasing it onto the table and recording which side ends up "up"...) will that produce a "random" number or would I just have a complex simulation which really accomplishes nothing.

答:
You would have a complex simulation which really accomplishes nothing.

(other than to return the same value every time, or add unnecessary complexity to an existing PRNG)

Unless you seed the simulated environment with "random" variables (i.e. depend on a different means of generating random numbers), you will always get the same value back, because every step  in the process will happen the same way every time.

Say you did use a base pseudo random number generator (PRNG):

Since your simulation would only be as random as the other PRNG you were using, you may as well just use the other PRNG directly, without all the extra work!  (In fact, your simulation may not do anything except make the output less random than the values from your base PRNG)

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Daniel L

LastEditorDisplayName: Daniel L


问:
Pyspark crossjoin between 2 dataframes with millions of records
I have 2 dataframes A(35 Million records) and B(30000 records)

A

```<code>|Text |
-------
| pqr  |
-------
| xyz  |
-------
</code>```

B

```<code>|Title |
-------
| a  |
-------
| b  |
-------
| c  |
-------
</code>```

Below dataframe C is obtained after a crossjoin between A and B.

```<code>c = A.crossJoin(B, on = [A.text == B.Title)
</code>```

C

```<code>|text | Title |
---------------
| pqr  | a    |
---------------
| pqr  | b    |
---------------
| pqr  | c    |
---------------
| xyz  | a    |
---------------
| xyz  | b    |
---------------
| xyz  | c    |
---------------
</code>```

Both the columns above are of type String.

I am performing the below operation and it results in an Spark error(Job aborted due to stage failure)

```<code>display(c.withColumn("Contains", when(col('text').contains(col('Title')), 1).otherwise(0)).filter(col('Contains') == 0).distinct())

</code>```

Any suggestions on how this join needs to be done to avoid the Spark error() on the resulting operations?

Spark error message

答:
try using broadcast joins

```<code>from pyspark.sql.functions import broadcast
c = broadcast(A).crossJoin(B)
</code>```

If you don't need and extra column "Contains" column thne you can just filter it as

```<code>display(c.filter(col("text").contains(col("Title"))).distinct())
</code>```

Body:
I have 2 dataframes A(35 Million records) and B(30000 records)

A

|Text |
-------
| pqr  |
-------
| xyz  |
-------

B

|Title |
-------
| a  |
-------
| b  |
-------
| c  |
-------

Below dataframe C is obtained after a crossjoin between A and B.

c = A.crossJoin(B, on = [A.text == B.Title)

C

|text | Title |
---------------
| pqr  | a    |
---------------
| pqr  | b    |
---------------
| pqr  | c    |
---------------
| xyz  | a    |
---------------
| xyz  | b    |
---------------
| xyz  | c    |
---------------

Both the columns above are of type String.

I am performing the below operation and it results in an Spark error(Job aborted due to stage failure)

display(c.withColumn("Contains", when(col('text').contains(col('Title')), 1).otherwise(0)).filter(col('Contains') == 0).distinct())

Any suggestions on how this join needs to be done to avoid the Spark error() on the resulting operations?

Spark error message

Body:
try using broadcast joins

from pyspark.sql.functions import broadcast
c = broadcast(A).crossJoin(B)

If you don't need and extra column "Contains" column thne you can just filter it as

display(c.filter(col("text").contains(col("Title"))).distinct())


问:
ask deploy hangs while deploying to lambda
I have manually deployed a number of Alexa skills using a lambda backend and understand the manual process, however I am new to using the ask cli v2.

I believe I have all of the steps in the guide as far as having both ask and aws cli set. I have set my roles in AWS.

I am currently just trying to get used to the process and running

```<code>ask new
</code>```

changing the invocation and then running

```<code>ask deploy
</code>```

Everything runs seemingly correct until

Skill code built successfully.
  Code for region default built to C:\location\projectName.ask\lambda\build.zip successfully with build flow nodejs-npm.

==================== Deploy Skill Infrastructure ====================
  / Deploy Alexa skill infrastructure for region "default"
→ No IAM role exists. Creating an IAM role...

And then we just wait... forever.

The AWS CLI profile has IAMFullAccess to create roles as needed.

What am I missing?

答:
So It ended up being an issue somewhere between permissions on my aws role and the configuration. I changed which role I was using and re-configured ask and aws.

I am not exactly sure where things were fixed because I immediately ran into another error that ended up being a bit of a rabbit hole. That I will describe here because it is common enough and could be seen while trouble shooting my original issue.

The issue I ran into is was when the deploy would happen successfully I could not test with the code that made it to my lambda. In cloud watch it presented as

```<code>"Runtime.ImportModuleError: Error: Cannot find module './dispatcher/error/mapper/GenericErrorMapper'"
</code>```

This ended up being a bug within powershell and compressing to .zip on windows and being unpacked on linux.

I had to run

```<code>Install-Module Microsoft.PowerShell.Archive -MinimumVersion 1.2.3.0 -Repository PSGallery -Force
</code>```

https://github.com/PowerShell/PowerShell/issues/2140

This fixed my final issue.

Body:
I have manually deployed a number of Alexa skills using a lambda backend and understand the manual process, however I am new to using the ask cli v2.

I believe I have all of the steps in the guide as far as having both ask and aws cli set. I have set my roles in AWS.

I am currently just trying to get used to the process and running

ask new

changing the invocation and then running

ask deploy

Everything runs seemingly correct until

Skill code built successfully.
  Code for region default built to C:\location\projectName.ask\lambda\build.zip successfully with build flow nodejs-npm.

==================== Deploy Skill Infrastructure ====================
  / Deploy Alexa skill infrastructure for region "default"
→ No IAM role exists. Creating an IAM role...

And then we just wait... forever.

The AWS CLI profile has IAMFullAccess to create roles as needed.

What am I missing?

Body:
So It ended up being an issue somewhere between permissions on my aws role and the configuration. I changed which role I was using and re-configured ask and aws.

I am not exactly sure where things were fixed because I immediately ran into another error that ended up being a bit of a rabbit hole. That I will describe here because it is common enough and could be seen while trouble shooting my original issue.

The issue I ran into is was when the deploy would happen successfully I could not test with the code that made it to my lambda. In cloud watch it presented as

"Runtime.ImportModuleError: Error: Cannot find module './dispatcher/error/mapper/GenericErrorMapper'"

This ended up being a bug within powershell and compressing to .zip on windows and being unpacked on linux.

I had to run

Install-Module Microsoft.PowerShell.Archive -MinimumVersion 1.2.3.0 -Repository PSGallery -Force

https://github.com/PowerShell/PowerShell/issues/2140

This fixed my final issue.


问:
Query using from / to tables
I have one from / to table which has some data like this:

```<code>FROM                 | TO
---------------------+----------------
Apple iPhone SE 64GB | IPHONE SE 64GB
</code>```

And I have two other tables which are populated with data from the FROM and from the TO columns respectively:

Table 1:

```<code>Device               | price
---------------------+--------
Apple iPhone SE 64GB | xxxx
</code>```

Table 2:

```<code>Device         | Price
---------------+--------
IPHONE SE 64GB | XXXX
</code>```

Sometimes, using a web scraper, the tables 1 and two get populated by values which won't exist in the From To table. For example:

Table 1:

```<code>Device         | price
---------------+--------
Samsung Flip Z | xxxx
</code>```

Table 2:

```<code>Device                    | Price
--------------------------+--------
Smartphone Samsung Flip Z | XXXX
</code>```

So, I'd have to insert one record inside the From To table like this:

```<code>FROM           | TO
---------------+----------------------------
Samsung Flip Z | Smartphone Samsung Flip Z
</code>```

So, given these three tables, is it possible to have a query to find out which values are and which values are not in the From To Table? Because we have to fill it periodically.

答:
you could use left join where don't match

```<code>  select t1.device
  from table1 t1
  left join  table_from_to  tft on t1.device = tft.[from]
  where table tft.[from] is null
</code>```

anyway FROM is reserved word so you should use square brackets better use another word

Title: Query using from / to tables

Body:
I have one from / to table which has some data like this:

FROM                 | TO
---------------------+----------------
Apple iPhone SE 64GB | IPHONE SE 64GB

And I have two other tables which are populated with data from the FROM and from the TO columns respectively:

Table 1:

Device               | price
---------------------+--------
Apple iPhone SE 64GB | xxxx

Table 2:

Device         | Price
---------------+--------
IPHONE SE 64GB | XXXX

Sometimes, using a web scraper, the tables 1 and two get populated by values which won't exist in the From To table. For example:

Table 1:

Device         | price
---------------+--------
Samsung Flip Z | xxxx

Table 2:

Device                    | Price
--------------------------+--------
Smartphone Samsung Flip Z | XXXX

So, I'd have to insert one record inside the From To table like this:

FROM           | TO
---------------+----------------------------
Samsung Flip Z | Smartphone Samsung Flip Z

So, given these three tables, is it possible to have a query to find out which values are and which values are not in the From To Table? Because we have to fill it periodically.

Body:
you could use left join where don't match

  select t1.device
  from table1 t1
  left join  table_from_to  tft on t1.device = tft.[from]
  where table tft.[from] is null

anyway FROM is reserved word so you should use square brackets better use another word


问:
SKBitmap.Decode(imageStream) is returning null
I am trying to use skiasharp to edit an image I have as a stream, but when I try to turn it into an SKBitmap the resulting variable is always none. I am using Xam.Plugin.Media to get the image.

```<code>var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { SaveToAlbum = false });

if (photo != null)
{
    var imageStream = photo.GetStream();
    SKBitmap bitmap = SKBitmap.Decode(imageStream);
    using (SKPaint textPaint = new SKPaint { TextSize = 48 })
    using (SKCanvas canvas = new SKCanvas(bitmap))
    {
        canvas.DrawText("test", 0, 0, textPaint);
    }

    SKImage image = SKImage.FromBitmap(bitmap);
    SKData encoded = image.Encode();
    Stream stream = encoded.AsStream();

    PhotoImage.Source = ImageSource.FromStream(() => { return stream; });
}
</code>```

答:
I add this line after obtaining a stream with
var imageStream = photo.GetStream();

```<code>imageStream.seek(0, SeekOrigin.Begin);
</code>```

Body:
I am trying to use skiasharp to edit an image I have as a stream, but when I try to turn it into an SKBitmap the resulting variable is always none. I am using Xam.Plugin.Media to get the image.

var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { SaveToAlbum = false });

if (photo != null)
{
    var imageStream = photo.GetStream();
    SKBitmap bitmap = SKBitmap.Decode(imageStream);
    using (SKPaint textPaint = new SKPaint { TextSize = 48 })
    using (SKCanvas canvas = new SKCanvas(bitmap))
    {
        canvas.DrawText("test", 0, 0, textPaint);
    }

    SKImage image = SKImage.FromBitmap(bitmap);
    SKData encoded = image.Encode();
    Stream stream = encoded.AsStream();

    PhotoImage.Source = ImageSource.FromStream(() => { return stream; });
}

Body:
I add this line after obtaining a stream with
var imageStream = photo.GetStream();

imageStream.seek(0, SeekOrigin.Begin);


问:
How does .apply work on a Pandas DataFrame.groupby?
```<code>              Count
League  Result
EPL     H      16
        D      9
        A      10
Champ   H      67
        D      15
        A      57
        H      87
La Liga D      35
        A      40

</code>```

I have a breakdown of football results for different leagues and a count of how many times that result occurred.

I want to see the proportion of home wins, draws, away wins as a percentage of the total games played. I have seen a solution to this below:

```<code>df.groupby("League").apply(lambda g: (g/g.sum()*100)
</code>```

At first glance, this made sense, but what exactly is g here? I assumed it was the H, D or A count and then the g.sum() summed all of the H,D,A counts grouped by each division. But, if g is just a value, how are we calling the method g.sum()? What exactly is g here?

答:
g is a DataFrame. Since you group on 'League' you will split the DataFrame up into separate chunks which contain the unique values of 'League'. To illustrate this, we can iterate over the GroupBy object.

```<code>for idx, g in df.groupby('League'):  # `idx` is the unique group key
    print(g, '\n')
</code>```

```<code>               Count
League Result
Champ  H          67
       D          15
       A          57
       H          87

               Count
League Result
EPL    H          16
       D           9
       A          10

                Count
League  Result
La Liga D          35
        A          40
</code>```

The apply then acts to apply your function to each of these DataFrame separately. Calling g.sum() will give you a Series that sums each column within the group.

```<code>for idx, g in df.groupby('League'):
    print(g.sum(), '\n')

Count    226
dtype: int64

Count    35
dtype: int64

Count    75
dtype: int64
</code>```

Body:
              Count
League  Result
EPL     H      16
        D      9
        A      10
Champ   H      67
        D      15
        A      57
        H      87
La Liga D      35
        A      40

I have a breakdown of football results for different leagues and a count of how many times that result occurred.

I want to see the proportion of home wins, draws, away wins as a percentage of the total games played. I have seen a solution to this below:

df.groupby("League").apply(lambda g: (g/g.sum()*100)

At first glance, this made sense, but what exactly is g here? I assumed it was the H, D or A count and then the g.sum() summed all of the H,D,A counts grouped by each division. But, if g is just a value, how are we calling the method g.sum()? What exactly is g here?

Body:
g is a DataFrame. Since you group on 'League' you will split the DataFrame up into separate chunks which contain the unique values of 'League'. To illustrate this, we can iterate over the GroupBy object.

for idx, g in df.groupby('League'):  # `idx` is the unique group key
    print(g, '\n')

               Count
League Result
Champ  H          67
       D          15
       A          57
       H          87

               Count
League Result
EPL    H          16
       D           9
       A          10

                Count
League  Result
La Liga D          35
        A          40

The apply then acts to apply your function to each of these DataFrame separately. Calling g.sum() will give you a Series that sums each column within the group.

for idx, g in df.groupby('League'):
    print(g.sum(), '\n')

Count    226
dtype: int64

Count    35
dtype: int64

Count    75
dtype: int64


问:
Google API returns Nothing when uploaded file greater than approx 30MB using PHP
Why my PHP code returns nothing while uploading file greater than 30MB approx, but it works on localhost the problem is in Server Side. Sometime it says 503 error or err: NET CONNECTION RESET.
but mostly returns nothing.

when i upload file that are less than 25MB they get uploaded pretty quietly.

And also if someone can help me with the progress bar while data is been uploading in drive , in my code the progress is showing but after the file is been uploaded, not while uploading(I read about the getURI and ... but didn't understood properly) can anyone guide me here too?

I am using V3 of Google-drive-api.

INDEX.php

```<code><!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8">

    <title>Google Drive Example App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script>
        $(function () {
            $('#btn').click(function () {
                $('.myprogress').css('width', '0');
                $('.msg').text('');
                var filename = $('#filename').val();
                var myfile = $('#myfile').val();
                var discription = $('#discription').val();
                if (filename == '' || myfile == '') {
                    alert('Please enter file name and select file');
                    return;
                }
                var formData = new FormData();
                formData.append('pdf', $('#myfile')[0].files[0]);
                formData.append('name', filename);
                formData.append('discription', discription);
                $('#btn').attr('disabled', 'disabled');
                 $('.msg').text('Uploading in progress...');
                $.ajax({
                    url: 'action.php',
                    data: formData,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    // this part is progress bar
                    xhr: function () {
                        var xhr = new window.XMLHttpRequest();
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                percentComplete = parseInt(percentComplete * 100);
                                $('.myprogress').text(percentComplete + '%');
                                $('.myprogress').css('width', percentComplete + '%');
                            }
                        }, false);
                        return xhr;
                    },
                    success: function (data) {
                        $('.msg').text(data);
                        $('#btn').removeAttr('disabled');
                    }
                });
            });
        });

    </script>
 </head>
 <body>
      <div class="container">
            <div class="row">
                <h3>File Upload</h3>
                <form id="myform" method="post">
                    <div class="form-group">
                        <label>File name: </label>
                        <input class="form-control" type="text" id="filename" />
                    </div>
                    <div class="form-group">
                        <label>File Discription: </label>
                        <input class="form-control" type="text" id="discription" />
                    </div>
                    <div class="form-group">
                        <label>Select file: </label>
                        <input class="form-control" type="file" id="myfile" />
                    </div>
                    <div class="form-group">
                        <div class="progress">
                            <div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
                        </div>
                        <div class="msg"></div>
                    </div>
                    <input type="button" id="btn" class="btn-success" value="Upload" />
                </form>
            </div>
        </div>
    </body>

</html>
</code>```

ACTION.php

```<code><?php

   ini_set('upload_max_filesize', '1000M');
   ini_set('post_max_size', '1000M');
   set_time_limit(5000);

if(isset($_FILES['pdf']) && isset($_POST['name'])){
    $name = $_POST['name'];
    if($name == ''){
        echo "file name is Empty";
    }else{
        $discription = $_POST['discription'];
        $target_dir = "files/";
        $file_name = basename($_FILES["pdf"]["name"]);
        $filesize = $_FILES['pdf']['size'];
        $FileType = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
        $file = "test_file.".$FileType;
        $file_path = $target_dir . $file;
        $tmpname = $_FILES['pdf']['tmp_name'];
        $upload = move_uploaded_file($tmpname, $file_path);

        if($upload == true){
            include_once __DIR__ . '/google-api-php-client-master/vendor/autoload.php';
            $client = new Google_Client();
            $client->setAuthConfig('credentials.json');
            $client->addScope('https://www.googleapis.com/auth/drive.file');

            $service = new Google_Service_Drive($client);
            $service = new Google_Service_Drive($client);
            $client->getAccessToken();

            $file = new Google_Service_Drive_DriveFile();
            $chunkSizeBytes = 1 * 1024 * 1024;
            $client->setDefer(true);

            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            $parentId = "PARENT_FOLDER_ID";
            $file->setParents(array($parentId));

            $mime_type = finfo_file($finfo, $file_path);
            $file->setName($name);
            $file->setDescription($discription);

            $response = $service->files->create($file);

            // Create a media file upload to represent our upload process.
            $media = new Google_Http_MediaFileUpload(
              $client,
              $response,
              $mime_type,
              null,
              true,
              $chunkSizeBytes
            );
            $media->setFileSize(filesize($file_path));

            function readVideoChunk ($handle, $chunkSize){
                $byteCount = 0;
                $giantChunk = "";
                while (!feof($handle)) {
                    $chunk = fread($handle, $chunkSize);
                    $byteCount += strlen($chunk);
                    $giantChunk .= $chunk;
                    if ($byteCount >= $chunkSize)
                    {
                        return $giantChunk;
                    }
                }
                return $giantChunk;
            }

            // Upload the various chunks. $status will be false until the process is complete.
            $status = false;
            $handle = fopen($file_path, "rb");
            while (!$status && !feof($handle)) {
                // An example of a read buffered file is when reading from a URL
                $chunk = readVideoChunk($handle, $chunkSizeBytes);
                $status = $media->nextChunk($chunk);
               //if want to show the progress bar too but not working while uploading , but it shows the uploaded chunks after the files is been uploaded.
                if(!$status){ //nextChunk() returns 'false' whenever the upload is still in progress
                    echo 'sucessfully uploaded file up to byte ' . $media->getProgress() . ' which is ' . ( $media->getProgress() / $chunkSizeBytes ) . '% of the whole file';
                }
            }
            $result = false;
            if ($status != false) {
                $result = $status;
            }

            $file_id = $status['id'];

            fclose($handle);

            // Reset to the client to execute requests immediately in the future.
            $client->setDefer(false);
           //i am manually creating the wbViewLink by the ID i am getting in response
            $webViewLink = "https://drive.google.com/file/d/$file_id/view?usp=drivesdk";

            $myobj = new StdClass();
            $myobj->{'alt_link'} = $webViewLink;
            $myobj->{'size'} = $filesize;
            print_r($myobj);
        }else{
            echo "upload failed";
        }
    }
  }
?>
</code>```

Can anyone Help me here ?
I am using service account as you can see to Authenticate the user on my behalf...

when everything is fine then result is something like this{image}

but when i upload file then is greater then 30MB result (only on server, on localhost is works fine) {image}

also you can see in the 2nd image the status in OK but still no response.

答:
You can't always override upload size setting with ini_set, depending on hosting provider.  Try this in your .htaccess:</p>

```<code>php_value upload_max_filesize 100M
php_value post_max_size 100M
</code>```

Body:
Why my PHP code returns nothing while uploading file greater than 30MB approx, but it works on localhost the problem is in Server Side. Sometime it says 503 error or err: NET CONNECTION RESET.
but mostly returns nothing.

when i upload file that are less than 25MB they get uploaded pretty quietly.

And also if someone can help me with the progress bar while data is been uploading in drive , in my code the progress is showing but after the file is been uploaded, not while uploading(I read about the getURI and ... but didn't understood properly) can anyone guide me here too?

I am using V3 of Google-drive-api.

INDEX.php

<!DOCTYPE html>

        <meta charset="UTF-8">

    <title>Google Drive Example App</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

File Upload

                <form id="myform" method="post">

                        File name:
                        <input class="form-control" type="text" id="filename" />

                        File Discription:
                        <input class="form-control" type="text" id="discription" />

                        Select file:
                        <input class="form-control" type="file" id="myfile" />

0%

                    <input type="button" id="btn" class="btn-success" value="Upload" />
                </form>

ACTION.php

<?php

   ini_set('upload_max_filesize', '1000M');
   ini_set('post_max_size', '1000M');
   set_time_limit(5000);

if(isset($_FILES['pdf']) && isset($_POST['name'])){
    $name = $_POST['name'];
    if($name == ''){
        echo "file name is Empty";
    }else{
        $discription = $_POST['discription'];
        $target_dir = "files/";
        $file_name = basename($_FILES["pdf"]["name"]);
        $filesize = $_FILES['pdf']['size'];
        $FileType = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
        $file = "test_file.".$FileType;
        $file_path = $target_dir . $file;
        $tmpname = $_FILES['pdf']['tmp_name'];
        $upload = move_uploaded_file($tmpname, $file_path);

        if($upload == true){
            include_once __DIR__ . '/google-api-php-client-master/vendor/autoload.php';
            $client = new Google_Client();
            $client->setAuthConfig('credentials.json');
            $client->addScope('https://www.googleapis.com/auth/drive.file');

            $service = new Google_Service_Drive($client);
            $service = new Google_Service_Drive($client);
            $client->getAccessToken();

            $file = new Google_Service_Drive_DriveFile();
            $chunkSizeBytes = 1 * 1024 * 1024;
            $client->setDefer(true);

            $finfo = finfo_open(FILEINFO_MIME_TYPE);

            $parentId = "PARENT_FOLDER_ID";
            $file->setParents(array($parentId));

            $mime_type = finfo_file($finfo, $file_path);
            $file->setName($name);
            $file->setDescription($discription);

            $response = $service->files->create($file);

            // Create a media file upload to represent our upload process.
            $media = new Google_Http_MediaFileUpload(
              $client,
              $response,
              $mime_type,
              null,
              true,
              $chunkSizeBytes
            );
            $media->setFileSize(filesize($file_path));

            function readVideoChunk ($handle, $chunkSize){
                $byteCount = 0;
                $giantChunk = "";
                while (!feof($handle)) {
                    $chunk = fread($handle, $chunkSize);
                    $byteCount += strlen($chunk);
                    $giantChunk .= $chunk;
                    if ($byteCount >= $chunkSize)
                    {
                        return $giantChunk;
                    }
                }
                return $giantChunk;
            }

            // Upload the various chunks. $status will be false until the process is complete.
            $status = false;
            $handle = fopen($file_path, "rb");
            while (!$status && !feof($handle)) {
                // An example of a read buffered file is when reading from a URL
                $chunk = readVideoChunk($handle, $chunkSizeBytes);
                $status = $media->nextChunk($chunk);
               //if want to show the progress bar too but not working while uploading , but it shows the uploaded chunks after the files is been uploaded.
                if(!$status){ //nextChunk() returns 'false' whenever the upload is still in progress
                    echo 'sucessfully uploaded file up to byte ' . $media->getProgress() . ' which is ' . ( $media->getProgress() / $chunkSizeBytes ) . '% of the whole file';
                }
            }
            $result = false;
            if ($status != false) {
                $result = $status;
            }

            $file_id = $status['id'];

            fclose($handle);

            // Reset to the client to execute requests immediately in the future.
            $client->setDefer(false);
           //i am manually creating the wbViewLink by the ID i am getting in response
            $webViewLink = "https://drive.google.com/file/d/$file_id/view?usp=drivesdk";

            $myobj = new StdClass();
            $myobj->{'alt_link'} = $webViewLink;
            $myobj->{'size'} = $filesize;
            print_r($myobj);
        }else{
            echo "upload failed";
        }
    }
  }
?>

Can anyone Help me here ?
I am using service account as you can see to Authenticate the user on my behalf...

when everything is fine then result is something like this{image}

but when i upload file then is greater then 30MB result (only on server, on localhost is works fine) {image}

also you can see in the 2nd image the status in OK but still no response.

Body:
You can't always override upload size setting with ini_set, depending on hosting provider.  Try this in your .htaccess:

php_value upload_max_filesize 100M
php_value post_max_size 100M


问:
Java date time subtraction
String date1 = "2020/05/08 16.38.37"
String date2 = "2020/04/08 20.18.10"

I wish to subtract complete date1 with complete date2 (date and time both included) and get the result in hours  in java .
How to proceed ?

答:
Knowing how many hours are between 2 given timestamps is not possible unless you tell me where on the planet you want to do the math for. For example, if you ask me the minutes between 01:30 and 03:30, the answer would seem to be 120, but if due to daylight savings that so happens to be exactly the night where the clocks are moved an hour forward, the actual correct answer'd be 60.

If you never want that kind of adjustment, UTC doesn't 'suffer' from weird adjustments like this, so you can always elect to do the math in the UTC zone.

Thus, the steps:

parse your strings (which represent 'local' date/times, given that they include no timezone info at all) into LocalDateTime objects.

Zone these 2 objects by turning them into ZonedDateTime objects at a zone of your choosing.

Now ask the API to calculate the hours, minutes, whichever one you prefer between the two.

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH.mm.ss");
ZoneId zone = ZoneId.of("Europe/Amsterdam");

LocalDateTime input1 = LocalDateTime.parse("2020/05/08 16.38.37", formatter);
LocalDateTime input2 = LocalDateTime.parse("2020/04/08 20.18.10", formatter);
ZonedDateTime zoned1 = input1.atZone(zone);
ZonedDateTime zoned2 = input2.atZone(zone);

Duration duration = Duration.between(zoned1, zoned2);

long hours = duration.toHours();
System.out.println(hours);
</code>```

the above would print -716 (as in, the first stamp is at least 716 hours, and less than 717 hours, before the second.... at least, if you ask someone living in Amsterdam).

NB: If you want to talk about weeks, months, etc - you want Period and not Duration.

Title: Java date time subtraction

Body:
Knowing how many hours are between 2 given timestamps is not possible unless you tell me where on the planet you want to do the math for. For example, if you ask me the minutes between 01:30 and 03:30, the answer would seem to be 120, but if due to daylight savings that so happens to be exactly the night where the clocks are moved an hour forward, the actual correct answer'd be 60.

If you never want that kind of adjustment, UTC doesn't 'suffer' from weird adjustments like this, so you can always elect to do the math in the UTC zone.

Thus, the steps:

parse your strings (which represent 'local' date/times, given that they include no timezone info at all) into LocalDateTime objects.

Zone these 2 objects by turning them into ZonedDateTime objects at a zone of your choosing.

Now ask the API to calculate the hours, minutes, whichever one you prefer between the two.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH.mm.ss");
ZoneId zone = ZoneId.of("Europe/Amsterdam");

LocalDateTime input1 = LocalDateTime.parse("2020/05/08 16.38.37", formatter);
LocalDateTime input2 = LocalDateTime.parse("2020/04/08 20.18.10", formatter);
ZonedDateTime zoned1 = input1.atZone(zone);
ZonedDateTime zoned2 = input2.atZone(zone);

Duration duration = Duration.between(zoned1, zoned2);

long hours = duration.toHours();
System.out.println(hours);

the above would print -716 (as in, the first stamp is at least 716 hours, and less than 717 hours, before the second.... at least, if you ask someone living in Amsterdam).

NB: If you want to talk about weeks, months, etc - you want Period and not Duration.


问:
Why i can not connect to admin panel/client by domain?
I try install ejabberd on my server. Then i install it, i edit ejabberd.yml file. Add domain in hosts section. When I try to connect to the admin panel by domain, it just doesn’t connect. But if I connect by ip everything works. What should I do ? Where to look ?</p>

答:
it just doesn’t connect

Does ejabberd show the connection attempt in the ejabberd log file?

If yes: I guess the web browser also requests you an admin account and password. You will have to register a new account in ejabberd, grant it admin rights in the configuration file, and restart ejabberd.

If nothing shown in the log file, then maybe your web browser doesn't know how to connect to ejabberd. Maybe you need to setup DNS.


问:
(FLASK) I can't figure out why my html file doesn't update/render
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

```<code>from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)
</code>```

index.html (inherits from sample.html)

```<code>{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}
<h1> Welcome to the Index Page!</h1>
{% endblock %}
</code>```

sample.html

```<code><!doctype html>
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
       <span class="navbar-toggler-icon"></span>
   </button>
         <div class="collapse navbar-collapse" id="navbarNav">
             <ul class="navbar-nav">
           <li class="nav-item active">
                     <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
    </li>
    <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
    </li>
      </ul>
        </div>
    </nav>
    {% block content %}
    {% endblock %}
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
</code>```

答:
You should render index.html

return render_template("index.html")
```

instead of simple.html, as index.html is extending simple.html.

Body:
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)

index.html (inherits from sample.html)

{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}

 Welcome to the Index Page!

{% endblock %}

sample.html

<!doctype html>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>

        Navbar
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

   </button>

                     Home (current)

        Features

        Pricing

        Disabled

    {% block content %}
    {% endblock %}

Body:
You should render index.html

return render_template("index.html")

instead of simple.html, as index.html is extending simple.html.


问:
What is the most accurate/granular Python3 timestamp?
What is the most accurate timestamp in Python3?

Associated question: would it make sense to write a little timestamp program in C and invoke it from Python, or perhaps use C++'s std::chrono::high_resolution_clock? Thx, Keith :^)

答:
python's datetime package has both datetime and time classes, which are accurate to microseconds. A small demonstration:

```<code>>>> import datetime
>>> d = datetime.datetime.now()
>>> elements = ['year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']
>>> for element in elements:
>>>     print(f'{element}: {getattr(d,element)}')
year: 2020
month: 5
day: 29
hour: 11
minute: 48
second: 48
microsecond: 979449
</code>```

Hope this helps, Happy Coding!

Body:
python's datetime package has both datetime and time classes, which are accurate to microseconds. A small demonstration:

>>> import datetime
>>> d = datetime.datetime.now()
>>> elements = ['year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']
>>> for element in elements:
>>>     print(f'{element}: {getattr(d,element)}')
year: 2020
month: 5
day: 29
hour: 11
minute: 48
second: 48
microsecond: 979449

Hope this helps, Happy Coding!


问:
Obj C: Grouping strings into NSMutableDictionary
I have an NSArray that contains a bunch of strings.  Each string lists a parent and child type, such as:

```<code>Tool: Saw
Fruit: Apple
Fruit: Orange
Tree: Maple
Fruit: Banana
Tree: Oak
Tool: Hammer
Tree: Cedar
</code>```

My final structure that I need to put them into is (sorted parents and children):

```<code>Fruit:
  - Apple
  - Banana
  - Orange
Tool:
  - Hammer
  - Saw
Tree:
  - Cedar
  - Maple
  - Oak
</code>```

I would like to know how to group these under their parent type, sorting by that parent type and sorting the children. I assume the best thing to use would be an NSMutableDictionary to make them into keys and objects.

Here is what I tested so far but does not turn out how I want:

```<code>// Add to tree
if ([tree objectForKey:pathParent]) {
    NSMutableArray *temp = (NSMutableArray *)[tree objectForKey:pathParent];
    [temp addObject:name];
    [tree removeObjectForKey:pathParent];
    [tree setObject:temp forKey:pathParent];

} else {
    [tree setObject:[NSMutableArray arrayWithObject:name] forKey:pathParent];
}//end
</code>```

How would I do this?

答:
I think the simplest way would be to perform an alphabetical sort on the original list

```<code>Tool: Saw
Fruit: Apple
Fruit: Orange
Tree: Maple
Fruit: Banana
Tree: Oak
Tool: Hammer
Tree: Cedar
</code>```

To get:

```<code>Fruit: Apple
Fruit: Banana
Fruit: Orange
Tool: Hammer
Tool: Saw
Tree: Cedar
Tree: Maple
Tree: Oak
</code>```

From there you can easily iterate over the array and format it. Look at the first part of the first string and print it then newline the second part. Look at the second string if its first part differs you have a new parent so print like you did the first otherwise just print the second part of the string. Continue in this fashion.

You could also store the elements in a tree so instead of having a list of strings that are in the "parent:node" format you would have a tree of nodes with children. This would give you the ability to have child nodes with children and so forth.

The first option works, but the tree data structure is the more robust option that would be easier to expand upon.

Let me know if those don't make sense and I'll update to clarify.

Body:
I have an NSArray that contains a bunch of strings.  Each string lists a parent and child type, such as:

Tool: Saw
Fruit: Apple
Fruit: Orange
Tree: Maple
Fruit: Banana
Tree: Oak
Tool: Hammer
Tree: Cedar

My final structure that I need to put them into is (sorted parents and children):

Fruit:
  - Apple
  - Banana
  - Orange
Tool:
  - Hammer
  - Saw
Tree:
  - Cedar
  - Maple
  - Oak

I would like to know how to group these under their parent type, sorting by that parent type and sorting the children. I assume the best thing to use would be an NSMutableDictionary to make them into keys and objects.

Here is what I tested so far but does not turn out how I want:

// Add to tree
if ([tree objectForKey:pathParent]) {
    NSMutableArray *temp = (NSMutableArray *)[tree objectForKey:pathParent];
    [temp addObject:name];
    [tree removeObjectForKey:pathParent];
    [tree setObject:temp forKey:pathParent];

} else {
    [tree setObject:[NSMutableArray arrayWithObject:name] forKey:pathParent];
}//end

How would I do this?

Body:
I think the simplest way would be to perform an alphabetical sort on the original list

Tool: Saw
Fruit: Apple
Fruit: Orange
Tree: Maple
Fruit: Banana
Tree: Oak
Tool: Hammer
Tree: Cedar

To get:

Fruit: Apple
Fruit: Banana
Fruit: Orange
Tool: Hammer
Tool: Saw
Tree: Cedar
Tree: Maple
Tree: Oak

From there you can easily iterate over the array and format it. Look at the first part of the first string and print it then newline the second part. Look at the second string if its first part differs you have a new parent so print like you did the first otherwise just print the second part of the string. Continue in this fashion.

You could also store the elements in a tree so instead of having a list of strings that are in the "parent:node" format you would have a tree of nodes with children. This would give you the ability to have child nodes with children and so forth.

The first option works, but the tree data structure is the more robust option that would be easier to expand upon.

Let me know if those don't make sense and I'll update to clarify.


问:
Why this compound statement as a sequence of statements enclosed by braces and inside parentheses does not appear to be a valid statement expression
Why this compound statement  as a sequence of statements enclosed by braces (in GNU C++) and inside parentheses does not appear to be a valid Statement expression.

```<code>// my second program in C++
#include <iostream>
using namespace std;

int main ()
{
  cout << "Hello World! ";
  ({cout << "I'm a C++ program";});

}
</code>```

Compiler output:

```<code> In function 'int main()':
8:32: error: use of deleted function 'std::basic_ostream<char>::basic_ostream(const std::basic_ostream<char>&)'
In file included from /usr/include/c++/4.9/iostream:39:0,
                 from 2:
/usr/include/c++/4.9/ostream:58:11: note: 'std::basic_ostream<char>::basic_ostream(const std::basic_ostream<char>&)' is implicitly deleted because the default definition would be ill-formed:
     class basic_ostream : virtual public basic_ios<_CharT, _Traits>
           ^
/usr/include/c++/4.9/ostream:58:11: error: use of deleted function 'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)'
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: note: 'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)' is implicitly deleted because the default definition would be ill-formed:
     class basic_ios : public ios_base
           ^
In file included from /usr/include/c++/4.9/ios:42:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/ios_base.h:786:5: error: 'std::ios_base::ios_base(const std::ios_base&)' is private
     ios_base(const ios_base&);
     ^
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: error: within this context
     class basic_ios : public ios_base
           ^
</code>```

I have found a good answer about 'statement expression' in What's this C++ syntax that puts a brace-surrounded block where an expression is expected?

答:
From the reference:

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct.

and

In G++, the result value of a statement expression undergoes array and function pointer decay, and is returned by value to the enclosing expression.

This means in the expression:

```<code>({cout << "I'm a C++ program";});
</code>```

the object std::cout is returned by value. This invokes the copy constructor of std::basic_ostream, which is deleted, and hence the error.

Body:
Why this compound statement  as a sequence of statements enclosed by braces (in GNU C++) and inside parentheses does not appear to be a valid Statement expression.

// my second program in C++
#include <iostream>
using namespace std;

int main ()
{
  cout << "Hello World! ";
  ({cout << "I'm a C++ program";});

}

Compiler output:

 In function 'int main()':
8:32: error: use of deleted function 'std::basic_ostream<char>::basic_ostream(const std::basic_ostream<char>&)'
In file included from /usr/include/c++/4.9/iostream:39:0,
                 from 2:
/usr/include/c++/4.9/ostream:58:11: note: 'std::basic_ostream<char>::basic_ostream(const std::basic_ostream<char>&)' is implicitly deleted because the default definition would be ill-formed:
     class basic_ostream : virtual public basic_ios<_CharT, _Traits>
           ^
/usr/include/c++/4.9/ostream:58:11: error: use of deleted function 'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)'
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: note: 'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)' is implicitly deleted because the default definition would be ill-formed:
     class basic_ios : public ios_base
           ^
In file included from /usr/include/c++/4.9/ios:42:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/ios_base.h:786:5: error: 'std::ios_base::ios_base(const std::ios_base&)' is private
     ios_base(const ios_base&);
     ^
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: error: within this context
     class basic_ios : public ios_base
           ^

I have found a good answer about 'statement expression' in What's this C++ syntax that puts a brace-surrounded block where an expression is expected?

Body:
From the reference:

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct.

and

In G++, the result value of a statement expression undergoes array and function pointer decay, and is returned by value to the enclosing expression.

This means in the expression:

({cout << "I'm a C++ program";});

the object std::cout is returned by value. This invokes the copy constructor of std::basic_ostream, which is deleted, and hence the error.


问:
What causes "Cannot configure the test module when the test module has already been instantiated"?
here is my test :

describe('ValueService', () => {

  it('#getValue should return real value', () => {
    expect(true).toBeTruthy();
  });
});
```

And I have this error :

Failed: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject before R3TestBed.configureTestingModule.
Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject before R3TestBed.configureTestingModule.

答:
As discussed with the author, the problem arise when the TestBed is initialized outside a describe when having two spec files or more.

For example:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
describe('AppComponent', () => {
  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
 });
```
<p>will instanciate a <code>TestBed</code> beforeEach tests, not only the spec file. Hence, if you have another .spec with a TestBed and a beforeEach it will be interpreted as 2 TestBed instanciated like this:</p>

<pre class="lang-ts prettyprint-override"><code>  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
describe('AppComponent', () => {
  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
 });
</code>```

The error

Failed: Cannot configure the test module when the test module has
already been instantiated.

will be right, since you instanciate two TestBed (but in two spec files).

To solve this problem, you must always put the TestBed definition (so the beforeEach) in a describe like this:

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
});
```

Body:
here is my test :

describe('ValueService', () => {

  it('#getValue should return real value', () => {
    expect(true).toBeTruthy();
  });
});

And I have this error :

Failed: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject before R3TestBed.configureTestingModule.
Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject before R3TestBed.configureTestingModule.

Body:
As discussed with the author, the problem arise when the TestBed is initialized outside a describe when having two spec files or more.

For example:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
describe('AppComponent', () => {
  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
 });

will instanciate a TestBed beforeEach tests, not only the spec file. Hence, if you have another .spec with a TestBed and a beforeEach it will be interpreted as 2 TestBed instanciated like this:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
describe('AppComponent', () => {
  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
 });

The error

Failed: Cannot configure the test module when the test module has
already been instantiated.

will be right, since you instanciate two TestBed (but in two spec files).

To solve this problem, you must always put the TestBed definition (so the beforeEach) in a describe like this:

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
});


问:
ServiceWorker script evaluation failed
I have added google code to my service worker but it gives me error in google console...

The error in console Google:

pwaupdate:176 Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('https://myweb.org/') with script ('/pwabuilder-sw.js'): ServiceWorker script evaluation failed

My service worker:

```<code>const CACHE = "pwabuilder-offline-page";

const offlineFallbackPage = "/offline.html";

// Install stage sets up the offline page in the cache and opens a new cache
self.addEventListener("install", function (event) {
  console.log("[PWA Builder] Install Event processing");

  event.waitUntil(
    http://caches.open(CACHE).then(function (cache) {
      console.log("[PWA Builder] Cached offline page during install");

      if (offlineFallbackPage === "offline.html") {
        return cache.add(new Response("TODO: Update the value of the offlineFallbackPage constant in the serviceworker."));
      }

      return cache.add(offlineFallbackPage);
    })
  );
});

//https://developers.google.com/web/updates/2017/02/navigation-preload
//Acelerar al trabajador de servicio con precargas de navegación
self.addEventListener('fetch', event => {
  event.respondWith(async function() {
    // Respond from the cache if we can
    const cachedResponse = await caches.match(event.request);
    if (cachedResponse) return cachedResponse;

    // Else, use the preloaded response, if it's there
    const response = await event.preloadResponse;
    if (response) return response;

    // Else try the network.
    return fetch(event.request);
  }());
});

function fromCache(request) {
  // Check to see if you have it in the cache
  // Return response
  // If not in the cache, then return the offline page
  return http://caches.open(CACHE).then(function (cache) {
    return cache.match(request).then(function (matching) {
      if (!matching || matching.status === 404) {
        // The following validates that the request was for a navigation to a new document
        if (request.destination !== "document" || request.mode !== "navigate") {
          return Promise.reject("no-match");
        }

        return cache.match(offlineFallbackPage);
      }

      return matching;
    });
  });
}

function updateCache(request, response) {
  return http://caches.open(CACHE).then(function (cache) {
    return cache.put(request, response);
  });
}
</code>```

答:
It's a simple bug =)

The error means: there's a problem in the script file, it is NOT valid JavaScript.

I'm pretty sure this line is the culprit. This is not valid code:

```<code>  return http://caches.open(CACHE).then(function (cache) {
</code>```

Title: ServiceWorker script evaluation failed

Body:
I have added google code to my service worker but it gives me error in google console...

The error in console Google:

pwaupdate:176 Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('https://myweb.org/') with script ('/pwabuilder-sw.js'): ServiceWorker script evaluation failed

My service worker:

const CACHE = "pwabuilder-offline-page";

const offlineFallbackPage = "/offline.html";

// Install stage sets up the offline page in the cache and opens a new cache
self.addEventListener("install", function (event) {
  console.log("[PWA Builder] Install Event processing");

  event.waitUntil(
    http://caches.open(CACHE).then(function (cache) {
      console.log("[PWA Builder] Cached offline page during install");

      if (offlineFallbackPage === "offline.html") {
        return cache.add(new Response("TODO: Update the value of the offlineFallbackPage constant in the serviceworker."));
      }

      return cache.add(offlineFallbackPage);
    })
  );
});

//https://developers.google.com/web/updates/2017/02/navigation-preload
//Acelerar al trabajador de servicio con precargas de navegación
self.addEventListener('fetch', event => {
  event.respondWith(async function() {
    // Respond from the cache if we can
    const cachedResponse = await caches.match(event.request);
    if (cachedResponse) return cachedResponse;

    // Else, use the preloaded response, if it's there
    const response = await event.preloadResponse;
    if (response) return response;

    // Else try the network.
    return fetch(event.request);
  }());
});

function fromCache(request) {
  // Check to see if you have it in the cache
  // Return response
  // If not in the cache, then return the offline page
  return http://caches.open(CACHE).then(function (cache) {
    return cache.match(request).then(function (matching) {
      if (!matching || matching.status === 404) {
        // The following validates that the request was for a navigation to a new document
        if (request.destination !== "document" || request.mode !== "navigate") {
          return Promise.reject("no-match");
        }

        return cache.match(offlineFallbackPage);
      }

      return matching;
    });
  });
}

function updateCache(request, response) {
  return http://caches.open(CACHE).then(function (cache) {
    return cache.put(request, response);
  });
}

Body:
It's a simple bug =)

The error means: there's a problem in the script file, it is NOT valid JavaScript.

I'm pretty sure this line is the culprit. This is not valid code:

  return http://caches.open(CACHE).then(function (cache) {