问:
Groups of pairwise combinations where each member appears only once
I have a list of unique tuples each containing 2 elements from 1 to 10. A total number of elements in a list is 45. I would like to divide them into 10 groups each of them containing only numbers from 1 to 10.

I have tried solve my problem using this answer:
python get groups of combinations that each member appear only once

python:

```<code>from itertools import combinations, chain
l = ['A','B','C','D','E', 'F', 'G','H','I','J']
c = list(combinations(l,2))
[set(i) for i in list(combinations(c,5)) if (len(set(l) & set(chain(*i))) == len(l))]
</code>```

But I get repetitions, like so:

```<code>[{('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('I', 'J')},
 {('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'I'), ('H', 'J')},...]
</code>```

答:
not 10 pairs , but there are 945 such pair that satisy your conditions

what i did was, get all the permutation of number, create a dictionary which
keeps all combinations as key.

now for each permutation element, I have taken them in pair of 2 ie [1,2,3,4] is [(1,2),(2,3),(3,4)]

this will create a list

now for all such list and their element, I have compared them from the dictionary whether they are present in the dictionary or not.

ps. this is a long and time-consuming solution, with graph theory we can reduce size considerably.

```<code>from itertools import combinations, permutations
l=['A','B','C','D','E','F','G','H','I','J']
c=list(permutations(l))
d=list(combinations(l,2))
from collections import defaultdict

dic = defaultdict(int)

for i in d:
    dic[i]=1

new =[]
for i in c:
    tmp=[]
    for j in range(1,len(i),2):
        tmp.append((i[j-1],i[j]))
    new.append(tmp)

final =[]

for i in new:
    flag =True
    count =0
    for j in i:
        try:
            if dic[j]:
                count+=1
                pass

        except:
            flag=False
            count=0
            break
    if flag and count==5:
        final.append(i)

final2 = [tuple(sorted(i)) for i in final]

solution = list(set(final2))
print(solution)
</code>```

there  will be 945 such values pair that exist this way

Body:
I have a list of unique tuples each containing 2 elements from 1 to 10. A total number of elements in a list is 45. I would like to divide them into 10 groups each of them containing only numbers from 1 to 10.

I have tried solve my problem using this answer:
python get groups of combinations that each member appear only once

python:

from itertools import combinations, chain
l = ['A','B','C','D','E', 'F', 'G','H','I','J']
c = list(combinations(l,2))
[set(i) for i in list(combinations(c,5)) if (len(set(l) & set(chain(*i))) == len(l))]

But I get repetitions, like so:

[{('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'H'), ('I', 'J')},
 {('A', 'B'), ('C', 'D'), ('E', 'F'), ('G', 'I'), ('H', 'J')},...]

Body:
not 10 pairs , but there are 945 such pair that satisy your conditions

what i did was, get all the permutation of number, create a dictionary which
keeps all combinations as key.

now for each permutation element, I have taken them in pair of 2 ie [1,2,3,4] is [(1,2),(2,3),(3,4)]

this will create a list

now for all such list and their element, I have compared them from the dictionary whether they are present in the dictionary or not.

ps. this is a long and time-consuming solution, with graph theory we can reduce size considerably.

from itertools import combinations, permutations
l=['A','B','C','D','E','F','G','H','I','J']
c=list(permutations(l))
d=list(combinations(l,2))
from collections import defaultdict

dic = defaultdict(int)

for i in d:
    dic[i]=1

new =[]
for i in c:
    tmp=[]
    for j in range(1,len(i),2):
        tmp.append((i[j-1],i[j]))
    new.append(tmp)

final =[]

for i in new:
    flag =True
    count =0
    for j in i:
        try:
            if dic[j]:
                count+=1
                pass

        except:
            flag=False
            count=0
            break
    if flag and count==5:
        final.append(i)

final2 = [tuple(sorted(i)) for i in final]

solution = list(set(final2))
print(solution)

there  will be 945 such values pair that exist this way


来源: stackexchange

问:
How to get rid of Naming rule violation messages in Visual Studio?
I just installed Visual Studio 2017. When I open an existing website, I get all sorts of warning messages such as this one:

IDE1006 Naming rule violation: These words must begin with upper case
  characters: swe_calc

In the code it is defined as:

```<code>[System.Runtime.InteropServices.DllImport("swedll32.dll")]
public static extern Int32 swe_calc(double tjd, int ipl, Int32 iflag, IntPtr xx, IntPtr serr);
</code>```

This also occurs with my ASP.Net controls. As an example of a DropDownList:

IDE1006 Naming rule violation: These words must begin with upper case
  characters: ddlMonth_SelectedIndexChanged

How can I eliminate these type of warnings under Visual Studio?

答:
This can be done using normal VS2017 & VS2019 using the .editorconfig settings file, using the naming rules: https://learn.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference

The file can be created by hand, or in VS2019 you can get Visual Studio to create it for your from your preferences (i.e. after following configuring your prefs as in https://stackoverflow.com/a/41131563/131701 ), by hitting the generate editor config file from settings button.

For example, the following sets of rules will enable camelCase for all non public methods, and keep the other default naming rules that comes with VS.

```<code>#### Naming styles ####

# Naming rules

dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i

dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case

dotnet_naming_rule.private_method_should_be_camelcasestyle.severity = suggestion
dotnet_naming_rule.private_method_should_be_camelcasestyle.symbols = private_method
dotnet_naming_rule.private_method_should_be_camelcasestyle.style = camelcasestyle

dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case

# Symbol specifications

dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal
dotnet_naming_symbols.interface.required_modifiers =

dotnet_naming_symbols.private_method.applicable_kinds = method
dotnet_naming_symbols.private_method.applicable_accessibilities = private, protected, internal, protected_internal
dotnet_naming_symbols.private_method.required_modifiers =

dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal
dotnet_naming_symbols.types.required_modifiers =

dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal
dotnet_naming_symbols.non_field_members.required_modifiers =

# Naming styles

dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case

dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case

dotnet_naming_style.camelcasestyle.required_prefix =
dotnet_naming_style.camelcasestyle.required_suffix =
dotnet_naming_style.camelcasestyle.word_separator =
dotnet_naming_style.camelcasestyle.capitalization = camel_case
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I just installed Visual Studio 2017. When I open an existing website, I get all sorts of warning messages such as this one:

IDE1006 Naming rule violation: These words must begin with upper case
  characters: swe_calc

In the code it is defined as:

[System.Runtime.InteropServices.DllImport("swedll32.dll")]
public static extern Int32 swe_calc(double tjd, int ipl, Int32 iflag, IntPtr xx, IntPtr serr);

This also occurs with my ASP.Net controls. As an example of a DropDownList:

IDE1006 Naming rule violation: These words must begin with upper case
  characters: ddlMonth_SelectedIndexChanged

How can I eliminate these type of warnings under Visual Studio?

Body:
This can be done using normal VS2017 & VS2019 using the .editorconfig settings file, using the naming rules: https://learn.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference

The file can be created by hand, or in VS2019 you can get Visual Studio to create it for your from your preferences (i.e. after following configuring your prefs as in https://stackoverflow.com/a/41131563/131701 ), by hitting the generate editor config file from settings button.

For example, the following sets of rules will enable camelCase for all non public methods, and keep the other default naming rules that comes with VS.

#### Naming styles ####

# Naming rules

dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i

dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case

dotnet_naming_rule.private_method_should_be_camelcasestyle.severity = suggestion
dotnet_naming_rule.private_method_should_be_camelcasestyle.symbols = private_method
dotnet_naming_rule.private_method_should_be_camelcasestyle.style = camelcasestyle

dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case

# Symbol specifications

dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal
dotnet_naming_symbols.interface.required_modifiers =

dotnet_naming_symbols.private_method.applicable_kinds = method
dotnet_naming_symbols.private_method.applicable_accessibilities = private, protected, internal, protected_internal
dotnet_naming_symbols.private_method.required_modifiers =

dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal
dotnet_naming_symbols.types.required_modifiers =

dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal
dotnet_naming_symbols.non_field_members.required_modifiers =

# Naming styles

dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case

dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case

dotnet_naming_style.camelcasestyle.required_prefix =
dotnet_naming_style.camelcasestyle.required_suffix =
dotnet_naming_style.camelcasestyle.word_separator =
dotnet_naming_style.camelcasestyle.capitalization = camel_case


问:
What's the best way to detect a 'touch screen' device using JavaScript?
I've written a jQuery plug-in that's for use on both desktop and mobile devices. I wondered if there is a way with JavaScript to detect if the device has touch screen capability. I'm using jquery-mobile.js to detect the touch screen events and it works on iOS, Android etc., but I'd also like to write conditional statements based on whether the user's device has a touch screen.

Is that possible?

答:
I think the best method is:</p>
```<code>var isTouchDevice =
    (('ontouchstart' in window) ||
    (navigator.maxTouchPoints > 0) ||
    (navigator.msMaxTouchPoints > 0));
if(!isTouchDevice){
    /* Code for touch device /*
}else{
    /* Code for non touch device */
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think the best method is:

var isTouchDevice =
    (('ontouchstart' in window) ||
    (navigator.maxTouchPoints > 0) ||
    (navigator.msMaxTouchPoints > 0));
if(!isTouchDevice){
    /* Code for touch device /*
}else{
    /* Code for non touch device */
}


问:
timeout Exception even when element is already clicked
I am trying to click one button Sign In but even after button is clicked I am getting timeout exception.

I have verified the code and verified that I am using right locator.

description: CAP Demo
  Navigate to the GitHub website, find the React repo using the
  search functionality and go to the repo's homepage
actors:
  - actor: WEB
    segments:
      - segment: 1
        actions:
          - description: Navigate to the GitHub homepage
            action: org.getopentest.selenium.NavigateTo
            args:
              url: http://192.168.200.98:8780/CAFPortal/#/login

```<code>      - description: Enter Login id
        action: org.getopentest.selenium.SendKeys
        args:
          locator: {xpath: "//*[@id='login']/app-root/app-caf-login/div/div/div[2]/form/div[1]/input"}
          text: ksood
          sendEnter: true

      - description: Enter password
        action: org.getopentest.selenium.SendKeys
        args:
          locator: {xpath: "//*[@id='login']/app-root/app-caf-login/div/div/div[2]/form/div[2]/input"}
          text: Acs@2018
          sendEnter: true

      - description: Pause for 60 second
        action: org.getopentest.selenium.ActionsPause
        args:
          durationMs: 60000

      - description: Display a greeting dialog box in the browser
        action: org.getopentest.selenium.ExecuteScript
        args:
        script:
          var message = "Hello World!";
          alert(message);

      - description: Click on sign in
        action: org.getopentest.selenium.Click
        args:
          locator: {xpath: "//*[@id='login']/app-root/app-caf-login/div/div/div[2]/form/div[3]/div/div/button"}
</code>```

Just want the last testcase to pass

答:
You don't need the sendEnter: true argument with any of the SendKeys actions. When you pass sendEnter: true , the action will "press" the enter key after sending the keys to the textbox element. So basically, in the test you showed, the first action will input the username and then press enter, thus trying to log in without a password, which will of course fail.

The other problem is that you are using the ActionsPause keyword incorrectly (more info here). If you want to introduce a delay in your test, you can use the $delay() API, but you very rarely need to do this with OpenTest, since synchronization is built-in, meaning all test actions that perform some work on a UI element know how to wait for that element to be available before doing the work.

Body:
I am trying to click one button Sign In but even after button is clicked I am getting timeout exception.

I have verified the code and verified that I am using right locator.

description: CAP Demo
  Navigate to the GitHub website, find the React repo using the
  search functionality and go to the repo's homepage
actors:
  - actor: WEB
    segments:
      - segment: 1
        actions:
          - description: Navigate to the GitHub homepage
            action: org.getopentest.selenium.NavigateTo
            args:
              url: http://192.168.200.98:8780/CAFPortal/#/login

      - description: Enter Login id
        action: org.getopentest.selenium.SendKeys
        args:
          locator: {xpath: "//*[@id='login']/app-root/app-caf-login/div/div/div[2]/form/div[1]/input"}
          text: ksood
          sendEnter: true

      - description: Enter password
        action: org.getopentest.selenium.SendKeys
        args:
          locator: {xpath: "//*[@id='login']/app-root/app-caf-login/div/div/div[2]/form/div[2]/input"}
          text: Acs@2018
          sendEnter: true

      - description: Pause for 60 second
        action: org.getopentest.selenium.ActionsPause
        args:
          durationMs: 60000

      - description: Display a greeting dialog box in the browser
        action: org.getopentest.selenium.ExecuteScript
        args:
        script:
          var message = "Hello World!";
          alert(message);

      - description: Click on sign in
        action: org.getopentest.selenium.Click
        args:
          locator: {xpath: "//*[@id='login']/app-root/app-caf-login/div/div/div[2]/form/div[3]/div/div/button"}

Just want the last testcase to pass


问:
Singularity exclude some directory
singularity -B is used to mount some directories so that those directories can be used inside the singularity container. However, there are some directories that I would like to exclude. For example, I would like to use
singularity shell -B /foo/ bar.simg to have access to /foo

But I would like to exclude /foo/foo1/ in the container. Is there any way to work around this?

答: Nope. The container isn't showing a copy or a link to files, it is making that directory (and all its contents) available inside the container. It's the same when mounting directories in docker.</p>

Title: Singularity exclude some directory


问:
Use a variable as a function name in PHP
I'm creating a dynamic function in WordPress that requires I create my function names dynamically.

In this instance, I need to generate a unique function name for this gravityforms code:

```<code>add_filter( 'gform_validation_message', 'change_message', 10, 2 );
function change_message( $message, $form ) {
    return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
}
</code>```

So, I have a variable (which will change from time to time) that I want to use for my function name...

```<code>$newitem = 'new_item';
</code>```

...and tried this...

```<code>add_filter( 'gform_validation_message', $newitem, 10, 2 );
function $newitem( $message, $form ) {
    return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
}
</code>```

...but obviously that does not work. But I think you get the idea of what I am trying to achieve.

Is anything like this even possible?

Any help is appreciated.

答:
You can simply pass Anonymous function to add_filter function as parameter:</p>

```<code>$newitem = function($message, $form) {
    return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
};

add_filter('gform_validation_message', $newitem, 10, 2);

</code>```

Body:
I'm creating a dynamic function in WordPress that requires I create my function names dynamically.

In this instance, I need to generate a unique function name for this gravityforms code:

add_filter( 'gform_validation_message', 'change_message', 10, 2 );
function change_message( $message, $form ) {
    return "
Failed Validation - " . $form['title'] . '
';
}

So, I have a variable (which will change from time to time) that I want to use for my function name...

$newitem = 'new_item';

...and tried this...

add_filter( 'gform_validation_message', $newitem, 10, 2 );
function $newitem( $message, $form ) {
    return "
Failed Validation - " . $form['title'] . '
';
}

...but obviously that does not work. But I think you get the idea of what I am trying to achieve.

Is anything like this even possible?

Any help is appreciated.

Body:
You can simply pass Anonymous function to add_filter function as parameter:

$newitem = function($message, $form) {
    return "<div class='validation_error'>Failed Validation - " . $form['title'] . '</div>';
};

add_filter('gform_validation_message', $newitem, 10, 2);


问:
How to align the child of a FlatButton
I am trying to align 2 Texts and an Image as a child of a FlatButton (like this) but somehow the elements don't align as they should.

I tried using Stack, Align, Rows and so on but I weren't really successful (I am also a beginner when it comes to dart or flutter)

```<code>new ButtonTheme(
          minWidth: 171,
          height: 176,
          child:new Container(
                decoration: new BoxDecoration(
                borderRadius: new BorderRadius.circular(19),
                gradient: new LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Color(0xFF8F94FB),
                    Color(0xFF5D62D4)
                  ]
                )
                ),
                child: FlatButton(
                  onPressed: () => handleButtonClick(),
                  shape: new RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(19)
                  ),
                  child: new Stack(
                    children: <Widget>[
                      Align(
                        alignment: Alignment.bottomLeft,
                        child: Image.asset('assets/daily_icon.png', width: 109, height: 109),
                      )
                    ],
                  ),
                  ),
              ),
          ),
</code>```

This is the result:Image

答:
You can debug step by step. First, this is a technique that I use with me and my other fellows devs. In the child parameter, pass a Container, this container will receive a color, Colors.red for example, with that you can see how much size your container's area contain.

After that, if you want to centralize the content inside this Container, passa a Center as child, and the child of this Center widget, you can pass your Image, and define this Image's size.

```<code>child: Container(
        color: Colors.red,
        child: Center(
          child: Image.asset('assets/daily_icon.png', width: 109, height: 109),
        ),
      ),
</code>```

Tell me if this worked for you.

Title: How to align the child of a FlatButton

Body:
I am trying to align 2 Texts and an Image as a child of a FlatButton (like this) but somehow the elements don't align as they should.

I tried using Stack, Align, Rows and so on but I weren't really successful (I am also a beginner when it comes to dart or flutter)

new ButtonTheme(
          minWidth: 171,
          height: 176,
          child:new Container(
                decoration: new BoxDecoration(
                borderRadius: new BorderRadius.circular(19),
                gradient: new LinearGradient(
                  begin: Alignment.centerLeft,
                  end: Alignment.centerRight,
                  colors: [
                    Color(0xFF8F94FB),
                    Color(0xFF5D62D4)
                  ]
                )
                ),
                child: FlatButton(
                  onPressed: () => handleButtonClick(),
                  shape: new RoundedRectangleBorder(
                    borderRadius: new BorderRadius.circular(19)
                  ),
                  child: new Stack(
                    children: <Widget>[
                      Align(
                        alignment: Alignment.bottomLeft,
                        child: Image.asset('assets/daily_icon.png', width: 109, height: 109),
                      )
                    ],
                  ),
                  ),
              ),
          ),

This is the result:Image

Body:
You can debug step by step. First, this is a technique that I use with me and my other fellows devs. In the child parameter, pass a Container, this container will receive a color, Colors.red for example, with that you can see how much size your container's area contain.

After that, if you want to centralize the content inside this Container, passa a Center as child, and the child of this Center widget, you can pass your Image, and define this Image's size.

child: Container(
        color: Colors.red,
        child: Center(
          child: Image.asset('assets/daily_icon.png', width: 109, height: 109),
        ),
      ),

Tell me if this worked for you.


问:
How am I supposed to set a Gtk Notebook page tab expandable?
When I add a page to a Gtk.Notebook programatically, I can't find a way to set the tab to expand. The property is available in Glade, so I know it can be done. Here is a snippet using reorderable and detachable properties.

```<code>#!/usr/bin/env python

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class GUI:
    def __init__(self):

        window = Gtk.Window()
        notebook = Gtk.Notebook()
        window.add(notebook)
        for i in range (4):
            label = Gtk.Label('label in page number ' + str(i))
            tab_label = Gtk.Label('page ' + str(i))
            notebook.append_page(label, tab_label)
            notebook.set_tab_detachable(label, True)
            notebook.set_tab_reorderable(label, True)
        window.show_all()
        window.connect('destroy', Gtk.main_quit)

app = GUI()
Gtk.main()
</code>```

However,

notebook.set_tab_expandable(label, True)

fails with

AttributeError: 'Notebook' object has no attribute 'set_tab_expandable'

答:
The solution is:</p>

```<code>notebook.child_set_property(label, 'tab-expand', True)
</code>```

Body:
When I add a page to a Gtk.Notebook programatically, I can't find a way to set the tab to expand. The property is available in Glade, so I know it can be done. Here is a snippet using reorderable and detachable properties.

#!/usr/bin/env python

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class GUI:
    def __init__(self):

        window = Gtk.Window()
        notebook = Gtk.Notebook()
        window.add(notebook)
        for i in range (4):
            label = Gtk.Label('label in page number ' + str(i))
            tab_label = Gtk.Label('page ' + str(i))
            notebook.append_page(label, tab_label)
            notebook.set_tab_detachable(label, True)
            notebook.set_tab_reorderable(label, True)
        window.show_all()
        window.connect('destroy', Gtk.main_quit)

app = GUI()
Gtk.main()

However,

notebook.set_tab_expandable(label, True)

fails with

AttributeError: 'Notebook' object has no attribute 'set_tab_expandable'

Body:
The solution is:

notebook.child_set_property(label, 'tab-expand', True)


问:
How to echo a function in php using button?
I am making an event calendar.I want to echo a function in php using button.

My actual code:

Calendar.php

```<code><?php include_once('functions.php'); ?>
<?php echo getCalender(); ?>
</code>```

functions.php

```<code><?php

if(isset($_POST['func']) && !empty($_POST['func'])){
    switch($_POST['func']){
        case 'getCalender':
            getCalender($_POST['year'],$_POST['month']);
            break;
        case 'getEvents':
            getEvents($_POST['date']);
            break;
        default:
            break;
    }
}
//Get calendar full HTML
function getCalender($year = '',$month = '')
{
    $dateYear = ($year != '')?$year:date("Y");
    $dateMonth = ($month != '')?$month:date("m");
    $date = $dateYear.'-'.$dateMonth.'-01';
    $currentMonthFirstDay = date("N",strtotime($date));
    $totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
    $totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
    $boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
?>
    <div id="calender_section">
    //
}
 <script type="text/javascript">
    function getCalendar(target_div,year,month){
        $.ajax({
            type:'POST',
            url:'functions.php',
            data:'func=getCalender&year='+year+'&month='+month,
            success:function(html){
                $('#'+target_div).html(html);
            }
        });
    }

function getEvents(date){
        $.ajax({
            type:'POST',
            url:'functions.php',
            data:'func=getEvents&date='+date,
            success:function(html){
                $('#event_list').html(html);
                $('#event_add').slideUp('slow');
                $('#event_list').slideDown('slow');
            }
        });
    }
</code>```

Now I want to use button to call the getcalendar function. I've tried this:

Calendar.php

```<code> <form class="" action="" method="post">
               <input type="button" value="Dhaka" onclick="<?php echo getCalender(); ?>"/>
              </form>
</code>```

Now this is not waitiing for button click. When I refresh the page it is showing the calendat even if i didn't click the button.
How can I solve this?

答:
You can use

```<code>print_f(Object);
</code>```

And then try your code, instead of echo;

Body:
I am making an event calendar.I want to echo a function in php using button.

My actual code:

Calendar.php

<?php include_once('functions.php'); ?>
<?php echo getCalender(); ?>

functions.php

<?php

if(isset($_POST['func']) && !empty($_POST['func'])){
    switch($_POST['func']){
        case 'getCalender':
            getCalender($_POST['year'],$_POST['month']);
            break;
        case 'getEvents':
            getEvents($_POST['date']);
            break;
        default:
            break;
    }
}
//Get calendar full HTML
function getCalender($year = '',$month = '')
{
    $dateYear = ($year != '')?$year:date("Y");
    $dateMonth = ($month != '')?$month:date("m");
    $date = $dateYear.'-'.$dateMonth.'-01';
    $currentMonthFirstDay = date("N",strtotime($date));
    $totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
    $totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
    $boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
?>

    //
}

Body:
You can use

print_f(Object);

And then try your code, instead of echo;


问:
best way to copy data from one aws queue (SQS) to another SQS
I have an sqs queue in the same account and region, for some new features testing I have deployed my UAT code on prod environment with different config it's a connect process where one process passes the message to other using SQS.

Now since UAT has a different SQS queue but expects the same message as we publish on the prod queue, just wanted to check if there is a config which can help me replicate the messages into a differnt queue instead of explicitly writing a code.

答:
Option 1: Use Amazon SNS to fan-out to Amazon SQS queues

If you have access to the process that sends the message to the Amazon SQS queue, then you could change it:

Send the message to an Amazon SNS topic

Subscribe the Amazon SQS queues to the SNS topic

This way, when a message is sent to SNS, it will be forwarded to all of the subscribed SQS queues. This avoids having to copy messages between queues.

Be sure to configure the SQS subscriptions for Raw Message Delivery so that they receive exactly the same message as was originally sent to SNS.

Option 2: Duplicate messages

If you do not have the ability to change how messages are sent and you do actually need to copy messages from one queue to another, you will need to write a program to do so. It would need to:

Loop through the source queue by calling ReceiveMessages() multiple times to get each message, passing a high VisibilityTimeout value

Use SendMessage() to send the message to the destination queue

Do not delete the source message (This will cause the messages to remain invisible for a period)

The ReceiveMessage() call can specify a VisibilityTimeout period. Set this very high such that the messages won't become visible again until after all messages have been retrieved. This will prevent messages being processed more than once.

The new messages in the destination queue will not be identical to the source messages because they will have different IDs and timestamps. However, the content of the message itself will be preserved.


问:
My function based on user input and if/else statements gives the same output no matter the user input
I get the same output no matter what the user input is. The main python file I'm working from calls on the function from a secondary file.

I've tried changing the if else statement conditions but I keep having the same issue.

if __name__ == '__main__':
    import No_2

    No_2.cont()

    print('File1: This would be a good place to continue data manipulation.')
    input("Press the enter key to close")
```

<p>And here is No_2</p>

<pre class="lang-py prettyprint-override"><code>
def cont():
    import sys

    c = input('File2: Would you like to continue? ')
    if c == 'Y' or 'y':
        print('File2: Ok we\'ll carry on...')
        print(' ')
        return

    else: sys.exit()
</code>```

I expect the script to close when C does not = Y or y...
Where as I would like it to return to the main script if the input is Y or y.

答: Try to update if condition with if c == 'Y' or c=='y': It should work.</p>

Body:
I get the same output no matter what the user input is. The main python file I'm working from calls on the function from a secondary file.

I've tried changing the if else statement conditions but I keep having the same issue.

if __name__ == '__main__':
    import No_2

    No_2.cont()

    print('File1: This would be a good place to continue data manipulation.')
    input("Press the enter key to close")

And here is No_2

def cont():
    import sys

    c = input('File2: Would you like to continue? ')
    if c == 'Y' or 'y':
        print('File2: Ok we\'ll carry on...')
        print(' ')
        return

    else: sys.exit()

I expect the script to close when C does not = Y or y...
Where as I would like it to return to the main script if the input is Y or y.


问:
Is it possible to define global variables in postgresql
I am using postgresql 9.4 and while writing functions I want to use self-defined error_codes (int). However I may want to change the exact numeric values later.

For instance

-1 means USER_NOT_FOUND.

-2 means USER_DOES_NOT_HAVE_PERMISSION.

I can define these in a table codes_table(code_name::text, code_value::integer) and use them in functions as follows

```<code>(SELECT codes_table.code_value FROM codes_table WHERE codes_table.code_name = 'USER_NOT_FOUND')
</code>```

Is there another way for this. Maybe global variables?

答:
You can use this

```<code>CREATE OR REPLACE FUNCTION globals.maxCities()
  RETURNS integer AS
  $$SELECT 100 $$ LANGUAGE sql IMMUTABLE;
</code>```

.. and directly use globals.maxCities() in the code.

Body:
I am using postgresql 9.4 and while writing functions I want to use self-defined error_codes (int). However I may want to change the exact numeric values later.

For instance

-1 means USER_NOT_FOUND.

-2 means USER_DOES_NOT_HAVE_PERMISSION.

I can define these in a table codes_table(code_name::text, code_value::integer) and use them in functions as follows

(SELECT codes_table.code_value FROM codes_table WHERE codes_table.code_name = 'USER_NOT_FOUND')

Is there another way for this. Maybe global variables?

Body:
You can use this

CREATE OR REPLACE FUNCTION globals.maxCities()
  RETURNS integer AS
  $$SELECT 100 $$ LANGUAGE sql IMMUTABLE;

.. and directly use globals.maxCities() in the code.


问:
how to change log_reuse_wait and log_reuse_wait_desc
I have been created new database and the log file groth very past, and I get error mesaage that the log is full due to 'BACKUP'.

I looked in the differences between this Database and other databases in the SERVER, and I seen that in all databases log_reuse_wait is 0 and log_reuse_wait_desc is NOTHING and in my database log_reuse_wait is 0 and log_reuse_wait_desc is LOG_BACKUP.

I want to change this property in my database to 0 and NOTHING.
How can I do that?

答:
I know this is old, but the answers are wrong.

If the database has recovery mode FULL and that is intended, then do not change it to simple.

The log_reuse_wait_desc says what the state is before the log can be reused or shrinked. In this case it is LOG_BACKUP, meaning that, to shrink the transaction log, you need to backup the transaction log first and shrink it or backup the log and let the SQLServer reuse the log space.

A description of the log_reuse_wait_desc states can be found here


问:
REST path design for resources having multiple IDs
I'm trying to define the API for the REST paths of a new service where I have devices, and each device has a current location.

It needs a bit of background to understand the problem:

This is about pushing current device locations to a central server

Position updates are sometimes calculated on the device itself (GPS) and sent from the device (smartphone) to a server, but sometimes also via an external service (e.g. WiFi positioning system) and send from that system to a server

Each device has a unique id which the smartphone knows. The WiFi positioning system cannot know this id, it just knows the WiFi mac address.

Each device has several interfaces for position updates (mac addresses)

Regardless of where / from which interface location updates come, all location data should be linked to the same unique device id

So much for the background. Now about the API design. As mentioned above, I may get location updates where only the mac address is known, and I may get location updates where the unique device id is known. In both cases I can assume the id I get is unique and theoretically I can say that mac address x belongs to device y. Practically, this means I have a non-unique index to my location REST API:

For an example, consider I have a device with ID "123" and two mac addresses "abc" and "xyz". Commonly, my REST API path would group locations under the unique device:

```<code>/devices/$id/location
</code>```

Now the problem is that there are multiple (unique) ids, each however related to one same device.

Like for example this would push a location by unique device id from the smartphone (where I know that unique ID, but do NOT know the mac address of the interface):

```<code>PUT /devices/123/location
</code>```

And this is where an external system which only knows the mac address is pushing the location update using the mac address as key:

```<code>PUT /devices/abc/location
PUT /devices/xyz/location
</code>```

You can assume that internally I can relate mac addresses and unique device IDs to one unique internal device. I could update and return location and device info using either a mac address and a device id.

For example the following GET requests using either the unique device id or unique mac will return the same location object:

```<code>GET /devices/123/location
GET /devices/abc/location
GET /devices/xyz/location
</code>```

But is that a valid REST design where I can have multiple paths to the same resource? Should I rather change my REST paths, and how?

答:
It might be useful to think about how you would design a web site that supports this behavior...

You might design that protocol this way: the client loads a known bookmark URI.  Available in the representation of that page are two links, one for clients that know the mac address, a different link for those that know the identifier.  The client would choose the appropriate link to follow.  The representation returned by that would be a form, customized for the specific use case; the description of the form would specify the expected fields.  The client would fill in the known fields (ignoring any unknown fields, which presumably have reasonable default values), and submit the form.  The browser would use standard processing rules to produce the appropriate HTTP request to the action specified in the form.

In this case, where what we are interested in is (effectively) looking up the URI of the resource we want based on the information we have, we would normally use GET as the form method.  That would send a query to the server, and from there the server can communicate (perhaps via re-direct) the appropriate URI to use for that device.

Once you've got the correct URI to use, GET/PUT/POST/PATCH/DELETE should all work as you would expect.

is that a valid REST design where I can have multiple paths to the same resource?

If the identifiers are different, then the resources are different.  You are, of course, allowed to have more than one resource that expresses some concept (or, to put it another way, two different resources are allowed to share a single semantic mapping).

For your specific case, it would probably be OK to have a resource for clients that know the device by id, and another for clients that know the device by location.  However, sharing a single resource identifier for both cases simplifies the server side caching story.

Part of the point of REST: if you define your media types and relations carefully, the server should be able to change the caching strategies used without breaking any clients (because the clients are just following links and submitting forms provided by the server).

Body:
I'm trying to define the API for the REST paths of a new service where I have devices, and each device has a current location.

It needs a bit of background to understand the problem:

This is about pushing current device locations to a central server

Position updates are sometimes calculated on the device itself (GPS) and sent from the device (smartphone) to a server, but sometimes also via an external service (e.g. WiFi positioning system) and send from that system to a server

Each device has a unique id which the smartphone knows. The WiFi positioning system cannot know this id, it just knows the WiFi mac address.

Each device has several interfaces for position updates (mac addresses)

Regardless of where / from which interface location updates come, all location data should be linked to the same unique device id

So much for the background. Now about the API design. As mentioned above, I may get location updates where only the mac address is known, and I may get location updates where the unique device id is known. In both cases I can assume the id I get is unique and theoretically I can say that mac address x belongs to device y. Practically, this means I have a non-unique index to my location REST API:

For an example, consider I have a device with ID "123" and two mac addresses "abc" and "xyz". Commonly, my REST API path would group locations under the unique device:

/devices/$id/location

Now the problem is that there are multiple (unique) ids, each however related to one same device.

Like for example this would push a location by unique device id from the smartphone (where I know that unique ID, but do NOT know the mac address of the interface):

PUT /devices/123/location

And this is where an external system which only knows the mac address is pushing the location update using the mac address as key:

PUT /devices/abc/location
PUT /devices/xyz/location

You can assume that internally I can relate mac addresses and unique device IDs to one unique internal device. I could update and return location and device info using either a mac address and a device id.

For example the following GET requests using either the unique device id or unique mac will return the same location object:

GET /devices/123/location
GET /devices/abc/location
GET /devices/xyz/location

But is that a valid REST design where I can have multiple paths to the same resource? Should I rather change my REST paths, and how?


问:
How can i use the value to calculate? "10/10"
Hi i was wondering if i can make the value 10/10 and 90/100 in 4 different var so i can calculate the avarge?

I tried calling the var with innerHTML, but it doesn't seem to work.

This are the div's:

```<code><div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
<div class="course_eval_cell hasGrade">90/100</div>

</code>```

example: 10 + 90 / 10 + 100 => 90.9%. Any suggestion/ideas on how to become this solution?

答:
You are calculating your average incorrectly. Get the values by classname and innerText, map over each value and split and divide them accordingly. Then add them together, and divide by how many grades there are, and times by 100 for a percentage:

var grades = Array.from(document.getElementsByClassName('hasGrade')).map(grade => {
  gradeArr = grade.innerText.split('/')
  return gradeArr[0] / gradeArr[1]
})

var percentage = grades.reduce((acc, grade) => acc + grade, 0) / grades.length * 100 + '%'
console.log(percentage)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
<div class="course_eval_cell hasGrade">90/100</div></code>```

Body:
Hi i was wondering if i can make the value 10/10 and 90/100 in 4 different var so i can calculate the avarge?

I tried calling the var with innerHTML, but it doesn't seem to work.

This are the div's:

10/10

90/100

example: 10 + 90 / 10 + 100 => 90.9%. Any suggestion/ideas on how to become this solution?

Body:
You are calculating your average incorrectly. Get the values by classname and innerText, map over each value and split and divide them accordingly. Then add them together, and divide by how many grades there are, and times by 100 for a percentage:

var grades = Array.from(document.getElementsByClassName('hasGrade')).map(grade => {
  gradeArr = grade.innerText.split('/')
  return gradeArr[0] / gradeArr[1]
})

var percentage = grades.reduce((acc, grade) => acc + grade, 0) / grades.length * 100 + '%'
console.log(percentage)

<div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
<div class="course_eval_cell hasGrade">90/100</div>


问:
tvOS how to check if the UITabBar is focused
I'm looking for a way to make a custom transition when changing the focus from or to the UITabBar.

I'm currently trying this by overriding the didUpdateFocus method but I seem to be unable to check if the the tabBar is focused.

The tabBar itself seem to never be in the "focused" state:

override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinatora)
{
    super.didUpdateFocus(in: context, with: coordinator)

    print(self.tabBar.isFocused) // always false
}
```

<p>When checking the <code>UIFocusUpdateContext</code> the currently focused element is a <code>UITabBarButton</code>. </p>

<p>But I'm unable to check if the context is an instance of <code>UITabBarButton</code> because that type isn't available:</p>

<pre class="lang-swift prettyprint-override"><code>context.nextFocusedItem is UITabBarButton // can't compile
</code>```

I'm really stuck here and would love any suggestions on how to tackle this one.

Thanks.

答:
I have created extension on UIView which will check if there is focus somewhere in its hierarchy:

```<code>func containsFocus() -> Bool {
    if self.isFocused { return true }
    else {
        for subview in self.subviews {
            if subview.containsFocus() { return true }
        }

        return false
    }
}
</code>```

This way you can check if your UITabBar has focus.

Note:

This is very expensive way of checking if your view has focus, because it is recursive function and it will potentially traverse the whole hierarchy of your view.

Tip:

If you are trying to implement custom transition when selecting tabs in UITabBar you should use UITabBarDelegate method:

```<code> func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem)
</code>```

If not, just ignore this tip.

Body:
I'm looking for a way to make a custom transition when changing the focus from or to the UITabBar.

I'm currently trying this by overriding the didUpdateFocus method but I seem to be unable to check if the the tabBar is focused.

The tabBar itself seem to never be in the "focused" state:

override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinatora)
{
    super.didUpdateFocus(in: context, with: coordinator)

    print(self.tabBar.isFocused) // always false
}

When checking the UIFocusUpdateContext the currently focused element is a UITabBarButton.

But I'm unable to check if the context is an instance of UITabBarButton because that type isn't available:

context.nextFocusedItem is UITabBarButton // can't compile

I'm really stuck here and would love any suggestions on how to tackle this one.

Thanks.

Body:
I have created extension on UIView which will check if there is focus somewhere in its hierarchy:

func containsFocus() -> Bool {
    if self.isFocused { return true }
    else {
        for subview in self.subviews {
            if subview.containsFocus() { return true }
        }

        return false
    }
}

This way you can check if your UITabBar has focus.

Note:

This is very expensive way of checking if your view has focus, because it is recursive function and it will potentially traverse the whole hierarchy of your view.

Tip:

If you are trying to implement custom transition when selecting tabs in UITabBar you should use UITabBarDelegate method:

 func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem)

If not, just ignore this tip.


问:
useEffect function open/close modal based in props works only at first time (click)
Im learning React and using the new implemented "Hooks" from Documentation. I got a problem with a Modal (Dialog from Material UI) and the open/close function using useEffect() function.

I have already read these both articles: React.useState does not reload state from props and How to sync props to state using React hook : setState()

It's already helped me, I have forgot to use the useEffect() function instead I was just setting the useState from what comes from props. Learned that useState will be executed only one time for setting the initial state. But I have however more one problem.

```<code>function AddItemModal(props) {
  const [open, setOpen] = useState(props.isOpen);

  useEffect(() => {
    setOpen(props.isOpen);
  }, [props.isOpen]);

  function handleClose() {
    setOpen(false);
  }
</code>```

That works for the first time when I click at the add button (in another Component) and handle the click (it changes the state to true) and I pass it as props to the Modal. But when I click (in modal) at close and try to click at add to open it again, nothing happens. In case needed, here's the code from the component where I handle the click and call the modal.

```<code>function ItemsTable() {
  const [addModalOpen, setAddModalOpen] = React.useState(false);

  const handleAddClick = () => {
    setAddModalOpen(true);
  };

  <Box mt={4} position="fixed" bottom={10} right={10}>
    <Fab color="secondary" aria-label="Add" onClick={handleAddClick}>
      <AddIcon />
    </Fab>
  </Box>
  <AddItemModal isOpen={addModalOpen} />
</code>```

答: I am not sure if I understood exactly what are you trying to do, but I see that useEffect does not use the state. In order useEffect to be called more than one times, you need to pass the state to it, so your [props.isOpen] needs to change to [open]

Body:
Im learning React and using the new implemented "Hooks" from Documentation. I got a problem with a Modal (Dialog from Material UI) and the open/close function using useEffect() function.

I have already read these both articles: React.useState does not reload state from props and How to sync props to state using React hook : setState()

It's already helped me, I have forgot to use the useEffect() function instead I was just setting the useState from what comes from props. Learned that useState will be executed only one time for setting the initial state. But I have however more one problem.

function AddItemModal(props) {
  const [open, setOpen] = useState(props.isOpen);

  useEffect(() => {
    setOpen(props.isOpen);
  }, [props.isOpen]);

  function handleClose() {
    setOpen(false);
  }

That works for the first time when I click at the add button (in another Component) and handle the click (it changes the state to true) and I pass it as props to the Modal. But when I click (in modal) at close and try to click at add to open it again, nothing happens. In case needed, here's the code from the component where I handle the click and call the modal.

function ItemsTable() {
  const [addModalOpen, setAddModalOpen] = React.useState(false);

  const handleAddClick = () => {
    setAddModalOpen(true);
  };

  <Box mt={4} position="fixed" bottom={10} right={10}>
    <Fab color="secondary" aria-label="Add" onClick={handleAddClick}>
      <AddIcon />
    </Fab>
  </Box>
  <AddItemModal isOpen={addModalOpen} />


问:
Bugs TabActivity in Child ActivityGroup
I created a TabActivity ...

and in the first tab, I call the class 'input'

I use ActivityGroup .. this example when I call the class 'input'

```<code>TabGroupActivity parentActivity = (TabGroupActivity)getParent();

Intent intent = new Intent(getParent(), Input.class);

parentActivity.startChildActivity("Input", intent);
</code>```

Within the child activity, I made a edittext. This example image of what I mean ...

But when I enter text, and a virtual keyboard out ...

virtual keyboard does not appear above the tabs, but he pushed the tab above the virtual keyboard .. This example image is what I mean ...

see image above, tab above the virtual keyboard ..

This happens if I do it in the child activity group .. if I put edittext on the main tab. everything went smoothly ..

I need a solution about a problem that I can ...

Kind Regards,

Vootsugu

答:
I am also facing the similar issue.Thanks in advance.
I solved it via putting in AndroidManifest.xml, and add the following to your specific activity:</p>

```<code>android:windowSoftInputMode="adjustPan"
</code>```

ContentLicense: CC BY-SA 2.5

Title: Bugs TabActivity in Child ActivityGroup

Body:
I created a TabActivity ...

and in the first tab, I call the class 'input'

I use ActivityGroup .. this example when I call the class 'input'

TabGroupActivity parentActivity = (TabGroupActivity)getParent();

Intent intent = new Intent(getParent(), Input.class);

parentActivity.startChildActivity("Input", intent);

Within the child activity, I made a edittext. This example image of what I mean ...

But when I enter text, and a virtual keyboard out ...

virtual keyboard does not appear above the tabs, but he pushed the tab above the virtual keyboard .. This example image is what I mean ...

see image above, tab above the virtual keyboard ..

This happens if I do it in the child activity group .. if I put edittext on the main tab. everything went smoothly ..

I need a solution about a problem that I can ...

Kind Regards,

Vootsugu

Body:
I am also facing the similar issue.Thanks in advance.
I solved it via putting in AndroidManifest.xml, and add the following to your specific activity:

android:windowSoftInputMode="adjustPan"


问:
How to add margin with Angular Flex Layout?
How can I add margin or padding to a container when using the Flex Layout Module?

Template:

```<code><div class="container">
  hell
  <div fxLayout="column" fxLayoutAlign="center center">
    <mat-card fxFill>Simple card test</mat-card>
  </div>
</div>
</code>```

Style:

```<code>.container{
    margin: 60px;
}
</code>```

I noticed it doesn't seem to be adding the correct amount of margin. You'll be able to see in the screenshot, the flex container has less margin than the text outside of it.

答: you may use fxLayoutGap="20px"

Body:
How can I add margin or padding to a container when using the Flex Layout Module?

Template:

  hell

    <mat-card fxFill>Simple card test</mat-card>

Style:

.container{
    margin: 60px;
}

I noticed it doesn't seem to be adding the correct amount of margin. You'll be able to see in the screenshot, the flex container has less margin than the text outside of it.

Body: you may use fxLayoutGap="20px"


问:
Create a variable table and retrieve @COLUMN_NAME
I would like to retrieve @COLUMN_NAME of a table as a variable.
I use SQL Server Management Studio 2016.

```<code>declare @tmp TABLE ([TABLE_CATALOG] varchar(128), [TABLE_SCHEMA] varchar(128), [TABLE_NAME] varchar(128), [COLUMN_NAME] varchar(128), [ORDINAL_POSITION] varchar(128),[COLUMN_DEFAULT] varchar(128),
 [IS_NULLABLE] varchar(128), [DATA_TYPE] varchar(128), [CHARACTER_MAXIMUM_LENGTH] varchar(128), [CHARACTER_OCTET_LENGTH] varchar(128), [NUMERIC_PRECISION] varchar(128), [NUMERIC_PRECISION_RADIX] varchar(128), [NUMERIC_SCALE] varchar(128),
 [DATETIME_PRECISION] varchar(128), [CARACTER_SET_CATALOG] varchar(128), [CARACTER_SET_SCHEMA] varchar(128), [CARACTER_SET_NAME] varchar(128), [COLLATION_CATALOG] varchar(128),
 [COLLATION_SCHEMA] varchar(128), [COLLATION_NAME] varchar(128), [DOMAIN_CATALOG] varchar(128), [DOMAIN_SCHEMA] varchar(128), [DOMAIN_NAME] varchar(128) )

INSERT INTO  @tmp
EXEC sp_executesql (' SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'maTable' ')

DECLARE @COLUMN_NAME varchar(128)
SET @COLUMN_NAME =(SELECT COLUMN_NAME FROM @tmp )
</code>```

Here is the error that I get ==>

Msg 102, Level 15, State 1, Line 9 Incorrect syntax near 'maTable'.

Even if I tried the same syntax before in an other code.
Does anyone have an idea?
Thank you

答:
You don't need to write </p>

```<code>EXEC sp_executesql (' SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'maTable' ')`
</code>```

<p>you can write </p>

```<code>SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'maTable'
</code>```

Body:
I would like to retrieve @COLUMN_NAME of a table as a variable.
I use SQL Server Management Studio 2016.

declare @tmp TABLE ([TABLE_CATALOG] varchar(128), [TABLE_SCHEMA] varchar(128), [TABLE_NAME] varchar(128), [COLUMN_NAME] varchar(128), [ORDINAL_POSITION] varchar(128),[COLUMN_DEFAULT] varchar(128),
 [IS_NULLABLE] varchar(128), [DATA_TYPE] varchar(128), [CHARACTER_MAXIMUM_LENGTH] varchar(128), [CHARACTER_OCTET_LENGTH] varchar(128), [NUMERIC_PRECISION] varchar(128), [NUMERIC_PRECISION_RADIX] varchar(128), [NUMERIC_SCALE] varchar(128),
 [DATETIME_PRECISION] varchar(128), [CARACTER_SET_CATALOG] varchar(128), [CARACTER_SET_SCHEMA] varchar(128), [CARACTER_SET_NAME] varchar(128), [COLLATION_CATALOG] varchar(128),
 [COLLATION_SCHEMA] varchar(128), [COLLATION_NAME] varchar(128), [DOMAIN_CATALOG] varchar(128), [DOMAIN_SCHEMA] varchar(128), [DOMAIN_NAME] varchar(128) )

INSERT INTO  @tmp
EXEC sp_executesql (' SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'maTable' ')

DECLARE @COLUMN_NAME varchar(128)
SET @COLUMN_NAME =(SELECT COLUMN_NAME FROM @tmp )

Here is the error that I get ==>

Msg 102, Level 15, State 1, Line 9 Incorrect syntax near 'maTable'.

Even if I tried the same syntax before in an other code.
Does anyone have an idea?
Thank you

Body:
You don't need to write

EXEC sp_executesql (' SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'maTable' ')`

you can write

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'maTable'


问:
concerns about required A records for setting up Firebase Dynamic Links with a custom subdomain
In setting up our own subdomain to handle Firebase Dynamic Links using these docs, the wizard says to put the A records at example.com in our DNS.  I'm getting pushback from our network administrators who are wary of creating an A record at the root of our domain, which is a large e-commerce web site.

A couple of concerns/questions about this:

The IP addresses required (151.101.1.195 and 151.101.65.195) point to non-Google servers (looks like Fastly), which is a bit alarming - it seems strange that Google would outsource their deep link hosting.

We don't want all of our e-commerce traffic (coming through example.com) to be subject to these A records.  Is it possible to put the A records at link.example.com instead?

答:
Here is the answer I received from Firebase support about these my two concerns/questions:

Regarding Fastly, Firebase uses this subprocessor to deliver content and managed services on Firebase Hosting. For more details you could check the list of Subprocessors used by Firebase on this doc.

It's possible to use a subdomain as your Firebase project's FDL domain. You'd need to create a subdomain (link.example.com) on your domain's DNS provider and connect it to Firebase Hosting. You could check out this guide for more details.


问:
Converting Hexadecimal NUmbers in English ASCII characters
In the below given code I am getting Hexa decimal values..i.e. 68 65 68 65... I want to convert it into English alphabetical characters like hehe...

I am not able to convert the hexadecimal numbers obtained to their          English characters

```<code>printf("\nCommand: ");
for(i = 54; i<=57; i++)
{
printf("%X", packet[i]);
printf(" ");
}
</code>```

Prints 68 65 68 65 but I want hehe

答:
You can use below code to get Alphabet for a Number: </p>

```<code>alphabet = printf("%c", Number);
</code>```

Body:
In the below given code I am getting Hexa decimal values..i.e. 68 65 68 65... I want to convert it into English alphabetical characters like hehe...

I am not able to convert the hexadecimal numbers obtained to their          English characters

printf("\nCommand: ");
for(i = 54; i<=57; i++)
{
printf("%X", packet[i]);
printf(" ");
}

Prints 68 65 68 65 but I want hehe

Body:
You can use below code to get Alphabet for a Number:

alphabet = printf("%c", Number);


问:
Power bi code move to SQL as precalculation
I want to move some calculation from Powerbi to SQL so only the results will be in Powerbi

Powerbi code:

```<code>MoM =
IF(
    ISFILTERED('X'[Year-month]),
    VAR __PREV_MONTH =
        CALCULATE(
            SUM('X'[stock_value_current]),
            DATEADD('X'[Year-month].[Date], -1, MONTH)
        )
    RETURN
        CALCULATE(SUM('X'[stock_value_current])-__PREV_MONTH)
)
</code>```

答:
Assuming this is a headline figure, and that [year-month] is a date column:</p>

```<code>select sum(t1.stock_value_current) - sum(t2.stock_value_current)
from MyTable t1
left join MyTable t2
on t2.[year-month] = dateadd(mm,-1,t1.[year-month])
where t1.[year-month] = @MyDateParameter
</code>```

Body:
I want to move some calculation from Powerbi to SQL so only the results will be in Powerbi

Powerbi code:

MoM =
IF(
    ISFILTERED('X'[Year-month]),
    VAR __PREV_MONTH =
        CALCULATE(
            SUM('X'[stock_value_current]),
            DATEADD('X'[Year-month].[Date], -1, MONTH)
        )
    RETURN
        CALCULATE(SUM('X'[stock_value_current])-__PREV_MONTH)
)

Body:
Assuming this is a headline figure, and that [year-month] is a date column:

select sum(t1.stock_value_current) - sum(t2.stock_value_current)
from MyTable t1
left join MyTable t2
on t2.[year-month] = dateadd(mm,-1,t1.[year-month])
where t1.[year-month] = @MyDateParameter


问:
Get SSL Certificate 'Issued to'
I want to know how can I get Local Computer SSL certificates Issued to field values. I used this command to show all SSL certificates informations but it did not show me Issued To field

GET-CHILDITEM -Path 'Cert:\LocalMachine\' –RECURSE | FORMAT-LIST –PROPERTY *

答:
Use the Subject property.

```<code>Get-ChildItem -Path 'Cert:\LocalMachine\' -Recurse | Format-List -Property Subject
</code>```

Title: Get SSL Certificate 'Issued to'

Body:
Use the Subject property.

Get-ChildItem -Path 'Cert:\LocalMachine\' -Recurse | Format-List -Property Subject


问:
Why is int calculation slower than string conversion?
I've written two different crossfoot functions, one uses simple integer calculation and one string conversion.

After measuring time, the results have been as expected. String conversion is somewhat slower.

But! If one does not print the result, but only makes an assignment to a variable, the timing is the opposite. Why?

Here's the code:

```<code>import time

def crossfoot(num, iterated=False):
    result = 0
    while num:
        result += num % 10
        num //= 10

    if iterated:
        num = result
        result = 0
        while num:
            result += num % 10
            num //= 10

    return result

def crossfoot2(num, iterated=False):
    digits = [int(x) for x in str(num)]

    result = sum(digits)

    if iterated and result > 9:
        return crossfoot2(result, True)

    return result
</code>```

And here's the testing I've made:

```<code>start = time.process_time()
res = crossfoot(20991231235959, True)
print(res)
end = time.process_time()
print("Crossfoot : {}".format(end-start))

start = time.process_time()
res = crossfoot2(20991231235959, True)
print(res)
end = time.process_time()
print("Crossfoot2: {}".format(end-start))
</code>```

Results with given code:
 Crossfoot : 2.0396000000002384e-05

  Crossfoot2: 3.288599999999933e-05

If one removes the lines with print(res) the first function will be way slower than the second one.

Results with print removed:

  Crossfoot : 5.549999999999999e-06

  Crossfoot2: 2.6244000000001655e-05

What is the reason for that?

This is not time critical, but I'd like to understand the cause.

答:
crossfoot remains faster in both cases. You probably missed that it's e-06 when you remove the print call.

With both at e-05, that would be 0.554 vs 2.624

Body:
I've written two different crossfoot functions, one uses simple integer calculation and one string conversion.

After measuring time, the results have been as expected. String conversion is somewhat slower.

But! If one does not print the result, but only makes an assignment to a variable, the timing is the opposite. Why?

Here's the code:

import time

def crossfoot(num, iterated=False):
    result = 0
    while num:
        result += num % 10
        num //= 10

    if iterated:
        num = result
        result = 0
        while num:
            result += num % 10
            num //= 10

    return result

def crossfoot2(num, iterated=False):
    digits = [int(x) for x in str(num)]

    result = sum(digits)

    if iterated and result > 9:
        return crossfoot2(result, True)

    return result

And here's the testing I've made:

start = time.process_time()
res = crossfoot(20991231235959, True)
print(res)
end = time.process_time()
print("Crossfoot : {}".format(end-start))

start = time.process_time()
res = crossfoot2(20991231235959, True)
print(res)
end = time.process_time()
print("Crossfoot2: {}".format(end-start))

Results with given code:
 Crossfoot : 2.0396000000002384e-05

  Crossfoot2: 3.288599999999933e-05

If one removes the lines with print(res) the first function will be way slower than the second one.

Results with print removed:

  Crossfoot : 5.549999999999999e-06

  Crossfoot2: 2.6244000000001655e-05

What is the reason for that?

This is not time critical, but I'd like to understand the cause.


问:
Calling functions and returning values
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

```<code> void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }
</code>```

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...

答:
In case getRequiredInfo get the address of the strings, try this:

```<code>getInfo.getRequiredInfo(&sSw, &sName, &sList);
</code>```

Now the function can change the value of the arguments.

Title: Calling functions and returning values

Body:
I am a beginner in C++.I have a function which returns some parameters that i need ,to use in  the rest of my program.I am trying to access that function within another class.I am confused with the way i can do it...Can anyone please help me..?

Following is my code :

 void SampleProgram :: myFunction()
   {
         string sInput;
         GetInfo  getInfo(sInput);  //creating instance of the class containing the function

            string sSw="";
       string sName="ram";
       string sList="list";

           getInfo.getRequiredInfo(sSw,sName,sList); //calling the function

    }

How can i access the output parameters of getRequiredInfo() ..?and save it if the ouput parameters are as following :string name,int status
Please help me...

Body:
In case getRequiredInfo get the address of the strings, try this:

getInfo.getRequiredInfo(&sSw, &sName, &sList);

Now the function can change the value of the arguments.


问:
Fetching Data from PivotTable into Array in VBA (Excel)
i'm trying to fetch the Data from a PivotTable, use it in Array in VBA and then to print it. I'm new to VBA and I've watched a few tutorials, but i can't actually get it.

I've tried with referencing the range of my column with "DataBodyRange", but i always get different errors. "Sheet4" is the sheet where my "PivotTable1" is located. And i need all the data from a column.

```<code>Public Sub ReadToArray()
    'Range
    Dim rg As Range
    Set rg = Worksheets("Sheet4").pt("PivotTable1").DataBodyRange

    'Dynamic Array
     Dim Done As Variant
     Done = rg.Value

    'Array Values
     Debug.Print "i", "Value"
     Dim i As Long
     For i = LBound(Done) To UBound(Done)
         Debug.Print i, Done(i)
     Next i
 End Sub
</code>```

The end result is that I want to print out the values for the whole column and use them afterwards.

答:
So I can see a few problems that are causing this. FIrst, to reference a pivot table in a sheet, you need .pivottables() not .pt().

Next, setting an array to have the value from a range like this will give you a 2D array, so you need to loop through it in two dimensions to get all the values. I've added a nested loop using a second iterator, j:

```<code>Public Sub ReadToArray()

     Dim pt As PivotTable
     Dim rg As Range
     Set pt = Worksheets("Sheet4").PivotTables("PivotTable1")

     Set rg = pt.DataBodyRange

     Dim Done As Variant

     Done = rg.Value

     Debug.Print "i", "Value"
     Dim i As Long, j As Long

     For i = LBound(Done, 1) To UBound(Done, 1)
        For j = LBound(Done, 2) To UBound(Done, 2)
            Debug.Print i & ", " & j & ", " & Done(i, j)
        Next j
     Next i

 End Sub
</code>```

Body:
i'm trying to fetch the Data from a PivotTable, use it in Array in VBA and then to print it. I'm new to VBA and I've watched a few tutorials, but i can't actually get it.

I've tried with referencing the range of my column with "DataBodyRange", but i always get different errors. "Sheet4" is the sheet where my "PivotTable1" is located. And i need all the data from a column.

Public Sub ReadToArray()
    'Range
    Dim rg As Range
    Set rg = Worksheets("Sheet4").pt("PivotTable1").DataBodyRange

    'Dynamic Array
     Dim Done As Variant
     Done = rg.Value

    'Array Values
     Debug.Print "i", "Value"
     Dim i As Long
     For i = LBound(Done) To UBound(Done)
         Debug.Print i, Done(i)
     Next i
 End Sub

The end result is that I want to print out the values for the whole column and use them afterwards.

Body:
So I can see a few problems that are causing this. FIrst, to reference a pivot table in a sheet, you need .pivottables() not .pt().

Next, setting an array to have the value from a range like this will give you a 2D array, so you need to loop through it in two dimensions to get all the values. I've added a nested loop using a second iterator, j:

Public Sub ReadToArray()

     Dim pt As PivotTable
     Dim rg As Range
     Set pt = Worksheets("Sheet4").PivotTables("PivotTable1")

     Set rg = pt.DataBodyRange

     Dim Done As Variant

     Done = rg.Value

     Debug.Print "i", "Value"
     Dim i As Long, j As Long

     For i = LBound(Done, 1) To UBound(Done, 1)
        For j = LBound(Done, 2) To UBound(Done, 2)
            Debug.Print i & ", " & j & ", " & Done(i, j)
        Next j
     Next i

 End Sub


问:
Eclipse dark theme highlight issue
I just switched from geany to eclipse and I have a little problem

How can I change that highlight color which is VERY annoying

As you can see, whenever I highlight anything and click somewhere else, it changes like this. How can fix this little bug?

答:
For me, this is what did it (seems it's different for everyone):

Open Windows -> Preferences -> General -> Editors -> Text Editors -> Annotations

Under "Annotation Types":

select "Boot Dynamic Info", then uncheck the "Text as" checkbox on the right.

Title: Eclipse dark theme highlight issue


问:
How to crop images of different length and width to equal length and width?
I'm using COCO data-set. in that data-set images have different length and width but I have to crop them to equal length and width.

All the images are placed in a folder. I have tried to crop them into equal length and width i.e. 386X386

```<code>import sys
import os
from PIL import Image

filepath = "/content/drive/My Drive/Colab Notebooks/SRGAN/data"

# Loop through all provided arguments
for filename in os.listdir(filepath):
    if "." not in filename:
        continue
    ending = filename.split(".")[1]
    if ending not in ["jpg", "gif", "png"]:
        continue

    # Attempt to open an image file
    image = Image.open(os.path.join(filepath, filename))

    # Perform operations on the image here
    image = image.crop((0, 0, 386, 386))

    # Split our origional filename into name and extension
    name, extension = os.path.splitext(filename)

    # Save the image as "(origional_name)_thumb.jpg
    print(name + '_cropped.jpg')
    image.save(os.path.join("/content/drive/My Drive/Colab Notebooks/SRGAN/data", name + '_cropped.jpg'))
</code>```

It should crop all images to size 386X386, but it is generating multiple copies of same images with different length and width.

答:
```<code>from keras.preprocessing import image
test_img = image.load_img('Image Path', target_size=(386,386))
</code>```

<p>'target size' defines the dimensions to crop to. </p>

Body:
I'm using COCO data-set. in that data-set images have different length and width but I have to crop them to equal length and width.

All the images are placed in a folder. I have tried to crop them into equal length and width i.e. 386X386

import sys
import os
from PIL import Image

filepath = "/content/drive/My Drive/Colab Notebooks/SRGAN/data"

# Loop through all provided arguments
for filename in os.listdir(filepath):
    if "." not in filename:
        continue
    ending = filename.split(".")[1]
    if ending not in ["jpg", "gif", "png"]:
        continue

    # Attempt to open an image file
    image = Image.open(os.path.join(filepath, filename))

    # Perform operations on the image here
    image = image.crop((0, 0, 386, 386))

    # Split our origional filename into name and extension
    name, extension = os.path.splitext(filename)

    # Save the image as "(origional_name)_thumb.jpg
    print(name + '_cropped.jpg')
    image.save(os.path.join("/content/drive/My Drive/Colab Notebooks/SRGAN/data", name + '_cropped.jpg'))

It should crop all images to size 386X386, but it is generating multiple copies of same images with different length and width.

Body:
from keras.preprocessing import image
test_img = image.load_img('Image Path', target_size=(386,386))

'target size' defines the dimensions to crop to.


问:
Post image object Clarifai rest api swift
I want to upload an image that captured in swift application so the image as object I need to do this thru http request
First I tried to do that with curl but I got an error that the string is too long second I tried with the example code that published in the site and that not works

Code example from the site:

```<code>curl -X POST
    -H 'Authorization: Key YOUR_API_KEY'
    -H "Content-Type: application/json"
    -d '
    {
      "inputs": [
        {
          "data": {
            "image": {
              "url": "https://samples.clarifai.com/demographics.jpg"
            }
          }
        }
      ]
    }'
</code>```

https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs

I want to upload an image as object UIImage that captured in swift, not as URL

答:
Try the following curl command:

```<code>curl -X POST \
     -H "Authorization: Key YOUR_API_KEY" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d '{"inputs":[{"data":{"image":{"url":"https://samples.clarifai.com/demographics.jpg"}}}]}' \
     https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs
</code>```

It seems to have worked for me.

Body:
I want to upload an image that captured in swift application so the image as object I need to do this thru http request
First I tried to do that with curl but I got an error that the string is too long second I tried with the example code that published in the site and that not works

Code example from the site:

curl -X POST
    -H 'Authorization: Key YOUR_API_KEY'
    -H "Content-Type: application/json"
    -d '
    {
      "inputs": [
        {
          "data": {
            "image": {
              "url": "https://samples.clarifai.com/demographics.jpg"
            }
          }
        }
      ]
    }'

https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs

I want to upload an image as object UIImage that captured in swift, not as URL

Body:
Try the following curl command:

curl -X POST \
     -H "Authorization: Key YOUR_API_KEY" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d '{"inputs":[{"data":{"image":{"url":"https://samples.clarifai.com/demographics.jpg"}}}]}' \
     https://api.clarifai.com/v2/models/c0c0ac362b03416da06ab3fa36fb58e3/outputs

It seems to have worked for me.


问:
Cannot do CSS animation in Angular
I'm trying to use a vanilla css animation like so :

```<code>div {
  height: 0.5rem;
  width: 1rem;
  background-color: blue;
  transform-origin: left;
  transition: transform 5s;
  transition-delay: 2s;
  transform: scaleX(15);
}

</code>```

That it just not working at all. The div is displaying at scaleX(15)but with no duration.

It does work properly with CodePen but not with Stackblitz. What am I missing here? Can't CSS animation works with Angular?

答:
Your div needs to have an initial state without the transform. transition: transform will only work when a transform value changes. If it's already set from the beginning, there won't be an animation. I made an example where a click on the div triggers the animation, inspired by your CSS snippet.

https://stackblitz.com/edit/angular-uenfjp

Title: Cannot do CSS animation in Angular

Body:
I'm trying to use a vanilla css animation like so :

div {
  height: 0.5rem;
  width: 1rem;
  background-color: blue;
  transform-origin: left;
  transition: transform 5s;
  transition-delay: 2s;
  transform: scaleX(15);
}

That it just not working at all. The div is displaying at scaleX(15)but with no duration.

It does work properly with CodePen but not with Stackblitz. What am I missing here? Can't CSS animation works with Angular?


问:
Classic UI | Unable to add or move components inside "Experience Fragment Container"
We cannot use /cf# mode to add or move components inside the "Experience Fragment Container" inside the Experience Fragments.

To add a new component once we've added this component to an experience fragment we have to switch to the .editor.html view.

AEM version is used: 6.3.3

Touch UI
Classic UI

答: Adobe is not updating the Classic UI anymore and it will be phased out in the future editions. So it will be better to use the touch UI rather than clasic UI. In 6.3 one can easily use touch UI. It will be helpful to use the Touch to build the components and then use it experience fragment. </p>


问:
navigator.serviceWorker.ready not fireing when sw placed in subfolder
Our app is served (by IIS in a virtual application) from https://myserver.com/myapp

The HTML returned from https://myserver.com/myapp are:

```<code><html>
  <!-- This file is served as a virtual application from https://myserver.com/myapp-->
  <head>
    <script src="/myapp/file.js"></script>
  </head>
<body>
</body>
</code>```

To register the serviceworker I need to add the subfolder as shown below

```<code>// This does not work since the app is served from /myapp
navigator.serviceWorker.register("/sw.js")  // Fail, will try loading https://myServer.com/sw.js

// This works (registration successful)
navigator.serviceWorker.register("/myapp/sw.js")  // This will register the sw.
</code>```

Problem happens when I try to use the serviceworker, that is waiting for the ready event:

```<code>// Inside of file.js
navigator.serviceWorker.ready.then(...) // Will not fire
</code>```

I guess of whats happening is that the ready event is not firing becouse the serviceworker "thinks" it is beeing installed from a subfolder named "MyApp", but when the file.js runs and tries to use the serviceworker, it looks like the file.js is served from root, and thus outside the scope of the serviceworker.

Any ideas on how to handle this? I tried using the scope parameter, but I think that is only use to limit the scope, not expand it.

```<code>{ scope: '/' } // Will fail with outside root error
{ scope: '/MyApp' } // Works, but still no ready event
</code>```

I'm sure I'm missing something here, but I've no idea what it is.

答:
I found a workaround, but still not sure why the ready is not fireing.</p>

```<code>navigator.serviceWorker.ready.then(function(reg){...}) // Will not fire

// Instead, assume registred and active, then this is a workaround
navigator.serviceWorker.getRegistrations().then(function ([reg]) {...})
</code>```

Body:
Our app is served (by IIS in a virtual application) from https://myserver.com/myapp

The HTML returned from https://myserver.com/myapp are:

To register the serviceworker I need to add the subfolder as shown below

// This does not work since the app is served from /myapp
navigator.serviceWorker.register("/sw.js")  // Fail, will try loading https://myServer.com/sw.js

// This works (registration successful)
navigator.serviceWorker.register("/myapp/sw.js")  // This will register the sw.

Problem happens when I try to use the serviceworker, that is waiting for the ready event:

// Inside of file.js
navigator.serviceWorker.ready.then(...) // Will not fire

I guess of whats happening is that the ready event is not firing becouse the serviceworker "thinks" it is beeing installed from a subfolder named "MyApp", but when the file.js runs and tries to use the serviceworker, it looks like the file.js is served from root, and thus outside the scope of the serviceworker.

Any ideas on how to handle this? I tried using the scope parameter, but I think that is only use to limit the scope, not expand it.

{ scope: '/' } // Will fail with outside root error
{ scope: '/MyApp' } // Works, but still no ready event

I'm sure I'm missing something here, but I've no idea what it is.

Body:
I found a workaround, but still not sure why the ready is not fireing.

navigator.serviceWorker.ready.then(function(reg){...}) // Will not fire

// Instead, assume registred and active, then this is a workaround
navigator.serviceWorker.getRegistrations().then(function ([reg]) {...})


问:
Spring boot project is spring boot test initialisation error
My spring boot project is showing build failure with the following error

```
-------------------------------------------------------------------------------
Test set: com.examples.springbootdemo.SpringbootDemoApplicationTests
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.055 s <<< FAILURE! - in com.examples.springbootdemo.SpringbootDemoApplicationTests
initializationError(com.examples.springbootdemo.SpringbootDemoApplicationTests)  Time elapsed: 0 s  <<< ERROR!
java.lang.TypeNotPresentException: Type org.springframework.test.context.junit4.SpringRunner not present
Caused by: java.lang.ClassNotFoundException: org.springframework.test.context.junit4.SpringRunner
```

POM.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example2</groupId>
    <artifactId>spring-hello</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-hello</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

答:
Add JUnit dependency in your pom.</p>

```<code> <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
</dependency>
</code>```

Body:
My spring boot project is showing build failure with the following error

-------------------------------------------------------------------------------
Test set: com.examples.springbootdemo.SpringbootDemoApplicationTests
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.055 s <<< FAILURE! - in com.examples.springbootdemo.SpringbootDemoApplicationTests
initializationError(com.examples.springbootdemo.SpringbootDemoApplicationTests)  Time elapsed: 0 s  <<< ERROR!
java.lang.TypeNotPresentException: Type org.springframework.test.context.junit4.SpringRunner not present
Caused by: java.lang.ClassNotFoundException: org.springframework.test.context.junit4.SpringRunner

POM.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example2</groupId>
    <artifactId>spring-hello</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-hello</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Body:
Add JUnit dependency in your pom.

 <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
</dependency>


答:
Angular contains css animations

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

https://stackblitz.com/angular/eqxqkpyrdgr?file=src%2Fapp%2Fhero-list-groups.component.ts

Title: Cannot do CSS animation in Angular


问:
How to sort an array starting from the middle?
Considering, I have an array like this [..., n-2, n-1, n, n+1, n+2, ...]. I would like to sort it in this way [n, n+1, n-1, n+2, n-2,...] with n equals to the middle of my array.

For example:

Input:

```<code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

Output:

```<code>[5, 6, 4, 7, 3, 8, 2, 9, 1, 0]
</code>```

let arrayNotSorted = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let positionMiddleArray = Math.trunc(arrayNotSorted.length / 2);

let arraySorted = [arrayNotSorted[positionMiddleArray]];

for(let i=1; i <= positionMiddleArray; i++){
 if(arrayNotSorted[positionMiddleArray + i] !== undefined){
  arraySorted.push(arrayNotSorted[positionMiddleArray + i]);
  }
  if(arrayNotSorted[positionMiddleArray - i] !== undefined){
   arraySorted.push(arrayNotSorted[positionMiddleArray - i]);
  }
}

console.log('Not_Sorted', arrayNotSorted);
console.log('Sorted', arraySorted);```

What I have done works properly, but I would like to know if there is a better way or a more efficient way to do so ?

答:
You could take a pivot value 5 and sort by the absolute delta of the value and the pivot values an sort descending for same deltas.

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    pivot = 5;

array.sort((a, b) => Math.abs(a - pivot) - Math.abs(b - pivot) || b - a);

console.log(...array); // 5 6 4 7 3 8 2 9 1 0```

Body:
Considering, I have an array like this [..., n-2, n-1, n, n+1, n+2, ...]. I would like to sort it in this way [n, n+1, n-1, n+2, n-2,...] with n equals to the middle of my array.

For example:

Input:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Output:

[5, 6, 4, 7, 3, 8, 2, 9, 1, 0]

let arrayNotSorted = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
let positionMiddleArray = Math.trunc(arrayNotSorted.length / 2);

let arraySorted = [arrayNotSorted[positionMiddleArray]];

for(let i=1; i <= positionMiddleArray; i++){
 if(arrayNotSorted[positionMiddleArray + i] !== undefined){
  arraySorted.push(arrayNotSorted[positionMiddleArray + i]);
  }
  if(arrayNotSorted[positionMiddleArray - i] !== undefined){
   arraySorted.push(arrayNotSorted[positionMiddleArray - i]);
  }
}

console.log('Not_Sorted', arrayNotSorted);
console.log('Sorted', arraySorted);

What I have done works properly, but I would like to know if there is a better way or a more efficient way to do so ?


问:
Class is not key value coding-compliant for the key
My app crashes on launch with the following error:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key tableViewChannels.

This is a project that I've inherited and re-worked significantly. I thought initially that tableViewChannels was an old array, but I've searched the whole project in XCode and it doesn't appear anywhere.

I went into the storyboard with my favorite text editor to look at the raw XML, and did indeed find two instances of "tableViewChannels" which appear to have been old IBOutlets (they no longer actually appear in the visual storyboard). I deleted both, saved, cleaned the build folder, restarted XCode, and still crash with exactly the same error. I'm perplexed as to where this code is still lurking in the project. I appreciate any help. Thanks!

答: Had the same issue, there were no outlets to delete, it was just an XCode problem and got it resolved by deleting Derived Data and cleaning the project.</p>


问:
Get values from a number line at specific position
I have a dataframe with three columns. The first is "A" or "B" the second is a value and the third is a value (from and to). Now I want to get the values of the first column for given values of the two other columns.

I got this data frame:

```<code>a <- c('A','B','A','B')
b <- c(0,40,60,80)
c <- c(40,60,80,100)

frame <- data.frame(a,b,c)

> frame
  a  b   c
1 A  0  40
2 B 40  60
3 A 60  80
4 B 80 100
</code>```

And I want to generate this second data frame from the first one.

```<code>> frame2
   d   e
1  A  10
2  A  20
3  A  30
4  A  40
5  B  50
6  B  60
7  A  70
8  A  80
9  B  90
10 B 100
</code>```

答:
You can use pmap from tidyverse(purrr)

```<code>library(tidyverse)

pmap_dfr(frame, ~tibble(a = ..1, e = seq(..2 + 10, ..3, 10)))

# # A tibble: 10 x 2
#        a     e
#    <int> <dbl>
#  1     1    10
#  2     1    20
#  3     1    30
#  4     1    40
#  5     2    50
#  6     2    60
#  7     1    70
#  8     1    80
#  9     2    90
# 10     2   100
</code>```

Edit: Actually, you have to fix the fact that a is converted to a factor by data.frame first.

```<code>frame <- frame %>% mutate_if(is.factor, as.character)

pmap_dfr(frame, ~tibble(a = ..1, e = seq(..2 + 10, ..3, 10)))

# # A tibble: 10 x 2
#    a         e
#    <chr> <dbl>
#  1 A        10
#  2 A        20
#  3 A        30
#  4 A        40
#  5 B        50
#  6 B        60
#  7 A        70
#  8 A        80
#  9 B        90
# 10 B       100
</code>```

Body:
I have a dataframe with three columns. The first is "A" or "B" the second is a value and the third is a value (from and to). Now I want to get the values of the first column for given values of the two other columns.

I got this data frame:

a <- c('A','B','A','B')
b <- c(0,40,60,80)
c <- c(40,60,80,100)

frame <- data.frame(a,b,c)

> frame
  a  b   c
1 A  0  40
2 B 40  60
3 A 60  80
4 B 80 100

And I want to generate this second data frame from the first one.

> frame2
   d   e
1  A  10
2  A  20
3  A  30
4  A  40
5  B  50
6  B  60
7  A  70
8  A  80
9  B  90
10 B 100

Body:
You can use pmap from tidyverse(purrr)

library(tidyverse)

pmap_dfr(frame, ~tibble(a = ..1, e = seq(..2 + 10, ..3, 10)))

# # A tibble: 10 x 2
#        a     e
#    <int> <dbl>
#  1     1    10
#  2     1    20
#  3     1    30
#  4     1    40
#  5     2    50
#  6     2    60
#  7     1    70
#  8     1    80
#  9     2    90
# 10     2   100

Edit: Actually, you have to fix the fact that a is converted to a factor by data.frame first.

frame <- frame %>% mutate_if(is.factor, as.character)

pmap_dfr(frame, ~tibble(a = ..1, e = seq(..2 + 10, ..3, 10)))

# # A tibble: 10 x 2
#    a         e
#    <chr> <dbl>
#  1 A        10
#  2 A        20
#  3 A        30
#  4 A        40
#  5 B        50
#  6 B        60
#  7 A        70
#  8 A        80
#  9 B        90
# 10 B       100


问:
How to remove empty strings from the end of a list of strings (only at the end)
i have some list of strings. I want to remove empty strings from the end of the list (i.e.  each list should end with a non empty element).

```<code>input
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']
</code>```

output

```<code>list1= ['a1','b1','c1','d1']
list2 = ['a2','','b2','','c2','d2']
list3 = ['a3','','b3']
list4 = ['']
</code>```

if all the elements are empty strings , only one empty string should remain (eg. list4).

答:
You can use a generator comprehension with enumerate and keep the first index starting from the end where there is a non-empty string. By using next we only need to iterate until the first non-empty string is found:

```<code>def trim_empty_end(l):
    last_ix = next((ix for ix, i in enumerate(l[::-1]) if i), len(l)-1)
    return l[:len(l) - last_ix]
</code>```

```<code>trim_empty_end(['a1','b1','c1','d1',''])
# ['a1', 'b1', 'c1', 'd1']

trim_empty_end(['a2','','b2','','c2','d2',''])
# ['a2', '', 'b2', '', 'c2', 'd2']

trim_empty_end(['a3','','b3','','',''])
# ['a3', '', 'b3']

trim_empty_end(['','','','',''])
# ['']
</code>```

Body:
i have some list of strings. I want to remove empty strings from the end of the list (i.e.  each list should end with a non empty element).

input
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']

output

list1= ['a1','b1','c1','d1']
list2 = ['a2','','b2','','c2','d2']
list3 = ['a3','','b3']
list4 = ['']

if all the elements are empty strings , only one empty string should remain (eg. list4).

Body:
You can use a generator comprehension with enumerate and keep the first index starting from the end where there is a non-empty string. By using next we only need to iterate until the first non-empty string is found:

def trim_empty_end(l):
    last_ix = next((ix for ix, i in enumerate(l[::-1]) if i), len(l)-1)
    return l[:len(l) - last_ix]

trim_empty_end(['a1','b1','c1','d1',''])
# ['a1', 'b1', 'c1', 'd1']

trim_empty_end(['a2','','b2','','c2','d2',''])
# ['a2', '', 'b2', '', 'c2', 'd2']

trim_empty_end(['a3','','b3','','',''])
# ['a3', '', 'b3']

trim_empty_end(['','','','',''])
# ['']


问:
What is the point of AutoLogin?
Miles Johnson just updated his CakePHP AutoLogin Plugin, and although I am grateful for his work and contributions, I seem to miss the point: what is the difference, or why is it better than just having a long duration session cookie set by CakePHP?

答:
that is exactly what it does, https://github.com/milesj/cake-auto_login/blob/master/controllers/components/auto_login.php#L202

also does this over and above just a long running cookie

Requires no installation except for adding the checkbox into your user login forms

Automatically saves the cookie and info when a user logs in

Automatically kills the cookie and session when a user logs out

Inserts a hash within the cookie so that it cannot be hijacked

Encrypts the cookie so the information cannot be harvested

Configuration options for cookie name and length

Functionality for additional user updating or error logging

Title: What is the point of AutoLogin?