问:
Changing exists rule based on choosen option
So i have this simple code to input value based on database value in registration form and it's work great,

The code below located at register.blade.php

This for selecting branch

```<code><div class="form-group form-material floating">
  <select class="form-control" name="branch" id="branch">
      <option value="1">Option A</option>
      <option value="2">Option B</option>
  </select>
  <label class="floating-label" for="inputStatus">Branch</label>
</div>
</code>```

This one for inputing reference

```<code><div class="form-group form-material floating {{ $errors->has('reference') ? ' has-error' : '' }}">
        <input type="text" class="form-control empty" id="reference" name="reference">
          <label class="floating-label" for="inputStatus">Reference</label>
          @if ($errors->has('reference'))
              <span class="help-block">
                  <strong>{{ $errors->first('reference') }}</strong>
              </span>
          @endif
      </div>
</code>```

the code below located atRegisterController.php

And this one for validation

```<code>protected function validator(array $data)
 {

 return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'phone' => 'required|string|min:5|max:20',
'rate' => 'required',
'product' => 'required',
'branch' => 'required',
'reference' => [
    'required',
        Rule::exists('references')->where(function ($query) {
            if( 'branch' == 1 ){
                $query->where('references.type', '=', "TOP");
            }
            else{
                $query->where('references.type', '=', "BOTTOM");
            }
        }),
    ],
   ]
  );
 }
</code>```

In registration form when user choose the first option on branch, the user can only write (Example : 'ABC', 'DEF', 'GHI') if the user write another value it will return Error Message : 'Wrong reference code', but when the user choose second option on branch, the user can only write (Example : '123', '456', '789'), , does anyone have and idea how to do it? Thanks

Edit 1 :
The code above works fine, but the exists rule for reference is not working, user still able to input 'ABC', 'DEF', or 'GHI' when choosing second option.

Edit 2 :
I also have this custom validation inside register.blade.php

```<code>fields: {
        reference: {
            validators: {
                notEmpty: {
                    message: 'Reference must be filled'
                },
                stringLength: {
                    max: 8,
                    message: 'Max 8 character'
                }
            }
        }
    }
</code>```

答:
For this you need Custom Validation .Custom Validation . and about query, you can do that inside

```<code>public function passes($attribute, $value){
  //value will have your reference value
 //Logic here and return true/false
}

 public function message()
    {
       //error message
        //return "The :attribute value doesnt exist.";
    }
</code>```

and if you want to pass parameters in custom rule then you need to use constructor and use it . i.e

```<code>protected $customParams;
    public function __construct($customParams)
    {
        $this->customParams = $customParams;
    }
</code>```

and rules would look like this

```<code> 'reference' => ['required',new CustomRule('customvalue')]
</code>```

Hope this helps.

Body:
So i have this simple code to input value based on database value in registration form and it's work great,

The code below located at register.blade.php

This for selecting branch

  <select class="form-control" name="branch" id="branch">
      <option value="1">Option A</option>
      <option value="2">Option B</option>
  </select>
  Branch

This one for inputing reference

has('reference') ? ' has-error' : '' }}">
        <input type="text" class="form-control empty" id="reference" name="reference">
          Reference
          @if ($errors->has('reference'))

                  {{ $errors->first('reference') }}

          @endif

the code below located atRegisterController.php

And this one for validation

protected function validator(array $data)
 {

 return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'phone' => 'required|string|min:5|max:20',
'rate' => 'required',
'product' => 'required',
'branch' => 'required',
'reference' => [
    'required',
        Rule::exists('references')->where(function ($query) {
            if( 'branch' == 1 ){
                $query->where('references.type', '=', "TOP");
            }
            else{
                $query->where('references.type', '=', "BOTTOM");
            }
        }),
    ],
   ]
  );
 }

In registration form when user choose the first option on branch, the user can only write (Example : 'ABC', 'DEF', 'GHI') if the user write another value it will return Error Message : 'Wrong reference code', but when the user choose second option on branch, the user can only write (Example : '123', '456', '789'), , does anyone have and idea how to do it? Thanks

Edit 1 :
The code above works fine, but the exists rule for reference is not working, user still able to input 'ABC', 'DEF', or 'GHI' when choosing second option.

Edit 2 :
I also have this custom validation inside register.blade.php

fields: {
        reference: {
            validators: {
                notEmpty: {
                    message: 'Reference must be filled'
                },
                stringLength: {
                    max: 8,
                    message: 'Max 8 character'
                }
            }
        }
    }

Body:
For this you need Custom Validation .Custom Validation . and about query, you can do that inside

public function passes($attribute, $value){
  //value will have your reference value
 //Logic here and return true/false
}

 public function message()
    {
       //error message
        //return "The :attribute value doesnt exist.";
    }

and if you want to pass parameters in custom rule then you need to use constructor and use it . i.e

protected $customParams;
    public function __construct($customParams)
    {
        $this->customParams = $customParams;
    }

and rules would look like this

 'reference' => ['required',new CustomRule('customvalue')]

Hope this helps.


来源: stackexchange

问:
Is there a function in python to map out the values of dates like [2011,2012,2013,204] to 2011-2014. where as [2003,2006,2007,2008] to 2003, 2006-2008
Iam working on the file that has lots of dates that are in consecutive order. There are few instances where there are not in consecutive order e.g. 2004, 2007, 2008. is there a way to write python function to get the values. </p>

答:
Here's how you can build a function to do group them using itertools yourself, others have suggested external libraries which can probably also do this

```<code>>>> from itertools import count, groupby
>>> years = [2003, 2006, 2007, 2008]
>>> [list(g) for k, g in groupby(years, key=lambda x, c=count(): x - next(c))]
[[2003], [2006, 2007, 2008]]
</code>```

Getting the first and last elements

```<code>>>> [[next(g)] + list(g)[-1:] for k, g in
     groupby(years, key=lambda x, c=count(): x-next(c))]
[[2003], [2006, 2008]]
</code>```

How it Works:

itertools.count gives you an iterator that gives values 0, 1, 2, 3

So then when you have the years eg. 2003, 2006, 2007, 2008

The key lambda used to group the years, takes one parameter x which is the year in this case. We also initialize a count() within the lambda which we subtract from each year, giving us

```<code>2003, 2005, 2005, 2005
</code>```

as count keeps incrementing eg.

```<code>count = 0, 1, 2, 3, ... # as we go on
</code>```

Which allows groupby to create the correct groups

The last part

```<code>[next(g)] + list(g)[-1:]
</code>```

works because the groups returned by groupby are iterators so next(g) gives us the first element in the group and list(g) gives us the rest of the elements, of which we take a slice [-1:] which gives us a list of only the last element if it exists, otherwise just an empty list

ContentLicense: CC BY-SA 4.0

Body:
Here's how you can build a function to do group them using itertools yourself, others have suggested external libraries which can probably also do this

>>> from itertools import count, groupby
>>> years = [2003, 2006, 2007, 2008]
>>> [list(g) for k, g in groupby(years, key=lambda x, c=count(): x - next(c))]
[[2003], [2006, 2007, 2008]]

Getting the first and last elements

>>> [[next(g)] + list(g)[-1:] for k, g in
     groupby(years, key=lambda x, c=count(): x-next(c))]
[[2003], [2006, 2008]]

How it Works:

itertools.count gives you an iterator that gives values 0, 1, 2, 3

So then when you have the years eg. 2003, 2006, 2007, 2008

The key lambda used to group the years, takes one parameter x which is the year in this case. We also initialize a count() within the lambda which we subtract from each year, giving us

2003, 2005, 2005, 2005

as count keeps incrementing eg.

count = 0, 1, 2, 3, ... # as we go on

Which allows groupby to create the correct groups

The last part

[next(g)] + list(g)[-1:]

works because the groups returned by groupby are iterators so next(g) gives us the first element in the group and list(g) gives us the rest of the elements, of which we take a slice [-1:] which gives us a list of only the last element if it exists, otherwise just an empty list


问:
Maven ignore signature of a dependency package
I have a custom built jar of the Hadoop-azure package under the hadoop project. I need to use this JAR in my project. I imported the JAR as a dependency under Maven using the following configuration.

```<code><dependency>
    <groupId>org.apache.hadoop.fs.abfs</groupId>
     <artifactId>hadoop-azure</artifactId>
     <version>2.7.1</version>
 </dependency>
</code>```

However, the when I try to import a signed version of the JAR i encounter the following error.

```<code>java.lang.SecurityException: class "org.apache.hadoop.fs.azurebfs.AzureBlobFileSystem"'s signer information does not match signer information of other classes in the same package
</code>```

I see that the signed files from the Manifest could be ignored using the Maven shade plugin. However, these would be ignored from the Uber Jar which shade plugin builds. The structure of tests for this projects is not well done and it is built as a different sub-project under the main project; having its own pom file. When I write integration tests for the classes I intend I keep seeing the java security signature error. Is there a way to ignore the signed files from the Manifest folder other than the shade plugin option?

Thanks

答:
I think you can use this link to add third party library(in your case hadoop-azure) to your local maven repository then your run your project and should it be well. E.g:</p>

```<code>mvn install:install-file -Dfile=C:\Projects\HadoopAzure\hadoop.jar -DgroupId=org.apache.hadoop.fs.abfs \
    -DartifactId=hadoop-azure -Dversion=2.7.1 -Dpackaging=jar
</code>```

Body:
I have a custom built jar of the Hadoop-azure package under the hadoop project. I need to use this JAR in my project. I imported the JAR as a dependency under Maven using the following configuration.

<dependency>
    <groupId>org.apache.hadoop.fs.abfs</groupId>
     <artifactId>hadoop-azure</artifactId>
     <version>2.7.1</version>
 </dependency>

However, the when I try to import a signed version of the JAR i encounter the following error.

java.lang.SecurityException: class "org.apache.hadoop.fs.azurebfs.AzureBlobFileSystem"'s signer information does not match signer information of other classes in the same package

I see that the signed files from the Manifest could be ignored using the Maven shade plugin. However, these would be ignored from the Uber Jar which shade plugin builds. The structure of tests for this projects is not well done and it is built as a different sub-project under the main project; having its own pom file. When I write integration tests for the classes I intend I keep seeing the java security signature error. Is there a way to ignore the signed files from the Manifest folder other than the shade plugin option?

Thanks

Body:
I think you can use this link to add third party library(in your case hadoop-azure) to your local maven repository then your run your project and should it be well. E.g:

mvn install:install-file -Dfile=C:\Projects\HadoopAzure\hadoop.jar -DgroupId=org.apache.hadoop.fs.abfs \
    -DartifactId=hadoop-azure -Dversion=2.7.1 -Dpackaging=jar


问:
python-fortran integration: callback comparison between f2py and ctypes
I found an instructive example in : https://numpy.org/devdocs/f2py/python-usage.html#call-back-arguments.
Here the fortran routine:

```<code>C FILE: CALLBACK.F
  SUBROUTINE FOO(FUN,R)
  EXTERNAL FUN
  INTEGER I
  REAL*8 R, FUN
Cf2py intent(out) r
  R = 0D0
  DO I=-5,5
     R = R + FUN(I)
  ENDDO
  END
C END OF FILE CALLBACK.F
</code>```

This can be compiled with the comand  f2py -c -m callback callback.f
and called with the python code:

```<code>import callback
print(callback.foo.__doc__)
def f(i):
    return i * i
print(callback.foo(f))
</code>```

Everything works fine. Now, I would like to repeat the test using ctypes.
I can compile easily the fortran source with: gfortran -shared callback.f -o callback.dll
and I can load the library with:

```<code>import ctypes as ct
import numpy as np
# import the dll
fortlib = ct.CDLL('callback.dll')
</code>```

Questions:

How can I call the foo function in the dll coming from ctypes like I
did with the code compiled with f2py?

How I can interface the two
variables (pointer to function and pointer to real) required?

Thanks in advance. Gianmarco

Platform: Anaconda python 3.7.6, Mingw-64 on Windows 10

答:
Good programming style dictates us to never use single-character variable names. A modern Fortran-2008 implementation of your Fortran subroutine would be something similar to the following:

```<code>module foo_mod

    use iso_c_binding, only: RK => c_double, IK => c_int32_t
    implicit none

    abstract interface
        function getFunVal_proc(inputInteger) result(funVal) bind(C)
            import :: RK, IK
            implicit none
            integer(IK), intent(in), value :: inputInteger
            real(RK) :: funVal
        end function getFunVal_proc
    end interface

contains

    subroutine getFoo(getFunValFromC,outputReal) bind(C,name="getFoo")
        !DEC$ ATTRIBUTES DLLEXPORT :: getFoo
        use, intrinsic :: iso_c_binding, only: c_funptr, c_f_procpointer
        implicit none
        type(c_funptr), intent(in), value   :: getFunValFromC
        procedure(getFunVal_proc), pointer  :: getFunVal
        real(RK), intent(out)               :: outputReal
        integer(IK)                         :: indx

        ! associate the input C procedure pointer to a Fortran procedure pointer
        call c_f_procpointer(cptr=getFunValFromC, fptr=getFunVal)

        outputReal = 0._RK
        do indx = -5,5
            write(*,"(*(g0,:,' '))") "value of indx from inside Fortran: ", indx
            outputReal = outputReal + getFunVal(indx)
        end do

        write(*,"(*(g0,:,' '))") "value of outputReal from inside Fortran: ", outputReal

        ! nullify the Fortran pointer
        nullify(getFunVal)

    end subroutine getFoo

end module foo_mod
</code>```

This looks rather verbose, but it is far better than F77. We live in the 21 century, after all. Then you would compile this Fortran code via Intel ifort, for example, like,

```<code>ifort /dll /threads /libs:static foo_mod.f90 /exe:foo.dll
</code>```

Then, you would call getFoo() from the generated DLL foo.dll like in the following Python script,

```<code>import ctypes as ct
import numpy as np

# This is the Python callback function to be passed to Fortran
def getSquare(inputInteger):
    print("value of indx received by getSquare() inside Python: ",inputInteger)
    return np.double(inputInteger**2)

# define ctypes wrapper function, with the proper result and argument types
getFunVal_proc =    ct.CFUNCTYPE( ct.c_double                  # callback (python) function result
                                , ct.c_int32                   # callback (python) function input integer argument
                                )
getSquare_pntr = getFunVal_proc(getSquare)

libpath = "foo.dll"
try:

    # open DLL
    foolib = ct.CDLL(libpath)

except Exception as e:

    import logging
    logger = logging.Logger("catch_all")
    logger.error(e, exc_info=True)

# define getFoo's interface from Fortran dll

foolib.getFoo.restype = None # return type of the Fortran subroutine/function
foolib.getFoo.argtypes =    [ getFunVal_proc            # procedure
                            , ct.POINTER(ct.c_double)   # real64 return value
                            , ]

outputReal = ct.c_double(0.)
foolib.getFoo   ( getSquare_pntr
                , ct.byref(outputReal)
                )
print("value of outputReal received in Python: ", np.double(outputReal))
</code>```

Running this script would yield something like the following,

```<code>In [1]: run main.py
value of indx from inside Fortran:  -5
value of indx received by getSquare() inside Python:  -5
value of indx from inside Fortran:  -4
value of indx received by getSquare() inside Python:  -4
value of indx from inside Fortran:  -3
value of indx received by getSquare() inside Python:  -3
value of indx from inside Fortran:  -2
value of indx received by getSquare() inside Python:  -2
value of indx from inside Fortran:  -1
value of indx received by getSquare() inside Python:  -1
value of indx from inside Fortran:  0
value of indx received by getSquare() inside Python:  0
value of indx from inside Fortran:  1
value of indx received by getSquare() inside Python:  1
value of indx from inside Fortran:  2
value of indx received by getSquare() inside Python:  2
value of indx from inside Fortran:  3
value of indx received by getSquare() inside Python:  3
value of indx from inside Fortran:  4
value of indx received by getSquare() inside Python:  4
value of indx from inside Fortran:  5
value of indx received by getSquare() inside Python:  5
value of outputReal from inside Fortran:  110.0000000000000
value of outputReal received in Python:  110.0
</code>```

The above Python script might again look rather verbose compared to your F2PY code. But it is far more professional, modern, and standard-compliant, both with Python and Fortran standards than your implementation.

footnote: Intel ifort is available free of charge to all students, teachers, and open-source developers on Windows, Linux, and Mac platforms. This does not mean that gfortran is not good. But in my opinion, using gcc on Windows OS is in general no better than a never-ending nightmare (I have no affiliations with Intel, just a user).

Body:
I found an instructive example in : https://numpy.org/devdocs/f2py/python-usage.html#call-back-arguments.
Here the fortran routine:

C FILE: CALLBACK.F
  SUBROUTINE FOO(FUN,R)
  EXTERNAL FUN
  INTEGER I
  REAL*8 R, FUN
Cf2py intent(out) r
  R = 0D0
  DO I=-5,5
     R = R + FUN(I)
  ENDDO
  END
C END OF FILE CALLBACK.F

This can be compiled with the comand  f2py -c -m callback callback.f
and called with the python code:

import callback
print(callback.foo.__doc__)
def f(i):
    return i * i
print(callback.foo(f))

Everything works fine. Now, I would like to repeat the test using ctypes.
I can compile easily the fortran source with: gfortran -shared callback.f -o callback.dll
and I can load the library with:

import ctypes as ct
import numpy as np
# import the dll
fortlib = ct.CDLL('callback.dll')

Questions:

How can I call the foo function in the dll coming from ctypes like I
did with the code compiled with f2py?

How I can interface the two
variables (pointer to function and pointer to real) required?

Thanks in advance. Gianmarco

Platform: Anaconda python 3.7.6, Mingw-64 on Windows 10

Body:
Good programming style dictates us to never use single-character variable names. A modern Fortran-2008 implementation of your Fortran subroutine would be something similar to the following:

module foo_mod

    use iso_c_binding, only: RK => c_double, IK => c_int32_t
    implicit none

    abstract interface
        function getFunVal_proc(inputInteger) result(funVal) bind(C)
            import :: RK, IK
            implicit none
            integer(IK), intent(in), value :: inputInteger
            real(RK) :: funVal
        end function getFunVal_proc
    end interface

contains

    subroutine getFoo(getFunValFromC,outputReal) bind(C,name="getFoo")
        !DEC$ ATTRIBUTES DLLEXPORT :: getFoo
        use, intrinsic :: iso_c_binding, only: c_funptr, c_f_procpointer
        implicit none
        type(c_funptr), intent(in), value   :: getFunValFromC
        procedure(getFunVal_proc), pointer  :: getFunVal
        real(RK), intent(out)               :: outputReal
        integer(IK)                         :: indx

        ! associate the input C procedure pointer to a Fortran procedure pointer
        call c_f_procpointer(cptr=getFunValFromC, fptr=getFunVal)

        outputReal = 0._RK
        do indx = -5,5
            write(*,"(*(g0,:,' '))") "value of indx from inside Fortran: ", indx
            outputReal = outputReal + getFunVal(indx)
        end do

        write(*,"(*(g0,:,' '))") "value of outputReal from inside Fortran: ", outputReal

        ! nullify the Fortran pointer
        nullify(getFunVal)

    end subroutine getFoo

end module foo_mod

This looks rather verbose, but it is far better than F77. We live in the 21 century, after all. Then you would compile this Fortran code via Intel ifort, for example, like,

ifort /dll /threads /libs:static foo_mod.f90 /exe:foo.dll

Then, you would call getFoo() from the generated DLL foo.dll like in the following Python script,

import ctypes as ct
import numpy as np

# This is the Python callback function to be passed to Fortran
def getSquare(inputInteger):
    print("value of indx received by getSquare() inside Python: ",inputInteger)
    return np.double(inputInteger**2)

# define ctypes wrapper function, with the proper result and argument types
getFunVal_proc =    ct.CFUNCTYPE( ct.c_double                  # callback (python) function result
                                , ct.c_int32                   # callback (python) function input integer argument
                                )
getSquare_pntr = getFunVal_proc(getSquare)

libpath = "foo.dll"
try:

    # open DLL
    foolib = ct.CDLL(libpath)

except Exception as e:

    import logging
    logger = logging.Logger("catch_all")
    logger.error(e, exc_info=True)

# define getFoo's interface from Fortran dll

foolib.getFoo.restype = None # return type of the Fortran subroutine/function
foolib.getFoo.argtypes =    [ getFunVal_proc            # procedure
                            , ct.POINTER(ct.c_double)   # real64 return value
                            , ]

outputReal = ct.c_double(0.)
foolib.getFoo   ( getSquare_pntr
                , ct.byref(outputReal)
                )
print("value of outputReal received in Python: ", np.double(outputReal))

Running this script would yield something like the following,

In [1]: run main.py
value of indx from inside Fortran:  -5
value of indx received by getSquare() inside Python:  -5
value of indx from inside Fortran:  -4
value of indx received by getSquare() inside Python:  -4
value of indx from inside Fortran:  -3
value of indx received by getSquare() inside Python:  -3
value of indx from inside Fortran:  -2
value of indx received by getSquare() inside Python:  -2
value of indx from inside Fortran:  -1
value of indx received by getSquare() inside Python:  -1
value of indx from inside Fortran:  0
value of indx received by getSquare() inside Python:  0
value of indx from inside Fortran:  1
value of indx received by getSquare() inside Python:  1
value of indx from inside Fortran:  2
value of indx received by getSquare() inside Python:  2
value of indx from inside Fortran:  3
value of indx received by getSquare() inside Python:  3
value of indx from inside Fortran:  4
value of indx received by getSquare() inside Python:  4
value of indx from inside Fortran:  5
value of indx received by getSquare() inside Python:  5
value of outputReal from inside Fortran:  110.0000000000000
value of outputReal received in Python:  110.0

The above Python script might again look rather verbose compared to your F2PY code. But it is far more professional, modern, and standard-compliant, both with Python and Fortran standards than your implementation.

footnote: Intel ifort is available free of charge to all students, teachers, and open-source developers on Windows, Linux, and Mac platforms. This does not mean that gfortran is not good. But in my opinion, using gcc on Windows OS is in general no better than a never-ending nightmare (I have no affiliations with Intel, just a user).


问:
what happens behind the scenes of executing `UIApplication.shared.registerForRemoteNotifications()` in iOS?
I'm wondering what's happening behind the scenes when registering ios applications for push notifications and how the ios device receives device-token in application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) callback. I need to know the complete scenario and protocol communication.

答:
So this all works like this:

1) Your app asks to be registered with APNs.

2) On successful registration, APNs sends an app-specific device token to the device.

3) The system delivers the device to your app by calling a method in your app delegate.

For more information, check these links :-
https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/HandlingRemoteNotifications.html

https://nshipster.com/apns-device-tokens/


答:
try this :</p>

```<code>select REFERENCE_NO ,TASK_ID,CREATED_DATE from [dbo].[Table_1]
where TASK_ID in (select max(TASK_ID) from [dbo].[Table_1])
</code>```

Title: Select max TASK_ID and CREATED_DATE - already tried MAX and DISTINCT

Body:
I need to fetch only the second record and ignore the first one.
I have this data:

REFERENCE_NO       TASK_ID        CREATED_DATE
------------------------------------------------------------
244038             83102          2020-01-14 09:23:21:000000
244038             83114          2020-01-14 09:23:21:867000

Expected Output:

REFERENCE_NO       TASK_ID        CREATED_DATE
------------------------------------------------------------
244038             83114          2020-01-14 09:23:21:867000

Body:
try this :

select REFERENCE_NO ,TASK_ID,CREATED_DATE from [dbo].[Table_1]
where TASK_ID in (select max(TASK_ID) from [dbo].[Table_1])


问:
Good REST API design for operations on resource sets
With REST it is pretty clear how to operate on resources, e.g.

```<code>PUT /users/{userId} - updates the user with userId
GET /users/{userId} - reads the user with userId
</code>```

Similarly for resource sets

```<code>POST /users - creates a new user
GET /users/{userId}/books - reads list of books from a user
GET /users/{userId}/books?filter=x - reads list of books from a user with specific filter
</code>```

What if I want to develop more elaborate operations on resource sets, e.g.

with the request body, add a list of books to the existing list and accepting duplicates (basically concatenating the list)

```<code>POST /users/{userId}/books
or PUT /users/{userId}/books
or PATCH?
or POST /users/{userId}/books/concatenate
</code>```

with the request body, add a list of books to the existing list but no duplicates (basically merging the list)

```<code>POST /users/{userId}/books
or PUT /users/{userId}/books
or PATCH?
or POST /users/{userId}/books/merge
</code>```

also for deleting parts of resource sets:
with the request body, delete a list of books from the existing list that have a certain property

```<code>POST /users/{userId}/books/delete?category=x
or DELETE /users/{userId}/books?category=x
</code>```

or deleting all resources in a resource set:

```<code>POST /users/{userId}/books/delete_all
or DELETE /users/{userId}/books
</code>```

Would be thankful for some hints or guidelines

答:
"Resource sets", from the point of view of REST, are a fiction.  There are only resources.  As far as a general-purpose HTTP component is concerned, there is _no relation implied by the following URI:

```<code>/users
/users/{userId}
/users/{userId}/books
/users/{userId}/books?filter=x
/users/{userId}/books/concatenate
</code>```

They are completely independent of one another; for instance, DELETE /users does not imply anything about the other resources.

We human beings tend to assign identifiers in patterns that make sense, but the machines don't care.

with the request body, add a list of books to the existing list and accepting duplicates (basically concatenating the list)

PUT and PATCH have remote authoring semantics; they act like you would expect if you were trying to edit a copy of a file on the server.  You GET a copy of the current representation of the resource, make edits to your local copy, and then request that the server change its copy to match your copy.  With PUT, you send a complete copy of your representation of the resource; with PATCH, you send a patch-document that describes the changes you made.

It's okay to use POST; HTML got along just fine using nothing but GET and POST, and the web took over the world.

You don't need a separate resource for POST; you can use one if you like, but it isn't necessary to do so.

with the request body, add a list of books to the existing list but no duplicates (basically merging the list)

Not really any different; what we agree upon in HTTP is the semantics of the request and response messages.  What the server chooses to do is an implementation concern.  See Fielding 2002.

So if I send to you a representation of a list with duplicate entries, and you strip out the duplicates, that's "fine"; you just need to exercise some care with your responses to ensure that you don't imply that you accepted the requested representation as is.

With PATCH, it's a bit fuzzy, in that the RFC describes all or nothing semantics, but based on the language used it is reasonable to infer that the implementation is restricted as well.

also for deleting parts of resource sets: with the request body, delete a list of books from the existing list that have a certain property

Give RFC 7231 a careful read: DELETE doesn't quite mean what your examples hint at.  DELETE breaks the associate between a key (the target uri) and a value (the resource representations), but that doesn't necessarily mean "and also garbage collect the representation".

The same idea expressed another way -- suppose I GET /list-of-books from the server, and the returned representation is a list of three books.  In the case where I want that resource to instead return a representation of an empty list, DELETE is the wrong tool.  DELETE tells the server that I want future calls to GET /list-of-books to return 404 Not Found or possibly 410 Gone.  If what I really want is a 200 OK with an empty list, then I need to PUT/PATCH/POST/etc. the resource.

deleting all resources in a resource set

Same problem as before.

With REST it is pretty clear how to operate on resources

This is the problem - it is NOT clear how to operate on resources.  The web is cluttered with literature that makes a complete hash of it (we use REST to fetch documents that mangle the lessons of REST -- fabulous irony).

REST includes a uniform interface as a constraint.  In HTTP, that interface is effectively a document store.  PUT and PATCH just edit document contents - which is perfectly satisfactory if your domain is anemic or declarative.  For anything else where we don't have standardized semantics, we use POST.

See Jim Webber, 2011:  "You have to learn how to use HTTP to trigger business activity as a side effect of moving documents around the network."

Body:
With REST it is pretty clear how to operate on resources, e.g.

PUT /users/{userId} - updates the user with userId
GET /users/{userId} - reads the user with userId

Similarly for resource sets

POST /users - creates a new user
GET /users/{userId}/books - reads list of books from a user
GET /users/{userId}/books?filter=x - reads list of books from a user with specific filter

What if I want to develop more elaborate operations on resource sets, e.g.

with the request body, add a list of books to the existing list and accepting duplicates (basically concatenating the list)

POST /users/{userId}/books
or PUT /users/{userId}/books
or PATCH?
or POST /users/{userId}/books/concatenate

with the request body, add a list of books to the existing list but no duplicates (basically merging the list)

POST /users/{userId}/books
or PUT /users/{userId}/books
or PATCH?
or POST /users/{userId}/books/merge

also for deleting parts of resource sets:
with the request body, delete a list of books from the existing list that have a certain property

POST /users/{userId}/books/delete?category=x
or DELETE /users/{userId}/books?category=x

or deleting all resources in a resource set:

POST /users/{userId}/books/delete_all
or DELETE /users/{userId}/books

Would be thankful for some hints or guidelines

Body:
"Resource sets", from the point of view of REST, are a fiction.  There are only resources.  As far as a general-purpose HTTP component is concerned, there is _no relation implied by the following URI:

/users
/users/{userId}
/users/{userId}/books
/users/{userId}/books?filter=x
/users/{userId}/books/concatenate

They are completely independent of one another; for instance, DELETE /users does not imply anything about the other resources.

We human beings tend to assign identifiers in patterns that make sense, but the machines don't care.

with the request body, add a list of books to the existing list and accepting duplicates (basically concatenating the list)

PUT and PATCH have remote authoring semantics; they act like you would expect if you were trying to edit a copy of a file on the server.  You GET a copy of the current representation of the resource, make edits to your local copy, and then request that the server change its copy to match your copy.  With PUT, you send a complete copy of your representation of the resource; with PATCH, you send a patch-document that describes the changes you made.

It's okay to use POST; HTML got along just fine using nothing but GET and POST, and the web took over the world.

You don't need a separate resource for POST; you can use one if you like, but it isn't necessary to do so.

with the request body, add a list of books to the existing list but no duplicates (basically merging the list)

Not really any different; what we agree upon in HTTP is the semantics of the request and response messages.  What the server chooses to do is an implementation concern.  See Fielding 2002.

So if I send to you a representation of a list with duplicate entries, and you strip out the duplicates, that's "fine"; you just need to exercise some care with your responses to ensure that you don't imply that you accepted the requested representation as is.

With PATCH, it's a bit fuzzy, in that the RFC describes all or nothing semantics, but based on the language used it is reasonable to infer that the implementation is restricted as well.

also for deleting parts of resource sets: with the request body, delete a list of books from the existing list that have a certain property

Give RFC 7231 a careful read: DELETE doesn't quite mean what your examples hint at.  DELETE breaks the associate between a key (the target uri) and a value (the resource representations), but that doesn't necessarily mean "and also garbage collect the representation".

The same idea expressed another way -- suppose I GET /list-of-books from the server, and the returned representation is a list of three books.  In the case where I want that resource to instead return a representation of an empty list, DELETE is the wrong tool.  DELETE tells the server that I want future calls to GET /list-of-books to return 404 Not Found or possibly 410 Gone.  If what I really want is a 200 OK with an empty list, then I need to PUT/PATCH/POST/etc. the resource.

deleting all resources in a resource set

Same problem as before.

With REST it is pretty clear how to operate on resources

This is the problem - it is NOT clear how to operate on resources.  The web is cluttered with literature that makes a complete hash of it (we use REST to fetch documents that mangle the lessons of REST -- fabulous irony).

REST includes a uniform interface as a constraint.  In HTTP, that interface is effectively a document store.  PUT and PATCH just edit document contents - which is perfectly satisfactory if your domain is anemic or declarative.  For anything else where we don't have standardized semantics, we use POST.

See Jim Webber, 2011:  "You have to learn how to use HTTP to trigger business activity as a side effect of moving documents around the network."


问:
Create text input bar always pinned to bottom
I'm trying to create a Row widget that will be pinned to the bottom always like the below screenshot. I currently have a large container containing text (open to changing this to a card) followed by smaller cards which are scrollable. I would like to pin a bar to the bottom so a user can enter text and add a card. I'm not sure how to pin this to the bottom of the UI without interfering with the cards causing a pixel overflow. What is the best way to achieve this? I'd ideally like to achieve a bottom row that is similar to Facebook Messengers'

Code:

```<code>class TextBarAtBottom extends StatelessWidget {
  TextEditingController commentController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return
    Container(
              height: 20.0,
              padding: EdgeInsets.symmetric(vertical: 2.0),
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  // First child is enter comment text input
                  TextFormField(
                                  controller: commentController,
                                  autocorrect: false,
                                  decoration: new InputDecoration(
                                    labelText: "Some Text",
                                    labelStyle:
                                        TextStyle(fontSize: 20.0, color: Colors.white),
                                    fillColor: Colors.blue,
                                    border: OutlineInputBorder(
                                        // borderRadius:
                                        //     BorderRadius.all(Radius.zero(5.0)),
                                        borderSide:
                                            BorderSide(color: Colors.purpleAccent)),
                                  ),
                    ),
                    // Second child is button
                  IconButton(
                    icon: Icon(Icons.send),
                    iconSize: 20.0,
                    onPressed: _onPressedSend(),
                  )
                ]
              )
              );
  }
}
</code>```

答:
correct and optimal way would be using Expanded widget with Column .

Use Expanded for content of screen which takes up all empty space screen leaves behind and then text input field below it. You can see output below.

```<code>    return Scaffold(
      appBar: AppBar(
        title: AppBarTitle(title: "Profile"),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
              child: ListView(
            children: <Widget>[
              Text("Message1"),
              Text("Message2"),
              Text("Message3"),
              Text("Message4"),
              Text("Message5"),
            ],
          )),
          Container(
              padding: EdgeInsets.symmetric(vertical: 2.0),
              child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                // First child is enter comment text input
                Expanded(
                  child: TextFormField(
                    autocorrect: false,
                    decoration: new InputDecoration(
                      labelText: "Some Text",
                      labelStyle:
                          TextStyle(fontSize: 20.0, color: Colors.white),
                      fillColor: Colors.blue,
                      border: OutlineInputBorder(
                          // borderRadius:
                          //     BorderRadius.all(Radius.zero(5.0)),
                          borderSide: BorderSide(color: Colors.purpleAccent)),
                    ),
                  ),
                ),
                // Second child is button
                IconButton(
                  icon: Icon(Icons.send),
                  iconSize: 20.0,
                  onPressed: () {},
                )
              ])),
        ],
      ),
);
</code>```

Body:
I'm trying to create a Row widget that will be pinned to the bottom always like the below screenshot. I currently have a large container containing text (open to changing this to a card) followed by smaller cards which are scrollable. I would like to pin a bar to the bottom so a user can enter text and add a card. I'm not sure how to pin this to the bottom of the UI without interfering with the cards causing a pixel overflow. What is the best way to achieve this? I'd ideally like to achieve a bottom row that is similar to Facebook Messengers'

Code:

class TextBarAtBottom extends StatelessWidget {
  TextEditingController commentController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return
    Container(
              height: 20.0,
              padding: EdgeInsets.symmetric(vertical: 2.0),
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  // First child is enter comment text input
                  TextFormField(
                                  controller: commentController,
                                  autocorrect: false,
                                  decoration: new InputDecoration(
                                    labelText: "Some Text",
                                    labelStyle:
                                        TextStyle(fontSize: 20.0, color: Colors.white),
                                    fillColor: Colors.blue,
                                    border: OutlineInputBorder(
                                        // borderRadius:
                                        //     BorderRadius.all(Radius.zero(5.0)),
                                        borderSide:
                                            BorderSide(color: Colors.purpleAccent)),
                                  ),
                    ),
                    // Second child is button
                  IconButton(
                    icon: Icon(Icons.send),
                    iconSize: 20.0,
                    onPressed: _onPressedSend(),
                  )
                ]
              )
              );
  }
}

Body:
correct and optimal way would be using Expanded widget with Column .

Use Expanded for content of screen which takes up all empty space screen leaves behind and then text input field below it. You can see output below.

    return Scaffold(
      appBar: AppBar(
        title: AppBarTitle(title: "Profile"),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
              child: ListView(
            children: <Widget>[
              Text("Message1"),
              Text("Message2"),
              Text("Message3"),
              Text("Message4"),
              Text("Message5"),
            ],
          )),
          Container(
              padding: EdgeInsets.symmetric(vertical: 2.0),
              child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                // First child is enter comment text input
                Expanded(
                  child: TextFormField(
                    autocorrect: false,
                    decoration: new InputDecoration(
                      labelText: "Some Text",
                      labelStyle:
                          TextStyle(fontSize: 20.0, color: Colors.white),
                      fillColor: Colors.blue,
                      border: OutlineInputBorder(
                          // borderRadius:
                          //     BorderRadius.all(Radius.zero(5.0)),
                          borderSide: BorderSide(color: Colors.purpleAccent)),
                    ),
                  ),
                ),
                // Second child is button
                IconButton(
                  icon: Icon(Icons.send),
                  iconSize: 20.0,
                  onPressed: () {},
                )
              ])),
        ],
      ),
);


问:
Forge viewer coordinate units and mapping those to a ThreeJS scene
I'm trying to show HTML content in 3D alongside a Forge mode using the ThreeJS CSS3dRenderer (https://threejs.org/docs/#examples/en/renderers/CSS3DRenderer).

An example of the functionality: http://learningthreejs.com/data/2013-04-30-closing-the-gap-between-html-and-webgl/index.html

In purely a normal ThreeJS context the the steps needed for that are:

Create a ThreeJS scene #1 for the DOM content.

Create another scene #2 for the 3D content.

Add CSS3DObjects with the HTML content into scene #1

Add a matching 3D element into scene #2 with blending enabled. This makes the HTML content able to occlude the objects in scene #2.

Add other 3D objects into scene #2.

Render #1 with CSS3DRenderer and #2 with the normal WebGLRenderer.

In the Forge viewer context scene #2 is replaced with an overlay scene.

I applied the tricks featured here https://forge.autodesk.com/blog/transparent-background-viewer-long-last to make the CSS scene visible through the viewer scene and that works ok, except for the strange effect that when the renderer alpha is enabled elements in the overlay scene are only rendered when the occlude the Forge model.

The problem I'm having is point 4. In the case of two normal ThreeJS scenes the position, rotation and scale of the CSS3DObject in scene #1 can just be copied to the object in scene #2 and they match perfectly. Not so between a ThreeJS scene and the viewer's overlay scene as the units don't match up. (Or that's how I've reasoned it.)

Is there some way I can transform between these units?

答:
According to our Engineering - hats off for Cleve to put the demo together:

The camera you are using NOP_VIEWER.impl.camera isn't a THREE camera. It is a UnifiedCamera defined by LMV to hold both a perspective and orthographic camera. You need to get the right camera from the UnifiedCamera and use that for the render. Just realized that the CSS3DRenderer was taken from a more recent version of THREE.js and it assumes things that aren't true about THREE.js r71 that LMV uses. I noticed that it uses camera.isPerspectiveCamera to decide when a camera is perspective, That isn't defined in r71 which uses instance of THREE.PerspectiveCamera.

```<code> camera = new THREE.PerspectiveCamera(
        45, window.innerWidth / window.innerHeight, 0.1, 4000
    );
</code>```

The CSS3DRenderer renders into a flat plane that is composited with the LMV 3D scene. I found an example that faked putting the CSS3D scene with a WebGL scene by zapping transparent holes in the WebGL scene where CSS3D objects were in front of the WebGL scene. This is the example: https://codepen.io/Fyrestar/pen/QOXJaJ

Body:
According to our Engineering - hats off for Cleve to put the demo together:

The camera you are using NOP_VIEWER.impl.camera isn't a THREE camera. It is a UnifiedCamera defined by LMV to hold both a perspective and orthographic camera. You need to get the right camera from the UnifiedCamera and use that for the render. Just realized that the CSS3DRenderer was taken from a more recent version of THREE.js and it assumes things that aren't true about THREE.js r71 that LMV uses. I noticed that it uses camera.isPerspectiveCamera to decide when a camera is perspective, That isn't defined in r71 which uses instance of THREE.PerspectiveCamera.

 camera = new THREE.PerspectiveCamera(
        45, window.innerWidth / window.innerHeight, 0.1, 4000
    );

The CSS3DRenderer renders into a flat plane that is composited with the LMV 3D scene. I found an example that faked putting the CSS3D scene with a WebGL scene by zapping transparent holes in the WebGL scene where CSS3D objects were in front of the WebGL scene. This is the example: https://codepen.io/Fyrestar/pen/QOXJaJ


答:
Wrap your parent Widget With Stack and Use Align widget to place your textBox always bottom.

```<code>return
      Stack(children: <Widget>[
        yourMainContent(),
        Align(
          alignment: Alignment.bottomCenter,
          ///Your TextBox Container
          child: Container(
              height: 20.0,
              padding: EdgeInsets.symmetric(vertical: 2.0),
              alignment: Alignment.bottomCenter,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    // First child is enter comment text input
                    TextFormField(
                      controller: commentController,
                      autocorrect: false,
                      decoration: new InputDecoration(
                        labelText: "Some Text",
                        labelStyle:
                        TextStyle(fontSize: 20.0, color: Colors.white),
                        fillColor: Colors.blue,
                        border: OutlineInputBorder(
                          // borderRadius:
                          //     BorderRadius.all(Radius.zero(5.0)),
                            borderSide:
                            BorderSide(color: Colors.purpleAccent)),
                      ),
                    ),
                    // Second child is button
                    IconButton(
                      icon: Icon(Icons.send),
                      iconSize: 20.0,
                      onPressed: _onPressedSend(),
                    )
                  ]
              )
          ),
        )
      ],)
</code>```

Title: Create text input bar always pinned to bottom

Body:
Wrap your parent Widget With Stack and Use Align widget to place your textBox always bottom.

return
      Stack(children: <Widget>[
        yourMainContent(),
        Align(
          alignment: Alignment.bottomCenter,
          ///Your TextBox Container
          child: Container(
              height: 20.0,
              padding: EdgeInsets.symmetric(vertical: 2.0),
              alignment: Alignment.bottomCenter,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    // First child is enter comment text input
                    TextFormField(
                      controller: commentController,
                      autocorrect: false,
                      decoration: new InputDecoration(
                        labelText: "Some Text",
                        labelStyle:
                        TextStyle(fontSize: 20.0, color: Colors.white),
                        fillColor: Colors.blue,
                        border: OutlineInputBorder(
                          // borderRadius:
                          //     BorderRadius.all(Radius.zero(5.0)),
                            borderSide:
                            BorderSide(color: Colors.purpleAccent)),
                      ),
                    ),
                    // Second child is button
                    IconButton(
                      icon: Icon(Icons.send),
                      iconSize: 20.0,
                      onPressed: _onPressedSend(),
                    )
                  ]
              )
          ),
        )
      ],)


问:
Where do I call my function so it successfully updates my UI?
I have written the following function to ensure my user fills in a textField before being able to continue.

```<code>func validateFields() -> String {

    if textfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
        return "Please fill in textField"
    }

    return "A-OK."
}

 func updateUI() {
    let verdict = validateFields()

    if verdict == "A-OK." {
        self.buttonOne.alpha = 1
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

     updateUI()
}
</code>```

However, once the textField has been filled in, the above code fails to update the UI. I know I am missing out on something trivial here, I just cannot wrap my head around what. I'd really appreciate the help.

答:
I suppose you can easily bind you text view to a local property and observer changes on that property. And when everything is valid, you can enable your buttonOne and use the value of that property in future computations.

```<code>var myTextFieldData: String {
    didSet {
        updateUI()
    }
}
</code>```

Also, keep in mind that you'll also have to implement the UITextField delegate in order to bind your textField with myTextFieldData:

```<code>textField.delegate = self

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    myTextFieldData = string
    return true
}
</code>```

Body:
I have written the following function to ensure my user fills in a textField before being able to continue.

func validateFields() -> String {

    if textfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
        return "Please fill in textField"
    }

    return "A-OK."
}

 func updateUI() {
    let verdict = validateFields()

    if verdict == "A-OK." {
        self.buttonOne.alpha = 1
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

     updateUI()
}

However, once the textField has been filled in, the above code fails to update the UI. I know I am missing out on something trivial here, I just cannot wrap my head around what. I'd really appreciate the help.

Body:
I suppose you can easily bind you text view to a local property and observer changes on that property. And when everything is valid, you can enable your buttonOne and use the value of that property in future computations.

var myTextFieldData: String {
    didSet {
        updateUI()
    }
}

Also, keep in mind that you'll also have to implement the UITextField delegate in order to bind your textField with myTextFieldData:

textField.delegate = self

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    myTextFieldData = string
    return true
}


问:
How to select two attributes from the same node with one expression in XPath?
For example:

```<code>//person[@id='abc123']/@haircolor|/@weight"
</code>```

PS. there are lots of "person" records

答:
Try this:

```<code>//person[@id='abc123']/@*[name()='weight' or name()='haircolor']
</code>```

If you're using an XPath 2.0 processor, you may also use a prettier option:

```<code>//person[@id='abc123']/(@haircolor|@weight)`
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example:

//person[@id='abc123']/@haircolor|/@weight"

PS. there are lots of "person" records

Body:
Try this:

//person[@id='abc123']/@*[name()='weight' or name()='haircolor']

If you're using an XPath 2.0 processor, you may also use a prettier option:

//person[@id='abc123']/(@haircolor|@weight)`


问:
Unable to SSH into Docker container running Alpine Linux 3.10
I am having problems using SSH to connect into a Docker container (from this image) running Alpine Linux 3.10.

SSH must be used for this connection, as I am using a backup software barman which requires an SSH connection to the PostgreSQL 11 database running inside the Docker container.

First I connected into the docker container using

```<code>docker exec -it <container_name> /bin/bash
</code>```

then tried to reinstall and start sshd

```<code>bash-5.0# apk add openssh --no-cache
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
OK: 117 MiB in 42 packages

bash-5.0# apk add openrc --no-cache
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
OK: 117 MiB in 42 packages

bash-5.0# rc-update add sshd
 * rc-update: sshd already installed in runlevel `sysinit'; skipping

bash-5.0# /etc/init.d/sshd start
 * WARNING: sshd is already starting
</code>```

However, I am unable to connect to the local sshd server from inside the Docker container

```<code># ssh root@127.0.0.1
ssh: connect to host 127.0.0.1 port 22: Connection refused
</code>```

Similarly, connecting into the Docker container via SSH from the Ubuntu host machine fails as well.

```<code>$ ssh postgres@172.26.0.4
ssh: connect to host 172.26.0.4 port 22: Connection refused
</code>```

where 172.26.0.4 is the IP address shown from running ifconfig inside the Docker container.

Any ideas how we can solve this?

答:
Might be relevant to your issue if you used --net=host along with docker run command:

We were facing similar issues with running SSH server inside our Ubuntu container.
We realized that the SSH server on the container's host was running and it used the same port that container's SSH server wanted to use.

We changed the port used by the SSH server to solve this issue.

Please note, our Docker container used --net=host and hence both container and host had the same IP address. Hence, the 2 SSH servers were fighting over a single port and that didn't allow the server inside the container to start properly.

Body:
I am having problems using SSH to connect into a Docker container (from this image) running Alpine Linux 3.10.

SSH must be used for this connection, as I am using a backup software barman which requires an SSH connection to the PostgreSQL 11 database running inside the Docker container.

First I connected into the docker container using

docker exec -it <container_name> /bin/bash

then tried to reinstall and start sshd

bash-5.0# apk add openssh --no-cache
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
OK: 117 MiB in 42 packages

bash-5.0# apk add openrc --no-cache
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
OK: 117 MiB in 42 packages

bash-5.0# rc-update add sshd
 * rc-update: sshd already installed in runlevel `sysinit'; skipping

bash-5.0# /etc/init.d/sshd start
 * WARNING: sshd is already starting

However, I am unable to connect to the local sshd server from inside the Docker container

# ssh root@127.0.0.1
ssh: connect to host 127.0.0.1 port 22: Connection refused

Similarly, connecting into the Docker container via SSH from the Ubuntu host machine fails as well.

$ ssh postgres@172.26.0.4
ssh: connect to host 172.26.0.4 port 22: Connection refused

where 172.26.0.4 is the IP address shown from running ifconfig inside the Docker container.

Any ideas how we can solve this?


问:
snowflake data transfer and formatting
We are in the process of creating a DataWarehouse in Snowflake, basically what our developers have done is by using stitch they have transferred all existing data to a Database in Snowflake and then are updating this further daily.

Now I am in the process of formatting the table structure into something legible for use with PowerBI and 3rd parties, which hasn't been a problem. I have created all the necessary SQL for the tables and or views I wish as well as inserting the existing data this new structure.

However my issue is how do I then, say, update any new data that comes along?

E.g. dev have a table called SN_BARCODE which has all the barcodes for all products in it, the fields in that table are:

```<code>   APNS (VARCHAR)
 , BARCODEID (NUMBER)
 , DATECREATED (TIMESTAMP)
 , DATEMODIFIED (TIMESTAMP)
 , DATEUPDATED (TIMESTAMP)
 , ID (NUMBER)
 , PRODUCTID (NUMBER)
 , VENUEID (NUMBER)
 , _SDC_BATCHED_AT(TIMESTAMP)
 , _SDC_RECEIVE_AT (TIMESTAMP)
 , _SDC_SEQUENCE (TIMESTAMP)
 , _SDC_TABLE_VERSION (TIMESTAMP)
</code>```

to which I do the following

```<code>CREATE OR REPLACE Table pc_stitch_db.Dim_BarCodes
 (Barcodes_Id int, Barcodes_ProductId, Barcodes_APN, PRIMARY KEY (Barcodes_Id)) AS
SELECT
    "PC_STITCH_DB".sn_barcode.barcodeid AS Barcodes_Id,
    "PC_STITCH_DB".sn_product.id AS Barcodes_ProductId,
    "PC_STITCH_DB".sn_barcode.apns AS Barcodes_APN
FROM "PC_STITCH_DB".sn_Barcode
INNER JOIN "PC_STITCH_DB".sn_product  ON (
        "PC_STITCH_DB".sn_product.PRODUCTID = "PC_STITCH_DB".sn_barcode.productid
    AND "PC_STITCH_DB".sn_product.venueid = "PC_STITCH_DB".sn_barcode.venueid
);
</code>```

How can I update these daily after stitch has loaded the data from the other source?

答:
You have the dilemma of simplicity vs. efficiency.

You can easily create TASKs that recreate your tables on eg. a daily schedule using statements like the CREATE OR REPLACE TABLE statement you provided above.  This means your data is reloaded completely every day.

However, if you have huge and growing tables that approach eventually will cause capacity problems.  Then you have to modify your solution to do incremental updates.

There are two main types of incremental updates,

appending data using INSERT

merging data using MERGE (in general more complex and more flexible)

Title: snowflake data transfer and formatting

Body:
We are in the process of creating a DataWarehouse in Snowflake, basically what our developers have done is by using stitch they have transferred all existing data to a Database in Snowflake and then are updating this further daily.

Now I am in the process of formatting the table structure into something legible for use with PowerBI and 3rd parties, which hasn't been a problem. I have created all the necessary SQL for the tables and or views I wish as well as inserting the existing data this new structure.

However my issue is how do I then, say, update any new data that comes along?

E.g. dev have a table called SN_BARCODE which has all the barcodes for all products in it, the fields in that table are:

   APNS (VARCHAR)
 , BARCODEID (NUMBER)
 , DATECREATED (TIMESTAMP)
 , DATEMODIFIED (TIMESTAMP)
 , DATEUPDATED (TIMESTAMP)
 , ID (NUMBER)
 , PRODUCTID (NUMBER)
 , VENUEID (NUMBER)
 , _SDC_BATCHED_AT(TIMESTAMP)
 , _SDC_RECEIVE_AT (TIMESTAMP)
 , _SDC_SEQUENCE (TIMESTAMP)
 , _SDC_TABLE_VERSION (TIMESTAMP)

to which I do the following

CREATE OR REPLACE Table pc_stitch_db.Dim_BarCodes
 (Barcodes_Id int, Barcodes_ProductId, Barcodes_APN, PRIMARY KEY (Barcodes_Id)) AS
SELECT
    "PC_STITCH_DB".sn_barcode.barcodeid AS Barcodes_Id,
    "PC_STITCH_DB".sn_product.id AS Barcodes_ProductId,
    "PC_STITCH_DB".sn_barcode.apns AS Barcodes_APN
FROM "PC_STITCH_DB".sn_Barcode
INNER JOIN "PC_STITCH_DB".sn_product  ON (
        "PC_STITCH_DB".sn_product.PRODUCTID = "PC_STITCH_DB".sn_barcode.productid
    AND "PC_STITCH_DB".sn_product.venueid = "PC_STITCH_DB".sn_barcode.venueid
);

How can I update these daily after stitch has loaded the data from the other source?


问:
Choosing photo using new Google Photos app is broken
My app has ability to select photo from library. Exactly I want file path from this selection.

This is the code to create intent for selecting photo:

```<code>    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, INTENT_REQUEST_CODE_SELECT_PHOTO);
</code>```

This is the code that gets file path from URI:

```<code>    Cursor cursor = null;
    String path = null;
    try {
        String[] projection = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
        int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
        cursor.moveToFirst();
        path = cursor.getString(columnIndex);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return path;
</code>```

Before yesterday's update of Google Photos app everything worked perfectly fine.
Now path is null after parsing URI.

URI is similar to this: content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F75209/ACTUAL

I also tried to create intent with Intent.ACTION_GET_CONTENT action - no luck.

答:
I know this question is bit old, still I did the following to get the image from gallery and use it. Below is the extension function for the same.

```<code>fun Uri.toBitmap(context: Context?): Bitmap {
    return MediaStore.Images.Media.getBitmap(context?.contentResolver, this)
}
</code>```

It takes context as parameter to get contentResolver and Uri received from onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?).

To use, just do the following:

```<code>intent?.data.toBitmap(context)
</code>```

where intent?.data is the Uri received from onActivityResult().

Body:
My app has ability to select photo from library. Exactly I want file path from this selection.

This is the code to create intent for selecting photo:

    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, INTENT_REQUEST_CODE_SELECT_PHOTO);

This is the code that gets file path from URI:

    Cursor cursor = null;
    String path = null;
    try {
        String[] projection = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
        int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
        cursor.moveToFirst();
        path = cursor.getString(columnIndex);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return path;

Before yesterday's update of Google Photos app everything worked perfectly fine.
Now path is null after parsing URI.

URI is similar to this: content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F75209/ACTUAL

I also tried to create intent with Intent.ACTION_GET_CONTENT action - no luck.

Body:
I know this question is bit old, still I did the following to get the image from gallery and use it. Below is the extension function for the same.

fun Uri.toBitmap(context: Context?): Bitmap {
    return MediaStore.Images.Media.getBitmap(context?.contentResolver, this)
}

It takes context as parameter to get contentResolver and Uri received from onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?).

To use, just do the following:

intent?.data.toBitmap(context)

where intent?.data is the Uri received from onActivityResult().


问:
Azure monitor for containers v/s Application insights
We are designing an application which will be hosted on AKS(Azure kubernetes service). The application will consist of a set of services written in asp .net core running in docker containers. I want to monitor the services as well as the containers/nodes and have the observability across the cluster. Azure monitor for containers seems to be a good solution for monitoring containers, nodes and the cluster as a whole however I want the advanced monitoring capabilities of the application insights for the asp .net core services for example application maps, live metrics streams, transaction tracing and such features. Moreover, I don't want to have overlapping solutions. Is the Azure monitor for containers able to provide all or most of these application insights features or do I have to have both solutions in order to get proper cluster monitoring and also the advanced application monitoring?</p>

答:
Azure Monitor for containers provide infrastructure level monitoring and basic application logs with stdout and stderr, Kubernetes events captured out of the box.

It does not provide instrumentation for your apps or distributed tracing capabilities today, which is possible with Application Insights.

If you are looking for application map & instrumentation for events metrics and logs for your app, you can use both together and it's possible to correlate data from both and create dashboards and views.

The long term road map has Azure Monitor for containers & Application insights combined offering


问:
How to loop through json defined in typescript
I'm working with Angular. There is a similar question but not answered -

How to loop through a JSON object with typescript

I'm not getting any error or warning. But I'm not getting the output also. I'm trying to imitate twitter-api. I've created a json object in my typescript and I'm trying to loop through my json in HTML. Here's my code:

twitter-timeline.component.ts

```<code>  output: JSON;
  twitter_data:any = {
      statuses: [
        {screen_name:"tanzeel", status: "wonderful day, enjoying at beach"},
        {screen_name:"pablo", status: "what a lovely morning #surfing #beach #relax"},
        {screen_name:"ricky", status: "feeling sick :-( #typhoid"}
      ]
  }

  ngOnInit() {
    this.output = <JSON>this.twitter_data;
  }
</code>```

twitter-timeline.component.html

```<code><div class="container" *ngFor="let tweets of output; let i=index">
    <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-12 text-column">
            <p class="screen-name">{{tweets.statuses[i].screen_name}}</p>
            <p class="user-status">{{tweets.statuses[i].status}}</p>
            <br>
        </div>
    </div>
</div>
</code>```

Is there anything wrong with the way I'm creating JSON object, or there's something wrong with the way I'm reading values in HTML. Please correct me.

I also tried this kind of JSON structure:

```<code>output: JSON;
obj: any =
{
"col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"},
"col2":{"Attribute1": "value4", "Attribute2": "value5", "Attribute3": "value6"},
"col3":{"Attribute1": "value7", "Attribute2": "value8", "Attribute3": "value9"}
};
</code>```

答:
You need to change *ngFor as *ngFor="let tweets of output.statuses; let i=index" .

output is an object so, you cannot iterate object like this, instead iterate the array output.statuses and then you can get the related data like,

```<code>        <p class="screen-name">{{tweets.screen_name}}</p>
        <p class="user-status">{{tweets.status}}</p>
</code>```

You need to change let tweets of output to let tweets of output.statuses.

twitter-timeline.component.html

```<code><div class="container" *ngFor="let tweets of output.statuses; let i=index">
    <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-12 text-column">
            <p class="screen-name">{{tweets.screen_name}}</p>
            <p class="user-status">{{tweets.status}}</p>
            <br>
        </div>
    </div>
</div>
</code>```

Working Stackblitz

Body:
I'm working with Angular. There is a similar question but not answered -

How to loop through a JSON object with typescript

I'm not getting any error or warning. But I'm not getting the output also. I'm trying to imitate twitter-api. I've created a json object in my typescript and I'm trying to loop through my json in HTML. Here's my code:

twitter-timeline.component.ts

  output: JSON;
  twitter_data:any = {
      statuses: [
        {screen_name:"tanzeel", status: "wonderful day, enjoying at beach"},
        {screen_name:"pablo", status: "what a lovely morning #surfing #beach #relax"},
        {screen_name:"ricky", status: "feeling sick :-( #typhoid"}
      ]
  }

  ngOnInit() {
    this.output = <JSON>this.twitter_data;
  }

twitter-timeline.component.html

{{tweets.statuses[i].screen_name}}

{{tweets.statuses[i].status}}

Is there anything wrong with the way I'm creating JSON object, or there's something wrong with the way I'm reading values in HTML. Please correct me.

I also tried this kind of JSON structure:

output: JSON;
obj: any =
{
"col1":{"Attribute1": "value1", "Attribute2": "value2", "Attribute3": "value3"},
"col2":{"Attribute1": "value4", "Attribute2": "value5", "Attribute3": "value6"},
"col3":{"Attribute1": "value7", "Attribute2": "value8", "Attribute3": "value9"}
};

Body:
You need to change *ngFor as *ngFor="let tweets of output.statuses; let i=index" .

output is an object so, you cannot iterate object like this, instead iterate the array output.statuses and then you can get the related data like,

        <p class="screen-name">{{tweets.screen_name}}</p>
        <p class="user-status">{{tweets.status}}</p>

You need to change let tweets of output to let tweets of output.statuses.

twitter-timeline.component.html

<div class="container" *ngFor="let tweets of output.statuses; let i=index">
    <div class="row">
        <div class="col-sm-12 col-md-12 col-lg-12 text-column">
            <p class="screen-name">{{tweets.screen_name}}</p>
            <p class="user-status">{{tweets.status}}</p>
            <br>
        </div>
    </div>
</div>

Working Stackblitz


问:
sharding in mongodb with other type of _id
It's possible that i face with problems in mongoDB sharding if change type of _id in mongoDB to other format same as int, string or .... ?
because the structure of _id is:
1- The first 4 bytes representing the seconds since the unix epoch
2- The next 3 bytes are the machine identifier
3- The next 2 bytes consists of process id
4- The last 3 bytes are a random counter value

and i think those 3 bytes that use for machine identifier are very helpful for sharding.

答:
The makeup of the ObjectId has changed.
and it has 5 bytes instead of machine id and process id.

https://www.mongodb.com/blog/post/quick-start-bson-data-types--objectid


问:
loading json data from local file into React JS
I have a React component and I want to load in my JSON data from a file. The console log currently doesn't work, even though I'm creating the variable data as a global

```<code>'use strict';

var React = require('react/addons');

// load in JSON data from file
var data;

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "data.json", true);
oReq.send();

function reqListener(e) {
    data = JSON.parse(this.responseText);
}
console.log(data);

var List = React.createClass({
  getInitialState: function() {
    return {data: this.props.data};
  },
  render: function() {
    var listItems = this.state.data.map(function(item) {
        var eachItem = item.works.work;

        var photo = eachItem.map(function(url) {
            return (
                <td>{url.urls}</td>
            )
        });
    });
    return <ul>{listItems}</ul>
  }
});

var redBubble = React.createClass({
    render: function() {
      return (
        <div>
          <List data={data}/>
        </div>
      );
    }
  });

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

Ideally, I would prefer to do it something like this, but it's not working - it tries to add ".js" onto the end of the filename.

```<code>var data = require('./data.json');
</code>```

Any advice on the best way, preferably the "React" way, would be much appreciated!

答:
My JSON file name: terrifcalculatordata.json

```<code>[
    {
      "id": 1,
      "name": "Vigo",
      "picture": "./static/images/vigo.png",
      "charges": "PKR 100 per excess km"
    },
    {
      "id": 2,
      "name": "Mercedes",
      "picture": "./static/images/Marcedes.jpg",
      "charges": "PKR 200 per excess km"
    },
    {
        "id": 3,
        "name": "Lexus",
        "picture": "./static/images/Lexus.jpg",
        "charges": "PKR 150 per excess km"
      }
]
</code>```

First , import on top:

```<code>import calculatorData from "../static/data/terrifcalculatordata.json";
</code>```

then after return:

```<code>  <div>
  {
    calculatorData.map((calculatedata, index) => {
        return (
            <div key={index}>
                <img
                    src={calculatedata.picture}
                    class="d-block"
                    height="170"
                />
                <p>
                    {calculatedata.charges}
                </p>
            </div>

</code>```

Body:
I have a React component and I want to load in my JSON data from a file. The console log currently doesn't work, even though I'm creating the variable data as a global

'use strict';

var React = require('react/addons');

// load in JSON data from file
var data;

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "data.json", true);
oReq.send();

function reqListener(e) {
    data = JSON.parse(this.responseText);
}
console.log(data);

var List = React.createClass({
  getInitialState: function() {
    return {data: this.props.data};
  },
  render: function() {
    var listItems = this.state.data.map(function(item) {
        var eachItem = item.works.work;

        var photo = eachItem.map(function(url) {
            return (
                {url.urls}
            )
        });
    });
    return
{listItems}

  }
});

var redBubble = React.createClass({
    render: function() {
      return (

          <List data={data}/>

      );
    }
  });

module.exports = redBubble;

Ideally, I would prefer to do it something like this, but it's not working - it tries to add ".js" onto the end of the filename.

var data = require('./data.json');

Any advice on the best way, preferably the "React" way, would be much appreciated!

Body:
My JSON file name: terrifcalculatordata.json

[
    {
      "id": 1,
      "name": "Vigo",
      "picture": "./static/images/vigo.png",
      "charges": "PKR 100 per excess km"
    },
    {
      "id": 2,
      "name": "Mercedes",
      "picture": "./static/images/Marcedes.jpg",
      "charges": "PKR 200 per excess km"
    },
    {
        "id": 3,
        "name": "Lexus",
        "picture": "./static/images/Lexus.jpg",
        "charges": "PKR 150 per excess km"
      }
]

First , import on top:

import calculatorData from "../static/data/terrifcalculatordata.json";

then after return:

  <div>
  {
    calculatorData.map((calculatedata, index) => {
        return (
            <div key={index}>
                <img
                    src={calculatedata.picture}
                    class="d-block"
                    height="170"
                />
                <p>
                    {calculatedata.charges}
                </p>
            </div>


问:
Oracle SQL Update using cursor
I have a question about how to using a CURSOR to update an email domain name by using an new email domain name.  ex(gmail.com->hotmail.com)

execute procedure('gmail.com','hotmail.com' )

Here is what I write. please help me out, thank you!

```<code>create procedure PR_Q3
is P_NewEamil varchar2(50); P_Email_Address varchar2(50); exceptionforemail exception;
cursor E_info is select Email_Address from Broker where P_Email_Address = Email_Address
for update of Email_Address;
begin
open E_info;
fetch E_info into P_NewEamil;
while E_info%found loop
if(P_NewEamil like '%.com') then
update Broker set Email_Address = P_NewEamil where P_Email_Address = Email_Address;
</code>```

答:
Why you want to use the cursor when it can be done using a simple update statement as following:

```<code>UPDATE BROKER
SET
    EMAIL_ADDRESS = REPLACE(P_NEWEAMIL, :OLD_DOMAIN, :NEW_DOMAIN)
WHERE
    REGEXP_LIKE ( P_NEWEAMIL,'.*@'|| :OLD_DOMAIN|| '$' );
</code>```

Please add more WHERE conditions according to your requirements.

Cheers!!

Title: Oracle SQL Update using cursor

Body:
I have a question about how to using a CURSOR to update an email domain name by using an new email domain name.  ex(gmail.com->hotmail.com)

execute procedure('gmail.com','hotmail.com' )

Here is what I write. please help me out, thank you!

create procedure PR_Q3
is P_NewEamil varchar2(50); P_Email_Address varchar2(50); exceptionforemail exception;
cursor E_info is select Email_Address from Broker where P_Email_Address = Email_Address
for update of Email_Address;
begin
open E_info;
fetch E_info into P_NewEamil;
while E_info%found loop
if(P_NewEamil like '%.com') then
update Broker set Email_Address = P_NewEamil where P_Email_Address = Email_Address;

Body:
Why you want to use the cursor when it can be done using a simple update statement as following:

UPDATE BROKER
SET
    EMAIL_ADDRESS = REPLACE(P_NEWEAMIL, :OLD_DOMAIN, :NEW_DOMAIN)
WHERE
    REGEXP_LIKE ( P_NEWEAMIL,'.*@'|| :OLD_DOMAIN|| '$' );

Please add more WHERE conditions according to your requirements.

Cheers!!


问:
Is there a good way to implement RealityKit into a Swift playground?
I want to be able to add a file created in Reality Composer into a Swift Playground for testing purposes.  I also think it would be interesting to use as a supplement to a playbook.  How would one go about adding an rcproject into a playground like the Experience.rcproject Apple provides with the scene “Box”?</p>

答:
You can read a .reality file format in Playground using the following code:

```<code>import Cocoa
import RealityKit
import PlaygroundSupport

let arView = ARView(frame: CGRect(x: 0, y: 0, width: 800, height: 200))
arView.environment.background = .color(.black)

let fileURL = Bundle.main.url(forResource: "main", withExtension: "reality")
let bowlingScene = try! Entity.load(contentsOf: fileURL!)

let anchor = AnchorEntity()
anchor.addChild(bowlingScene)
anchor.scale = [4,4,4]
anchor.position.y = -0.5

arView.scene.anchors.append(anchor)

PlaygroundPage.current.liveView = arView
</code>```

So, supply a .playground file with a main.reality scene, making it nested.

About Swift Playgrounds for iPad read here.

Body:
You can read a .reality file format in Playground using the following code:

import Cocoa
import RealityKit
import PlaygroundSupport

let arView = ARView(frame: CGRect(x: 0, y: 0, width: 800, height: 200))
arView.environment.background = .color(.black)

let fileURL = Bundle.main.url(forResource: "main", withExtension: "reality")
let bowlingScene = try! Entity.load(contentsOf: fileURL!)

let anchor = AnchorEntity()
anchor.addChild(bowlingScene)
anchor.scale = [4,4,4]
anchor.position.y = -0.5

arView.scene.anchors.append(anchor)

PlaygroundPage.current.liveView = arView

So, supply a .playground file with a main.reality scene, making it nested.

About Swift Playgrounds for iPad read here.


问:
How to install Android apk from code in unity
I found snippet for Java. How can I write such a code in C# Unity?</p>

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File("link to downloaded file")),"application/vnd.android.package-archive");
startActivity(intent);
</code>```

答:
Here we have to change your manifest file. We have to give Read & Write permissions.
after change this we can easily install downloaded application file.

Without these permissions we can't access Android External Files.

```<code><?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.product" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal" android:versionName="1.0" android:versionCode="1">
      <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
      <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="true">
        <activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name">
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
          <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>

        <provider
              android:name="android.support.v4.content.FileProvider"
              android:authorities="com.company.product.fileprovider"
              android:exported="false"
              android:grantUriPermissions="true">
          <meta-data
              android:name="android.support.FILE_PROVIDER_PATHS"
              android:resource="@xml/provider_paths"/>
        </provider>

      </application>
      <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <uses-sdk android:minSdkVersion="16"   android:maxSdkVersion="29"  />
    </manifest>
</code>```

Body:
I found snippet for Java. How can I write such a code in C# Unity?

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(new File("link to downloaded file")),"application/vnd.android.package-archive");
startActivity(intent);

Body:
Here we have to change your manifest file. We have to give Read & Write permissions.
after change this we can easily install downloaded application file.

Without these permissions we can't access Android External Files.

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.product" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal" android:versionName="1.0" android:versionCode="1">
      <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
      <application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" android:debuggable="true">
        <activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name">
          <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
          <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
        </activity>

        <provider
              android:name="android.support.v4.content.FileProvider"
              android:authorities="com.company.product.fileprovider"
              android:exported="false"
              android:grantUriPermissions="true">
          <meta-data
              android:name="android.support.FILE_PROVIDER_PATHS"
              android:resource="@xml/provider_paths"/>
        </provider>

      </application>
      <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <uses-sdk android:minSdkVersion="16"   android:maxSdkVersion="29"  />
    </manifest>


问:
How do I terminate/stop all other thread when I catch specific value in one of the thread execution (in activemq cpp)?
I have parallely  launched 5 threads which are calling specific function. If one of them returns some specific value, I need to terminate the further processing of all other remaining threads and the specific function is called asynchronously in the onMessage() method.

答:
Pass a std::atomic<bool>& terminate_flag to all launched threads. When one process find the searched for value, update the terminate_flag. All threads should be running an infinite loop? Modify the loop to exit when the terminate_flag gets set to true.

```<code>void thread_function(std::atomic<bool>& terminate_flag, T& search_value, ...)
{
    while(terminate_flag == false)
    {
        ...do stuff...
        if (found_value == search_value)
        {
            terminate_flag = true;
        }
    }
}
</code>```

Body:
Pass a std::atomic<bool>& terminate_flag to all launched threads. When one process find the searched for value, update the terminate_flag. All threads should be running an infinite loop? Modify the loop to exit when the terminate_flag gets set to true.

void thread_function(std::atomic<bool>& terminate_flag, T& search_value, ...)
{
    while(terminate_flag == false)
    {
        ...do stuff...
        if (found_value == search_value)
        {
            terminate_flag = true;
        }
    }
}


问:
Hot module replacement for native ES Modules (browser or Node.js) *without* Webpack? No build tools
I'm looking to add HMR to plain Node.js code or browser code written with native ES Modules.

There's no Babel, no Webpack, no transpilation, just plain JS files and ES Module import and export calls.

Can we do HMR in plain Node or browser?

答:
Here's a pure node HMR module from a developer/entrepreneur who i work with personally: https://github.com/huan/hot-import

Hope this helps.


问:
SQL to find the number of distinct values in a column
I can select all the distinct values in a column in the following ways:

SELECT DISTINCT column_name FROM table_name;

SELECT column_name FROM table_name GROUP BY column_name;

But how do I get the row count from that query? Is a subquery required?

答:
After MS SQL Server 2012, you can use window function too.</p>
```<code>SELECT column_name, COUNT(column_name) OVER (PARTITION BY column_name)
FROM table_name
GROUP BY column_name
</code>```

OwnerDisplayName: Gorgapor

Body:
After MS SQL Server 2012, you can use window function too.

SELECT column_name, COUNT(column_name) OVER (PARTITION BY column_name)
FROM table_name
GROUP BY column_name


问:
jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null
I have the following code:

$(document).ready
(
    function ()
    {
        $.validator.addMethod(
        "lessThan",
        function (value, element, param)
        {
            // bind to the blur event of the target in order to revalidate whenever the target field is updated
            var target = $(param)
            .unbind(".validate-lessThan")
            .bind
            (
                "blur.validate-lessThan",
                function ()
                {
                    $(element).valid();
                }
            );
            return parseFloat(value) <= parseFloat(target.val());
        },
        "Valoarea trebuie sa fie mai mica sau egala decat valoarea initiala"
        );
    }
);

$('#gvListDetaliiElemTranAdaugare input[name$=Valoare]').each
    (
        function (index, domEle)
        {
            $(this).rules
            (
                "add"
                , {

                    required: true,
                    minlength: 1,
                    range: [0.1, Number.MAX_VALUE],
                    lessThan: '#ListaDetaliiElemTranModelAdaugare_' + index + '__ValoareRamasa',
                    messages:
                    {
                        required: "Valoarea este necesara!",
                        minlength: "Valoarea este necesara!",
                        range: "Valoarea este necesara!",
                        lessThan: "Valoarea trebuie sa fie mai mica sau egala cu " + $('#ListaDetaliiElemTranModelAdaugare_' + index + '__ValoareRamasa').val()

                    }
                }
            );
        }
    );
```

<p>The code fails then it reeaches $(this).rules() with: <code>Uncaught TypeError: Cannot read property 'nodeName' of null</code>.
 the html returned by <code>$('#gvListDetaliiElemTranAdaugare input[name$=Valoare]')</code> is:</p>

```[
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_0__Valoare" name="ListaDetaliiElemTranModelAdaugare[0].Valoare" onchange="OnValoareChange($(this).val(), 18590 , 0)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_1__Valoare" name="ListaDetaliiElemTranModelAdaugare[1].Valoare" onchange="OnValoareChange($(this).val(), 22972 , 1)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_2__Valoare" name="ListaDetaliiElemTranModelAdaugare[2].Valoare" onchange="OnValoareChange($(this).val(), 23036 , 2)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_3__Valoare" name="ListaDetaliiElemTranModelAdaugare[3].Valoare" onchange="OnValoareChange($(this).val(), 23038 , 3)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_4__Valoare" name="ListaDetaliiElemTranModelAdaugare[4].Valoare" onchange="OnValoareChange($(this).val(), 425306 , 4)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_5__Valoare" name="ListaDetaliiElemTranModelAdaugare[5].Valoare" onchange="OnValoareChange($(this).val(), 425308 , 5)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_6__Valoare" name="ListaDetaliiElemTranModelAdaugare[6].Valoare" onchange="OnValoareChange($(this).val(), 425309 , 6)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_7__Valoare" name="ListaDetaliiElemTranModelAdaugare[7].Valoare" onchange="OnValoareChange($(this).val(), 425310 , 7)" type="text" value="0.00000000000">
]
```

答:
I ran into this issue when the number of  tags in the '' did not match the number of  in the
 section

```<code><thead>
    <tr>
        <th></th>
        <th>Subject Areas</th>
        <th></th>
        <th>Option(s)</th>
    <tr>
</thead>

<tbody></tbody>

<tfoot>
    <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
    </tr>
</tfoot>
</code>```

Body:
I have the following code:

$(document).ready
(
    function ()
    {
        $.validator.addMethod(
        "lessThan",
        function (value, element, param)
        {
            // bind to the blur event of the target in order to revalidate whenever the target field is updated
            var target = $(param)
            .unbind(".validate-lessThan")
            .bind
            (
                "blur.validate-lessThan",
                function ()
                {
                    $(element).valid();
                }
            );
            return parseFloat(value) <= parseFloat(target.val());
        },
        "Valoarea trebuie sa fie mai mica sau egala decat valoarea initiala"
        );
    }
);

$('#gvListDetaliiElemTranAdaugare input[name$=Valoare]').each
    (
        function (index, domEle)
        {
            $(this).rules
            (
                "add"
                , {

                    required: true,
                    minlength: 1,
                    range: [0.1, Number.MAX_VALUE],
                    lessThan: '#ListaDetaliiElemTranModelAdaugare_' + index + '__ValoareRamasa',
                    messages:
                    {
                        required: "Valoarea este necesara!",
                        minlength: "Valoarea este necesara!",
                        range: "Valoarea este necesara!",
                        lessThan: "Valoarea trebuie sa fie mai mica sau egala cu " + $('#ListaDetaliiElemTranModelAdaugare_' + index + '__ValoareRamasa').val()

                    }
                }
            );
        }
    );

The code fails then it reeaches $(this).rules() with: Uncaught TypeError: Cannot read property 'nodeName' of null.
 the html returned by $('#gvListDetaliiElemTranAdaugare input[name$=Valoare]') is:

[
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_0__Valoare" name="ListaDetaliiElemTranModelAdaugare[0].Valoare" onchange="OnValoareChange($(this).val(), 18590 , 0)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_1__Valoare" name="ListaDetaliiElemTranModelAdaugare[1].Valoare" onchange="OnValoareChange($(this).val(), 22972 , 1)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_2__Valoare" name="ListaDetaliiElemTranModelAdaugare[2].Valoare" onchange="OnValoareChange($(this).val(), 23036 , 2)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_3__Valoare" name="ListaDetaliiElemTranModelAdaugare[3].Valoare" onchange="OnValoareChange($(this).val(), 23038 , 3)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_4__Valoare" name="ListaDetaliiElemTranModelAdaugare[4].Valoare" onchange="OnValoareChange($(this).val(), 425306 , 4)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_5__Valoare" name="ListaDetaliiElemTranModelAdaugare[5].Valoare" onchange="OnValoareChange($(this).val(), 425308 , 5)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_6__Valoare" name="ListaDetaliiElemTranModelAdaugare[6].Valoare" onchange="OnValoareChange($(this).val(), 425309 , 6)" type="text" value="0.00000000000">
,
<input data-type="decimal" id="ListaDetaliiElemTranModelAdaugare_7__Valoare" name="ListaDetaliiElemTranModelAdaugare[7].Valoare" onchange="OnValoareChange($(this).val(), 425310 , 7)" type="text" value="0.00000000000">
]

Body:
I ran into this issue when the number of <th> tags in the '' did not match the number of  in the <tfoot> section

<thead>
    <tr>
        <th></th>
        <th>Subject Areas</th>
        <th></th>
        <th>Option(s)</th>
    <tr>
</thead>

<tbody></tbody>

<tfoot>
    <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
    </tr>
</tfoot>