问:
Uploading PyPi Package error
I am trying to upload a pypi package, first i found out that setup_tools was really old, so that is now updated, though i still get the same error, and google is not really helping me much on this subject.

```<code>python setup.py sdist upload -r pypitest
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'include_package_data'
  warnings.warn(msg)
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'zip_safe'
  warnings.warn(msg)
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
  warnings.warn(msg)
running sdist
running check
warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list)

warning: sdist: standard file not found: should have one of README, README.txt

writing manifest file 'MANIFEST'
creating arcsightrest-1.0
making hard links in arcsightrest-1.0...
hard linking arcsightrest.py -> arcsightrest-1.0
hard linking setup.cfg -> arcsightrest-1.0
hard linking setup.py -> arcsightrest-1.0
Creating tar archive
removing 'arcsightrest-1.0' (and everything under it)
running upload
Traceback (most recent call last):
  File "setup.py", line 20, in <module>
    'python-dateutil',
  File "/usr/lib64/python2.7/distutils/core.py", line 152, in setup
    dist.run_commands()
  File "/usr/lib64/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/usr/lib64/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "/usr/lib64/python2.7/distutils/command/upload.py", line 60, in run
    self.upload_file(command, pyversion, filename)
  File "/usr/lib64/python2.7/distutils/command/upload.py", line 70, in upload_file
    raise AssertionError("unsupported schema " + schema)
AssertionError: unsupported schema
</code>```

If i try to run register it works just fine:

```<code>python setup.py register -r test
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'include_package_data'
  warnings.warn(msg)
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'zip_safe'
  warnings.warn(msg)
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
  warnings.warn(msg)
running register
running check
Registering arcsightrest to https://testpypi.python.org/pypi
Server response (200): OK
</code>```

Anyone had this problem before?

.pypirc file is also available, and works just fine with register.

```<code>[distutils]
index-servers =
    pypi
    test

[pypi]
repository: https://pypi.python.org/pypi
username: ****
password: ****

[test]
repository: https://testpypi.python.org/pypi
username: ****
password: ****
</code>```

Setup.py file (UPDATED with the import mentioned in the answer):

```<code>from setuptools import setup

setup(
    name='arcsightrest',
    version='1.0',
    description='Python library to connect to the HP Arcsight Logger REST API',
    author='***',
    license='MIT',
    author_email='***',
    url='****',
    download_url='****',
    keywords=['arcsight', 'logger', 'rest'],
    include_package_data=True,
    zip_safe=True,
    py_modules=['arcsightrest'],
    install_requires=[
        'pytz',
        'untangle',
        'requests',
        'python-dateutil',
    ],
)
</code>```

UPDATE:
Trying to change the setup.py got me a bit closer, for some reason it asks for my password now, but the end result is still the same error:

```<code>python setup.py sdist upload -r pypitest
running sdist
running egg_info
writing requirements to arcsightrest.egg-info/requires.txt
writing arcsightrest.egg-info/PKG-INFO
writing top-level names to arcsightrest.egg-info/top_level.txt
writing dependency_links to arcsightrest.egg-info/dependency_links.txt
reading manifest file 'arcsightrest.egg-info/SOURCES.txt'
writing manifest file 'arcsightrest.egg-info/SOURCES.txt'
warning: sdist: standard file not found: should have one of README, README.rst, README.txt

running check
creating arcsightrest-1.0
creating arcsightrest-1.0/arcsightrest.egg-info
copying files to arcsightrest-1.0...
copying arcsightrest.py -> arcsightrest-1.0
copying setup.cfg -> arcsightrest-1.0
copying setup.py -> arcsightrest-1.0
copying arcsightrest.egg-info/PKG-INFO -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/SOURCES.txt -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/dependency_links.txt -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/requires.txt -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/top_level.txt -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/zip-safe -> arcsightrest-1.0/arcsightrest.egg-info
Writing arcsightrest-1.0/setup.cfg
Creating tar archive
removing 'arcsightrest-1.0' (and everything under it)
running upload
Password:
Traceback (most recent call last):
  File "setup.py", line 20, in <module>
    'python-dateutil',
  File "/usr/lib64/python2.7/distutils/core.py", line 152, in setup
    dist.run_commands()
  File "/usr/lib64/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/usr/lib64/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "/usr/lib64/python2.7/distutils/command/upload.py", line 60, in run
    self.upload_file(command, pyversion, filename)
  File "/usr/lib64/python2.7/distutils/command/upload.py", line 70, in upload_file
    raise AssertionError("unsupported schema " + schema)
AssertionError: unsupported schema
</code>```

Setuptools version:

```<code>setuptools 28.8.0 from /usr/lib/python2.7/site-packages (Python 2.7)
</code>```

答:
I was getting the same error. Then, I realize that the error should print the schema. But my error was like this

```<code>...
    raise AssertionError("unsupported schema " + schema)
AssertionError: unsupported schema
</code>```

Note that schema is an empty string. So, in my point of view, the schema hasn't been found. I tried many things, but only changing the permission of .pypirc file works. I just did

```<code>$ sudo chmod 777 ~/.pypirc
</code>```

Title: Uploading PyPi Package error

Body:
I am trying to upload a pypi package, first i found out that setup_tools was really old, so that is now updated, though i still get the same error, and google is not really helping me much on this subject.

python setup.py sdist upload -r pypitest
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'include_package_data'
  warnings.warn(msg)
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'zip_safe'
  warnings.warn(msg)
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
  warnings.warn(msg)
running sdist
running check
warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list)

warning: sdist: standard file not found: should have one of README, README.txt

writing manifest file 'MANIFEST'
creating arcsightrest-1.0
making hard links in arcsightrest-1.0...
hard linking arcsightrest.py -> arcsightrest-1.0
hard linking setup.cfg -> arcsightrest-1.0
hard linking setup.py -> arcsightrest-1.0
Creating tar archive
removing 'arcsightrest-1.0' (and everything under it)
running upload
Traceback (most recent call last):
  File "setup.py", line 20, in <module>
    'python-dateutil',
  File "/usr/lib64/python2.7/distutils/core.py", line 152, in setup
    dist.run_commands()
  File "/usr/lib64/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/usr/lib64/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "/usr/lib64/python2.7/distutils/command/upload.py", line 60, in run
    self.upload_file(command, pyversion, filename)
  File "/usr/lib64/python2.7/distutils/command/upload.py", line 70, in upload_file
    raise AssertionError("unsupported schema " + schema)
AssertionError: unsupported schema

If i try to run register it works just fine:

python setup.py register -r test
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'include_package_data'
  warnings.warn(msg)
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'zip_safe'
  warnings.warn(msg)
/usr/lib64/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
  warnings.warn(msg)
running register
running check
Registering arcsightrest to https://testpypi.python.org/pypi
Server response (200): OK

Anyone had this problem before?

.pypirc file is also available, and works just fine with register.

[distutils]
index-servers =
    pypi
    test

[pypi]
repository: https://pypi.python.org/pypi
username: ****
password: ****

[test]
repository: https://testpypi.python.org/pypi
username: ****
password: ****

Setup.py file (UPDATED with the import mentioned in the answer):

from setuptools import setup

setup(
    name='arcsightrest',
    version='1.0',
    description='Python library to connect to the HP Arcsight Logger REST API',
    author='***',
    license='MIT',
    author_email='***',
    url='****',
    download_url='****',
    keywords=['arcsight', 'logger', 'rest'],
    include_package_data=True,
    zip_safe=True,
    py_modules=['arcsightrest'],
    install_requires=[
        'pytz',
        'untangle',
        'requests',
        'python-dateutil',
    ],
)

UPDATE:
Trying to change the setup.py got me a bit closer, for some reason it asks for my password now, but the end result is still the same error:

python setup.py sdist upload -r pypitest
running sdist
running egg_info
writing requirements to arcsightrest.egg-info/requires.txt
writing arcsightrest.egg-info/PKG-INFO
writing top-level names to arcsightrest.egg-info/top_level.txt
writing dependency_links to arcsightrest.egg-info/dependency_links.txt
reading manifest file 'arcsightrest.egg-info/SOURCES.txt'
writing manifest file 'arcsightrest.egg-info/SOURCES.txt'
warning: sdist: standard file not found: should have one of README, README.rst, README.txt

running check
creating arcsightrest-1.0
creating arcsightrest-1.0/arcsightrest.egg-info
copying files to arcsightrest-1.0...
copying arcsightrest.py -> arcsightrest-1.0
copying setup.cfg -> arcsightrest-1.0
copying setup.py -> arcsightrest-1.0
copying arcsightrest.egg-info/PKG-INFO -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/SOURCES.txt -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/dependency_links.txt -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/requires.txt -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/top_level.txt -> arcsightrest-1.0/arcsightrest.egg-info
copying arcsightrest.egg-info/zip-safe -> arcsightrest-1.0/arcsightrest.egg-info
Writing arcsightrest-1.0/setup.cfg
Creating tar archive
removing 'arcsightrest-1.0' (and everything under it)
running upload
Password:
Traceback (most recent call last):
  File "setup.py", line 20, in <module>
    'python-dateutil',
  File "/usr/lib64/python2.7/distutils/core.py", line 152, in setup
    dist.run_commands()
  File "/usr/lib64/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/usr/lib64/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "/usr/lib64/python2.7/distutils/command/upload.py", line 60, in run
    self.upload_file(command, pyversion, filename)
  File "/usr/lib64/python2.7/distutils/command/upload.py", line 70, in upload_file
    raise AssertionError("unsupported schema " + schema)
AssertionError: unsupported schema

Setuptools version:

setuptools 28.8.0 from /usr/lib/python2.7/site-packages (Python 2.7)

Body:
I was getting the same error. Then, I realize that the error should print the schema. But my error was like this

...
    raise AssertionError("unsupported schema " + schema)
AssertionError: unsupported schema

Note that schema is an empty string. So, in my point of view, the schema hasn't been found. I tried many things, but only changing the permission of .pypirc file works. I just did

$ sudo chmod 777 ~/.pypirc


来源: stackexchange

问:
Weekly Group by not including Sunday
I am grouping the data by week in the following queries

```<code> select id,sum(quantity) ,dateadd(wk, datediff(wk,0, [createddate]), 0) from table1 where
 createddate >= '2017-10-02' and createddate <= '2017-11-12'
 and [id] = 111
 group by [id] , dateadd(wk, datediff(wk,0, [createddate]), 0)
</code>```

Its grouping the data upto Sat i.e. Mon - Sat, not Mon to Sun. Can someone explain what I am missing.

I cannot change the database start day

Sample data is :

02/10/2017 9.00

03/10/2017 10.50

04/10/2017 10.00

08/10/2017 1.00

答:
The first day of the week is based on your language settings (default value is us_english is 7 (Sunday)). And SET DATEFIRST has no effect on DATEDIFF

You can try this query instead

```<code>set DATEFIRST 1

select id,sum(quantity) ,dateadd(wk, datediff(wk,0, [createddate]), 0) from table1 where
createddate >= '2017-10-02' and createddate <= '2017-11-12'
and [id] = 111
group by [id] , dateadd(dd,(-1)*(datepart(dw,[createddate])-1),[createddate])

set DATEFIRST 7
</code>```

Updated:

```<code>dateadd(dd,(-1)*(datepart(dw,[createddate])-1),[createddate])
</code>```

It will return the Monday of the week as your original query.

ContentLicense: CC BY-SA 3.0

Title: Weekly Group by not including Sunday

Body:
I am grouping the data by week in the following queries

 select id,sum(quantity) ,dateadd(wk, datediff(wk,0, [createddate]), 0) from table1 where
 createddate >= '2017-10-02' and createddate <= '2017-11-12'
 and [id] = 111
 group by [id] , dateadd(wk, datediff(wk,0, [createddate]), 0)

Its grouping the data upto Sat i.e. Mon - Sat, not Mon to Sun. Can someone explain what I am missing.

I cannot change the database start day

Sample data is :

02/10/2017 9.00

03/10/2017 10.50

04/10/2017 10.00

08/10/2017 1.00

Body:
The first day of the week is based on your language settings (default value is us_english is 7 (Sunday)). And SET DATEFIRST has no effect on DATEDIFF

You can try this query instead

set DATEFIRST 1

select id,sum(quantity) ,dateadd(wk, datediff(wk,0, [createddate]), 0) from table1 where
createddate >= '2017-10-02' and createddate <= '2017-11-12'
and [id] = 111
group by [id] , dateadd(dd,(-1)*(datepart(dw,[createddate])-1),[createddate])

set DATEFIRST 7

Updated:

dateadd(dd,(-1)*(datepart(dw,[createddate])-1),[createddate])

It will return the Monday of the week as your original query.


问:
Find the empty column to fill it with a form
I've done a Form in VBA and now i want to use this form to fill with data the first empty column from a sheet like in the screenshot.

I need a macro to find and fill the column with TextBox1,2...

This is how i thought:

```<code>Private Sub CommandButton1_Click()

   Dim emptyColumn As Long

   emptyColumn = ....

   Cells(emptyColumn, 1).Value = TextBox1.Value
   Cells(emptyColumn, 2).Value = TextBox2.Value
   ...
End Sub
</code>```

What formula i should use for the "emptyColumn =" ?

答:
there are several ways to find and empty column, I suggest to use a code found in this site:

http://www.excelhowto.com/macros/delete-blank-empty-columns-use-excel-vba/

```<code>Sub FindBlankColumns()
'Step1:  Declare your variables.
    Dim MyRange As Range
    Dim iCounter As Long
'Step 2:  Define the target Range.
    Set MyRange = ActiveSheet.UsedRange

'Step 3:  Start reverse looping through the range.
'You can modify this according to your needs.
    For iCounter = MyRange.Columns.Count To 1 Step -1

'Step 4: If entire column is empty then do some stuff.
       If Application.CountA(Columns(iCounter).EntireColumn) = 0 Then
          ' DoSomeStuff
       End If
    Next
End Sub
</code>```

Hope it helps

ContentLicense: CC BY-SA 4.0

Body:
I've done a Form in VBA and now i want to use this form to fill with data the first empty column from a sheet like in the screenshot.

I need a macro to find and fill the column with TextBox1,2...

This is how i thought:

Private Sub CommandButton1_Click()

   Dim emptyColumn As Long

   emptyColumn = ....

   Cells(emptyColumn, 1).Value = TextBox1.Value
   Cells(emptyColumn, 2).Value = TextBox2.Value
   ...
End Sub

What formula i should use for the "emptyColumn =" ?

Body:
there are several ways to find and empty column, I suggest to use a code found in this site:

http://www.excelhowto.com/macros/delete-blank-empty-columns-use-excel-vba/

Sub FindBlankColumns()
'Step1:  Declare your variables.
    Dim MyRange As Range
    Dim iCounter As Long
'Step 2:  Define the target Range.
    Set MyRange = ActiveSheet.UsedRange

'Step 3:  Start reverse looping through the range.
'You can modify this according to your needs.
    For iCounter = MyRange.Columns.Count To 1 Step -1

'Step 4: If entire column is empty then do some stuff.
       If Application.CountA(Columns(iCounter).EntireColumn) = 0 Then
          ' DoSomeStuff
       End If
    Next
End Sub

Hope it helps


问:
get list of quarters between two dates (SQL)
I would like to receive a list of quarters between given dates (startDate and EndDate parameter).

For example partial quarter dates:

```<code>StartDate : 2017-01-01
EndDate : 2017-06-15
Result : Q1 Q2
</code>```

another sample :

```<code>StartDate : 2017-01-01
EndDate : 2017-06-30
Result : Q2
</code>```

答:
You could try something like this, you would need to override the maximum recursion if you have a lot of quarters to list though:</p>

```<code>DECLARE @start_date DATE = '20170101';
DECLARE @end_date DATE = '20170615';
WITH x AS (
    SELECT
        YEAR(@start_date) AS [year],
        DATEPART(QUARTER, @start_date) AS [quarter]
    UNION ALL
    SELECT
        CASE
            WHEN [quarter] = 4 THEN [year] + 1
            ELSE [year]
        END AS [year],
        CASE
            WHEN [quarter] = 4 THEN 1
            ELSE [quarter] + 1
        END AS [quarter]
    FROM
        x
    WHERE
        [year] <= YEAR(@end_date)
        AND [quarter] < DATEPART(QUARTER, @end_date))
SELECT * FROM x;
</code>```

Body:
I would like to receive a list of quarters between given dates (startDate and EndDate parameter).

For example partial quarter dates:

StartDate : 2017-01-01
EndDate : 2017-06-15
Result : Q1 Q2

another sample :

StartDate : 2017-01-01
EndDate : 2017-06-30
Result : Q2

Body:
You could try something like this, you would need to override the maximum recursion if you have a lot of quarters to list though:

DECLARE @start_date DATE = '20170101';
DECLARE @end_date DATE = '20170615';
WITH x AS (
    SELECT
        YEAR(@start_date) AS [year],
        DATEPART(QUARTER, @start_date) AS [quarter]
    UNION ALL
    SELECT
        CASE
            WHEN [quarter] = 4 THEN [year] + 1
            ELSE [year]
        END AS [year],
        CASE
            WHEN [quarter] = 4 THEN 1
            ELSE [quarter] + 1
        END AS [quarter]
    FROM
        x
    WHERE
        [year] <= YEAR(@end_date)
        AND [quarter] < DATEPART(QUARTER, @end_date))
SELECT * FROM x;


问:
MVC Return view from another method
i am unable to end response in case of some condition

eg below (in Upload Action Method), if Logerror method invoked i just want to return view(browser) without further action. i.e return from Upload Action Method.

        Plase find modified question what i am trying to achive,
In case of error i want to return view by stopping all further opeartion

```<code>    public ActionResult Index()
    {
       return View();
    }

    public ActionResult Upload()
    {

       int i=1;
       DoSomethingFirst();
       //if LogError i dont want execute code below, rather it should end responce
       //should not reach here

       string s="This should not be executed in case of LogError()";

       return View("Index");

    }

    public void DoSomethingFirst()
    {

       try{
           DoSomethingSecond();
       }
       catch(exception ex)
       {
           LogError();
       }

    }

    public void DoSomethingSecond()
    {

       try{
           DoSomethingThird();
       }
       catch(exception ex)
       {
           LogError();
       }

    }

    public void DoSomethingThird()
    {

       try{
           DoSomethingother();

       }
       catch(exception ex)
       {
           LogError();
       }

    }

    private LogError()
    {
        Viewbag.Error="Error details";
        return View("Index");
    }
</code>```

答:
This doesn't return a result from the current method:

```<code>DoSomething();
</code>```

But this does:

```<code>return DoSomething();
</code>```

If you want to end execution of the current method, you need to do something which exits the method.  Basically, either return from the method or throw an exception.  Since DoSomething returns a result, presumably you want to return that result.  So simply add a return statement when invoking the method.

i tried wit RedirectToAction("Index");

Same issue.  You'd need to return the result:

```<code>return RedirectToAction("Index");
</code>```

Edit: Based on your edit to the question, the overall concept still remains.  Focusing on this part of your code here:

```<code>var s = DoSomethingFirst();
//if true i dont want execute code below, rather it should end responce
//should not reach here
</code>```

In order to exit the method, any method in C#, you need to either return or throw.  So the first question is... Which do you want to do here?  If you want to return a redirect, for example, then return a redirect:

```<code>return RedirectToAction("SomeAction");
</code>```

If you want to return the default view, return that:

```<code>return View();
</code>```

If you want to throw an exception:

```<code>throw SomeException("Some Message");
</code>```

The choice is yours.  You just need to define:

What you want this method to return or throw under this condition.

How will you know the condition.

For that second point, your code comment says:

```<code>//if true ...
</code>```

Does this mean DoSomethingFirst() returns a bool indicating success or failure?  Then that would be a simple if statement:

```<code>if (!DoSomethingFirst())
    return View();
</code>```

Another Edit: Based on your comment below:

Inside LogError mehod called by any child method in action method, i want to update view with error message and end the operation without further operation

How will your Update method know that something it invoked internally called LogError()?  What information does DoSomethingFirst() return to indicate this fact?  Currently it doesn't.  Your various DoSomething methods are all swallowing exceptions, which means they are internally handling exceptions so that consuming code doesn't know about them.

If you want consuming code to know about an exception, re-throw that exception.  For example:

```<code>public void DoSomethingFirst()
{
    try
    {
        DoSomethingSecond();
    }
    catch(exception ex)
    {
        LogError();
        throw; // <-- this will re-throw ex without modifying it
    }
}
</code>```

This returns information from DoSomethingFirst(), specifically the fact that an error occurred.  Your consuming code can then check for that error:

```<code>try
{
    DoSomethingFirst();
}
catch (Exception ex)
{
    // You should *probably* do something with ex too.  So far all of your "logging" has been ignoring the actual error.
    return View();
}
</code>```

Regardless of the structure you build, the basics don't change.  In order for consuming code to know something about the code it invokes, that invoked code has to expose that information.  In order to end execution of a method, you have to either return or throw.  Don't hide exceptions from consuming code if you want consuming code to respond to those exceptions.

Title: MVC Return view from another method

Body:
i am unable to end response in case of some condition

eg below (in Upload Action Method), if Logerror method invoked i just want to return view(browser) without further action. i.e return from Upload Action Method.

        Plase find modified question what i am trying to achive,
In case of error i want to return view by stopping all further opeartion

    public ActionResult Index()
    {
       return View();
    }

    public ActionResult Upload()
    {

       int i=1;
       DoSomethingFirst();
       //if LogError i dont want execute code below, rather it should end responce
       //should not reach here

       string s="This should not be executed in case of LogError()";

       return View("Index");

    }

    public void DoSomethingFirst()
    {

       try{
           DoSomethingSecond();
       }
       catch(exception ex)
       {
           LogError();
       }

    }

    public void DoSomethingSecond()
    {

       try{
           DoSomethingThird();
       }
       catch(exception ex)
       {
           LogError();
       }

    }

    public void DoSomethingThird()
    {

       try{
           DoSomethingother();

       }
       catch(exception ex)
       {
           LogError();
       }

    }

    private LogError()
    {
        Viewbag.Error="Error details";
        return View("Index");
    }

Body:
This doesn't return a result from the current method:

DoSomething();

But this does:

return DoSomething();

If you want to end execution of the current method, you need to do something which exits the method.  Basically, either return from the method or throw an exception.  Since DoSomething returns a result, presumably you want to return that result.  So simply add a return statement when invoking the method.

i tried wit RedirectToAction("Index");

Same issue.  You'd need to return the result:

return RedirectToAction("Index");

Edit: Based on your edit to the question, the overall concept still remains.  Focusing on this part of your code here:

var s = DoSomethingFirst();
//if true i dont want execute code below, rather it should end responce
//should not reach here

In order to exit the method, any method in C#, you need to either return or throw.  So the first question is... Which do you want to do here?  If you want to return a redirect, for example, then return a redirect:

return RedirectToAction("SomeAction");

If you want to return the default view, return that:

return View();

If you want to throw an exception:

throw SomeException("Some Message");

The choice is yours.  You just need to define:

What you want this method to return or throw under this condition.

How will you know the condition.

For that second point, your code comment says:

//if true ...

Does this mean DoSomethingFirst() returns a bool indicating success or failure?  Then that would be a simple if statement:

if (!DoSomethingFirst())
    return View();

Another Edit: Based on your comment below:

Inside LogError mehod called by any child method in action method, i want to update view with error message and end the operation without further operation

How will your Update method know that something it invoked internally called LogError()?  What information does DoSomethingFirst() return to indicate this fact?  Currently it doesn't.  Your various DoSomething methods are all swallowing exceptions, which means they are internally handling exceptions so that consuming code doesn't know about them.

If you want consuming code to know about an exception, re-throw that exception.  For example:

public void DoSomethingFirst()
{
    try
    {
        DoSomethingSecond();
    }
    catch(exception ex)
    {
        LogError();
        throw; // <-- this will re-throw ex without modifying it
    }
}

This returns information from DoSomethingFirst(), specifically the fact that an error occurred.  Your consuming code can then check for that error:

try
{
    DoSomethingFirst();
}
catch (Exception ex)
{
    // You should *probably* do something with ex too.  So far all of your "logging" has been ignoring the actual error.
    return View();
}

Regardless of the structure you build, the basics don't change.  In order for consuming code to know something about the code it invokes, that invoked code has to expose that information.  In order to end execution of a method, you have to either return or throw.  Don't hide exceptions from consuming code if you want consuming code to respond to those exceptions.


问:
how to simplify scala's function literal like this?
I'm new to scala and trying to write a function literal that check whether a given integer is odd or not.
my first attempt is:

val isOdd = (x:Int) => (x & 1) == 1

it works great, and,  since the parameter x only appears once within this function literal, I'm tempted to use the "_" notation to simplify it further, like this:

val isOdd = ((_:Int) & 1 ) == 1

however this time the compiler complains :

```warning: comparing a fresh object using `==' will always yield false
val isOdd = ((_:Int) & 1 ) == 1
```

what does this warning mean? why does the compiler recognize ((_ :Int) & 1) as fresh object rather than a bitwise operation that results in a value? is there any way to write this function literal using the "_" notation?

答:
Only slightly cheating:

```<code>val isOdd = (_: Int) % 2 == 1
</code>```

:-)

ContentLicense: CC BY-SA 2.5

Body:
I'm new to scala and trying to write a function literal that check whether a given integer is odd or not.
my first attempt is:

val isOdd = (x:Int) => (x & 1) == 1

it works great, and,  since the parameter x only appears once within this function literal, I'm tempted to use the "_" notation to simplify it further, like this:

val isOdd = ((_:Int) & 1 ) == 1

however this time the compiler complains :

warning: comparing a fresh object using `==' will always yield false
val isOdd = ((_:Int) & 1 ) == 1

what does this warning mean? why does the compiler recognize ((_ :Int) & 1) as fresh object rather than a bitwise operation that results in a value? is there any way to write this function literal using the "_" notation?

Body:
Only slightly cheating:

val isOdd = (_: Int) % 2 == 1

:-)


问:
Discord Bot in Python - Im trying to pick a random person from all the people with a specific role
So, i am trying to make a Discord Bot in Python. I'm just trying to make a bot that slaps a random person with the role "slapped". I've gotten everything to work but i cant figure out how to call for a random member with the role.
and if possible also limit it to who's currently online.
I'm decently good at python but new to discord bots. If you could help, id be grateful.
My code</p>

```<code>import time
import discord
import random
from discord.ext import commands

bot = commands.Bot(command_prefix=',', description='Enjoy Being Slapped
Randomly')
intervalM = random.randint(5,15)
#intervalS = integerM * 60

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)

@bot.command()
async def slapInt(integer):
    await bot.say("Time Between Slaps is now... " + str(integer) + "min")
    intervalM = integer

@bot.command()
"""manually slap someone"""
async def slapMan(intervalM, user):
    #debug - await bot.say("oof " + str(intervalM))
    intervalS = float(intervalM) * 60
    await bot.say("Slapping someone in " + str(intervalS) + " seconds")
    for i in range(0,int(intervalS)+1):
        if i == int(intervalS):
            await bot.say(" just got slapped!")
            intervalM = random.randint(5,15)
            slap(intervalM)
        else:
            #await bot.say(i)
            time.sleep(1)

def slap(intervalM):
    intervalS = float(intervalM) * 60
    print("Slapping someone in " + str(intervalS) + " seconds")
    for i in range(0,int(intervalS)+1):
        if i == int(intervalS):
            print(" just got slapped!")
            intervalM = random.randint(5,15)
            slap(intervalM)
        else:
            #await bot.say(i)
            time.sleep(1)

bot.run('~~~~~~~~~')
slap(intervalM)
</code>```

答:
You could try this:

```<code>server = discord.Server(id='your_server_id')

def slap(intervalM):
    intervalS = float(intervalM) * 60
    print("Slapping someone in " + str(intervalS) + " seconds")
    for i in range(0,int(intervalS)+1):
        if i == int(intervalS):
            roleMembers = []
            for member in server.members:
                for role in member.roles:
                    if role.name == 'your_role_name' and member.status == 'online':
                        roleMembers.append(member)
            memberCount = len(roleMembers)
            randomNumber = random.randint(0, (memberCount -1)
            await bot.say(roleMembers[randomNumber].name + ' just got slapped!')
            intervalM = random.randint(5,15)
            slap(intervalM)
        else:
            #await bot.say(i)
            time.sleep(1)
</code>```

(code is not tested)

Body:
So, i am trying to make a Discord Bot in Python. I'm just trying to make a bot that slaps a random person with the role "slapped". I've gotten everything to work but i cant figure out how to call for a random member with the role.
and if possible also limit it to who's currently online.
I'm decently good at python but new to discord bots. If you could help, id be grateful.
My code

import time
import discord
import random
from discord.ext import commands

bot = commands.Bot(command_prefix=',', description='Enjoy Being Slapped
Randomly')
intervalM = random.randint(5,15)
#intervalS = integerM * 60

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)

@bot.command()
async def slapInt(integer):
    await bot.say("Time Between Slaps is now... " + str(integer) + "min")
    intervalM = integer

@bot.command()
"""manually slap someone"""
async def slapMan(intervalM, user):
    #debug - await bot.say("oof " + str(intervalM))
    intervalS = float(intervalM) * 60
    await bot.say("Slapping someone in " + str(intervalS) + " seconds")
    for i in range(0,int(intervalS)+1):
        if i == int(intervalS):
            await bot.say(" just got slapped!")
            intervalM = random.randint(5,15)
            slap(intervalM)
        else:
            #await bot.say(i)
            time.sleep(1)

def slap(intervalM):
    intervalS = float(intervalM) * 60
    print("Slapping someone in " + str(intervalS) + " seconds")
    for i in range(0,int(intervalS)+1):
        if i == int(intervalS):
            print(" just got slapped!")
            intervalM = random.randint(5,15)
            slap(intervalM)
        else:
            #await bot.say(i)
            time.sleep(1)

bot.run('~~~~~~~~~')
slap(intervalM)

Body:
You could try this:

server = discord.Server(id='your_server_id')

def slap(intervalM):
    intervalS = float(intervalM) * 60
    print("Slapping someone in " + str(intervalS) + " seconds")
    for i in range(0,int(intervalS)+1):
        if i == int(intervalS):
            roleMembers = []
            for member in server.members:
                for role in member.roles:
                    if role.name == 'your_role_name' and member.status == 'online':
                        roleMembers.append(member)
            memberCount = len(roleMembers)
            randomNumber = random.randint(0, (memberCount -1)
            await bot.say(roleMembers[randomNumber].name + ' just got slapped!')
            intervalM = random.randint(5,15)
            slap(intervalM)
        else:
            #await bot.say(i)
            time.sleep(1)

(code is not tested)


问:
Using Lucid for Simple Example
Given:

```<code>import Lucid
import Lucid.Base

mainPage :: Html ()
mainPage = div_ (p_ "hello")
</code>```

I get the following compile-time error:

```<code>/Users/kevinmeredith/Workspace/my-project/src/Lib.hs:9:18: error:
    • Couldn't match type ‘HtmlT Data.Functor.Identity.Identity ()’
                     with ‘[Char]’
        arising from a functional dependency between:
          constraint ‘Term [Char] (HtmlT Data.Functor.Identity.Identity ())’
            arising from a use of ‘p_’
          instance ‘Term (HtmlT m a) (HtmlT m a)’ at <no location info>
    • In the first argument of ‘div_’, namely ‘(p_ "hello")’
      In the expression: div_ (p_ "hello")
      In an equation for ‘mainPage’: mainPage = div_ (p_ "hello")
</code>```

How can I fix this compile-time error please?

答:
As is written in the documentation:

Intro

(..)

For GHCi:

```<code>:set -XOverloadedStrings -XExtendedDefaultRules@
import Lucid
</code>```

In a module: {-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-}

(..)

So you need to turn on the OverloadedStrings and ExtendedDefaultRules extensions.

You can do this by compiling with:

```<code>ghc <b>-XOverloadedStrings -XExtendedDefaultRules</b> file.hs</code>```

But perhaps more convenient is to turn the extensions on in the header of the file:

```<code><b>{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}</b>

import Lucid
import Lucid.Base

mainPage :: Html ()
mainPage = div_ (p_ "hello")</code>```

Like the compiler says in the error message, p_ and div_ do not expect Strings, but a HtmlT Data.Functor.Identity.Identity () type (some sort of string). This type is however a member of the IsString typeclass, so it can be seen as "string-like" types, and has an implementation [source code]:

```<code>instance (Monad m,a ~ ()) => IsString (HtmlT m a) where
  fromString = toHtml
</code>```

The reason this happens is because you can add HTML characters, in which case (p_ "<foo>") would look like:
<foo>
. But this is quite unsafe. By first processing it through toHtml, the result will be
<foo>
.

Title: Using Lucid for Simple Example

Body:
Given:

import Lucid
import Lucid.Base

mainPage :: Html ()
mainPage = div_ (p_ "hello")

I get the following compile-time error:

/Users/kevinmeredith/Workspace/my-project/src/Lib.hs:9:18: error:
    • Couldn't match type ‘HtmlT Data.Functor.Identity.Identity ()’
                     with ‘[Char]’
        arising from a functional dependency between:
          constraint ‘Term [Char] (HtmlT Data.Functor.Identity.Identity ())’
            arising from a use of ‘p_’
          instance ‘Term (HtmlT m a) (HtmlT m a)’ at <no location info>
    • In the first argument of ‘div_’, namely ‘(p_ "hello")’
      In the expression: div_ (p_ "hello")
      In an equation for ‘mainPage’: mainPage = div_ (p_ "hello")

How can I fix this compile-time error please?

Body:
As is written in the documentation:

Intro

(..)

For GHCi:

:set -XOverloadedStrings -XExtendedDefaultRules@
import Lucid

In a module: {-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-}

(..)

So you need to turn on the OverloadedStrings and ExtendedDefaultRules extensions.

You can do this by compiling with:

ghc -XOverloadedStrings -XExtendedDefaultRules file.hs

But perhaps more convenient is to turn the extensions on in the header of the file:

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}

import Lucid
import Lucid.Base

mainPage :: Html ()
mainPage = div_ (p_ "hello")

Like the compiler says in the error message, p_ and div_ do not expect Strings, but a HtmlT Data.Functor.Identity.Identity () type (some sort of string). This type is however a member of the IsString typeclass, so it can be seen as "string-like" types, and has an implementation [source code]:

instance (Monad m,a ~ ()) => IsString (HtmlT m a) where
  fromString = toHtml

The reason this happens is because you can add HTML characters, in which case (p_ "<foo>") would look like: <p><foo></p>. But this is quite unsafe. By first processing it through toHtml, the result will be <p>&lt;foo&gt;</p>.


问:
Finding Source of a UNIX Signal from Coredump
This has been long pending question in my mind. I see that GDB tells us the signal causing process termination.

How do I find the source of the signal from a core?

In two different occasions my two application received SIGEMT and SIGUSR1. I know that there are other applications in production which can send these signals.

Also, I know that the sender information can be seen within running program and the data would be present in  siginfo_t structure. But I don't have that luxury and in fact we don't have handler for this signal at all.

答:
You can also read this information from core dump by eu-readelf:

```<code>$ eu-readelf --notes coredump | head

Note segment of 3180 bytes at offset 0x4a0:
  Owner          Data size  Type
  CORE                 336  PRSTATUS
    info.si_signo: 6, info.si_code: 0, info.si_errno: 0, cursig: 6
    sigpend: <>
    sighold: <>
    pid: 28046, ppid: 3774, pgrp: 28046, sid: 3774
    utime: 0.000000, stime: 0.002895, cutime: 0.000000, cstime: 0.000000
    orig_rax: 35, fpvalid: 1
</code>```

Note info.si_signo: 6, which means that process was killed by SIGABRT.

Body:
You can also read this information from core dump by eu-readelf:

$ eu-readelf --notes coredump | head

Note segment of 3180 bytes at offset 0x4a0:
  Owner          Data size  Type
  CORE                 336  PRSTATUS
    info.si_signo: 6, info.si_code: 0, info.si_errno: 0, cursig: 6
    sigpend: <>
    sighold: <>
    pid: 28046, ppid: 3774, pgrp: 28046, sid: 3774
    utime: 0.000000, stime: 0.002895, cutime: 0.000000, cstime: 0.000000
    orig_rax: 35, fpvalid: 1

Note info.si_signo: 6, which means that process was killed by SIGABRT.


问:
ng-repeat doesn't expose array element (angularJS 1.6.6)
having a problem where ng-repeat doesn't render the array element usable variable.

eg :

```<code><li ng-repeat="i in [0,1,2,3,4]">{{i}}</li>
</code>```

should render something like:

```<code><li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</code>```

But I get:

```<code><li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</code>```

Body:
having a problem where ng-repeat doesn't render the array element usable variable.

eg :

{{i}}

should render something like:

0

1

2

3

4

But I get:

Body: <li ng-app ng-repeat="i in [0,1,2,3,4]">{{i}}</li>


问:
Page object covers fixed navigationbar
Im creating a simple website where I want the navigation bar to always stay on the top of the page and I want it to always be visible.

I achieved this, but when scrolling past some elements, the navigationbar is covered up by said elements.

I have googled around for a bit, and everyone says to add "z-index: 1", but the navbar (which I did not make myself) uses z-index: 2 and -1, and if I change it to 1, the navbar just gets wonky. I'm probably just changing the z-index of the wrong object or something stupid, but I feel like I have tried everything here..

I may or may not have copy-pasted a lot :P

HTML:

```<code><a relatively normal list> things in the list</a relatively normal list>
</code>```

CSS:

```<code>#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a {
margin: 0;
padding: 0;
border: 0;
list-style: none;
line-height: 1;
display: block;
position: relative;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#cssmenu:after,
#cssmenu > ul:after {
  content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#cssmenu {
width: 100%;
border-bottom: 3px solid #a24fef;
font-family: Raleway, sans-serif;
line-height: 1;
}
#cssmenu ul {
background: rgb(220, 220, 0);
background: rgba(220, 220, 0, 0);
}
#cssmenu > ul > li {
float: left;
}
#cssmenu.align-center > ul {
font-size: 0;
text-align: center;
}
#cssmenu.align-center > ul > li {
  display: inline-block;
  float: none;
}
#cssmenu.align-right > ul > li {
  float: right;
}
#cssmenu.align-right > ul > li > a {
  margin-right: 0;
  margin-left: -4px;
}
#cssmenu > ul > li > a {
  z-index: 2;
  padding: 18px 25px 12px 25px;
  font-size: 25px;
  font-weight: 400;
  text-decoration: none;
  color: #444444;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -ms-transition: all 1s ease;
      -o-transition: all 1s ease;
  transition: all 1s ease;
  margin-right: -4px;
}
#cssmenu > ul > li.active > a,
#cssmenu > ul > li:hover > a,
#cssmenu > ul > li > a:hover {
  color: #ffffff;
}
#cssmenu > ul > li > a:after {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -1;
  width: 100%;
  height: 120%;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  content: "";
  -webkit-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
  -webkit-transform: perspective(5px) rotateX(2deg);
  -webkit-transform-origin: bottom;
  -moz-transform: perspective(5px) rotateX(2deg);
  -moz-transform-origin: bottom;
  transform: perspective(5px) rotateX(2deg);
  transform-origin: bottom;
}
#cssmenu > ul > li.active > a:after,
#cssmenu > ul > li:hover > a:after,
#cssmenu > ul > li > a:hover:after {
  background: #a24fef;
}
</code>```

EDIT:  Here is a jsfiddle with more code and it shows what happens. WARNING: THIS INCLUDES A GIVEAWAY WHICH PROMOTES STUFF. (couldn't figure out how to use an example giveaway so I used my friend's one.)

https://jsfiddle.net/vvqLLb1x/

答: add overflow: hidden; to your css, i dont know for sure if this will work considering your lack of code in your question.

Title: Page object covers fixed navigationbar

Body:
Im creating a simple website where I want the navigation bar to always stay on the top of the page and I want it to always be visible.

I achieved this, but when scrolling past some elements, the navigationbar is covered up by said elements.

I have googled around for a bit, and everyone says to add "z-index: 1", but the navbar (which I did not make myself) uses z-index: 2 and -1, and if I change it to 1, the navbar just gets wonky. I'm probably just changing the z-index of the wrong object or something stupid, but I feel like I have tried everything here..

I may or may not have copy-pasted a lot :P

HTML:

 things in the list

CSS:

#cssmenu,
#cssmenu ul,
#cssmenu ul li,
#cssmenu ul li a {
margin: 0;
padding: 0;
border: 0;
list-style: none;
line-height: 1;
display: block;
position: relative;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
#cssmenu:after,
#cssmenu > ul:after {
  content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
#cssmenu {
width: 100%;
border-bottom: 3px solid #a24fef;
font-family: Raleway, sans-serif;
line-height: 1;
}
#cssmenu ul {
background: rgb(220, 220, 0);
background: rgba(220, 220, 0, 0);
}
#cssmenu > ul > li {
float: left;
}
#cssmenu.align-center > ul {
font-size: 0;
text-align: center;
}
#cssmenu.align-center > ul > li {
  display: inline-block;
  float: none;
}
#cssmenu.align-right > ul > li {
  float: right;
}
#cssmenu.align-right > ul > li > a {
  margin-right: 0;
  margin-left: -4px;
}
#cssmenu > ul > li > a {
  z-index: 2;
  padding: 18px 25px 12px 25px;
  font-size: 25px;
  font-weight: 400;
  text-decoration: none;
  color: #444444;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -ms-transition: all 1s ease;
      -o-transition: all 1s ease;
  transition: all 1s ease;
  margin-right: -4px;
}
#cssmenu > ul > li.active > a,
#cssmenu > ul > li:hover > a,
#cssmenu > ul > li > a:hover {
  color: #ffffff;
}
#cssmenu > ul > li > a:after {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -1;
  width: 100%;
  height: 120%;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  content: "";
  -webkit-transition: all 1s ease;
  -o-transition: all 1s ease;
  transition: all 1s ease;
  -webkit-transform: perspective(5px) rotateX(2deg);
  -webkit-transform-origin: bottom;
  -moz-transform: perspective(5px) rotateX(2deg);
  -moz-transform-origin: bottom;
  transform: perspective(5px) rotateX(2deg);
  transform-origin: bottom;
}
#cssmenu > ul > li.active > a:after,
#cssmenu > ul > li:hover > a:after,
#cssmenu > ul > li > a:hover:after {
  background: #a24fef;
}

EDIT:  Here is a jsfiddle with more code and it shows what happens. WARNING: THIS INCLUDES A GIVEAWAY WHICH PROMOTES STUFF. (couldn't figure out how to use an example giveaway so I used my friend's one.)

https://jsfiddle.net/vvqLLb1x/


问:
A simple way to substitute IDs for strings in a view
I am storing service names outside of services table. So services table contains everything I need in a tableView except that I'd like to show service names stored in service_types in the view.

As far as I understood, there is no way to make QSqlTableModel work with even a simplest join.

I know I'm supposed to inherit QAbstractTableModel, but I have no idea how to implement anything there. A wizard in Qt Creator made a .h/.cpp pair for me, but I can't find any examples on the internet to get an idea what am I supposed to be implementing.

So, I'm asking if there is any clever way to get all service types strings (there are just 200) into a QMap beforehand, and just make tableView display them instead of IDs.

答:
As I said in my comment, you can subclass your QSqlTableModel model and in the data() function substitute original data with one you query from another table. E.g.:

```<code>QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
  if (index.column() == 0 /*first column*/ && role == Qt::DisplayRole)
  {
    // Query data from another table (service_types) and as you get the right
    // type for the given row, return it.
    return type_I_got_from_service_type_table;
  }
  return QSqlTableModel::data(index, role);
}
</code>```

Body:
As I said in my comment, you can subclass your QSqlTableModel model and in the data() function substitute original data with one you query from another table. E.g.:

QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
  if (index.column() == 0 /*first column*/ && role == Qt::DisplayRole)
  {
    // Query data from another table (service_types) and as you get the right
    // type for the given row, return it.
    return type_I_got_from_service_type_table;
  }
  return QSqlTableModel::data(index, role);
}


问:
Can you set Gitlab CI stage so other stages don't wait for it to finish?
Let's say I have these stages defined in .gitlab-ci.yml:

```<code>stages:
    - build
    - analysis
    - tests
    - deploy
    - post-deploy
</code>```

Since analysis takes a lot of time and I don't really care about the result (I also have allow_failure: true set) - is it possible to somehow define to start analysis and then immediately launch the next stage tests?

I didn't find any reference to similar topic on official docs.

EDIT:

The main idea is that all other stages can be run as if the analysis didn't even exist. If i put analysis to same stage as tests, then both analysis and tests will run at the same time, however deploy won't be launched until both of them finish. This is no good. I want tests to finish and then launch deploy, after deploy finishes I want to launch post-deploy. I really don't care about analysis result, I simply want to trigger it and continue with the deployment.

答:
Stages are per definition serial. One stage will be executed after another.

If you want to process analysis and tests parallelly, you have to define them on the same stage.

```<code>stages:
 - build
 - processing
 - deploy
 - ...

analysis:
 stage: processing
 ...

tests:
 stage: processing
 ...
</code>```

https://docs.gitlab.com/ce/ci/yaml/README.html#stage

Body:
Let's say I have these stages defined in .gitlab-ci.yml:

stages:
    - build
    - analysis
    - tests
    - deploy
    - post-deploy

Since analysis takes a lot of time and I don't really care about the result (I also have allow_failure: true set) - is it possible to somehow define to start analysis and then immediately launch the next stage tests?

I didn't find any reference to similar topic on official docs.

EDIT:

The main idea is that all other stages can be run as if the analysis didn't even exist. If i put analysis to same stage as tests, then both analysis and tests will run at the same time, however deploy won't be launched until both of them finish. This is no good. I want tests to finish and then launch deploy, after deploy finishes I want to launch post-deploy. I really don't care about analysis result, I simply want to trigger it and continue with the deployment.

Body:
Stages are per definition serial. One stage will be executed after another.

If you want to process analysis and tests parallelly, you have to define them on the same stage.

stages:
 - build
 - processing
 - deploy
 - ...

analysis:
 stage: processing
 ...

tests:
 stage: processing
 ...

https://docs.gitlab.com/ce/ci/yaml/README.html#stage


问:
WebRTC in Chrome (JsSIP) and SDP directive "UDP/TLS/RTP/SAVPF"
I use the library JsSIP to make SIP calls over WebRTC plataform in Google Chrome web browser. I have to change the SDP directive "UDP/TLS/RTP/SAVPF" in SIP request to "UDP/RTP/AVPF" in JsSIP.js file because the Asterisk server reject calls no encrypted in TLS context and i need the calls no encrypted. But even with the change, the browser continues to send the "UDP/TLS/RTP/SAVPF" in SIP request. Anyone can help me? The WebRTC implementation or Chrome intercepts the SIP request and change to "UDP/TLS/RTP/SAVPF"? Or in some way, this directive is in cache request and needs a clean up? (I already tried to clean the Chrome cache). Or have another explanation to that?</p>

答:
You should be able to capture SDP under 'sdp' event thrown by jssip and over write with new sdp</p>

```<code>'sdp': function(evt){
    evt.sdp = your changed sdp
 }
</code>```

Body:
You should be able to capture SDP under 'sdp' event thrown by jssip and over write with new sdp

'sdp': function(evt){
    evt.sdp = your changed sdp
 }


问:
Why we overriding the bootstrap in bower.json
I am having some issue with including bootstrap. Why we are trying to override the bower.json with bootstrap? Here is the code

```<code>"overrides": {
    "bootstrap": {
      "main": [
        "dist/js/bootstrap.js",
        "dist/css/bootstrap.css",
        "less/bootstrap.less"
      ]
    }
  }
</code>```

What is the use for the override? Is this correct way?

Other way I found is including in stylesheet like @import "../../bower_components/file". but it is not a good practice.

Is there any other way to include?

答:
You can use the directory property of the config to change the path where everything gets saves:
https://bower.io/docs/config/

.bowerrc

```<code>{
    "directory": "assets/vendors",
}
</code>```

This way you can include bootstrap in you CSS like the following

```<code>@import '../vendor/bootstrap/dist/bootstrap.css'
</code>```

Assuming you file structure like similar to this one:

```<code>/assets/css/styles.css
/assets/js/scripts.js
/assets/vendors/bootstrap
</code>```

Body:
I am having some issue with including bootstrap. Why we are trying to override the bower.json with bootstrap? Here is the code

"overrides": {
    "bootstrap": {
      "main": [
        "dist/js/bootstrap.js",
        "dist/css/bootstrap.css",
        "less/bootstrap.less"
      ]
    }
  }

What is the use for the override? Is this correct way?

Other way I found is including in stylesheet like @import "../../bower_components/file". but it is not a good practice.

Is there any other way to include?

Body:
You can use the directory property of the config to change the path where everything gets saves:
https://bower.io/docs/config/

.bowerrc

{
    "directory": "assets/vendors",
}

This way you can include bootstrap in you CSS like the following

@import '../vendor/bootstrap/dist/bootstrap.css'

Assuming you file structure like similar to this one:

/assets/css/styles.css
/assets/js/scripts.js
/assets/vendors/bootstrap


问:
BUG IN DEVC++ (Comparing String and Character)
I'm trying to make a program that will count how many letters occur in my string. I want only to count letters A and B on a give string.

```<code>char string[10];
int countA, countB;
gets(string);

for(int i = 0; i <strlen(string); i++){
    if(string[i] == 'A')
    countA++;
    else if(string[i] == 'B')
    countB++;
}

printf("%d %d", countA, countB);
return 0;
</code>```

for example my  input is: ABABA
the output should be 3 2 however it print a different answer for countB. I'm using devc++. Is this  a bug?

答:
Reason for getting different result:

Earlier when you didn't initialize the variable countA and countB they contained indeterminate value. Using them in your code introduces undefined behavior.

Two points:

Intialize the variables to zero. countA and countB.

And don't use gets rather use fgets.

I am giving you an example:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(){
    char string[10];
    unsigned int countA=0, countB=0;
    if( fgets(string,10,stdin) == NULL){
        fprintf(stderr, "%s\n", "Error in string input");
        exit(1);
    }
    size_t len = strlen(string);
    if( len > 0 )
        string[len-1]='\0';
    for(size_t i = 0; i <strlen(string); i++){
        if(string[i] == 'A'){
            countA++;
        }
        else if(string[i] == 'B'){
            countB++;
        }

    }

    printf("%u %u", countA, countB);
    return EXIT_SUCCESS;
}
</code>```

Note:

Also you are asked whether it is gloabal variable. If it was then probably you wouldn't have to worry about initialization. They would be initialized with 0.

gets() goes on reading characters until it encounters \n or EOF. And on doing this it is not constrained in anyway with the buffer size, leaving a chance of buffer overflow.

Body:
I'm trying to make a program that will count how many letters occur in my string. I want only to count letters A and B on a give string.

char string[10];
int countA, countB;
gets(string);

for(int i = 0; i <strlen(string); i++){
    if(string[i] == 'A')
    countA++;
    else if(string[i] == 'B')
    countB++;
}

printf("%d %d", countA, countB);
return 0;

for example my  input is: ABABA
the output should be 3 2 however it print a different answer for countB. I'm using devc++. Is this  a bug?

Body:
Reason for getting different result:

Earlier when you didn't initialize the variable countA and countB they contained indeterminate value. Using them in your code introduces undefined behavior.

Two points:

Intialize the variables to zero. countA and countB.

And don't use gets rather use fgets.

I am giving you an example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(){
    char string[10];
    unsigned int countA=0, countB=0;
    if( fgets(string,10,stdin) == NULL){
        fprintf(stderr, "%s\n", "Error in string input");
        exit(1);
    }
    size_t len = strlen(string);
    if( len > 0 )
        string[len-1]='\0';
    for(size_t i = 0; i <strlen(string); i++){
        if(string[i] == 'A'){
            countA++;
        }
        else if(string[i] == 'B'){
            countB++;
        }

    }

    printf("%u %u", countA, countB);
    return EXIT_SUCCESS;
}

Note:

Also you are asked whether it is gloabal variable. If it was then probably you wouldn't have to worry about initialization. They would be initialized with 0.

gets() goes on reading characters until it encounters \n or EOF. And on doing this it is not constrained in anyway with the buffer size, leaving a chance of buffer overflow.


问:
how to set pandas dataframe multiindex in constructor
After preparing the data

```<code>import pandas as pd

_indexcols = ['key1', 'key2']
_columns = ['key1', 'key2', 'data1', 'data2']

_data = []
_data.append(['k11', 'k12', 'd11', 'd12'])
_data.append(['k21', 'k22', 'd21', 'd22'])
</code>```

I can do this

```<code>_df = pd.DataFrame(_data, columns=_columns)
_df = _df.set_index(keys=_indexcols)
</code>```

But not this.

```<code>_df = pd.DataFrame(_data, columns=_columns, index=_indexcols)
</code>```

Why?

How do I define the indexcols so that they are accepted immediately?

答:
The dataframe constructor creates index first and assigns the data second. So you can't access the data earlier to assign it to index.

But if you are looking for the approach using only constructor and dont want set_index you can make use of numpy and pd.MultiIndex

```<code>temp = np.array(_data)
idx = pd.MultiIndex.from_arrays(temp[:,:2])
_df = pd.DataFrame(temp[:,2:],columns=_columns[2:],index =idx)
</code>```

```
        data1 data2
k11 k21   d11   d12
k12 k22   d21   d22
```

Body:
After preparing the data

import pandas as pd

_indexcols = ['key1', 'key2']
_columns = ['key1', 'key2', 'data1', 'data2']

_data = []
_data.append(['k11', 'k12', 'd11', 'd12'])
_data.append(['k21', 'k22', 'd21', 'd22'])

I can do this

_df = pd.DataFrame(_data, columns=_columns)
_df = _df.set_index(keys=_indexcols)

But not this.

_df = pd.DataFrame(_data, columns=_columns, index=_indexcols)

Why?

How do I define the indexcols so that they are accepted immediately?

Body:
The dataframe constructor creates index first and assigns the data second. So you can't access the data earlier to assign it to index.

But if you are looking for the approach using only constructor and dont want set_index you can make use of numpy and pd.MultiIndex

temp = np.array(_data)
idx = pd.MultiIndex.from_arrays(temp[:,:2])
_df = pd.DataFrame(temp[:,2:],columns=_columns[2:],index =idx)

        data1 data2
k11 k21   d11   d12
k12 k22   d21   d22


问:
How can i map control to it's device?
amixer -c 0 controls:

```<code>...
numid=22,iface=MIXER,name='Capture Switch'

numid=24,iface=MIXER,name='Capture Switch',index=1

numid=21,iface=MIXER,name='Capture Volume'

numid=23,iface=MIXER,name='Capture Volume',index=1

...
</code>```

arecord -l:

```<code>card 0: PCH [HDA Intel PCH], device 0: ALC662 rev3 Analog [ALC662 rev3 Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 2: ALC662 rev3 Alt Analog [ALC662 rev3 Alt Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
</code>```

I have two controls with the same names. I know, that one is handle stream Card=0,device=0, second - Card=0,device=2. But how can i get from my program which control response for specific device?  Contol with numid = 21 or control with numid = 23 handle device 2?

I can find some useful info about it in /proc/asound/cord0/codec#0. But I need to detect in from my code.

答:
Controls of interface MIXER are not directly associated with any device.

The only way to find out more would be to use some hardware-dependent mechanism. However, in the case of HDA, reading codec#x is not very useful because the exact algorithm the kernel uses to map widgets to controls is not guaranteed.

Title: How can i map control to it's device?

Body:
amixer -c 0 controls:

...
numid=22,iface=MIXER,name='Capture Switch'

numid=24,iface=MIXER,name='Capture Switch',index=1

numid=21,iface=MIXER,name='Capture Volume'

numid=23,iface=MIXER,name='Capture Volume',index=1

...

arecord -l:

card 0: PCH [HDA Intel PCH], device 0: ALC662 rev3 Analog [ALC662 rev3 Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: PCH [HDA Intel PCH], device 2: ALC662 rev3 Alt Analog [ALC662 rev3 Alt Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

I have two controls with the same names. I know, that one is handle stream Card=0,device=0, second - Card=0,device=2. But how can i get from my program which control response for specific device?  Contol with numid = 21 or control with numid = 23 handle device 2?

I can find some useful info about it in /proc/asound/cord0/codec#0. But I need to detect in from my code.


问:
How to get last records with conditions from SQLite?
I need to get last records from SQLite but with some conditions.. Let's say I have this table

```<code>id         course
1           math
2           english
3           math
4           english
5           chemistry
</code>```

and I need to return records of ids 3,4,5 because for math the id: 3 is the last(newest) record, for english the id: 4 is the last(newest) record and so on..

I don't know how to group them and then pick the newest record and so on..

答:
SQLite has a rowid that you can query over it like this:

```<code>select *
from Table1 t
where exists (
  select 1
  from Table1 ti
  where t.course = ti.course
  group by ti.course
  having t.rowid = max(ti.rowid);    -- filtering rows that are newest rows in table
  );
</code>```

SQLite Fiddle Demo

Sample Data:

```<code>| id |    course |      ... hidden rowid |
|----+-----------|      ... -------------|
|  1 |      math |      ...            1 |
|  2 |   english |      ...            2 |
|  3 |      math |      ...            3 |
|  4 |   english |      ...            4 |
|  5 | chemistry |      ...            5 |
|  8 |      test |      ...            6 |
|  7 |      test |      ...            7 |
</code>```

Result:

```<code>| id |    course |      ... hidden rowid |
|----+-----------|      ... -------------|
|  3 |      math |      ...            3 |
|  4 |   english |      ...            4 |
|  5 | chemistry |      ...            5 |
|  7 |      test |      ...            7 |
</code>```

Body:
I need to get last records from SQLite but with some conditions.. Let's say I have this table

id         course
1           math
2           english
3           math
4           english
5           chemistry

and I need to return records of ids 3,4,5 because for math the id: 3 is the last(newest) record, for english the id: 4 is the last(newest) record and so on..

I don't know how to group them and then pick the newest record and so on..

Body:
SQLite has a rowid that you can query over it like this:

select *
from Table1 t
where exists (
  select 1
  from Table1 ti
  where t.course = ti.course
  group by ti.course
  having t.rowid = max(ti.rowid);    -- filtering rows that are newest rows in table
  );

SQLite Fiddle Demo

Sample Data:

| id |    course |      ... hidden rowid |
|----+-----------|      ... -------------|
|  1 |      math |      ...            1 |
|  2 |   english |      ...            2 |
|  3 |      math |      ...            3 |
|  4 |   english |      ...            4 |
|  5 | chemistry |      ...            5 |
|  8 |      test |      ...            6 |
|  7 |      test |      ...            7 |

Result:

| id |    course |      ... hidden rowid |
|----+-----------|      ... -------------|
|  3 |      math |      ...            3 |
|  4 |   english |      ...            4 |
|  5 | chemistry |      ...            5 |
|  7 |      test |      ...            7 |


问:
problem in an update form
when i was trying to work on update form I found that there is something wrong in it . the form works well but the new data don't insert to the database but show in the URL

code :

```<code>include"connection.php";

$gid = intval($_GET['id']);
$id = $_POST['product_id'];
$content = $_POST['content'];
$link = $_POST['link'];

if(isset($_POST['saveedit']) && $_POST['saveedit']=='products'){
    $update = mysql_query(" UPDATE products SET
                            content='$content',
                            link='$link'
                            WHERE product_id='$id' ") or die (mysql_error());

    if(isset($update)){
        echo "<b>update is done</b>";
    }
}

$query = mysql_query(" SELECT * FROM products WHERE product_id='".$gid."' ") or die (mysql_error());
$re = mysql_fetch_assoc($query);

if($_REQUEST['do'] == 'edit'){

echo"
<form action='".$_SERVER['PHP_SELF']."' metho='post'>
    <table>
    <tr>
    <td>Link : </td>
    <td><input type='text' name='link' value='".$re['link']."'/></td
    </tr>
    <tr>
    <td>Content :</td>
    <td><textarea name='content'>".$re['content']."</textarea></td>
    </tr>
    <tr>
    <td colspan='2'>
    <input type='submit' name='saveedit' value='save'/>
    <input type='hidden' name='id' value='".$gid."'/>
    <input type='hidden' name='productedit' value='products'/>
    </td>
    </tr>
    </table>
</form>
";
}

$data = mysql_query("SELECT * FROM products ORDER BY product_id");

echo"
    <table width='500' border='1'>
    <tr>
        <td>Link</td>
        <td>Content</td>
        <td>Option</td>
    </tr>
";

while($row = mysql_fetch_assoc($data)){
    echo"
        <tr>
        <td>".$row['link']."</td>
        <td>".$row['content']."</td>
        <td>
            <a href='edit.php?do=edit&id=".$row['product_id']."'> Edit </a>
        </td>
        </tr>
    ";
}
echo"</table>";
</code>```

?>

答:
what i see is that in the form you have ,
inputname='saveedit' with  value='save'

and you compare it to something else

```<code>isset($_POST['saveedit']) && $_POST['saveedit']=='products'
</code>```

its sould be

```<code>isset($_POST['saveedit']) && $_POST['productedit']=='products'
</code>```

Title: problem in an update form

Body:
when i was trying to work on update form I found that there is something wrong in it . the form works well but the new data don't insert to the database but show in the URL

code :

include"connection.php";

$gid = intval($_GET['id']);
$id = $_POST['product_id'];
$content = $_POST['content'];
$link = $_POST['link'];

if(isset($_POST['saveedit']) && $_POST['saveedit']=='products'){
    $update = mysql_query(" UPDATE products SET
                            content='$content',
                            link='$link'
                            WHERE product_id='$id' ") or die (mysql_error());

    if(isset($update)){
        echo "update is done";
    }
}

$query = mysql_query(" SELECT * FROM products WHERE product_id='".$gid."' ") or die (mysql_error());
$re = mysql_fetch_assoc($query);

if($_REQUEST['do'] == 'edit'){

echo"
<form action='".$_SERVER['PHP_SELF']."' metho='post'>

    Link :
    <input type='text' name='link' value='".$re['link']."'/></td

    Content :
    <textarea name='content'>".$re['content']."</textarea>

    <input type='submit' name='saveedit' value='save'/>
    <input type='hidden' name='id' value='".$gid."'/>
    <input type='hidden' name='productedit' value='products'/>

</form>
";
}

$data = mysql_query("SELECT * FROM products ORDER BY product_id");

echo"

        Link
        Content
        Option

";

while($row = mysql_fetch_assoc($data)){
    echo"

        ".$row['link']."
        ".$row['content']."

             Edit

    ";
}
echo"
";

?>

Body:
what i see is that in the form you have ,
inputname='saveedit' with  value='save'

and you compare it to something else

isset($_POST['saveedit']) && $_POST['saveedit']=='products'

its sould be

isset($_POST['saveedit']) && $_POST['productedit']=='products'


问:
Android toolbar not getting its background transparent
I have a layout with a toolbar and a navigation drawer:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/transparent"
          android:fitsSystemWindows="true"
          android:orientation="vertical"
          tools:context="com.my.app.GUI.MainActivity">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/mainBackground"
    android:contentInsetEnd="0dp"
    android:contentInsetLeft="0dp"
    android:contentInsetRight="0dp"
    android:contentInsetStart="0dp"
    app:contentInsetEnd="0dp"
    app:contentInsetLeft="0dp"
    app:contentInsetRight="0dp"
    app:contentInsetStart="0dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent">

        <FrameLayout
            android:id="@+id/frameLayoutTitleBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:padding="10dp">

            <ImageView
                android:id="@+id/imageViewHamburger"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/icon_hamburger_menu"/>

            <TextView
                android:id="@+id/textViewToolbarTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/transparent"
                android:gravity="center"
                android:text="TITLE"
                android:textColor="@android:color/white"
                android:textSize="@dimen/very_large_font_size"/>

        </FrameLayout>

        <ImageView
            android:id="@+id/imageViewToolbarRightSide"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/frameLayoutTitleBar"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@+id/frameLayoutTitleBar"
            android:layout_marginRight="10dp"
            android:visibility="invisible"
            app:srcCompat="@drawable/icon_hamburger_menu"/>

        <View
            android:id="@+id/viewTitleUnderLine"
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:layout_alignParentBottom="true"
            android:background="@color/secondaryBackground"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
</FrameLayout>
</LinearLayout>
</code>```

This all layout is later then added as an include to another layout which includes the layout for the navigation drawer.

In my code I'm setting the images, strings and also the toolbar's background.
The background is set like this:

```<code>public static void setTitleBarBackgroundColor(int color)
{
    if(toolBar != null)
    {
        toolBar.setBackgroundColor(color);
    }
}
...
MyToolBarClass.setTitleBarBackgroundColor(getResources().getColor(android.R.color.transparent));
</code>```

When invoking this, the color does change but instead of being transparent, the toolbar (or something else) is changing to some color similar to gray and I can also see 3 faded icons of 2 people like the old MSN messenger icon, a chat icon and a wheel settings icon, which probably came with the toolbar. If I'm setting the color of the toolbar to something else then there's no problem and it's being set to that color.

Why won't the toolbar background change to transparent so I can see what's below it?

答: Try to Remove the background of a main linear layout or white color.</p>

Body:
I have a layout with a toolbar and a navigation drawer:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/transparent"
          android:fitsSystemWindows="true"
          android:orientation="vertical"
          tools:context="com.my.app.GUI.MainActivity">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/mainBackground"
    android:contentInsetEnd="0dp"
    android:contentInsetLeft="0dp"
    android:contentInsetRight="0dp"
    android:contentInsetStart="0dp"
    app:contentInsetEnd="0dp"
    app:contentInsetLeft="0dp"
    app:contentInsetRight="0dp"
    app:contentInsetStart="0dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent">

        <FrameLayout
            android:id="@+id/frameLayoutTitleBar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:padding="10dp">

            <ImageView
                android:id="@+id/imageViewHamburger"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/icon_hamburger_menu"/>

            <TextView
                android:id="@+id/textViewToolbarTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/transparent"
                android:gravity="center"
                android:text="TITLE"
                android:textColor="@android:color/white"
                android:textSize="@dimen/very_large_font_size"/>

        </FrameLayout>

        <ImageView
            android:id="@+id/imageViewToolbarRightSide"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/frameLayoutTitleBar"
            android:layout_alignParentRight="true"
            android:layout_alignTop="@+id/frameLayoutTitleBar"
            android:layout_marginRight="10dp"
            android:visibility="invisible"
            app:srcCompat="@drawable/icon_hamburger_menu"/>

        <View
            android:id="@+id/viewTitleUnderLine"
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:layout_alignParentBottom="true"
            android:background="@color/secondaryBackground"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
</FrameLayout>
</LinearLayout>

This all layout is later then added as an include to another layout which includes the layout for the navigation drawer.

In my code I'm setting the images, strings and also the toolbar's background.
The background is set like this:

public static void setTitleBarBackgroundColor(int color)
{
    if(toolBar != null)
    {
        toolBar.setBackgroundColor(color);
    }
}
...
MyToolBarClass.setTitleBarBackgroundColor(getResources().getColor(android.R.color.transparent));

When invoking this, the color does change but instead of being transparent, the toolbar (or something else) is changing to some color similar to gray and I can also see 3 faded icons of 2 people like the old MSN messenger icon, a chat icon and a wheel settings icon, which probably came with the toolbar. If I'm setting the color of the toolbar to something else then there's no problem and it's being set to that color.

Why won't the toolbar background change to transparent so I can see what's below it?


问:
Compute symmetric surface distances [Python]
I want to compute surface distance metrics between 2 binary objects, aka segmentations of liver tumors. I am looking to compute:

Average symmetric surface distance

Root mean square symmetric distance

Hausdorff distance (also known as maximum symmetric distance)

I found two libraries that could help me compute those metrics, but I am getting conflicting results, so i am confused how they work.

SimpleITK:https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1SignedMaurerDistanceMapImageFilter.html
https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1HausdorffDistanceImageFilter.html

MedPy:
https://github.com/loli/medpy/. DOCS

This is my code for Simple ITK and MedPy.

```<code>from medpy import metric
import pandas as pd
import SimpleITK as sitk
import numpy as np
reference_segmentation = sitk.ReadImage('tumorSegm', sitk.sitkUInt8)
segmentation = sitk.ReadImage('tumorSegm2',sitk.sitkUInt8)
class SurfaceDistanceMeasuresITK(Enum):
    hausdorff_distance, max_surface_distance, avg_surface_distance, median_surface_distance, std_surface_distance = range(5)

class MedpyMetricDists(Enum):
    hausdorff_distance, avg_surface_distance, avg_symmetric_surface_distance = range(3)

  surface_distance_results = np.zeros((1,len(SurfaceDistanceMeasuresITK.__members__.items())))
surface_dists_Medpy = np.zeros((1,len(MedpyMetricDists.__members__.items())))
segmented_surface = sitk.LabelContour(segmentation)

# init signed mauerer distance as reference metrics
reference_distance_map = sitk.Abs(sitk.SignedMaurerDistanceMap(reference_segmentation, squaredDistance=False, useImageSpacing=True))

label_intensity_statistics_filter = sitk.LabelIntensityStatisticsImageFilter()
label_intensity_statistics_filter.Execute(segmented_surface, reference_distance_map)

hausdorff_distance_filter = sitk.HausdorffDistanceImageFilter()
hausdorff_distance_filter.Execute(reference_segmentation, segmentation)

surface_distance_results[0,SurfaceDistanceMeasuresITK.hausdorff_distance.value] = hausdorff_distance_filter.GetHausdorffDistance()
surface_distance_results[0,SurfaceDistanceMeasuresITK.max_surface_distance.value] = label_intensity_statistics_filter.GetMaximum(label)
surface_distance_results[0,SurfaceDistanceMeasuresITK.avg_surface_distance.value] = label_intensity_statistics_filter.GetMean(label)
surface_distance_results[0,SurfaceDistanceMeasuresITK.median_surface_distance.value] = label_intensity_statistics_filter.GetMedian(label)
surface_distance_results[0,SurfaceDistanceMeasuresITK.std_surface_distance.value] = label_intensity_statistics_filter.GetStandardDeviation(label)

surface_distance_results_df = pd.DataFrame(data=surface_distance_results, index = list(range(1)),
                              columns=[name for name, _ in SurfaceDistanceMeasuresITK.__members__.items()])

img_array = sitk.GetArrayFromImage(reference_segmentation)
seg_array = sitk.GetArrayFromImage(segmentation)
# reverse array in the order x, y, z
img_array_rev = np.flip(img_array,2)
seg_array_rev = np.flip(seg_array,2)
vxlspacing = segmentation.GetSpacing()

surface_dists_Medpy[0,MedpyMetricDists.hausdorff_distance.value] = metric.binary.hd(seg_array_rev,img_array_rev, voxelspacing=vxlspacing)
surface_dists_Medpy[0,MedpyMetricDists.avg_surface_distance.value] = metric.binary.asd(seg_array_rev,img_array_rev, voxelspacing=vxlspacing)
surface_dists_Medpy[0,MedpyMetricDists.avg_symmetric_surface_distance.value] = metric.binary.assd(seg_array_rev,img_array_rev, voxelspacing=vxlspacing)

surface_dists_Medpy_df = pd.DataFrame(data=surface_dists_Medpy, index = list(range(1)),
                              columns=[name for name, _ in MedpyMetricDists.__members__.items()])
</code>```

At first sight I don't think that SimpleITK computes the
symmetric distances. Is there any implementation for those in that library? How can I obtain them?

Is MedPy a reliable library? Can I calculate the symmetric root mean
square with it?

Other recommendations of libraries for computing surface distance
metrics?

Should I compute the Absolute Values for the Mauerer Distances Map? I am not sure how it affects the results.   reference_distance_map = sitk.Abs(sitk.SignedMaurerDistanceMap(reference_segmentation, squaredDistance=False, useImageSpacing=True))

答:
Signed distance map is not symmetric. Hausdorff distance should be.

For mesh comparisons, I used metro in the past.

For Maurer, positive distances mean outside and negative distances mean inside. You should take absolute value if you want to calculate disagreement.

Body:
I want to compute surface distance metrics between 2 binary objects, aka segmentations of liver tumors. I am looking to compute:

Average symmetric surface distance

Root mean square symmetric distance

Hausdorff distance (also known as maximum symmetric distance)

I found two libraries that could help me compute those metrics, but I am getting conflicting results, so i am confused how they work.

SimpleITK:https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1SignedMaurerDistanceMapImageFilter.html
https://itk.org/SimpleITKDoxygen/html/classitk_1_1simple_1_1HausdorffDistanceImageFilter.html

MedPy:
https://github.com/loli/medpy/. DOCS

This is my code for Simple ITK and MedPy.

from medpy import metric
import pandas as pd
import SimpleITK as sitk
import numpy as np
reference_segmentation = sitk.ReadImage('tumorSegm', sitk.sitkUInt8)
segmentation = sitk.ReadImage('tumorSegm2',sitk.sitkUInt8)
class SurfaceDistanceMeasuresITK(Enum):
    hausdorff_distance, max_surface_distance, avg_surface_distance, median_surface_distance, std_surface_distance = range(5)

class MedpyMetricDists(Enum):
    hausdorff_distance, avg_surface_distance, avg_symmetric_surface_distance = range(3)

  surface_distance_results = np.zeros((1,len(SurfaceDistanceMeasuresITK.__members__.items())))
surface_dists_Medpy = np.zeros((1,len(MedpyMetricDists.__members__.items())))
segmented_surface = sitk.LabelContour(segmentation)

# init signed mauerer distance as reference metrics
reference_distance_map = sitk.Abs(sitk.SignedMaurerDistanceMap(reference_segmentation, squaredDistance=False, useImageSpacing=True))

label_intensity_statistics_filter = sitk.LabelIntensityStatisticsImageFilter()
label_intensity_statistics_filter.Execute(segmented_surface, reference_distance_map)

hausdorff_distance_filter = sitk.HausdorffDistanceImageFilter()
hausdorff_distance_filter.Execute(reference_segmentation, segmentation)

surface_distance_results[0,SurfaceDistanceMeasuresITK.hausdorff_distance.value] = hausdorff_distance_filter.GetHausdorffDistance()
surface_distance_results[0,SurfaceDistanceMeasuresITK.max_surface_distance.value] = label_intensity_statistics_filter.GetMaximum(label)
surface_distance_results[0,SurfaceDistanceMeasuresITK.avg_surface_distance.value] = label_intensity_statistics_filter.GetMean(label)
surface_distance_results[0,SurfaceDistanceMeasuresITK.median_surface_distance.value] = label_intensity_statistics_filter.GetMedian(label)
surface_distance_results[0,SurfaceDistanceMeasuresITK.std_surface_distance.value] = label_intensity_statistics_filter.GetStandardDeviation(label)

surface_distance_results_df = pd.DataFrame(data=surface_distance_results, index = list(range(1)),
                              columns=[name for name, _ in SurfaceDistanceMeasuresITK.__members__.items()])

img_array = sitk.GetArrayFromImage(reference_segmentation)
seg_array = sitk.GetArrayFromImage(segmentation)
# reverse array in the order x, y, z
img_array_rev = np.flip(img_array,2)
seg_array_rev = np.flip(seg_array,2)
vxlspacing = segmentation.GetSpacing()

surface_dists_Medpy[0,MedpyMetricDists.hausdorff_distance.value] = metric.binary.hd(seg_array_rev,img_array_rev, voxelspacing=vxlspacing)
surface_dists_Medpy[0,MedpyMetricDists.avg_surface_distance.value] = metric.binary.asd(seg_array_rev,img_array_rev, voxelspacing=vxlspacing)
surface_dists_Medpy[0,MedpyMetricDists.avg_symmetric_surface_distance.value] = metric.binary.assd(seg_array_rev,img_array_rev, voxelspacing=vxlspacing)

surface_dists_Medpy_df = pd.DataFrame(data=surface_dists_Medpy, index = list(range(1)),
                              columns=[name for name, _ in MedpyMetricDists.__members__.items()])

At first sight I don't think that SimpleITK computes the
symmetric distances. Is there any implementation for those in that library? How can I obtain them?

Is MedPy a reliable library? Can I calculate the symmetric root mean
square with it?

Other recommendations of libraries for computing surface distance
metrics?

Should I compute the Absolute Values for the Mauerer Distances Map? I am not sure how it affects the results.   reference_distance_map = sitk.Abs(sitk.SignedMaurerDistanceMap(reference_segmentation, squaredDistance=False, useImageSpacing=True))


问:
Typescript: downcast on "this" is not possible
In following example TypeScript compiler doesn't allow to cast this to Child directly. Indeed it is possible using intermediate variable temp or double casting as shown in the commented lines.
Is it a bug or is there any logical explanation?
The link to playground

```<code>    class Parent {
        prop: string = null;
        castToChild(): Child{
            let temp: Parent = this;
            return this as Child;
            //return temp as Child;
            //return this as Parent as Child;
        }
    }
    class Child extends Parent
    {
        otherProp: string = null;
    }
</code>```

答:
You cannot directly cast a Parent to a Child simply because the compiler has no way to know that your Parent instance really is a Child. Use a type guard instead of a cast:

```<code>class Parent {
    prop: string|null = null;
    isChild(): this is Child {
        return (this as any).otherProp !== undefined;
    }
}
class Child extends Parent
{
    otherProp: string|null = null;
}

function test(p: Parent) {
  if (p.isChild()) {
    console.log(p.otherProp);
  }
}
</code>```

Inside the guarded if the compiler now knows that p is a Child, outside it p is still just a Parent.

Or better still, override the guard in the subclass and you can avoid doing any typecasting at all:

```<code>class Parent {
    prop: string|null = null;
    isChild(): this is Child {
        return false;
    }
}
class Child extends Parent
{
    otherProp: string|null = null;
    isChild(): this is Child { return true; }
}

function test(p: Parent) {
  if (p.isChild()) {
    console.log(p.otherProp);
  }
}
</code>```

You are correct however that I haven't answered the question whether this is a bug or deliberate on the part of the Typescript authors. My guess is that they're trying to catch possible errors, but I haven't managed to find explanation of this exact behaviour that would confirm or deny it.

Another way you can make your original code work is to explicitly tell typescript the type of this in the castToChild method:

```<code>class Parent {
    prop: string|null = null;

    castToChild(this: Parent): Child{
        return this as Child;
    }
}
class Child extends Parent
{
    otherProp: string|null = null;
}

function foo() {
  let p: Parent = new Child();
  let c = p.castToChild();
  console.log(c.otherProp);
}
</code>```

This is still really just doing the double cast, but perhaps looks a bit cleaner. It does however still show the strangeness of the behaviour as without the explicit this parameter this is of type Parent but not directly castable, with the explicit parameter you can cast it.

Body:
In following example TypeScript compiler doesn't allow to cast this to Child directly. Indeed it is possible using intermediate variable temp or double casting as shown in the commented lines.
Is it a bug or is there any logical explanation?
The link to <a href="http://www.typescriptlang.org/play/index.html#src=class%20Parent%20%7B%0D%0A%09prop%20%3D%20%22%22%3B%0D%0A%09castToChild()%3A%20Child%7B%0D%0A%09%09let%20temp%3A%20Parent%20%3D%20this%3B%0D%0A%20%20%20%20%20%20%20%20return%20this%20as%20Child%3B%0D%0A%20%20%20%20%20%20%20%20%2F%2Freturn%20temp%20as%20Child%3B%0D%0A%20%20%20%20%20%20%20%20%2F%2Freturn%20temp%20as%20Parent%20Child%3B%0D%0A%09%7D%0D%0A%7D%0D%0Aclass%20Child%20extends%20Parent%7B%0D%0A%09otherProp%3A%20%22%22%3B%0D%0A%7D" rel="nofollow noreferrer">playground

    class Parent {
        prop: string = null;
        castToChild(): Child{
            let temp: Parent = this;
            return this as Child;
            //return temp as Child;
            //return this as Parent as Child;
        }
    }
    class Child extends Parent
    {
        otherProp: string = null;
    }

Body:
You cannot directly cast a Parent to a Child simply because the compiler has no way to know that your Parent instance really is a Child. Use a type guard instead of a cast:

class Parent {
    prop: string|null = null;
    isChild(): this is Child {
        return (this as any).otherProp !== undefined;
    }
}
class Child extends Parent
{
    otherProp: string|null = null;
}

function test(p: Parent) {
  if (p.isChild()) {
    console.log(p.otherProp);
  }
}

Inside the guarded if the compiler now knows that p is a Child, outside it p is still just a Parent.

Or better still, override the guard in the subclass and you can avoid doing any typecasting at all:

class Parent {
    prop: string|null = null;
    isChild(): this is Child {
        return false;
    }
}
class Child extends Parent
{
    otherProp: string|null = null;
    isChild(): this is Child { return true; }
}

function test(p: Parent) {
  if (p.isChild()) {
    console.log(p.otherProp);
  }
}

You are correct however that I haven't answered the question whether this is a bug or deliberate on the part of the Typescript authors. My guess is that they're trying to catch possible errors, but I haven't managed to find explanation of this exact behaviour that would confirm or deny it.

Another way you can make your original code work is to explicitly tell typescript the type of this in the castToChild method:

class Parent {
    prop: string|null = null;

    castToChild(this: Parent): Child{
        return this as Child;
    }
}
class Child extends Parent
{
    otherProp: string|null = null;
}

function foo() {
  let p: Parent = new Child();
  let c = p.castToChild();
  console.log(c.otherProp);
}

This is still really just doing the double cast, but perhaps looks a bit cleaner. It does however still show the strangeness of the behaviour as without the explicit this parameter this is of type Parent but not directly castable, with the explicit parameter you can cast it.


问:
iOS Keeping old launch screen and app icon after update
I have an app where I recently replaced the launch images and app icons, I removed all of the old assets from everywhere in the project. When I upgrade the app from the old version to the new version by just building in Xcode, everything is fine. However, if I have the old version of my app installed then upgrade it from TestFlight, every time I kill the app then restart it the old launch image briefly appears before showing the new launch image. Similarly when I then close the app, the old app icon briefly flashes before switching back to my new one.

I opened up the App using iExplorer and noticed that there is an image of the old launch screen saved in the /Library/Caches/Shapshots directory (I don't know how or why it got there). When I delete it manually through iExplorer, it stops appearing. However, when I try to remove it with code using NSFileManager methods, I get errors saying I am forbidden from deleting files in this directory.

Has anyone experienced this before and have any advice?

答:
I also faced the same issue. It happens because the simulator/ iOS device caches the launch image when you first launch the application. I added some modifications to Brian Trzupek's answer:

Delete the image set from Xcode assets (eg. launch_image)

Add a new image set and add images to it.

Switch off and switch on the iOS Device. (Reset Contents and Settings for simulator).

Clean the Xcode build folder (Press command + option + shift + K).

Delete the app from the device/simulator (if available).

Run again.


问:
Angular 4 Can't bind to <property> since it isn't a known property of <component>
I'm trying to create my own directive in Angular 4. But, I got this error when bind the property of class into component template.

Console error:

Unhandled Promise rejection: Template parse errors: Can't bind to
'data' since it isn't a known property of 'tree'. ("<tree [ERROR
->][data]="data"></tree>"):
```

<p>My tree-view-component.ts:</p>

```@Component({
    selector: 'app-tree-view',
    template: '<tree [data]="data"></tree>'
})
export class TreeViewComponent implements OnInit {

    @Input() data: any[];

    constructor() {
        this.data = [
        {
            label: 'a1',
            subs: [
                {
                    label: 'a11',
                    subs: [
                        {
                            label: 'a111',
                            subs: [
                                {
                                    label: 'a1111'
                                },
                                {
                                    label: 'a1112'
                                }
                            ]
                        },
                        {
                            label: 'a112'
                        }
                    ]
                },
                {
                    label: 'a12',
                }
            ]
         }
     ];
  }

  ngOnInit() { }

}
```

Here is my complete script file: https://pastebin.com/hDyX2Kjj

Is there anyone know about this? TiA

答:
As The Aelfinn pointed out if you are using your Component across Modules you need to export it. BUT you should not import, export and declare it in the Module you want to use it, since its not part of this Module !!!

So suppose you have a TreeViewStuffModule which declares the TreeViewComponent and a DoSomethingWithTreeViewModule where the TreeViewComponent is used in, your declarations would be as follows:

```<code>@NgModule({
  declarations: [
    TreeViewComponent
  ],
  exports: [
    TreeViewComponent
  ]
})
export class TreeViewStuffModule { }

@NgModule({
  imports: [
    TreeViewStuffModule
  ]
})
export class DoSomethingWithTreeViewModule
</code>```

Body:
I'm trying to create my own directive in Angular 4. But, I got this error when bind the property of class into component template.

Console error:

Unhandled Promise rejection: Template parse errors: Can't bind to
'data' since it isn't a known property of 'tree'. ("<tree [ERROR
->][data]="data"></tree>"):

My tree-view-component.ts:

@Component({
    selector: 'app-tree-view',
    template: '<tree [data]="data"></tree>'
})
export class TreeViewComponent implements OnInit {

    @Input() data: any[];

    constructor() {
        this.data = [
        {
            label: 'a1',
            subs: [
                {
                    label: 'a11',
                    subs: [
                        {
                            label: 'a111',
                            subs: [
                                {
                                    label: 'a1111'
                                },
                                {
                                    label: 'a1112'
                                }
                            ]
                        },
                        {
                            label: 'a112'
                        }
                    ]
                },
                {
                    label: 'a12',
                }
            ]
         }
     ];
  }

  ngOnInit() { }

}

Here is my complete script file: https://pastebin.com/hDyX2Kjj

Is there anyone know about this? TiA

Body:
As The Aelfinn pointed out if you are using your Component across Modules you need to export it. BUT you should not import, export and declare it in the Module you want to use it, since its not part of this Module !!!

So suppose you have a TreeViewStuffModule which declares the TreeViewComponent and a DoSomethingWithTreeViewModule where the TreeViewComponent is used in, your declarations would be as follows:

@NgModule({
  declarations: [
    TreeViewComponent
  ],
  exports: [
    TreeViewComponent
  ]
})
export class TreeViewStuffModule { }

@NgModule({
  imports: [
    TreeViewStuffModule
  ]
})
export class DoSomethingWithTreeViewModule