问:
Is a TIM interrupt also blocking background counting on STM32?
As the title says, with an STM32 if an interrupt lasts for 1 microsecond should one compensate the CCR by 1 microsecond converted in counter cycles in order to achieve the correct duty cycle?

For example with a period of 100Khz and an overflow interrupt of 1 microsecond should i use a CCR = 50Khz to achieve duty cycle of 50% or should i use a CCR = 50kHz - interrupt delay? Keep in mind that i'm using shadow register to preload the next period/duty cycle combination dynamically.

Oscilloscope readings tells me the second.

Does a flag for automatic compensation exist?

Below some code snippets

```<code>void MX_TIM9_Init(void){
    TIM_OC_InitTypeDef sConfigOC;
    htim9.Instance = TIM9;
    htim9.Init.Prescaler = PSC; // Get clock to <freq> Hz
    htim9.Init.CounterMode = TIM_COUNTERMODE_UP;
    htim9.Init.Period = 250;
    htim9.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;

    HAL_TIM_PWM_Init(&htim9);

    sConfigOC.OCMode = TIM_OCMODE_PWM1;
    sConfigOC.Pulse = 125;
    sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
    sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
    sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
    HAL_TIM_PWM_ConfigChannel(&htim9, &sConfigOC, TIM_CHANNEL_1);

    __HAL_TIM_ENABLE_IT(&htim9, TIM_IT_UPDATE);
    TIM9->CR1 |= TIM_CR1_ARPE;
}

void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef* htim_pwm){
    GPIO_InitTypeDef GPIO_InitStruct;
    if(htim_pwm->Instance==TIM9){
         __TIM9_CLK_ENABLE();
         /* Peripheral interrupt init*/
        HAL_NVIC_SetPriority(TIM1_BRK_TIM9_IRQn, 1, 1);
        HAL_NVIC_EnableIRQ(TIM1_BRK_TIM9_IRQn);
        GPIO_InitStruct.Pin = GPIO_PIN_5;
        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
        GPIO_InitStruct.Pull = GPIO_PULLUP;
        GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
        GPIO_InitStruct.Alternate = GPIO_AF3_TIM9;
        HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
    }
}

void TIM1_BRK_TIM9_IRQHandler(void){
    if(__HAL_TIM_GET_FLAG(&htim9, TIM_FLAG_UPDATE) != RESET){
        if(__HAL_TIM_GET_IT_SOURCE(&htim9, TIM_IT_UPDATE) !=RESET){
            __HAL_TIM_CLEAR_IT(&htim9, TIM_IT_UPDATE);
            myFunction(void);
        }
    }
}

void myFunction(){
    //perform logics with if
    tim9->ARR = r; // r is a value coming from the logics above
    tim9->CCR1 = r / 2;
}
</code>```

答: No - interrupts have not anything with the timers. When the interrupt line is set by the timer, it counts as normally - and the interrupt is dealt by the interrupt controller & the core. You do not have to compensate anything. </p>

Body:
As the title says, with an STM32 if an interrupt lasts for 1 microsecond should one compensate the CCR by 1 microsecond converted in counter cycles in order to achieve the correct duty cycle?

For example with a period of 100Khz and an overflow interrupt of 1 microsecond should i use a CCR = 50Khz to achieve duty cycle of 50% or should i use a CCR = 50kHz - interrupt delay? Keep in mind that i'm using shadow register to preload the next period/duty cycle combination dynamically.

Oscilloscope readings tells me the second.

Does a flag for automatic compensation exist?

Below some code snippets

void MX_TIM9_Init(void){
    TIM_OC_InitTypeDef sConfigOC;
    htim9.Instance = TIM9;
    htim9.Init.Prescaler = PSC; // Get clock to <freq> Hz
    htim9.Init.CounterMode = TIM_COUNTERMODE_UP;
    htim9.Init.Period = 250;
    htim9.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;

    HAL_TIM_PWM_Init(&htim9);

    sConfigOC.OCMode = TIM_OCMODE_PWM1;
    sConfigOC.Pulse = 125;
    sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
    sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
    sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
    HAL_TIM_PWM_ConfigChannel(&htim9, &sConfigOC, TIM_CHANNEL_1);

    __HAL_TIM_ENABLE_IT(&htim9, TIM_IT_UPDATE);
    TIM9->CR1 |= TIM_CR1_ARPE;
}

void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef* htim_pwm){
    GPIO_InitTypeDef GPIO_InitStruct;
    if(htim_pwm->Instance==TIM9){
         __TIM9_CLK_ENABLE();
         /* Peripheral interrupt init*/
        HAL_NVIC_SetPriority(TIM1_BRK_TIM9_IRQn, 1, 1);
        HAL_NVIC_EnableIRQ(TIM1_BRK_TIM9_IRQn);
        GPIO_InitStruct.Pin = GPIO_PIN_5;
        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
        GPIO_InitStruct.Pull = GPIO_PULLUP;
        GPIO_InitStruct.Speed = GPIO_SPEED_LOW;
        GPIO_InitStruct.Alternate = GPIO_AF3_TIM9;
        HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
    }
}

void TIM1_BRK_TIM9_IRQHandler(void){
    if(__HAL_TIM_GET_FLAG(&htim9, TIM_FLAG_UPDATE) != RESET){
        if(__HAL_TIM_GET_IT_SOURCE(&htim9, TIM_IT_UPDATE) !=RESET){
            __HAL_TIM_CLEAR_IT(&htim9, TIM_IT_UPDATE);
            myFunction(void);
        }
    }
}

void myFunction(){
    //perform logics with if
    tim9->ARR = r; // r is a value coming from the logics above
    tim9->CCR1 = r / 2;
}


来源: stackexchange

问:
Find Amount of Values in an Array

Problem

So, this is pretty straight forward; I am making a program that asks for some information (favorite numbers), and you separate the numbers by spaces, and that is sent to an array. Then, I need to find how many values are in the array.

Example

```<code>print "What is your favorite number? (if you have more than one, seperate by spaces)"
favoriteNumbersUnformat = gets.chomp
favoriteNumbers = favoriteNumbersUnformat.split(' ').map(&:to_i)
</code>```

Explanation & End

So, that block of code above will take some numbers, and send them to an array with it adding a new value for each space e.g 2 8 21 → [2, 8, 21]. That works just dandy but I want some way to have the program find how many values are in the array. That way, I could find out how many favorite numbers they have (for example).

I imagine this is a pretty simple problem and I thought something like this would have been asked before on Stackoverflow but I put in my title and I found nothing, over and over again. Even when I altered it a dozen times, it still didn't come up with what I want.

Any ideas? Thanks in advance!

答:
```<code>favoriteNumbers.count
</code>```

is the method you are looking for!

ContentLicense: CC BY-SA 3.0

Title: Find Amount of Values in an Array

Body:
Problem

So, this is pretty straight forward; I am making a program that asks for some information (favorite numbers), and you separate the numbers by spaces, and that is sent to an array. Then, I need to find how many values are in the array.

Example

print "What is your favorite number? (if you have more than one, seperate by spaces)"
favoriteNumbersUnformat = gets.chomp
favoriteNumbers = favoriteNumbersUnformat.split(' ').map(&:to_i)

Explanation & End

So, that block of code above will take some numbers, and send them to an array with it adding a new value for each space e.g 2 8 21 → [2, 8, 21]. That works just dandy but I want some way to have the program find how many values are in the array. That way, I could find out how many favorite numbers they have (for example).

I imagine this is a pretty simple problem and I thought something like this would have been asked before on Stackoverflow but I put in my title and I found nothing, over and over again. Even when I altered it a dozen times, it still didn't come up with what I want.

Any ideas? Thanks in advance!

Body:
favoriteNumbers.count

is the method you are looking for!


问:
Powershell, look through all drives
I'm new to Powershell and I've tried finding a solution to my problem online but I can't seem to find one. Basically I need to write something that will let powershell look through all drives and directories to find the following:

total number of files (exclude folders), largest file size, average file size, total file size

Here's what I've written so far:

```<code>$source = "get-psdrive"

#attempt at looking through all drives/directories which didn't work
foreach($a in $source) {

    #counts files in given directory
    Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object |
        ForEach-Object { $_.Count }

    #select largest file in given directory
    Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Sort-Object Length -Descending |
        Select-Object -First 1

    #get average file size in a given directory
    Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Property Length -Average

    #sum of file sizes in given directory
    (Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Sum Length).Sum
}
</code>```

The issue is that it only looks in the C drive. I don't know if there's a way to look through my computer instead of specific drives but I couldn't seem to find a way. Any help is appreciated.

答:
With "..." you define a string, so in your example you try to loop over a string.

Try it like this:

```<code>$Drives = Get-PSDrive -PSProvider 'FileSystem'

foreach($Drive in $drives) {

    #counts files in given directory
    Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object |
        ForEach-Object { $_.Count }

    #select largest file in given directory
    Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Sort-Object Length -Descending |
        Select-Object -First 1

    #get average file size in a given directory
    Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Property Length -Average

    #sum of file sizes in given directory
    (Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Sum Length).Sum

}
</code>```

Note! I didn't chang your Get-ChildItem code (except the path where it will search). I only wrote the foreach loop.

Title: Powershell, look through all drives

Body:
I'm new to Powershell and I've tried finding a solution to my problem online but I can't seem to find one. Basically I need to write something that will let powershell look through all drives and directories to find the following:

total number of files (exclude folders), largest file size, average file size, total file size

Here's what I've written so far:

$source = "get-psdrive"

#attempt at looking through all drives/directories which didn't work
foreach($a in $source) {

    #counts files in given directory
    Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object |
        ForEach-Object { $_.Count }

    #select largest file in given directory
    Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Sort-Object Length -Descending |
        Select-Object -First 1

    #get average file size in a given directory
    Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Property Length -Average

    #sum of file sizes in given directory
    (Get-ChildItem -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Sum Length).Sum
}

The issue is that it only looks in the C drive. I don't know if there's a way to look through my computer instead of specific drives but I couldn't seem to find a way. Any help is appreciated.

Body:
With "..." you define a string, so in your example you try to loop over a string.

Try it like this:

$Drives = Get-PSDrive -PSProvider 'FileSystem'

foreach($Drive in $drives) {

    #counts files in given directory
    Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object |
        ForEach-Object { $_.Count }

    #select largest file in given directory
    Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Sort-Object Length -Descending |
        Select-Object -First 1

    #get average file size in a given directory
    Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Property Length -Average

    #sum of file sizes in given directory
    (Get-ChildItem -Path $Drive.Root -Recurse -File -ErrorAction SilentlyContinue -Force |
        Measure-Object -Sum Length).Sum

}

Note! I didn't chang your Get-ChildItem code (except the path where it will search). I only wrote the foreach loop.


问:
XSLT :XSL:Number to start from 0
I have a requirement to increment a number using <xsl:number level="single"/>. However I need count to start from 0 instead of 1.

Sample Input:

```<code><name>
<Sequence>Id</Sequence>
<Field1>A1</Field1>
<Field2<A2</Field2>
</name>
<name>
<Sequence>Id</Sequence>
<Field1>A1</Field1>
<Field2<A2</Field2>
</name>
</code>```

Sample output:

```<code><name>
<Sequence>Id0</Sequence>
<Field1>A1</Field1>
<Field2<A2</Field2>
</name>
<name>
<Sequence>Id1</Sequence>
<Field1>A1</Field1>
<Field2<A2</Field2>
</name>
</code>```

XSLT Snippet:

```<code><name>
<Sequence>
Id<xsl:number level="single"/></Sequence>
------
</name>
</code>```

which generates Id1 & Id2 instead of Id0 & Id1. I could not use position() for some reason. Is it possible to have an arithmetic operation like -1 etc for eg: Id<xsl:number level="single"/> -1

答: https://www.w3.org/TR/xslt-30/#number has a start-at attribute. You can of course also use <xsl:variable name="n"><xsl:number/></xsl:variable><xsl:value-of select="$n - 1"/>.

Title: XSLT :XSL:Number to start from 0

Body:
I have a requirement to increment a number using <xsl:number level="single"/>. However I need count to start from 0 instead of 1.

Sample Input:

<name>
<Sequence>Id</Sequence>
<Field1>A1</Field1>
<Field2<A2</Field2>
</name>
<name>
<Sequence>Id</Sequence>
<Field1>A1</Field1>
<Field2<A2</Field2>
</name>

Sample output:

<name>
<Sequence>Id0</Sequence>
<Field1>A1</Field1>
<Field2<A2</Field2>
</name>
<name>
<Sequence>Id1</Sequence>
<Field1>A1</Field1>
<Field2<A2</Field2>
</name>

XSLT Snippet:

<name>
<Sequence>
Id<xsl:number level="single"/></Sequence>
------
</name>

which generates Id1 & Id2 instead of Id0 & Id1. I could not use position() for some reason. Is it possible to have an arithmetic operation like -1 etc for eg: Id<xsl:number level="single"/> -1


问:
Merging and saving images in PIL Python
I have two folders of images and I am trying to build one large image from all the slices in each folder. I need to alternate between folders to build the image. For example the first slice comes from folder 1, the second slice comes from folder 2, the third from folder 1 ect. I have the files ordered by filename in the individual folders so I am trying to iterate through the folders and add a new strip to an image. The code runs BUT it doesn't seem to be saving the composite image. I am new to PIL, so I am sure that it is something simple, but your help is appreciated. Thanks!</p>

```<code>def merge_images(file1, file2):
   """Merge two images into one, displayed above and below
   :param file1: path to first image file
   :param file2: path to second image file
   :return: the merged Image object
   """

   if file1.startswith('.'):
       return None

   image1 = Image.open(file1)
   image2 = Image.open(file2)

   (width1, height1) = image1.size
   (width2, height2) = image2.size

   result_width = width1 + width2
   result_height = max(height1, height2)

   result = Image.new('RGB', (result_width, result_height))
   result.paste(im=image1, box=(0, 0))
   result.paste(im=image2, box=(0, height1))

   return result

imageCounter = 0
firstPass = True
compImage = Image.new('RGBA', img.size, (0,0,0,0))

for i in range(len(boundingBoxes)+1):
    if firstPass:
        compImage = merge_images('./image_processing/'+ os.listdir('./image_processing/')[imageCounter],
        './img_patches/outputs/'+os.listdir('./img_patches/outputs/')[imageCounter])

        if compImage is not None:
            firstPass = False

            compImage.save('./image_processing/compImage.jpg')

    else:
        compImage = merge_images('./image_processing/compImage.jpg','./image_processing/'+ os.listdir('./image_processing/')[imageCounter])

        compImage.save('./image_processing/compImage.jpg')
        compImage = merge_images('./image_processing/compImage.jpg','./img_patches/outputs/'+ os.listdir('./img_patches/outputs/')[imageCounter])

        compImage.save('./image_processing/compImage.jpg')

    imageCounter = imageCounter + 1
</code>```

答:
You have to tell PIL to save the images:</p>

```<code>for i in range(len(boundingBoxes)+1):
    if firstPass:
        compImage = merge_images('./image_processing/'+ os.listdir('./image_processing/')[imageCounter],
        './img_patches/outputs/'+os.listdir('./img_patches/outputs/')[imageCounter])
        compImage.save(open('output/{}.png'.format(imageCounter), 'w'))
</code>```

Title: Merging and saving images in PIL Python

Body:
I have two folders of images and I am trying to build one large image from all the slices in each folder. I need to alternate between folders to build the image. For example the first slice comes from folder 1, the second slice comes from folder 2, the third from folder 1 ect. I have the files ordered by filename in the individual folders so I am trying to iterate through the folders and add a new strip to an image. The code runs BUT it doesn't seem to be saving the composite image. I am new to PIL, so I am sure that it is something simple, but your help is appreciated. Thanks!

def merge_images(file1, file2):
   """Merge two images into one, displayed above and below
   :param file1: path to first image file
   :param file2: path to second image file
   :return: the merged Image object
   """

   if file1.startswith('.'):
       return None

   image1 = Image.open(file1)
   image2 = Image.open(file2)

   (width1, height1) = image1.size
   (width2, height2) = image2.size

   result_width = width1 + width2
   result_height = max(height1, height2)

   result = Image.new('RGB', (result_width, result_height))
   result.paste(im=image1, box=(0, 0))
   result.paste(im=image2, box=(0, height1))

   return result

imageCounter = 0
firstPass = True
compImage = Image.new('RGBA', img.size, (0,0,0,0))

for i in range(len(boundingBoxes)+1):
    if firstPass:
        compImage = merge_images('./image_processing/'+ os.listdir('./image_processing/')[imageCounter],
        './img_patches/outputs/'+os.listdir('./img_patches/outputs/')[imageCounter])

        if compImage is not None:
            firstPass = False

            compImage.save('./image_processing/compImage.jpg')

    else:
        compImage = merge_images('./image_processing/compImage.jpg','./image_processing/'+ os.listdir('./image_processing/')[imageCounter])

        compImage.save('./image_processing/compImage.jpg')
        compImage = merge_images('./image_processing/compImage.jpg','./img_patches/outputs/'+ os.listdir('./img_patches/outputs/')[imageCounter])

        compImage.save('./image_processing/compImage.jpg')

    imageCounter = imageCounter + 1

Body:
You have to tell PIL to save the images:

for i in range(len(boundingBoxes)+1):
    if firstPass:
        compImage = merge_images('./image_processing/'+ os.listdir('./image_processing/')[imageCounter],
        './img_patches/outputs/'+os.listdir('./img_patches/outputs/')[imageCounter])
        compImage.save(open('output/{}.png'.format(imageCounter), 'w'))


问:
JS multiple scopes between files
This answer shows how to share a scope across several JS files.

But I'm wondering how one might go about having two (or more) levels of wider scope, shared between multiple files.

Experimenting, I've found that a slight tweak to the above answer involves sharing an object between files, and then initiating it the first time it is found to be an empty object like so:

```<code>var MODULE = (function( widerScopeVariables )
{
    if( $.isEmptyObject( widerScopeVariables ) ){
        // projectWide:
        widerScopeVariables[ 0 ] = {};
        // formsWide:
        widerScopeVariables[ 1 ] = {};
    }
    const projectWide = widerScopeVariables[ 0 ];
    ...
</code>```

... but the trouble is that projectWide and formsWide (intended to be of more restricted scope) are then both available to every file sharing this MODULE variable, even if by convention you restrict use by files which aren't intended to have access to the formsWide variables.

Furthermore, every file which might be the first to load has to include the above code.

Is there a better way to accomplish this sort of multi-level multi-file scoping in JS?

答:
I have found a sort of way to help accomplish this. It's not elegant, and merely encourages the right kind of use... it will not please JS purists, but it works for me.

For the avoidance of doubt I am aware that JS has only two scopes: global and function.

What I have done is to put a bunch of files in a subdirectory called "generic_elements".  Using the design pattern in the answer I referenced I then go like this in these files:

```<code>var HOLDER = (function( holderState )
{
  const genericDir = getDir( -2 );
  const genericWide = holderState[ genericDir ] = holderState[ genericDir ] || {};
  ...
  return holderState;
}( HOLDER || {} ));
</code>```

where getDir looks like this (global function):

```<code>function getDir( pathElement ){
    let info = new Error().stack;
    const infoLines = info.replace( /\n/g, ' ' ).split( ' ' );
    const delimiter = '/';
    // [0] or [1] would return the line for this file, not the calling file
    const tokens = infoLines[ 2 ].split(delimiter);
    // get a directory in this path. -2 means penultimate token = string between penultimate and last '/'
    return tokens.slice( pathElement )[ 0 ];
}
</code>```

... it's not the "full" version in that it only returns the final directory rather than the complete path from the main URL directory.

The idea is pretty simple: a bunch of files in a subdirectory use the path of the subdirectory containing these "files in a module" as a key in the holderState object.  They share the object genericWide.  Modules higher up can still look at this HOLDER object, but coders (hopefully) agree not to use key-value pairs from modules they know nothing about. Conversely, files in subdirectories will be able to work out the paths of ancestor directories, calling getDir with -3 or -4 or whatever... so they will be able to access their ancestor modules' "directory-wide" objects.

Title: JS multiple scopes between files

Body:
This answer shows how to share a scope across several JS files.

But I'm wondering how one might go about having two (or more) levels of wider scope, shared between multiple files.

Experimenting, I've found that a slight tweak to the above answer involves sharing an object between files, and then initiating it the first time it is found to be an empty object like so:

var MODULE = (function( widerScopeVariables )
{
    if( $.isEmptyObject( widerScopeVariables ) ){
        // projectWide:
        widerScopeVariables[ 0 ] = {};
        // formsWide:
        widerScopeVariables[ 1 ] = {};
    }
    const projectWide = widerScopeVariables[ 0 ];
    ...

... but the trouble is that projectWide and formsWide (intended to be of more restricted scope) are then both available to every file sharing this MODULE variable, even if by convention you restrict use by files which aren't intended to have access to the formsWide variables.

Furthermore, every file which might be the first to load has to include the above code.

Is there a better way to accomplish this sort of multi-level multi-file scoping in JS?

Body:
I have found a sort of way to help accomplish this. It's not elegant, and merely encourages the right kind of use... it will not please JS purists, but it works for me.

For the avoidance of doubt I am aware that JS has only two scopes: global and function.

What I have done is to put a bunch of files in a subdirectory called "generic_elements".  Using the design pattern in the answer I referenced I then go like this in these files:

var HOLDER = (function( holderState )
{
  const genericDir = getDir( -2 );
  const genericWide = holderState[ genericDir ] = holderState[ genericDir ] || {};
  ...
  return holderState;
}( HOLDER || {} ));

where getDir looks like this (global function):

function getDir( pathElement ){
    let info = new Error().stack;
    const infoLines = info.replace( /\n/g, ' ' ).split( ' ' );
    const delimiter = '/';
    // [0] or [1] would return the line for this file, not the calling file
    const tokens = infoLines[ 2 ].split(delimiter);
    // get a directory in this path. -2 means penultimate token = string between penultimate and last '/'
    return tokens.slice( pathElement )[ 0 ];
}

... it's not the "full" version in that it only returns the final directory rather than the complete path from the main URL directory.

The idea is pretty simple: a bunch of files in a subdirectory use the path of the subdirectory containing these "files in a module" as a key in the holderState object.  They share the object genericWide.  Modules higher up can still look at this HOLDER object, but coders (hopefully) agree not to use key-value pairs from modules they know nothing about. Conversely, files in subdirectories will be able to work out the paths of ancestor directories, calling getDir with -3 or -4 or whatever... so they will be able to access their ancestor modules' "directory-wide" objects.


问:
Using shared_ptr with a const reference
I need to make several Worker classes that have a pointer to an Object owned by the main program. This is in C++14

For reasons, the Object has to meet certain criteria - it has to have a deleted default constructor, its non-copyable, non-movable.  And I need to use smart pointers.

The main program will own the Object. Each worker class needs to read stuff from it

```<code>class Object
{
  Object() = delete;
  ~Object();

  // Non copyable
  Object(const Object &other) = delete;
  Object &operator=(const Object &other) = delete;

  // Non movable
  Object(Object &&other) = delete;
  Object &operator=(Object &&other) = delete;

  // Constructor
  explicit Object(double threshold);
};

class Worker
{
public:
  void initialize(const Object& obj)
  {
    // Option 1 - errors out, complains its non copyable
    object_ptr = std::make_shared<const Object>(obj);

    // Option 2
    object_ptr = std::shared_ptr<const Object>(&obj);

    // Option 3
    object_ptr = std::shared_ptr<const Object>(&obj, [](const Object*){});
  }

  void doSomething();

private:
  std::shared_ptr<const Object> object_ptr;
};

int main ()
{
  Object object;

  Worker worker1;
  Worker worker2;

  worker1.initialize(object);
  worker2.initialize(object);

  while(1)
  {
    // Main does stuff to Object

    worker1.doSomething();
    worker2.doSomething();
  }

  return 0;
}
</code>```

What's the best way to initialize the pointer inside of Worker?

答:
I personally would do this

```<code>class Worker
{
public:
    void initialize(const Object& obj)
    {
        object_ptr = &obj;
    }
private:
    const Object* object_ptr = nullptr;
};
</code>```

A raw pointer indicates non-ownership, which is exactly what the situation is.

If you must use a shared_ptr, there is no way around passing in one as an argument, shared_ptr has more data associated with it than just the managed object.

```<code>class Worker
{
public:
    void initialize(std::shared_ptr<const Object> p)
    {
        swap(object_ptr, p);
    }
private:
    std::shared_ptr<const Object> object_ptr;
};

int main()
{
    auto obj = std::make_shared<const Object>();
    //...
}
</code>```

A shared_ptr means exactly what it says: the resource is shared. To pass around a shared_ptr is to proclaim there are multiple owners and the resource is common to all of them, aka the resource must outlive any of them.

Note how you have the object on the stack (or rather, have automatic storage duration) which is indicative that this resource is not in fact, owned by the workers. By definition of the workers, we know automatically that the object will outlive the workers, and this is by far superior to using shared_ptrs.

Title: Using shared_ptr with a const reference

Body:
I need to make several Worker classes that have a pointer to an Object owned by the main program. This is in C++14

For reasons, the Object has to meet certain criteria - it has to have a deleted default constructor, its non-copyable, non-movable.  And I need to use smart pointers.

The main program will own the Object. Each worker class needs to read stuff from it

class Object
{
  Object() = delete;
  ~Object();

  // Non copyable
  Object(const Object &other) = delete;
  Object &operator=(const Object &other) = delete;

  // Non movable
  Object(Object &&other) = delete;
  Object &operator=(Object &&other) = delete;

  // Constructor
  explicit Object(double threshold);
};

class Worker
{
public:
  void initialize(const Object& obj)
  {
    // Option 1 - errors out, complains its non copyable
    object_ptr = std::make_shared<const Object>(obj);

    // Option 2
    object_ptr = std::shared_ptr<const Object>(&obj);

    // Option 3
    object_ptr = std::shared_ptr<const Object>(&obj, [](const Object*){});
  }

  void doSomething();

private:
  std::shared_ptr<const Object> object_ptr;
};

int main ()
{
  Object object;

  Worker worker1;
  Worker worker2;

  worker1.initialize(object);
  worker2.initialize(object);

  while(1)
  {
    // Main does stuff to Object

    worker1.doSomething();
    worker2.doSomething();
  }

  return 0;
}

What's the best way to initialize the pointer inside of Worker?

Body:
I personally would do this

class Worker
{
public:
    void initialize(const Object& obj)
    {
        object_ptr = &obj;
    }
private:
    const Object* object_ptr = nullptr;
};

A raw pointer indicates non-ownership, which is exactly what the situation is.

If you must use a shared_ptr, there is no way around passing in one as an argument, shared_ptr has more data associated with it than just the managed object.

class Worker
{
public:
    void initialize(std::shared_ptr<const Object> p)
    {
        swap(object_ptr, p);
    }
private:
    std::shared_ptr<const Object> object_ptr;
};

int main()
{
    auto obj = std::make_shared<const Object>();
    //...
}

A shared_ptr means exactly what it says: the resource is shared. To pass around a shared_ptr is to proclaim there are multiple owners and the resource is common to all of them, aka the resource must outlive any of them.

Note how you have the object on the stack (or rather, have automatic storage duration) which is indicative that this resource is not in fact, owned by the workers. By definition of the workers, we know automatically that the object will outlive the workers, and this is by far superior to using shared_ptrs.


问:
How can I get a JSON status that my server is busy?
My JSON Code:

```<code>Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            int success = jsonResponse.getInt("success");

                            if (success == 0) {

                            }
                            if (success == 1) {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                nRequest nRequest = new nRequest(edtTextReg.getText().toString(), responseListener);
                RequestQueue queue = Volley.newRequestQueue(login.this);
                queue.add(nRequest);
</code>```

How can I find a way that JSON give me the status "server is busy"? Busy means for example: thousands of people use my server.

答:
If your server is busy you don't want it to spend time rendering a JSON, moreover, if server load is in your mind you might end up putting your application behind a load-balancer and those usually knows nothing about JSON.

The proper way to handle this situation is to parse the correct HTTP status code, usually 429, see this answer

To access the status code your onResponse should look like this:

```<code>@Override
public void onSuccess(int statusCode, String content) {
}
</code>```

Body:
My JSON Code:

Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            int success = jsonResponse.getInt("success");

                            if (success == 0) {

                            }
                            if (success == 1) {

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };
                nRequest nRequest = new nRequest(edtTextReg.getText().toString(), responseListener);
                RequestQueue queue = Volley.newRequestQueue(login.this);
                queue.add(nRequest);

How can I find a way that JSON give me the status "server is busy"? Busy means for example: thousands of people use my server.

Body:
If your server is busy you don't want it to spend time rendering a JSON, moreover, if server load is in your mind you might end up putting your application behind a load-balancer and those usually knows nothing about JSON.

The proper way to handle this situation is to parse the correct HTTP status code, usually 429, see this answer

To access the status code your onResponse should look like this:

@Override
public void onSuccess(int statusCode, String content) {
}


问:
Numbering of groups in select (Oracle)
I have a following example - table with name, department and country. I need to create a select statement that lists all records and assigns unique number to each group of department and country (column Group in the example):

```<code>Name   Department   Country   Group
====== ============ ========= =====
James  HR           UK        1
John   HR           UK        1
Alice  Finance      UK        2
Bob    Finance      DE        3
Frank  Finance      DE        3
</code>```

I thought of some select with analytic function but I found only row_number() over (partition by department, country) which numbers records inside the group and not groups themselves. Do you have any idea how to solve this problem? Thank you!

答:
```<code>SELECT  t.*, q.grp
FROM    (
        SELECT  q.*, rownum AS grp
        FROM    (
                SELECT  DISTINCT department, country
                FROM    mytable
                ORDER BY
                        department, country
                ) q
        ) q
JOIN    mytable t
ON      t.department = q.department
        AND t.country = q.country
</code>```

or

```<code>SELECT  t.*, DENSE_RANK() OVER (ORDER BY department desc, country desc) AS grp
FROM    mytable
</code>```

ContentLicense: CC BY-SA 2.5

Title: Numbering of groups in select (Oracle)

Body:
I have a following example - table with name, department and country. I need to create a select statement that lists all records and assigns unique number to each group of department and country (column Group in the example):

Name   Department   Country   Group
====== ============ ========= =====
James  HR           UK        1
John   HR           UK        1
Alice  Finance      UK        2
Bob    Finance      DE        3
Frank  Finance      DE        3

I thought of some select with analytic function but I found only row_number() over (partition by department, country) which numbers records inside the group and not groups themselves. Do you have any idea how to solve this problem? Thank you!

Body:
SELECT  t.*, q.grp
FROM    (
        SELECT  q.*, rownum AS grp
        FROM    (
                SELECT  DISTINCT department, country
                FROM    mytable
                ORDER BY
                        department, country
                ) q
        ) q
JOIN    mytable t
ON      t.department = q.department
        AND t.country = q.country

or

SELECT  t.*, DENSE_RANK() OVER (ORDER BY department desc, country desc) AS grp
FROM    mytable


问:
Redux updating entire array
I'm trying to figure out why my components are not updating after Redux's store receives new data. Github issues seem to indicate that I'm mutating the object without returning it, but I haven't been able to find how to do this with entire arrays.

Here's my current code.

```<code>initialState = []
...
switch(action.type) {
   case "SET_STORIES": {
     state = [...action.payload]; // data is an array of objects.
     // does not work either: state = [...state, action.payload];
     break;
   }
}
return state;
</code>```

In the same command, I 'd also like to overwrite the entire array if there is previous data present.

Is this correct? (console logs logs the updated array, but does this mean its being returned to the components?)

答: It is hard to tell without whole code, this snippet does look OK, at least as long as payload is array of immutable objects. However, if it is array of mutable objects, and for instance your payload carries array of same objects as previous state, but mutated, then your sub-components displaying details of each element might fail to recognize change.</p>

Title: Redux updating entire array

Body:
I'm trying to figure out why my components are not updating after Redux's store receives new data. Github issues seem to indicate that I'm mutating the object without returning it, but I haven't been able to find how to do this with entire arrays.

Here's my current code.

initialState = []
...
switch(action.type) {
   case "SET_STORIES": {
     state = [...action.payload]; // data is an array of objects.
     // does not work either: state = [...state, action.payload];
     break;
   }
}
return state;

In the same command, I 'd also like to overwrite the entire array if there is previous data present.

Is this correct? (console logs logs the updated array, but does this mean its being returned to the components?)


问:
sap ui table max rows visible
I have an OpenUI5 xml view with 2 tables beneath each other.

I want the first one to display 5 rows at a time and the second one to display 20 rows.

What property do I need to set to get this?

EDIT: I'm using a sap.ui.table not the sap.m.table

答:
If in case its sap.ui.table.Table then use visibleRowCount='10'
 it will show 10 row data to user and if data is more that 10 it show scroll bar.</p>

Title: sap ui table max rows visible


问:
pypyodbc not throwing expected exception upon retry of connection
I am attempting to insert some rows of data in to a SQL Server database using pypyodbc. The code I have written, catches any pypyodbc.Error and if this occurs, retries the DB operation up to a maximum of 3 times. In my tests I have managed to attempt to insert a duplicate key row of data - the exception is caught and the retry begins. The problem is that upon the retry the exception is not caught and the code hangs. Here is the code:

```<code># attempt to connect to the db - if unsuccessful, try up to 3 times
for i in range (3):
    try:
        # connect to db
        db = pypyodbc.connect("DRIVER={SQL Server};SERVER=SERVER;DATABASE=DB;UID=user;PWD=password")
        cursor = db.cursor()

        # Loop round assigning the values in the lists at the given index to a new variable
        for j in range (0,sector):
            value1 = list1[j]
            value2 = list2[j]
            value3 = list3[j]

            # print each of the values, as a sanity check
            print('Value 1 = ' + value1)
            print('Value 2 = ' + value2)
            print('Value 3 = ' + value3+ "\n")

            #if (value1 is not None and value2 is not None and value3 is not None):
            cursor.execute('''INSERT INTO table(field1,field2,field3) VALUES (?,?,?)''', (value1,value2,value3))
            cursor.commit()

        # close off the open connections
        cursor.close()
        db.close()
        # if successful, break out of the loop so there is no retry
        break

    # if there is a mysql exception thrown, print a message and retry
    except pypyodbc.Error, e:
        message = "Connection attempt " + str(i+1) + ": " + str(e)
        print(message)

    # if we reach this stage for a 3rd time, exit the program as no connection is possible and send an error email
    if i == 2:
        message = message + "\nThe script will now terminate."
        print (message)
        send_error_email(message)
        sys.exit()
</code>```

Upon the first attempt the values are written to the console and the exception (u'23000', u"[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert duplicate key row in object....) is reported. The retry kicks in and the values are written to console again. This is where the program hangs. Why is the exception not being caught on the retry?

答:
Your code is repeating the whole insertion process every time it fails, and after failing the first attempt will fail again as the record has already been inserted.

I'd suggest using a counter instead of a for loop to limit your trials:

```<code>trials = 0
db = pypyodbc.connect("DRIVER={SQL Server};SERVER=SERVER;DATABASE=DB;UID=user;PWD=password")
cursor = db.cursor()

for j in range (0,sector):
    assert trials < 3
    value1 = list1[j]
    value2 = list2[j]
    value3 = list3[j]
    print('Value 1 = {0}\nValue 2 = {1}\nValue 3 = {2}'.format(value1,value2,value3))
    try:
        cursor.execute('''INSERT INTO table(field1,field2,field3) VALUES (?,?,?)'''
                       , (value1,value2,value3))
        cursor.commit()
    except pypyodbc.Error, e:
        trials += 1
        message = "Connection attempt " + str(trials) + ": " + str(e)
        print(message)
    except AssertionError:
        message = message + "\nThe script will now terminate."
        print (message)
        send_error_email(message)
        sys.exit()

cursor.close()
db.close()
</code>```

Hope that helps.

Body:
I am attempting to insert some rows of data in to a SQL Server database using pypyodbc. The code I have written, catches any pypyodbc.Error and if this occurs, retries the DB operation up to a maximum of 3 times. In my tests I have managed to attempt to insert a duplicate key row of data - the exception is caught and the retry begins. The problem is that upon the retry the exception is not caught and the code hangs. Here is the code:

# attempt to connect to the db - if unsuccessful, try up to 3 times
for i in range (3):
    try:
        # connect to db
        db = pypyodbc.connect("DRIVER={SQL Server};SERVER=SERVER;DATABASE=DB;UID=user;PWD=password")
        cursor = db.cursor()

        # Loop round assigning the values in the lists at the given index to a new variable
        for j in range (0,sector):
            value1 = list1[j]
            value2 = list2[j]
            value3 = list3[j]

            # print each of the values, as a sanity check
            print('Value 1 = ' + value1)
            print('Value 2 = ' + value2)
            print('Value 3 = ' + value3+ "\n")

            #if (value1 is not None and value2 is not None and value3 is not None):
            cursor.execute('''INSERT INTO table(field1,field2,field3) VALUES (?,?,?)''', (value1,value2,value3))
            cursor.commit()

        # close off the open connections
        cursor.close()
        db.close()
        # if successful, break out of the loop so there is no retry
        break

    # if there is a mysql exception thrown, print a message and retry
    except pypyodbc.Error, e:
        message = "Connection attempt " + str(i+1) + ": " + str(e)
        print(message)

    # if we reach this stage for a 3rd time, exit the program as no connection is possible and send an error email
    if i == 2:
        message = message + "\nThe script will now terminate."
        print (message)
        send_error_email(message)
        sys.exit()

Upon the first attempt the values are written to the console and the exception (u'23000', u"[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot insert duplicate key row in object....) is reported. The retry kicks in and the values are written to console again. This is where the program hangs. Why is the exception not being caught on the retry?

Body:
Your code is repeating the whole insertion process every time it fails, and after failing the first attempt will fail again as the record has already been inserted.

I'd suggest using a counter instead of a for loop to limit your trials:

trials = 0
db = pypyodbc.connect("DRIVER={SQL Server};SERVER=SERVER;DATABASE=DB;UID=user;PWD=password")
cursor = db.cursor()

for j in range (0,sector):
    assert trials < 3
    value1 = list1[j]
    value2 = list2[j]
    value3 = list3[j]
    print('Value 1 = {0}\nValue 2 = {1}\nValue 3 = {2}'.format(value1,value2,value3))
    try:
        cursor.execute('''INSERT INTO table(field1,field2,field3) VALUES (?,?,?)'''
                       , (value1,value2,value3))
        cursor.commit()
    except pypyodbc.Error, e:
        trials += 1
        message = "Connection attempt " + str(trials) + ": " + str(e)
        print(message)
    except AssertionError:
        message = message + "\nThe script will now terminate."
        print (message)
        send_error_email(message)
        sys.exit()

cursor.close()
db.close()

Hope that helps.


问:
Is there a full HTML/Javascript online search engine?
I'm looking for a search engine that would also index the html and javascript code, and not only the rendering.

Use case: Some specific hardcoded javascript parameter is used somewhere in the ~80000 pages site I work on. I need to find where is the page with a specific parameter.

Much appreciated.

EDIT: Context: I don't have direct access to the code. The parameter in question is used to configure some info to send to Adobe's Omniture (into which I get weird hits).

EDIT: Maybe there is no such search engine. I'll keep the question open...

答:
As far as I know, there isn't an online search engine that would do that. The closest you can get to that would be Google Code Search which indexes public source code. You might be able to make use of it if you host your code as a public repository on services such as github, google code, sourceforge, etc.

If it is a private project you're working on, then you should have access to the source code, no? If so, then as @Spiny Norman mentioned, you can simply use grep.

For a large source base, you might be better off using ack.

If you have your code in SVN/Git, look up svnquery or git grep.


问:
Node.JS with Express and SASS - Compiled CSS file not applied
I'm new to NodeJS and I'm using Express to serve my pug files/view. Furthermore I'm using "express-sass-middleware" to compile and serve the scss/css files. Everything works very well but unfortunately, the CSS are not applied.

My app.js files looks like:

```<code>var express = require('express');
var sassMiddleware = require('express-sass-middleware');
var app = express();
app.set('view engine', 'pug');

app.get('/css/bootstrap.css', sassMiddleware({
  file: 'css/bootstrap.scss', // the location of the entry point,
                                     // this can also be a directory

  precompile: true,                   // should it be compiled on server start
                                     // or deferred to the first request
                                     //  - defaults to false
}));

app.get('/', function (req, res) {
    res.render('index', {
        varTitle: 'Hello World'
    });
});

app.listen(3000, function() {
    console.log('Example app listening on port 3000!');
});
</code>```

And my simple css file looks like:

```<code>// $icon-font-path: /3rdparty/fonts;

// @import 'bootstrap/bootstrap';
// @import './node_modules/bootstrap-sass/assets/stylesheets/bootstrap/variables';

body
{
    background-color: green;
    font-size: 100px;
}
</code>```

My index.pug file is:

```<code>doctype html
html(lang='en')
  head
    title= varTitle
    link(ref='stylesheet' type='text/css' href='/css/bootstrap.css')
  body
    h1= varTitle
</code>```

Now, when I start my webserver using "node app.js", accessing http://localhost:3000, I see "Hello World" but unfortunately the body background isn't green and the text is also not 100px. That means that the css file is not applied. But when I access http://localhost:3000/css/bootstrap.css, I see the valid, css file.

Anyone know what I'm missing here? I'm a bit confused that I see the CSS source when accessing it directly but the browser doesn't apply the css styling. I already tried different browsers without any success. None of them applying the css file.

答:
you don't seem to be serving the static files from your nodejs server code. You have to add your css dir in order to allow access from your html code:

```<code>app.use('/static', express.static('public'))
</code>```

Now, you can load the files that are in the public directory from the /static path prefix.

```<code>http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
</code>```

Body:
I'm new to NodeJS and I'm using Express to serve my pug files/view. Furthermore I'm using "express-sass-middleware" to compile and serve the scss/css files. Everything works very well but unfortunately, the CSS are not applied.

My app.js files looks like:

var express = require('express');
var sassMiddleware = require('express-sass-middleware');
var app = express();
app.set('view engine', 'pug');

app.get('/css/bootstrap.css', sassMiddleware({
  file: 'css/bootstrap.scss', // the location of the entry point,
                                     // this can also be a directory

  precompile: true,                   // should it be compiled on server start
                                     // or deferred to the first request
                                     //  - defaults to false
}));

app.get('/', function (req, res) {
    res.render('index', {
        varTitle: 'Hello World'
    });
});

app.listen(3000, function() {
    console.log('Example app listening on port 3000!');
});

And my simple css file looks like:

// $icon-font-path: /3rdparty/fonts;

// @import 'bootstrap/bootstrap';
// @import './node_modules/bootstrap-sass/assets/stylesheets/bootstrap/variables';

body
{
    background-color: green;
    font-size: 100px;
}

My index.pug file is:

doctype html
html(lang='en')
  head
    title= varTitle
    link(ref='stylesheet' type='text/css' href='/css/bootstrap.css')
  body
    h1= varTitle

Now, when I start my webserver using "node app.js", accessing http://localhost:3000, I see "Hello World" but unfortunately the body background isn't green and the text is also not 100px. That means that the css file is not applied. But when I access http://localhost:3000/css/bootstrap.css, I see the valid, css file.

Anyone know what I'm missing here? I'm a bit confused that I see the CSS source when accessing it directly but the browser doesn't apply the css styling. I already tried different browsers without any success. None of them applying the css file.

Body:
you don't seem to be serving the static files from your nodejs server code. You have to add your css dir in order to allow access from your html code:

app.use('/static', express.static('public'))

Now, you can load the files that are in the public directory from the /static path prefix.

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html


问:
pass value to next page
I have a php page (search.php) which has a link to another php page. (reserve.php). I want to

```<code>  1. pass the link text to the next page
  2. display that link text in a input box
</code>```

Please tell me how should I write the proper coding for the above tasks.

search.php

```<code><a href="Reserve.php"><?php echo $row['AccNo'];?></a>
</code>```

答:
You could use the $_SESSION to pass value through pages.

```<code>$_SESSION['AccNo'] = $row['AccNo']
</code>```

You can then access it via $_SESSION['AccNo'] in your other page. Be careful, make sure you started a session using session_start() before use session.

If you prefer using something else, @Max answer was also a pretty way to get data from one page to another, but I would not recommend it for sensitive information.

Title: pass value to next page

Body:
I have a php page (search.php) which has a link to another php page. (reserve.php). I want to

  1. pass the link text to the next page
  2. display that link text in a input box

Please tell me how should I write the proper coding for the above tasks.

search.php

<?php echo $row['AccNo'];?>

Body:
You could use the $_SESSION to pass value through pages.

$_SESSION['AccNo'] = $row['AccNo']

You can then access it via $_SESSION['AccNo'] in your other page. Be careful, make sure you started a session using session_start() before use session.

If you prefer using something else, @Max answer was also a pretty way to get data from one page to another, but I would not recommend it for sensitive information.


问:
ADFS 3.0 server with JS Client on dfiferent domains, Oauth2 Sign out no redirect
We have an ADFS server setup on one domain:

```<code>ADFSSERVER.com/
</code>```

and we have a javascript client set up on another domain

```<code>JavascriptClient.com/
</code>```

We added the javascript client to the ADFS server using the Add-Client command in the powershell.

From here, we cann sign in using oauth 2 and obtain a token including claims.
The problem now is that we want the user to sign out from our app.

We have tried using the following url to sign out which works, but when we want to be able to redirect after sign out, when we specify the the redirect url (wreply=) in the query string, it never seems to work. We have tried everything

```<code>https://ADFSSERVER.coom/adfs/ls/?wa=wsignout1.0&wreply="https://JavascriptClient.com/" .
</code>```

How can we redirect after sign out in ADFS 3.00 server 2012r2?
If they are on different domains, on different servers is this possible?
If so, how is this acheived.

Any help would be greatly appreciated :)

答: ADFS 3.0 has OpenId Connect support (extension of OAuth 2). Check if there is a end_session_endpoint in the OpenID connect discovery endpoint defined https://ADFSSERVER/.well-known/openid-configuration see OpenID connect session management</p>

Body:
We have an ADFS server setup on one domain:

ADFSSERVER.com/

and we have a javascript client set up on another domain

JavascriptClient.com/

We added the javascript client to the ADFS server using the Add-Client command in the powershell.

From here, we cann sign in using oauth 2 and obtain a token including claims.
The problem now is that we want the user to sign out from our app.

We have tried using the following url to sign out which works, but when we want to be able to redirect after sign out, when we specify the the redirect url (wreply=) in the query string, it never seems to work. We have tried everything

https://ADFSSERVER.coom/adfs/ls/?wa=wsignout1.0&wreply="https://JavascriptClient.com/" .

How can we redirect after sign out in ADFS 3.00 server 2012r2?
If they are on different domains, on different servers is this possible?
If so, how is this acheived.

Any help would be greatly appreciated :)


问:
laravel can't retrieve session when redirect
in laravel 5.4

```<code>class AdminController extends Controller
{

   public function checkLogin(Request $request)
   {
      Session::put('admin','yes');
      return redirect('mobiles');
   }
}

class MobilesController extends Controller
{
      public function __construct()
      {
         if( ( Session::has('admin') ) )
           { dd('admin');}
        else
           { dd('not admin'); }
     }
}
</code>```

it prints 'not admin' so what happen to the session , if i prints the admin session in class checkLogin it prints normally

答:
Since L5.3, you cannot a access to the session in the controller's constructor. You have to use a closure :

```<code>public function __construct()
{
    $this->middleware(function ($request, $next) {
        echo Session::has('admin') ? 'admin' : 'not admin';
        return $next($request);
    });
}
</code>```

https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors

Body:
in laravel 5.4

class AdminController extends Controller
{

   public function checkLogin(Request $request)
   {
      Session::put('admin','yes');
      return redirect('mobiles');
   }
}

class MobilesController extends Controller
{
      public function __construct()
      {
         if( ( Session::has('admin') ) )
           { dd('admin');}
        else
           { dd('not admin'); }
     }
}

it prints 'not admin' so what happen to the session , if i prints the admin session in class checkLogin it prints normally

Body:
Since L5.3, you cannot a access to the session in the controller's constructor. You have to use a closure :

public function __construct()
{
    $this->middleware(function ($request, $next) {
        echo Session::has('admin') ? 'admin' : 'not admin';
        return $next($request);
    });
}

https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors


问:
Send data to server side from client
I'm currently creating a simple web-based data visualization tool. I basically want to be able to send the user selections to the server (which I have created using express) to query the database. The problem is I am not sure how to send the data to the server and then receive it at the other end in order to do this.

I want the data to be sent to the server on the click of a button

var data = {
    Admission_type: "";
    Gender: "";
    Max_age: 89,
    Min_age: 0
};

$( "#PlotBtn" ).click(function() {

});```

答:
There exists a lot of way to send data through the network. As explained @Asinus, the most common way is to use XMLHttpRequest (aka xhr) but the most modern browsers offers better way to achieve the purpose. One of them is the Fetch API. It is more powerful than its predecessor xhr!

I recommend you to take a look to this blog post about Fetch. Here, an example of use:

```<code>fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'get'
}).then(response => {
  console.log(response.json()); // Response, everything is fine
}).cath(err => {
  console.log(err); // Failure: an error occurred
});
</code>```

In your case, if you want to send data to your server, you have to make a POST request to be Restful.

Title: Send data to server side from client

Body:
There exists a lot of way to send data through the network. As explained @Asinus, the most common way is to use XMLHttpRequest (aka xhr) but the most modern browsers offers better way to achieve the purpose. One of them is the Fetch API. It is more powerful than its predecessor xhr!

I recommend you to take a look to this blog post about Fetch. Here, an example of use:

fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'get'
}).then(response => {
  console.log(response.json()); // Response, everything is fine
}).cath(err => {
  console.log(err); // Failure: an error occurred
});

In your case, if you want to send data to your server, you have to make a POST request to be Restful.


问:
How to develop a web-based XMPP chat facility using PHP and JQuery?
I am looking to develop a website which features a chat facility between a website visitor and the website administrator.

I know the best way to do this would be using XMPP, however I have no experience using it. I am looking to implement this using PHP.

I've downloaded XMPPHP and I edited an example to send a message to my Google Chat client in GMail, but when I reply Google tells me the other end didn't get the message.

So far, the most informative tutorial is http://www.ibm.com/developerworks/xml/tutorials/x-realtimeXMPPtut/ but I don't understand why I need to install 'Openfire' nor do I want to build the website on my local machine.

Can somebody please tell me what I need (and more importantly, why) to set up this project so I can start to build the code for it?

答:
Instant Messaging apps are supposed to be real time. A website works on HTTP protocol which uses request/response method. One way to do it is POLLING. send a request for new pending messages for the user to the server. The server should be able to  differentiate between the messages which has been sent and the ones which are yet to be delivered. this method is called Polling. Your browser is constantly asking the server to send any pending messages.
But this may waste bandwidth and also drain battery ( in case the website is accessed using a smartphone ). Better option is to still use the XMPP server.</p>


问:
Angular 2 Material change md-radio-button color
I want to change the default color of the md-radio-button to blue. Is there any way to override the current color?

https://material.angular.io/components/radio/overview

I tried (solution i found here):

```<code>.my-radio md-radio-button , md-radio-button.md-checked ._md-on{
  background-color: DodgerBlue !important;
}
</code>```

however this isnt working.

答:
You can set the style in the component's CSS file:

```<code>/deep/ .mat-radio-button.mat-accent.mat-radio-checked .mat-radio-outer-circle {
    border-color: DodgerBlue;
}

/deep/ .mat-radio-button.mat-accent .mat-radio-inner-circle {
    background-color: DodgerBlue;
}
</code>```

If you want to apply it for whole application, then put the css in root component's css.

Body:
I want to change the default color of the md-radio-button to blue. Is there any way to override the current color?

https://material.angular.io/components/radio/overview

I tried (solution i found here):

.my-radio md-radio-button , md-radio-button.md-checked ._md-on{
  background-color: DodgerBlue !important;
}

however this isnt working.

Body:
You can set the style in the component's CSS file:

/deep/ .mat-radio-button.mat-accent.mat-radio-checked .mat-radio-outer-circle {
    border-color: DodgerBlue;
}

/deep/ .mat-radio-button.mat-accent .mat-radio-inner-circle {
    background-color: DodgerBlue;
}

If you want to apply it for whole application, then put the css in root component's css.


问:
Best way to dynamically get column names from oracle tables
We are using an extractor application that will export data from the database to csv files. Based on some condition variable it extracts data from different tables, and for some conditions we have to use UNION ALL as the data has to be extracted from more than one table. So to satisfy the UNION ALL condition we are using nulls to match the number of columns.

Right now all the queries in the system are pre-built based on the condition variable. The problem is whenever there is change in the table projection (i.e new column added, existing column modified, column dropped) we have to manually change the code in the application.

Can you please give some suggestions how to extract the column names dynamically so that any changes in the table structure do not require change in the code?

My concern is the condition that decides which table to query. The variable condition is
like

if the condition is A, then load from TableX

if the condition is B  then load from TableA and TableY.

We must know from which table we need to get data.  Once we know the table it is  straightforward to query the column names from the data dictionary.  But there is one more condition, which is that some columns need to be excluded, and these columns are different for each table.

I am trying to solve the problem only for dynamically generating the list columns. But my manager told me to make solution on the conceptual level rather than just fixing. This is a very big system with providers and consumers constantly loading and consuming data. So he wanted solution that can be general.

So what is the best way for storing condition, tablename, excluded columns?  One way is storing in database.   Are there any other ways? If yes what is the best?  As I have to give at least a couple of ideas before finalizing.

Thanks,

答:
A simple query like this helps you to know each column name of a table in Oracle.

```<code>Select COLUMN_NAME from user_tab_columns where table_name='EMP'
</code>```

Use it in your code :)

Body:
A simple query like this helps you to know each column name of a table in Oracle.

Select COLUMN_NAME from user_tab_columns where table_name='EMP'

Use it in your code :)


问:
Could not find a version that satisfies the requirement lxml News-Please
I am trying to install a Python package called news-please. This package is already on PyPi and on Github.

When I do pip install news-please as shown on the Github page, it shows the following:

```<code>Collecting news-please
  Using cached news-please-1.1.48.tar.gz
Collecting Scrapy>=1.1.0 (from news-please)
  Using cached Scrapy-1.4.0-py2.py3-none-any.whl
Collecting PyMySQL>=0.7.9 (from news-please)
  Using cached PyMySQL-0.7.11-py2.py3-none-any.whl
Collecting hjson>=1.5.8 (from news-please)
  Using cached hjson-2.0.7.tar.gz
Collecting elasticsearch>=2.4 (from news-please)
  Using cached elasticsearch-5.4.0-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade):
beautifulsoup4>=4.3.2 in c:\users\[my name]\anaconda3\lib\site-packages
(from news-please)
Collecting readability-lxml>=0.6.2 (from news-please)
  Using cached readability-lxml-0.6.2.tar.gz
Collecting langdetect>=1.0.7 (from news-please)
  Using cached langdetect-1.0.7.zip
Requirement already satisfied (use --upgrade to upgrade): python-
dateutil>=2.4.0 in c:\users\[my name]\anaconda3\lib\site-packages (from
news-please)
Requirement already satisfied (use --upgrade to upgrade): plac>=0.9.6 in
c:\users\[my name]\anaconda3\lib\site-packages (from news-please)
Collecting dotmap>=1.2.17 (from news-please)
  Using cached dotmap-1.2.17.tar.gz
Collecting PyDispatcher>=2.0.5 (from news-please)
  Using cached PyDispatcher-2.0.5.tar.gz
Collecting warcio>=1.3.3 (from news-please)
  Using cached warcio-1.3.4-py2.py3-none-any.whl
Collecting ago>=0.0.9 (from news-please)
  Using cached ago-0.0.9.tar.gz
Collecting newspaper3k (from news-please)
  Using cached newspaper3k-0.2.2.tar.gz
Requirement already satisfied (use --upgrade to upgrade): pywin32>=220 in
c:\users\[my name]\anaconda3\lib\site-packages (from news-please)
Collecting lxml>=3.35 (from news-please)
 Could not find a version that satisfies the requirement lxml>=3.35 (from
 news-please) (from versions: 0.9, 0.9.1, 0.9.2, 1.0b0, 1.0, 1.0.1, 1.0.2,
 1.0.3, 1.0.4, 1.1a0, 1.1b0, 1.1, 1.1.1, 1.1.2, 1.2, 1.2.1, 1.3b0, 1.3,
 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 2.0a1, 2.0a2, 2.0a3, 2.0a4, 2.0a5,
 2.0a6, 2.0b1, 2.0b2, 2.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.0.6, 2.0.7,
 2.0.8, 2.0.9, 2.0.10, 2.0.11, 2.1a1, 2.1b1, 2.1b2, 2.1b3, 2.1, 2.1.1,
 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.2a1, 2.2b1, 2.2b2, 2.2b3, 2.2b4, 2.2, 2.2.1,
 2.2.2, 2.2.3, 2.2.4, 2.2.5, 2.2.6, 2.2.7, 2.2.8, 2.3b1, 2.3, 2.3.1, 2.3.2,
 2.3.3, 2.3.4, 2.3.5, 2.3.6, 3.0, 3.0.1, 3.0.2, 3.1b1, 3.1.0, 3.1.1, 3.1.2,
 3.2.0, 3.2.1, 3.2.2, 3.2.3, 3.2.4, 3.2.5, 3.3.0b1, 3.3.0b2, 3.3.0b3,
 3.3.0b4, 3.3.0b5, 3.3.0, 3.3.1, 3.3.2, 3.3.3, 3.3.4, 3.3.5, 3.3.6, 3.4.0,
 3.4.1, 3.4.2, 3.4.3, 3.4.4, 3.5.0b1, 3.5.0, 3.6.0, 3.6.1, 3.6.2, 3.6.3,
 3.6.4, 3.7.0, 3.7.1, 3.7.2, 3.7.3, 3.8.0)
No matching distribution found for lxml>=3.35 (from news-please)
You are using pip version 8.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip'
command.
</code>```

Now the problem is the part where it says it cannot find a version that satisfies the requirement lxml >=3.35.

I already have a version of lxml which is greater than 3.35. When I do `pip show lxml', it tells me that the version I currently have is 3.8.0.

How do I fix this problem?

答:
If you have already satisified these dependencies:

```<code>pywin32 >=220 ; sys_platform == 'win32'
lxml >=3.35 ; sys_platform == 'win32'
Scrapy>=1.1.0
PyMySQL>=0.7.9
hjson>=1.5.8
elasticsearch>=2.4
beautifulsoup4>=4.3.2
readability-lxml>=0.6.2
newspaper3k>=0.1.7 ; python_version >= '3.0'
newspaper>=0.0.9.8 ; python_version == '2.7'
langdetect>=1.0.7
python-dateutil>=2.4.0
plac>=0.9.6
future>=0.16.0 ; python_version == '2.7'
PyDispatcher>=2.0.5
dotmap>=1.2.17
warcio>=1.3.3
ago>=0.0.9
</code>```

then you could use

```<code>pip install --no-deps -U news-please
</code>```

to have pip install news-please without the dependencies.

Body:
I am trying to install a Python package called news-please. This package is already on PyPi and on Github.

When I do pip install news-please as shown on the Github page, it shows the following:

Collecting news-please
  Using cached news-please-1.1.48.tar.gz
Collecting Scrapy>=1.1.0 (from news-please)
  Using cached Scrapy-1.4.0-py2.py3-none-any.whl
Collecting PyMySQL>=0.7.9 (from news-please)
  Using cached PyMySQL-0.7.11-py2.py3-none-any.whl
Collecting hjson>=1.5.8 (from news-please)
  Using cached hjson-2.0.7.tar.gz
Collecting elasticsearch>=2.4 (from news-please)
  Using cached elasticsearch-5.4.0-py2.py3-none-any.whl
Requirement already satisfied (use --upgrade to upgrade):
beautifulsoup4>=4.3.2 in c:\users\[my name]\anaconda3\lib\site-packages
(from news-please)
Collecting readability-lxml>=0.6.2 (from news-please)
  Using cached readability-lxml-0.6.2.tar.gz
Collecting langdetect>=1.0.7 (from news-please)
  Using cached langdetect-1.0.7.zip
Requirement already satisfied (use --upgrade to upgrade): python-
dateutil>=2.4.0 in c:\users\[my name]\anaconda3\lib\site-packages (from
news-please)
Requirement already satisfied (use --upgrade to upgrade): plac>=0.9.6 in
c:\users\[my name]\anaconda3\lib\site-packages (from news-please)
Collecting dotmap>=1.2.17 (from news-please)
  Using cached dotmap-1.2.17.tar.gz
Collecting PyDispatcher>=2.0.5 (from news-please)
  Using cached PyDispatcher-2.0.5.tar.gz
Collecting warcio>=1.3.3 (from news-please)
  Using cached warcio-1.3.4-py2.py3-none-any.whl
Collecting ago>=0.0.9 (from news-please)
  Using cached ago-0.0.9.tar.gz
Collecting newspaper3k (from news-please)
  Using cached newspaper3k-0.2.2.tar.gz
Requirement already satisfied (use --upgrade to upgrade): pywin32>=220 in
c:\users\[my name]\anaconda3\lib\site-packages (from news-please)
Collecting lxml>=3.35 (from news-please)
 Could not find a version that satisfies the requirement lxml>=3.35 (from
 news-please) (from versions: 0.9, 0.9.1, 0.9.2, 1.0b0, 1.0, 1.0.1, 1.0.2,
 1.0.3, 1.0.4, 1.1a0, 1.1b0, 1.1, 1.1.1, 1.1.2, 1.2, 1.2.1, 1.3b0, 1.3,
 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 2.0a1, 2.0a2, 2.0a3, 2.0a4, 2.0a5,
 2.0a6, 2.0b1, 2.0b2, 2.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.0.6, 2.0.7,
 2.0.8, 2.0.9, 2.0.10, 2.0.11, 2.1a1, 2.1b1, 2.1b2, 2.1b3, 2.1, 2.1.1,
 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.2a1, 2.2b1, 2.2b2, 2.2b3, 2.2b4, 2.2, 2.2.1,
 2.2.2, 2.2.3, 2.2.4, 2.2.5, 2.2.6, 2.2.7, 2.2.8, 2.3b1, 2.3, 2.3.1, 2.3.2,
 2.3.3, 2.3.4, 2.3.5, 2.3.6, 3.0, 3.0.1, 3.0.2, 3.1b1, 3.1.0, 3.1.1, 3.1.2,
 3.2.0, 3.2.1, 3.2.2, 3.2.3, 3.2.4, 3.2.5, 3.3.0b1, 3.3.0b2, 3.3.0b3,
 3.3.0b4, 3.3.0b5, 3.3.0, 3.3.1, 3.3.2, 3.3.3, 3.3.4, 3.3.5, 3.3.6, 3.4.0,
 3.4.1, 3.4.2, 3.4.3, 3.4.4, 3.5.0b1, 3.5.0, 3.6.0, 3.6.1, 3.6.2, 3.6.3,
 3.6.4, 3.7.0, 3.7.1, 3.7.2, 3.7.3, 3.8.0)
No matching distribution found for lxml>=3.35 (from news-please)
You are using pip version 8.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip'
command.

Now the problem is the part where it says it cannot find a version that satisfies the requirement lxml >=3.35.

I already have a version of lxml which is greater than 3.35. When I do `pip show lxml', it tells me that the version I currently have is 3.8.0.

How do I fix this problem?

Body:
If you have already satisified these dependencies:

pywin32 >=220 ; sys_platform == 'win32'
lxml >=3.35 ; sys_platform == 'win32'
Scrapy>=1.1.0
PyMySQL>=0.7.9
hjson>=1.5.8
elasticsearch>=2.4
beautifulsoup4>=4.3.2
readability-lxml>=0.6.2
newspaper3k>=0.1.7 ; python_version >= '3.0'
newspaper>=0.0.9.8 ; python_version == '2.7'
langdetect>=1.0.7
python-dateutil>=2.4.0
plac>=0.9.6
future>=0.16.0 ; python_version == '2.7'
PyDispatcher>=2.0.5
dotmap>=1.2.17
warcio>=1.3.3
ago>=0.0.9

then you could use

pip install --no-deps -U news-please

to have pip install news-please without the dependencies.


问:
CSS: css image resize to fit browser
I am trying to make the images resize to fit the browser just like the background-image using

max-width:100%;
height:auto;
max-height:100%;

However, the images do not resize to fit the screen and i tried to adjust the size of the browser. The images would go everywhere. I want the images to stay on the same spot when ever resizing occur. Any ideas on what i might have missed?

body{
  background: url(http://www.planwallpaper.com/static/images/518169-backgrounds.jpg)no-repeat center center fixed;
 background-size: 100%;

}
.boat2{
  width: 400px;
  position:absolute; bottom: 160px; left: 800px;z-index: 1;

}
.cabbage{
  width: 150px;
position:absolute; bottom: 290px; right: 290px;z-index: 1;
}
.sheep{
  width: 150px;
  position:absolute; bottom: 300px; right: 180px;z-index: 1;
}
.wolf{
  width: 300px;
  position:absolute; bottom: 270px; right: -80px;z-index: 1;
}
img {
  max-width:100%;
 height:auto;
 max-height:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="style.css">

    <title>IQ River Crossing</title>

</head>
<body>
<div class="image">
<img class="boat2"src="http://www.planwallpaper.com/static/images/christmas-background.jpg" alt="">
<img class="cabbage" src="http://www.planwallpaper.com/static/images/christmas-background.jpg" alt="">
<img class="sheep" src="http://www.planwallpaper.com/static/images/christmas-background.jpg" alt="">
<img class="wolf" src="http://www.planwallpaper.com/static/images/christmas-background.jpg" alt="">
</div>

</body>
</html></code>```

答:
Try css reset

```<code>body {
  margin: 0;
  padding: 0;
}
</code>```

OR

you can refer https://css-tricks.com/perfect-full-page-background-image/

Hope it helps

Title: CSS: css image resize to fit browser

Body:
I am trying to make the images resize to fit the browser just like the background-image using

max-width:100%;
height:auto;
max-height:100%;

However, the images do not resize to fit the screen and i tried to adjust the size of the browser. The images would go everywhere. I want the images to stay on the same spot when ever resizing occur. Any ideas on what i might have missed?

body{
  background: url(http://www.planwallpaper.com/static/images/518169-backgrounds.jpg)no-repeat center center fixed;
 background-size: 100%;

}
.boat2{
  width: 400px;
  position:absolute; bottom: 160px; left: 800px;z-index: 1;

}
.cabbage{
  width: 150px;
position:absolute; bottom: 290px; right: 290px;z-index: 1;
}
.sheep{
  width: 150px;
  position:absolute; bottom: 300px; right: 180px;z-index: 1;
}
.wolf{
  width: 300px;
  position:absolute; bottom: 270px; right: -80px;z-index: 1;
}
img {
  max-width:100%;
 height:auto;
 max-height:100%;
}

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="style.css">

    <title>IQ River Crossing</title>

Body:
Try css reset

body {
  margin: 0;
  padding: 0;
}

OR

you can refer https://css-tricks.com/perfect-full-page-background-image/

Hope it helps


问:
ScrollView Inside ScrollView
I Know people from Google have asked us not to put Scrollable view inside another Scrollable view but is there any official statement from them directing us not to do so?</p>

答:
Its not only that Google says its bad practice, it just doesnt make much sense. Supose you have two vertical scrollable views nested one inside the other. When you move you finger over the scroll views, which one do you want to move, the inner or the outer one?

You should rethink your UI desing to something that does not require this, there a many ways to make a great UI and still keep it really simple.

Title: ScrollView Inside ScrollView


问:
Import module in React component for publish on NPM
It's my first React component for publication in NPM. I use react-webpack-component package from Yeoman to start my project. But when I install and import my component to React app, I catch error:

```<code>Failed to compile.

Error in ./~/kladrapi-react/index.js
Module not found: [CaseSensitivePathsPlugin] `/develop/myproject/node_modules/kladrapi-react/node_modules/React/react.js` does not match the corresponding path on disk `react`.

 @ ./~/kladrapi-react/index.js 1:82-98
</code>```

I'm understand this error, but not understand how correctly import React modules to my component!

Actual version on GitHub

答:
I think there are multiple issues in your code.

In index.html:

@line--

The file name is "kladrapi-react.jsx"  not "kladrapi-react.js".

Second issue, here you are expecting "kladrapi-react.js(x)" to be on root level. Which is not the case. According to your folder structure "kladrapi-react.js(x)" file is at ./lib/kladrapi-react.jsx.

Apart from this, in your kladrapi-react.js(x) file you have mixed ES5 and ES6 syntax. You are accessing the variable KladrapiReact in index.html but you haven't exported it as 'KladrapiReact'. I would recommend you to put 'React.createClass....' code in a separate component.

For the error you are receiving you need to use 'case-sensitive-paths-webpack-plugin':

This Webpack plugin enforces the entire path of all required modules match the exact case of the actual path on disk.

```<code>npm install --save-dev case-sensitive-paths-webpack-plugin
</code>```

Usage:

```<code>var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');

var webpackConfig = {
    plugins: [
        new CaseSensitivePathsPlugin()
        // other plugins ...
    ]
    // other webpack config ...
}
</code>```

For more info on this plugin read documentation here.

Body:
It's my first React component for publication in NPM. I use react-webpack-component package from Yeoman to start my project. But when I install and import my component to React app, I catch error:

Failed to compile.

Error in ./~/kladrapi-react/index.js
Module not found: [CaseSensitivePathsPlugin] `/develop/myproject/node_modules/kladrapi-react/node_modules/React/react.js` does not match the corresponding path on disk `react`.

 @ ./~/kladrapi-react/index.js 1:82-98

I'm understand this error, but not understand how correctly import React modules to my component!

Actual version on GitHub

Body:
I think there are multiple issues in your code.

In index.html:

@line-- <script src="kladrapi-react.js"></script>

The file name is "kladrapi-react.jsx"  not "kladrapi-react.js".

Second issue, here you are expecting "kladrapi-react.js(x)" to be on root level. Which is not the case. According to your folder structure "kladrapi-react.js(x)" file is at ./lib/kladrapi-react.jsx.

Apart from this, in your kladrapi-react.js(x) file you have mixed ES5 and ES6 syntax. You are accessing the variable KladrapiReact in index.html but you haven't exported it as 'KladrapiReact'. I would recommend you to put 'React.createClass....' code in a separate component.

For the error you are receiving you need to use 'case-sensitive-paths-webpack-plugin':

This Webpack plugin enforces the entire path of all required modules match the exact case of the actual path on disk.

npm install --save-dev case-sensitive-paths-webpack-plugin

Usage:

var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');

var webpackConfig = {
    plugins: [
        new CaseSensitivePathsPlugin()
        // other plugins ...
    ]
    // other webpack config ...
}

For more info on this plugin read documentation here.


问:
Static property not seen in Firefox
In my haxe project, I am targeting javascript, and exposing class using @:expose to call it from outside haxe project.

In my Main class, I am using instance to access the single tone class.

like:

com.Main.instance

now, when I try to access a function ini inside the class, it will work only when using Chrome, but it will get an error at Firefox:

TypeError: com.Main.instance is undefined

Any idea why it has worked on Chrome, but not in Firefox?

I am using haxe version 3.4.0

Updated
i added minimized haxe sample file to reproduce the problem

```<code>package com;

import js.Browser;
@:expose
class Main {
    /*
    Using this var results in undefined
    example at Firefox console:
    >> com.Main.instance
    undefined
    */
    @isVar public static var instance(get, null):Main = null;

    static function get_instance():Main {
        if (instance == null)
            instance = new Main();
        return instance;
    }

    function new() {
    }
    static function main() {
        trace('Hello World');
    }
    /*
    Calling this method results in error
    example at Firefox console:
    >> com.Main.instance.init();
    TypeError: com.Main.instance is undefined
    */
    public function init(){
        Browser.console.log("Main Initialized");
    }
}
</code>```

Here is the HTML page:

```<code><!DOCTYPE html>
<html>
<head>
    <script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

    <script type="text/javascript" src="map.js"></script>
</head>

<body >

     <script>

$(document).ready(function () {
   com.Main.instance.init();
});

        </script>

</body>
</html>
</code>```

And here is the compiled map.js:

```<code>// Generated by Haxe 3.4.0
(function ($hx_exports) { "use strict";
$hx_exports["com"] = $hx_exports["com"] || {};
var com_Main = $hx_exports["com"]["Main"] = function() {
};
com_Main.get_instance = function() {
    if(com_Main.instance == null) {
        com_Main.instance = new com_Main();
    }
    return com_Main.instance;
};
com_Main.main = function() {
    console.log("Hello World");
};
com_Main.init = function() {
    window.console.log("Main Initialized");
};
com_Main.__meta__ = { statics : { instance : { isVar : null}}};
com_Main.main();
})(typeof exports != "undefined" ? exports : typeof window != "undefined" ? window : typeof self != "undefined" ? self : this);

//# sourceMappingURL=map.js.map
</code>```

答:
The use of Haxe properties from external JS code isn't really supported, as far as I know (see issue #2469).

You can call the getter directly (e.g. com.Main.get_instance().init()) or check that issue for other solutions.

Note: I couldn't confirm that the example works in Chrome (59 or 60) and, really, I don't think that it could.

Title: Static property not seen in Firefox

Body:
In my haxe project, I am targeting javascript, and exposing class using @:expose to call it from outside haxe project.

In my Main class, I am using instance to access the single tone class.

like:

com.Main.instance

now, when I try to access a function ini inside the class, it will work only when using Chrome, but it will get an error at Firefox:

TypeError: com.Main.instance is undefined

Any idea why it has worked on Chrome, but not in Firefox?

I am using haxe version 3.4.0

Updated
i added minimized haxe sample file to reproduce the problem

package com;

import js.Browser;
@:expose
class Main {
    /*
    Using this var results in undefined
    example at Firefox console:
    >> com.Main.instance
    undefined
    */
    @isVar public static var instance(get, null):Main = null;

    static function get_instance():Main {
        if (instance == null)
            instance = new Main();
        return instance;
    }

    function new() {
    }
    static function main() {
        trace('Hello World');
    }
    /*
    Calling this method results in error
    example at Firefox console:
    >> com.Main.instance.init();
    TypeError: com.Main.instance is undefined
    */
    public function init(){
        Browser.console.log("Main Initialized");
    }
}

Here is the HTML page:

<!DOCTYPE html>

And here is the compiled map.js:

// Generated by Haxe 3.4.0
(function ($hx_exports) { "use strict";
$hx_exports["com"] = $hx_exports["com"] || {};
var com_Main = $hx_exports["com"]["Main"] = function() {
};
com_Main.get_instance = function() {
    if(com_Main.instance == null) {
        com_Main.instance = new com_Main();
    }
    return com_Main.instance;
};
com_Main.main = function() {
    console.log("Hello World");
};
com_Main.init = function() {
    window.console.log("Main Initialized");
};
com_Main.__meta__ = { statics : { instance : { isVar : null}}};
com_Main.main();
})(typeof exports != "undefined" ? exports : typeof window != "undefined" ? window : typeof self != "undefined" ? self : this);

//# sourceMappingURL=map.js.map


问:
In html, how to stretch an image in only one dimension?
Let's say that I want to fit an 10*60 image into a 15*15 container. That is to say, I want to stretch my image so that the width correspond (so that would be an image of 15*90), but I do not want the height to stretch more than the width, so the bottom of my image will not appear.

When I define my html image, I put an width=100% to stretch the width, but what do I say to the height?

Thank  you !

答:
CSS background-image with background-size: cover

You should use CSS background-image property for this kind of styling your web elements.

What you're looking for is probably the background-size: cover;. What it does is it fits the image based on width of the container.

CSS:

```<code>.cont {
    width: 200px;
    height: 200px;
    background-image: url('urlToImage100x300.jpg');
    background-size: cover;
}
</code>```

HTML:

```<code><div class="cont"></div>
</code>```

Also, if you want to center your image vertically use background-position-y: center;.

```<code>.cont {
    width: 200px;
    height: 200px;
    background-image: url('urlToImage100x300.jpg');
    background-size: cover;
    background-position-y: center;
}
</code>```

HTML img tag

If you really need to use an  tag for this operation; What you need is to put the image into container, then set the width, height to your desired size and overflow-y to hidden. After that, set the width of an img to 100% and it's done.

CSS:

```<code>.cont {
    width: 200px;
    height: 200px;
    overflow-y: hidden;
}

.cont img {
    width: 100%;
}
</code>```

HTML:

```<code><div class="cont"><img src="image100x300.jpg" /></div>
</code>```

Working demo CSS w/o y-axis center: https://jsfiddle.net/e2vt3sw6/

Working demo CSS w/ y-axis center: https://jsfiddle.net/e2vt3sw6/1/

Working demo HTML img tag: https://jsfiddle.net/e2vt3sw6/2/

Tests where made using 150x300px image and 200x200px container

Body:
CSS background-image with background-size: cover

You should use CSS background-image property for this kind of styling your web elements.

What you're looking for is probably the background-size: cover;. What it does is it fits the image based on width of the container.

CSS:

.cont {
    width: 200px;
    height: 200px;
    background-image: url('urlToImage100x300.jpg');
    background-size: cover;
}

HTML:

<div class="cont"></div>

Also, if you want to center your image vertically use background-position-y: center;.

.cont {
    width: 200px;
    height: 200px;
    background-image: url('urlToImage100x300.jpg');
    background-size: cover;
    background-position-y: center;
}

HTML img tag

If you really need to use an <img /> tag for this operation; What you need is to put the image into container, then set the width, height to your desired size and overflow-y to hidden. After that, set the width of an img to 100% and it's done.

CSS:

.cont {
    width: 200px;
    height: 200px;
    overflow-y: hidden;
}

.cont img {
    width: 100%;
}

HTML:

<div class="cont"><img src="image100x300.jpg" /></div>

Working demo CSS w/o y-axis center: https://jsfiddle.net/e2vt3sw6/

Working demo CSS w/ y-axis center: https://jsfiddle.net/e2vt3sw6/1/

Working demo HTML img tag: https://jsfiddle.net/e2vt3sw6/2/

Tests where made using 150x300px image and 200x200px container


问:
Conversion failed when converting date and/or time from character string.
Im currently doing a webapp in which I need to filter a chart with a date range, this range is selected with two calendars that pass the dates to two different textboxs. I have tried with two different ways: with filterparameters and with the "between @date1 and @date2" query.

The thing is i get a problem that says:

Conversion failed when converting date and/or time from character string.
This error only appears when i choose the second date range, it doesnt matter the order i choose the dates from the calendars. I've also checked my datetime conversions.

I have debbuged already and i dont see the error in my code:

```<code>protected void Calendar2_SelectionChanged(object sender, EventArgs e)
    {
        txtDate2.Text = Calendar2.SelectedDate.ToShortDateString();
        Calendar2.Visible = false;
    }

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        txtDate1.Text = Calendar1.SelectedDate.ToShortDateString();
        Calendar1.Visible = false;
    }
</code>```

this is my query in code and client side:

```<code>protected void btnShow_Click(object sender, EventArgs e)
{
    DateTime date1 = Convert.ToDateTime(txtDate1.Text);
    DateTime date2 = Convert.ToDateTime(txtDate2.Text);

    using (SqlConnection conn = new SqlConnection(CONNECTION_STRING))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = "select Family, sum (TimeMins) as sumfield from DTCres where DateCres between @Date1 and @Date2 group by Family order by sumfield desc ";
                cmd.Parameters.AddWithValue("@Date1", date1);
                cmd.Parameters.AddWithValue("@Date2", date2);

                conn.Open();
                cmd.ExecuteNonQuery();
                //SqlDataReader dr = cmd.ExecuteReader();

                //if (dr.HasRows == !true)
                //{
                //    //dateLabel.Visible = true;
                //}
                //if (dr.HasRows == true)
                //{
                //    //dateLabel.Visible = false;
                //}
                conn.Close();
            }
            catch (Exception nessie)
            {
                string doc = nessie.Message;
                //dateLabel.Visible = true;
            }
        }
    }
}
</code>```

```<code><asp:SqlDataSource ID="SqlDS" runat="server" ConnectionString="<%$ ConnectionStrings:DTCrestronConnectionString %>"
                    SelectCommand="select Family, sum (TimeMins) as sumfield from DTCres where DateCres between @Date1 and @Date2 group by Family order by sumfield desc"
                    FilterExpression="Family='{0}'">
                    <SelectParameters>
                        <asp:ControlParameter Name="Date1" ControlID="txtDate1" PropertyName="Text" Type="String"/>
                        <asp:ControlParameter Name="Date2" ControlID="txtDate2" PropertyName="Text" Type="String"/>
                    </SelectParameters>
                    <FilterParameters>
                        <asp:ControlParameter ConvertEmptyStringToNull="false" Name="Family" ControlID="cmbChartFam1" PropertyName="Text" />
                    </FilterParameters>
                </asp:SqlDataSource>
            </td>
</code>```

please, any help would be so nice, and thanks in advance

答: Oh thanks for replying! Ive already solved it: it seems that the textbox value wans't being converted at all, so I did this: txtDate1.Text = Calendar1.SelectedDate.Date.ToString("yyyy-MM-dd"); instead of having this: txtDate2.Text = Calendar2.SelectedDate.ToShortDateString(); I think ToShortDateString was creating conflict here hehe.

Body:
Im currently doing a webapp in which I need to filter a chart with a date range, this range is selected with two calendars that pass the dates to two different textboxs. I have tried with two different ways: with filterparameters and with the "between @date1 and @date2" query.

The thing is i get a problem that says:

Conversion failed when converting date and/or time from character string.
This error only appears when i choose the second date range, it doesnt matter the order i choose the dates from the calendars. I've also checked my datetime conversions.

I have debbuged already and i dont see the error in my code:

protected void Calendar2_SelectionChanged(object sender, EventArgs e)
    {
        txtDate2.Text = Calendar2.SelectedDate.ToShortDateString();
        Calendar2.Visible = false;
    }

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        txtDate1.Text = Calendar1.SelectedDate.ToShortDateString();
        Calendar1.Visible = false;
    }

this is my query in code and client side:

protected void btnShow_Click(object sender, EventArgs e)
{
    DateTime date1 = Convert.ToDateTime(txtDate1.Text);
    DateTime date2 = Convert.ToDateTime(txtDate2.Text);

    using (SqlConnection conn = new SqlConnection(CONNECTION_STRING))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = "select Family, sum (TimeMins) as sumfield from DTCres where DateCres between @Date1 and @Date2 group by Family order by sumfield desc ";
                cmd.Parameters.AddWithValue("@Date1", date1);
                cmd.Parameters.AddWithValue("@Date2", date2);

                conn.Open();
                cmd.ExecuteNonQuery();
                //SqlDataReader dr = cmd.ExecuteReader();

                //if (dr.HasRows == !true)
                //{
                //    //dateLabel.Visible = true;
                //}
                //if (dr.HasRows == true)
                //{
                //    //dateLabel.Visible = false;
                //}
                conn.Close();
            }
            catch (Exception nessie)
            {
                string doc = nessie.Message;
                //dateLabel.Visible = true;
            }
        }
    }
}

<asp:SqlDataSource ID="SqlDS" runat="server" ConnectionString="<%$ ConnectionStrings:DTCrestronConnectionString %>"
                    SelectCommand="select Family, sum (TimeMins) as sumfield from DTCres where DateCres between @Date1 and @Date2 group by Family order by sumfield desc"
                    FilterExpression="Family='{0}'">
                    <SelectParameters>
                        <asp:ControlParameter Name="Date1" ControlID="txtDate1" PropertyName="Text" Type="String"/>
                        <asp:ControlParameter Name="Date2" ControlID="txtDate2" PropertyName="Text" Type="String"/>
                    </SelectParameters>
                    <FilterParameters>
                        <asp:ControlParameter ConvertEmptyStringToNull="false" Name="Family" ControlID="cmbChartFam1" PropertyName="Text" />
                    </FilterParameters>
                </asp:SqlDataSource>

please, any help would be so nice, and thanks in advance


问:
Open Sybase Sql Anywhere 9 .db file without DBA PASSWORD of 3rd party
I'm Beginner in Sybase Sql Anywhere.

I have a "coop_db.db" file from the 2nd Party.

I want to open this file but i dont have a UserID and Password from the 3rd Party. I already tried the default authentication

```<code>UserID:"dba" and Password:"sql"
</code>```

but it won't work.

Can anyone help me figure it out what's the DBA PASSWORD to this file.? Thanks, deeply appreciate your help :D.

答: Unfortunately, there is no way to force your way into a SQL Anywhere database if you don't know the password. I looked into this in the past and there is no backdoor, nor a forced-reset procedure like ASE has. </p>

Body:
I'm Beginner in Sybase Sql Anywhere.

I have a "coop_db.db" file from the 2nd Party.

I want to open this file but i dont have a UserID and Password from the 3rd Party. I already tried the default authentication

UserID:"dba" and Password:"sql"

but it won't work.

Can anyone help me figure it out what's the DBA PASSWORD to this file.? Thanks, deeply appreciate your help :D.