问:
Unable to copy item from mapped network drive using powershell as file contains wierd characters
I am trying to copy files from mapped network drive.Some of them gets copied but others are not copied as filename has got some wierd characters.

for example my mapped network drive Z: contains the following files:

skifteretsattest 1(1).pdf

MailBody.msg

k�rekort terje(3).pdf

I am able to copy first two files from mapped network drive but not the last one using the below command

```<code>Copy-Item  -LiteralPath Z:\$name  -Destination I:\Dat\SomePath\ss/ -Force
</code>```

The error which I get is:

Copy-Item : Could not find file 'Z:\k�rekort terje(3).pdf

I tried [WildcardPattern]::Escape($name) but that also did not work
Kindly help if anybody knows the solution

答:
Maybe you could use robocopy.exe oder xcopy.exe instead?

Maybe old "dir /x" can help to find out the old "8.3" filename (like "GET-GP~1.PS1" for "Get-GPProcessingTime.ps1") and this can be used to copy or rename the file?

I also remember something about bypassing file system logic using unc-like syntax like \\0\driveletter\directory or whatever - unfortunately I don't remember the exact syntax. Maybe someone else does?

Body:
I am trying to copy files from mapped network drive.Some of them gets copied but others are not copied as filename has got some wierd characters.

for example my mapped network drive Z: contains the following files:

skifteretsattest 1(1).pdf

MailBody.msg

k�rekort terje(3).pdf

I am able to copy first two files from mapped network drive but not the last one using the below command

Copy-Item  -LiteralPath Z:\$name  -Destination I:\Dat\SomePath\ss/ -Force

The error which I get is:

Copy-Item : Could not find file 'Z:\k�rekort terje(3).pdf

I tried [WildcardPattern]::Escape($name) but that also did not work
Kindly help if anybody knows the solution


来源: stackexchange

问:
Ruby rspec Mocking a class
I have a file with two classes in it.

```<code>class LogStash::Filters::MyFilter< LogStash::Filters::Base
</code>```

and

```<code>class LogStash::JavaMysqlConnection
</code>```

JavaMysqlConnection has methods initialize and select. It is in use by the MyFilter class, and is used to query the database as you may have guessed.

How do I mock the initialize and select methods to return nil and an array respectively?

I tried using:

```<code>before(:each) do
  dbl = double("LogStash::JavaMysqlConnection", :initialize => nil)
end
</code>```

but this did not work, as I am still seeing a communication link failure.

I have rspec version 2.14.8

Thanks in advance.
PS. I am new to Ruby

答:
Using RSpec stub_const</p>

```<code>describe 'No User' do
  let(:user)       { double }
  let(:attributes) { { name: 'John' } }

  before do
    stub_const 'User', instance_double('User', new: user)
  end

  it 'creates user' do
    expect(user).to receive(:update!).with(attributes)

    User.new.update!(attributes)
  end
end
</code>```

ContentLicense: CC BY-SA 4.0

Title: Ruby rspec Mocking a class

Body:
I have a file with two classes in it.

class LogStash::Filters::MyFilter< LogStash::Filters::Base

and

class LogStash::JavaMysqlConnection

JavaMysqlConnection has methods initialize and select. It is in use by the MyFilter class, and is used to query the database as you may have guessed.

How do I mock the initialize and select methods to return nil and an array respectively?

I tried using:

before(:each) do
  dbl = double("LogStash::JavaMysqlConnection", :initialize => nil)
end

but this did not work, as I am still seeing a communication link failure.

I have rspec version 2.14.8

Thanks in advance.
PS. I am new to Ruby

Body:
Using RSpec stub_const

describe 'No User' do
  let(:user)       { double }
  let(:attributes) { { name: 'John' } }

  before do
    stub_const 'User', instance_double('User', new: user)
  end

  it 'creates user' do
    expect(user).to receive(:update!).with(attributes)

    User.new.update!(attributes)
  end
end


问:
There is no Logs and Stdout in Flink WebUI
Recently I have started a cluster of flink with Docker-compose.Here is my file:

```<code>version: "2.1"
services:
  jobmanager:
    image: flink:1.9.2-scala_2.11
    expose:
      - "6123"
    ports:
      - "8081:8081"
    command: jobmanager
    environment:
      - JOB_MANAGER_RPC_ADDRESS=jobmanager

  taskmanager:
    image: flink:1.9.2-scala_2.11
    expose:
      - "6121"
      - "6122"
    depends_on:
      - jobmanager
    command: taskmanager
    links:
      - "jobmanager:jobmanager"
    environment:
      - JOB_MANAGER_RPC_ADDRESS=jobmanager
</code>```

I started it with "docker-compose up -d --scale taskmanager=3" to assign 3 taskmanagers.
I have passed the WordCount Demo and when I input some words in the bash there is no error occurs.

However, I just cannot see the logs and stdout from the WebUI

答:
In containerized deployments, Flink's logs are sent to stdout/stderr rather than to log files, and infrastructure is available for log collection. With docker-compose, you can use docker-compose logs -f to follow all of the logs, docker-compose logs -f [SERVICE] to follow the logs for one service, etc.

Because the logs are not being written to the log files, Flink's web UI is unable to display them.

For what it's worth, there has been some discussion on the dev@flink.apache.org mailing list about writing the logs to both stdout/stderr and the log files.

Body:
Recently I have started a cluster of flink with Docker-compose.Here is my file:

version: "2.1"
services:
  jobmanager:
    image: flink:1.9.2-scala_2.11
    expose:
      - "6123"
    ports:
      - "8081:8081"
    command: jobmanager
    environment:
      - JOB_MANAGER_RPC_ADDRESS=jobmanager

  taskmanager:
    image: flink:1.9.2-scala_2.11
    expose:
      - "6121"
      - "6122"
    depends_on:
      - jobmanager
    command: taskmanager
    links:
      - "jobmanager:jobmanager"
    environment:
      - JOB_MANAGER_RPC_ADDRESS=jobmanager

I started it with "docker-compose up -d --scale taskmanager=3" to assign 3 taskmanagers.
I have passed the WordCount Demo and when I input some words in the bash there is no error occurs.

However, I just cannot see the logs and stdout from the WebUI


问:
Scraping webpage using BeautifulSoup
I am attempting to scrape this site: https://www.senate.gov/general/contact_information/senators_cfm.cfm

My Code:

```<code>import requests
from bs4 import BeautifulSoup

URL = 'https://www.senate.gov/general/contact_information/senators_cfm.cfm'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')

print(soup)
</code>```

The issue is that it's not actually going to the site. The HTML that I get in my soup var is not at all what the HTML is in the correct webpage.

答:
This worked for me

```<code>headers = {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    }
r = requests.get(URL,headers=headers)
</code>```

Found the info here - https://towardsdatascience.com/5-strategies-to-write-unblock-able-web-scrapers-in-python-5e40c147bdaf

Title: Scraping webpage using BeautifulSoup

Body:
I am attempting to scrape this site: https://www.senate.gov/general/contact_information/senators_cfm.cfm

My Code:

import requests
from bs4 import BeautifulSoup

URL = 'https://www.senate.gov/general/contact_information/senators_cfm.cfm'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')

print(soup)

The issue is that it's not actually going to the site. The HTML that I get in my soup var is not at all what the HTML is in the correct webpage.

Body:
This worked for me

headers = {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    }
r = requests.get(URL,headers=headers)

Found the info here - https://towardsdatascience.com/5-strategies-to-write-unblock-able-web-scrapers-in-python-5e40c147bdaf


问:
How can I check if an array contains a value of another array?
I would like to check to see if an array contains a value from another array. For example, I would like to check if the array A contains a value from an array B.

I'm looking for any value not one specific value.

答:
Make sure your array A and B are the same type.
then try like the following.

```<code>for (i in 0..arrayB.size-1) {
    arrayA.contains(arrayB[i]);
}
</code>```

Body:
Make sure your array A and B are the same type.
then try like the following.

for (i in 0..arrayB.size-1) {
    arrayA.contains(arrayB[i]);
}


问:
MVVM view switching - new view data context not populated under after InitializeComponent
I am developing my first WPF app and am trying to stick to an MVVM approach. I am using MVVM Light.  Its a simple app, which just displays a list of things called "Merges" and allows the user to select one and edit it.

I have MainView which is just this:

```<code><Window x:Class="FileMerger.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FileMerger"
        xmlns:Views="clr-namespace:FileMerger.Views"
        xmlns:ViewModels="clr-namespace:FileMerger.ViewModels"
        mc:Ignorable="d"
        Title="File Merge" Height="450" Width="800">
    <Window.DataContext>
        <ViewModels:MainViewModel></ViewModels:MainViewModel>
    </Window.DataContext>
    <Window.Resources>
        <DataTemplate DataType="{x:Type ViewModels:MergeListViewModel}">
            <Views:MergeList/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type ViewModels:EditMergeViewModel}">
            <Views:EditMergeView/>
        </DataTemplate>
    </Window.Resources>

    <ContentControl Content="{Binding CurrentPageViewModel}"></ContentControl>
</Window>
</code>```

and MainViewModel as follows:

```<code>public class MainViewModel:ViewModelBase
    {
            private ViewModelBase _currentPageViewModel;
            private MergeListViewModel _mergeListViewModel=new MergeListViewModel();
            private EditMergeViewModel _editMergeViewModel = new EditMergeViewModel();

        public MainViewModel()
            {
                // Set starting page
                _mergeListViewModel.MergeSelected += navToMergeEdit;
                CurrentPageViewModel = _mergeListViewModel;
            }

            public ViewModelBase CurrentPageViewModel
            {
                get
                {
                    return _currentPageViewModel;
                }
                set
                {
                    if (_currentPageViewModel != value)
                    {
                        _currentPageViewModel = value;
                        RaisePropertyChanged(nameof(CurrentPageViewModel));
                    }
                }
            }

       public void navToMergeEdit(int mergeId)
        {
            _editMergeViewModel.MergeId = mergeId;
            CurrentPageViewModel = _editMergeViewModel;
        }
     }
</code>```

My first view MergeListView has this event in the ViewModel (MergeListViewModel)

```<code>public event Action<int> MergeSelected = delegate { };
</code>```

The idea is that when a "Merge" is selected, EditMergeView is loaded with ViewModel EditMergeViewModel, passing mergeId as the parameter.  LoadedCommand in EditMergeViewModel should be run, which gets the data to populate the ViewModel with the Merge.

An EventTrigger in EditMergeView should do this:

```<code><i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <command:EventToCommand Command="{Binding LoadedCommand}" PassEventArgsToCommand="True" />
        </i:EventTrigger>
</i:Interaction.Triggers>
</code>```

What I found though is that LoadedCommand is not called, although breakpoints show that NavToMergeEdit in MainViewModel is being called via the event.  I stuck a breakpoint in the constructor of EditMergeView, and found that before InitializeComponent() is called, this.DataContext is null, and after InitializeComponent() it is populated.  I believe that the Loaded event is being triggered in InitializeComponent(), but at that point the datacontext is not set which is causing the issue.

This is supported by the following in the Output window in VS, which suggests to me that the EditMergeView is not binding to the ViewModel at the correct point

```<code>System.Windows.Data Error: 40 : BindingExpression path error: 'LoadedCommand' property not found on 'object' ''EditMergeViewModel' (HashCode=31475357)'. BindingExpression:Path=LoadedCommand; DataItem='EditMergeViewModel' (HashCode=31475357); target element is 'EventToCommand' (HashCode=41172271); target property is 'Command' (type 'ICommand')
Exception thrown: 'System.NullReferenceException' in FileMerger.exe
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll
System.Windows.Data Error: 17 : Cannot get 'MergeName' value (type 'String') from '' (type 'EditMergeViewModel'). BindingExpression:Path=MergeName; DataItem='EditMergeViewModel' (HashCode=31475357); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at FileMerger.ViewModels.EditMergeViewModel.get_MergeName() in C:\Users\JonathanS\source\repos\FileMerger\FileMerger\ViewModels\EditMergeViewModel.cs:line 270
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
   at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level)
   at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)'
System.Windows.Data Error: 40 : BindingExpression path error: 'EditMergeCommand' property not found on 'object' ''EditMergeViewModel' (HashCode=31475357)'. BindingExpression:Path=EditMergeCommand; DataItem='EditMergeViewModel' (HashCode=31475357); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')
</code>```

What am I doing wrong?  Do I need to just call it and create the ViewModel in the View constructor and set the DataContext there? .  Maybe less elegant but would avoid this.

答:
Right luckily I had a bit of time to solve this.  In EditMergeViewModel, I was not using properties with getters and setters for the commands.  So I had for example

```<code>public ICommand LoadedCommand;
</code>```

not

```<code>public ICommand LoadedCommand { get; set; }
</code>```

I think the reason it needs this something to do with reflection but if anyone cares to explain why this works feel free.  For now I will mark the question as answered.

Body:
I am developing my first WPF app and am trying to stick to an MVVM approach. I am using MVVM Light.  Its a simple app, which just displays a list of things called "Merges" and allows the user to select one and edit it.

I have MainView which is just this:

<Window x:Class="FileMerger.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:FileMerger"
        xmlns:Views="clr-namespace:FileMerger.Views"
        xmlns:ViewModels="clr-namespace:FileMerger.ViewModels"
        mc:Ignorable="d"
        Title="File Merge" Height="450" Width="800">
    <Window.DataContext>
        <ViewModels:MainViewModel></ViewModels:MainViewModel>
    </Window.DataContext>
    <Window.Resources>
        <DataTemplate DataType="{x:Type ViewModels:MergeListViewModel}">
            <Views:MergeList/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type ViewModels:EditMergeViewModel}">
            <Views:EditMergeView/>
        </DataTemplate>
    </Window.Resources>

    <ContentControl Content="{Binding CurrentPageViewModel}"></ContentControl>
</Window>

and MainViewModel as follows:

public class MainViewModel:ViewModelBase
    {
            private ViewModelBase _currentPageViewModel;
            private MergeListViewModel _mergeListViewModel=new MergeListViewModel();
            private EditMergeViewModel _editMergeViewModel = new EditMergeViewModel();

        public MainViewModel()
            {
                // Set starting page
                _mergeListViewModel.MergeSelected += navToMergeEdit;
                CurrentPageViewModel = _mergeListViewModel;
            }

            public ViewModelBase CurrentPageViewModel
            {
                get
                {
                    return _currentPageViewModel;
                }
                set
                {
                    if (_currentPageViewModel != value)
                    {
                        _currentPageViewModel = value;
                        RaisePropertyChanged(nameof(CurrentPageViewModel));
                    }
                }
            }

       public void navToMergeEdit(int mergeId)
        {
            _editMergeViewModel.MergeId = mergeId;
            CurrentPageViewModel = _editMergeViewModel;
        }
     }

My first view MergeListView has this event in the ViewModel (MergeListViewModel)

public event Action<int> MergeSelected = delegate { };

The idea is that when a "Merge" is selected, EditMergeView is loaded with ViewModel EditMergeViewModel, passing mergeId as the parameter.  LoadedCommand in EditMergeViewModel should be run, which gets the data to populate the ViewModel with the Merge.

An EventTrigger in EditMergeView should do this:

            <command:EventToCommand Command="{Binding LoadedCommand}" PassEventArgsToCommand="True" />

What I found though is that LoadedCommand is not called, although breakpoints show that NavToMergeEdit in MainViewModel is being called via the event.  I stuck a breakpoint in the constructor of EditMergeView, and found that before InitializeComponent() is called, this.DataContext is null, and after InitializeComponent() it is populated.  I believe that the Loaded event is being triggered in InitializeComponent(), but at that point the datacontext is not set which is causing the issue.

This is supported by the following in the Output window in VS, which suggests to me that the EditMergeView is not binding to the ViewModel at the correct point

System.Windows.Data Error: 40 : BindingExpression path error: 'LoadedCommand' property not found on 'object' ''EditMergeViewModel' (HashCode=31475357)'. BindingExpression:Path=LoadedCommand; DataItem='EditMergeViewModel' (HashCode=31475357); target element is 'EventToCommand' (HashCode=41172271); target property is 'Command' (type 'ICommand')
Exception thrown: 'System.NullReferenceException' in FileMerger.exe
Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll
System.Windows.Data Error: 17 : Cannot get 'MergeName' value (type 'String') from '' (type 'EditMergeViewModel'). BindingExpression:Path=MergeName; DataItem='EditMergeViewModel' (HashCode=31475357); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at FileMerger.ViewModels.EditMergeViewModel.get_MergeName() in C:\Users\JonathanS\source\repos\FileMerger\FileMerger\ViewModels\EditMergeViewModel.cs:line 270
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
   at MS.Internal.Data.PropertyPathWorker.GetValue(Object item, Int32 level)
   at MS.Internal.Data.PropertyPathWorker.RawValue(Int32 k)'
System.Windows.Data Error: 40 : BindingExpression path error: 'EditMergeCommand' property not found on 'object' ''EditMergeViewModel' (HashCode=31475357)'. BindingExpression:Path=EditMergeCommand; DataItem='EditMergeViewModel' (HashCode=31475357); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')

What am I doing wrong?  Do I need to just call it and create the ViewModel in the View constructor and set the DataContext there? .  Maybe less elegant but would avoid this.

Body:
Right luckily I had a bit of time to solve this.  In EditMergeViewModel, I was not using properties with getters and setters for the commands.  So I had for example

public ICommand LoadedCommand;

not

public ICommand LoadedCommand { get; set; }

I think the reason it needs this something to do with reflection but if anyone cares to explain why this works feel free.  For now I will mark the question as answered.


问:
Can't properly launch Scrapy shell
I'm trying to build a Scrapy spider from the very beginning. I managed to generate a spider using scrapy genspider name_of_spider, but when I typed scrapy shell, I received the following result.

Note that when I used another spider of mine to run scrapy crawl spider_name, that spider worked just fine. However, I couldn't launch that scrapy shell either.

```<code>(venv) jacquelinewong@Jacquelines-MBP rent_apt % scrapy shell
2020-05-29 09:29:12 [scrapy.utils.log] INFO: Scrapy 2.0.1 started (bot: rent_apt)
2020-05-29 09:29:12 [scrapy.utils.log] INFO: Versions: lxml 4.2.1.0, libxml2 2.9.8, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 20.3.0, Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) - [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)], pyOpenSSL 18.0.0 (OpenSSL 1.1.1g  21 Apr 2020), cryptography 2.9.2, Platform Darwin-19.3.0-x86_64-i386-64bit
2020-05-29 09:29:12 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2020-05-29 09:29:12 [scrapy.crawler] INFO: Overridden settings:
{'BOT_NAME': 'rent_apt',
 'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter',
 'LOGSTATS_INTERVAL': 0,
 'NEWSPIDER_MODULE': 'rent_apt.spiders',
 'ROBOTSTXT_OBEY': True,
 'SPIDER_MODULES': ['rent_apt.spiders']}
2020-05-29 09:29:12 [scrapy.extensions.telnet] INFO: Telnet Password: eb3c5554d18c822b
2020-05-29 09:29:12 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.memusage.MemoryUsage']
2020-05-29 09:29:12 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2020-05-29 09:29:12 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2020-05-29 09:29:12 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2020-05-29 09:29:12 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-05-29 09:29:13 [py.warnings] WARNING: /Users/jacquelinewong/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py:763: UserWarning: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
  warn("Attempting to work in a virtualenv. If you encounter problems, please "

[s] Available Scrapy objects:
[s]   scrapy     scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s]   crawler    <scrapy.crawler.Crawler object at 0x114358240>
[s]   item       {}
[s]   settings   <scrapy.settings.Settings object at 0x114354e80>
[s] Useful shortcuts:
[s]   fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s]   fetch(req)                  Fetch a scrapy.Request and update local objects
[s]   shelp()           Shell help (print this help)
[s]   view(response)    View response in a browser
In [1]: response

In [2]:
</code>```

If the shell works fine, it should return a 200 message.

```<code>In [2]: response
Out[2]: <200 http://quotes.toscrape.com/>
</code>```

Please help me out to debug this!

答:
It turned out I had a timeout issue. According to this post, reasons for requests getting timed out are:

Server has rate limited your IP Address.

Server only responds to the IP Addresses of the the specific region.

Server is too busy or under very heavy load for long period of time.

Server responds to only specific User-Agent.

Server responds only if Cookies are present inside request header.

think more reasons on your own ....

Once I tried to fetch another url, the shell works!

```<code>In [1]: fetch('https://www.apartments.com/manhattan-ny/')
2020-05-29 09:53:28 [scrapy.core.engine] INFO: Spider opened
2020-05-29 09:56:28 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.apartments.com/robots.txt> (failed 1 times): User timeout caused connection failure: Getting https://www.apartments.com/robots.txt took longer than 180.0 seconds..
2020-05-29 09:59:28 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.apartments.com/robots.txt> (failed 2 times): User timeout caused connection failure: Getting https://www.apartments.com/robots.txt took longer than 180.0 seconds..
2020-05-29 10:02:28 [scrapy.downloadermiddlewares.retry] ERROR: Gave up retrying <GET https://www.apartments.com/robots.txt> (failed 3 times): User timeout caused connection failure: Getting https://www.apartments.com/robots.txt took longer than 180.0 seconds..
2020-05-29 10:02:28 [scrapy.downloadermiddlewares.robotstxt] ERROR: Error downloading <GET https://www.apartments.com/robots.txt>: User timeout caused connection failure: Getting https://www.apartments.com/robots.txt took longer than 180.0 seconds..
</code>```

Title: Can't properly launch Scrapy shell

Body:
I'm trying to build a Scrapy spider from the very beginning. I managed to generate a spider using scrapy genspider name_of_spider, but when I typed scrapy shell, I received the following result.

Note that when I used another spider of mine to run scrapy crawl spider_name, that spider worked just fine. However, I couldn't launch that scrapy shell either.

(venv) jacquelinewong@Jacquelines-MBP rent_apt % scrapy shell
2020-05-29 09:29:12 [scrapy.utils.log] INFO: Scrapy 2.0.1 started (bot: rent_apt)
2020-05-29 09:29:12 [scrapy.utils.log] INFO: Versions: lxml 4.2.1.0, libxml2 2.9.8, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 20.3.0, Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) - [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)], pyOpenSSL 18.0.0 (OpenSSL 1.1.1g  21 Apr 2020), cryptography 2.9.2, Platform Darwin-19.3.0-x86_64-i386-64bit
2020-05-29 09:29:12 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor
2020-05-29 09:29:12 [scrapy.crawler] INFO: Overridden settings:
{'BOT_NAME': 'rent_apt',
 'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter',
 'LOGSTATS_INTERVAL': 0,
 'NEWSPIDER_MODULE': 'rent_apt.spiders',
 'ROBOTSTXT_OBEY': True,
 'SPIDER_MODULES': ['rent_apt.spiders']}
2020-05-29 09:29:12 [scrapy.extensions.telnet] INFO: Telnet Password: eb3c5554d18c822b
2020-05-29 09:29:12 [scrapy.middleware] INFO: Enabled extensions:
['scrapy.extensions.corestats.CoreStats',
 'scrapy.extensions.telnet.TelnetConsole',
 'scrapy.extensions.memusage.MemoryUsage']
2020-05-29 09:29:12 [scrapy.middleware] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware',
 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2020-05-29 09:29:12 [scrapy.middleware] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2020-05-29 09:29:12 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2020-05-29 09:29:12 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2020-05-29 09:29:13 [py.warnings] WARNING: /Users/jacquelinewong/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py:763: UserWarning: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
  warn("Attempting to work in a virtualenv. If you encounter problems, please "

[s] Available Scrapy objects:
[s]   scrapy     scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s]   crawler    <scrapy.crawler.Crawler object at 0x114358240>
[s]   item       {}
[s]   settings   <scrapy.settings.Settings object at 0x114354e80>
[s] Useful shortcuts:
[s]   fetch(url[, redirect=True]) Fetch URL and update local objects (by default, redirects are followed)
[s]   fetch(req)                  Fetch a scrapy.Request and update local objects
[s]   shelp()           Shell help (print this help)
[s]   view(response)    View response in a browser
In [1]: response

In [2]:

If the shell works fine, it should return a 200 message.

In [2]: response
Out[2]: <200 http://quotes.toscrape.com/>

Please help me out to debug this!

Body:
It turned out I had a timeout issue. According to this post, reasons for requests getting timed out are:

Server has rate limited your IP Address.

Server only responds to the IP Addresses of the the specific region.

Server is too busy or under very heavy load for long period of time.

Server responds to only specific User-Agent.

Server responds only if Cookies are present inside request header.

think more reasons on your own ....

Once I tried to fetch another url, the shell works!

In [1]: fetch('https://www.apartments.com/manhattan-ny/')
2020-05-29 09:53:28 [scrapy.core.engine] INFO: Spider opened
2020-05-29 09:56:28 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.apartments.com/robots.txt> (failed 1 times): User timeout caused connection failure: Getting https://www.apartments.com/robots.txt took longer than 180.0 seconds..
2020-05-29 09:59:28 [scrapy.downloadermiddlewares.retry] DEBUG: Retrying <GET https://www.apartments.com/robots.txt> (failed 2 times): User timeout caused connection failure: Getting https://www.apartments.com/robots.txt took longer than 180.0 seconds..
2020-05-29 10:02:28 [scrapy.downloadermiddlewares.retry] ERROR: Gave up retrying <GET https://www.apartments.com/robots.txt> (failed 3 times): User timeout caused connection failure: Getting https://www.apartments.com/robots.txt took longer than 180.0 seconds..
2020-05-29 10:02:28 [scrapy.downloadermiddlewares.robotstxt] ERROR: Error downloading <GET https://www.apartments.com/robots.txt>: User timeout caused connection failure: Getting https://www.apartments.com/robots.txt took longer than 180.0 seconds..


问:
Flutter - save file to download folder - downloads_path_provider
I'm developing a mobile app using flutter. For that I used downloads-path-provider to get the download directory of the mobile phone. The emulator returns /storage/emulated/0/Download. Also when I save a file in this directory the file can be visible in the Download folder.

But on a real devices it also returns the same directory path. /storage/emulated/0/Download Is this correct for the actual devices? Because on actual devices I cannot see the saved file in the Download folder.

Is there any solution to find the downloads directory on a real device?

答:
path_provider will probably undergo some changes soon, there are some open issues:

https://github.com/flutter/flutter/issues/35783

As of right now, the best way to get the download path on an Android device is to use:

```<code>/storage/emulated/0/Download/
</code>```

No (s) needed.

And to get the external dir path in Android:

```<code>/storage/emulated/0/
</code>```

The "emulated" word does not mean it's the emulator path, it's just a naming convention.

Make sure you have permission to write to the file, add this to manifest.xml file, right under <manifest tag:

```<code><manifest package="..." ... >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

and also request permission at run time.

See https://pub.dev/packages/permission_handler

Body:
path_provider will probably undergo some changes soon, there are some open issues:

https://github.com/flutter/flutter/issues/35783

As of right now, the best way to get the download path on an Android device is to use:

/storage/emulated/0/Download/

No (s) needed.

And to get the external dir path in Android:

/storage/emulated/0/

The "emulated" word does not mean it's the emulator path, it's just a naming convention.

Make sure you have permission to write to the file, add this to manifest.xml file, right under <manifest tag:

<manifest package="..." ... >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

and also request permission at run time.

See https://pub.dev/packages/permission_handler


问:
Why is Filter failing to take factors of a number?
I'm getting some strange behavior from some R code that I wrote to factor non-zero integers.

```<code>factors<-function(num) c(Filter(function(x) num%%x==0,(-num%/%2):num%/%2),num,-num)
</code>```

I expected factors(-15) to give the sequence -15, -5, -3, -1, 1, 3, 5, 15. Instead, I get:

```<code>> factors(-15)
 [1]   3   3   1   1  -1  -1  -3  -3  -5  -5 -15  15
</code>```

On top of being ordered very strangely (shouldn't it have checked from -7 to 7?) this misses out 5. What have I overlooked?

答:
You missed a couple of brackets

```<code>factors <- function(num) c(-num, Filter(function(x) num%%x==0, (-num%/%2):(num%/%2)), num)
factors(-15)
# [1]  15   5   3   1  -1  -3  -5 -15
</code>```

By the way, it checks from -8 to 7 in this case

```<code>(-15%/%2):(15%/%2)
# [1] -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7
</code>```

Body:
I'm getting some strange behavior from some R code that I wrote to factor non-zero integers.

factors<-function(num) c(Filter(function(x) num%%x==0,(-num%/%2):num%/%2),num,-num)

I expected factors(-15) to give the sequence -15, -5, -3, -1, 1, 3, 5, 15. Instead, I get:

> factors(-15)
 [1]   3   3   1   1  -1  -1  -3  -3  -5  -5 -15  15

On top of being ordered very strangely (shouldn't it have checked from -7 to 7?) this misses out 5. What have I overlooked?

Body:
You missed a couple of brackets

factors <- function(num) c(-num, Filter(function(x) num%%x==0, (-num%/%2):(num%/%2)), num)
factors(-15)
# [1]  15   5   3   1  -1  -3  -5 -15

By the way, it checks from -8 to 7 in this case

(-15%/%2):(15%/%2)
# [1] -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7


问:
Introspection to get decorator names on a method?
I am trying to figure out how to get the names of all decorators on a method. I can already get the method name and docstring, but cannot figure out how to get a list of decorators.</p>

答:
I've add the same question. In my unit tests I just wanted to make sure decorators were used by given functions/methods.

The decorators were tested separately so I didn't need to test the common logic for each decorated function, just that the decorators were used.

I finally came up with the following helper function:

```<code>import inspect

def get_decorators(function):
    """Returns list of decorators names

    Args:
        function (Callable): decorated method/function

    Return:
        List of decorators as strings

    Example:
        Given:

        @my_decorator
        @another_decorator
        def decorated_function():
            pass

        >>> get_decorators(decorated_function)
        ['@my_decorator', '@another_decorator']

    """
    source = inspect.getsource(function)
    index = source.find("def ")
    return [
        line.strip().split()[0]
        for line in source[:index].strip().splitlines()
        if line.strip()[0] == "@"
    ]
</code>```

With the list comprehension, it is a bit "dense" but it does the trick and in my case it's a test helper function.

It works if you are intrested only in the decorators names, not potential decorator arguments. If you want to support decorators taking arguments, something like line.strip().split()[0].split("(")[0] could do the trick (untested)

Finally, you can remove the "@" if you'd like by replacing line.strip().split()[0] by line.strip().split()[0][1:]

ContentLicense: CC BY-SA 2.5

Body:
I've add the same question. In my unit tests I just wanted to make sure decorators were used by given functions/methods.

The decorators were tested separately so I didn't need to test the common logic for each decorated function, just that the decorators were used.

I finally came up with the following helper function:

import inspect

def get_decorators(function):
    """Returns list of decorators names

    Args:
        function (Callable): decorated method/function

    Return:
        List of decorators as strings

    Example:
        Given:

        @my_decorator
        @another_decorator
        def decorated_function():
            pass

        >>> get_decorators(decorated_function)
        ['@my_decorator', '@another_decorator']

    """
    source = inspect.getsource(function)
    index = source.find("def ")
    return [
        line.strip().split()[0]
        for line in source[:index].strip().splitlines()
        if line.strip()[0] == "@"
    ]

With the list comprehension, it is a bit "dense" but it does the trick and in my case it's a test helper function.

It works if you are intrested only in the decorators names, not potential decorator arguments. If you want to support decorators taking arguments, something like line.strip().split()[0].split("(")[0] could do the trick (untested)

Finally, you can remove the "@" if you'd like by replacing line.strip().split()[0] by line.strip().split()[0][1:]


问:
Using server side html+js in phonegap (multiplatform mobile dev)
Phonegap uses html source located in www folder. I was testing what happens if index.html is still in www, but it links to other html that are located in at the server side. It will open the server side html in the web browser instead of handle it as part of the app.

Is there any way to make phonegap work with server side html + js source?

It is not a bad idea if you need to mix usage of libraries (jars + ios libraries), local phonegap html+js with server side dynamic html code (like php output).

thanks.

答: Phonegap is designed to deploy a client, a web app inside a native web view. You can write a server side API for returning any information your app may need and you can modify the DOM using JS. There are great templating solutions out there such as mustache.js. The idea is to write the app fully in JS and retrieve information from the server using any of Ajax implementations in your favourite JS framework. You shouldn't need any dynamic JS. Just information to template and insert into the DOM. </p>

ContentLicense: CC BY-SA 3.0


答:
If you're wanting to see if there is any overlap at all between two arrays, you can do this:

```<code>fun Array<*>.intersects(other: Array<*>) = any { it in other }
</code>```

As mentioned in the comments below, this is O(n^2) so with large arrays, prefer:

```<code>fun Array<*>.intersects(other: Array<*>) = intersect(other.toSet()).isNotEmpty()
</code>```

toSet() is only needed if the second collection is an Array rather than an Iterable like List.

Title: How can I check if an array contains a value of another array?

Body:
I would like to check to see if an array contains a value from another array. For example, I would like to check if the array A contains a value from an array B.

I'm looking for any value not one specific value.

Body:
If you're wanting to see if there is any overlap at all between two arrays, you can do this:

fun Array<*>.intersects(other: Array<*>) = any { it in other }

As mentioned in the comments below, this is O(n^2) so with large arrays, prefer:

fun Array<*>.intersects(other: Array<*>) = intersect(other.toSet()).isNotEmpty()

toSet() is only needed if the second collection is an Array rather than an Iterable like List.


问:
Getting "Bad Request" on the post request to Django Rest-Api using serializers
I am trying to save data into a model using django-rest framework. I have already written the api, it works fine when i access it directly using the url to api. But I get a bad-request error when i try to post data using ajax.
If it is working fine when data is inserted using the api interface, it should work fine when data is inserted using ajax....but instead i am getting a bad request.

here is the AJAX request method(Jquery):

```<code>$("form").submit(function(event){
           event.preventDefault();

            var this_ = $(this);
            var formData =this_.serialize();
            $.ajax({
                url: "/api/forum/posts/{{ post_question.thread_id.id }}/create",
                data: formData,
                method: "POST",
                success: function (data) {
                    console.log("successfully returned");
                    console.log(data);
                    displayPosts();

                },
         })
</code>```

Serializers are as follow, in api/serializers.py :

```<code>class ThreadModelSerializer(serializers.ModelSerializer):
    created_by = UserDisplaySerializer(read_only=True)
    class Meta:
       model = Thread
       fields = '__all__'

class PostModelSerializer(serializers.ModelSerializer):
    posted_by = UserDisplaySerializer(read_only=True)
    class Meta:
       model = Post
       fields = '__all__'
</code>```

Models for the Post and Thread are as follow in models.py:

```<code>class Thread(models.Model):
    thread_subject = models.CharField(max_length=250)
    posted_on = models.DateTimeField(auto_now=True)
    category = models.CharField(max_length=250)
    forum_id = models.ForeignKey(Forum, on_delete=models.CASCADE)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Post(models.Model):
    post_message = models.TextField()
    thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE)
    parent_id = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
    posted_on = models.DateTimeField(auto_now=True)
    posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

</code>```

and finally the API view is like this, in api/views.py:

```<code>class PostCreateApiView(generics.CreateAPIView):
    serializer_class = PostModelSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer, *args, **kwargs):
        thread_id = self.kwargs.get('thread_id', None)
        thread = get_object_or_404(Thread, id=thread_id)
        parent_post = get_object_or_404(Post, thread_id=thread_id, parent_id__isnull=True)

        serializer.save(posted_by=self.request.user, parent_id=parent_post, thread_id=thread)
</code>```

and url route is as follow in api/urls.py :

```<code>    path('posts/<int:thread_id>/create', PostCreateApiView.as_view(), name='post_create'),
</code>```

Hopefully I am able to make the problem statement clear, need help.
When I create a new post using the api url directly, example :

http://localhost:8000/api/forum/posts/4/create

I get no errors and post is successfully inserted in the database.

But when I try to insert the data using the template(ajax), example :

http://localhost:8000/forums/thread/4/

I get a bad request like following :

```<code>Bad Request: /api/forum/posts/4/create
HTTP POST /api/forum/posts/4/create 400 [0.02, 127.0.0.1:40630]
</code>```

Need help, I have tried hard, but can't find the solution.
Awaiting reply. Thanks.

答:
I had the exact same problem as you: Just a 400 Error with no further information.

Although i dont know what your Problem is exactly i can tell you that adding an error function to your ajax request will help you debug it.

The reason is that you are not actually causing a python error, you are just making a request that Django Rest Framework thinks is wrong. It will tell you what is wrong in the response which is returned under a 400 status code and thus not shown in the ajax success function but in the error function.

```<code>$("form").submit(function(event){
       event.preventDefault();

        var this_ = $(this);
        var formData =this_.serialize();
        $.ajax({
            url: "/api/forum/posts/{{ post_question.thread_id.id }}/create",
            data: formData,
            method: "POST",
            success: function (data) {
                console.log("successfully returned");
                console.log(data);
                displayPosts();

            },
            error: function (jqXhr, textStatus, errorThrown) {
                console.log('ERROR')
                console.log(jqXhr)
            },
     })
</code>```

Body:
I am trying to save data into a model using django-rest framework. I have already written the api, it works fine when i access it directly using the url to api. But I get a bad-request error when i try to post data using ajax.
If it is working fine when data is inserted using the api interface, it should work fine when data is inserted using ajax....but instead i am getting a bad request.

here is the AJAX request method(Jquery):

$("form").submit(function(event){
           event.preventDefault();

            var this_ = $(this);
            var formData =this_.serialize();
            $.ajax({
                url: "/api/forum/posts/{{ post_question.thread_id.id }}/create",
                data: formData,
                method: "POST",
                success: function (data) {
                    console.log("successfully returned");
                    console.log(data);
                    displayPosts();

                },
         })

Serializers are as follow, in api/serializers.py :

class ThreadModelSerializer(serializers.ModelSerializer):
    created_by = UserDisplaySerializer(read_only=True)
    class Meta:
       model = Thread
       fields = '__all__'

class PostModelSerializer(serializers.ModelSerializer):
    posted_by = UserDisplaySerializer(read_only=True)
    class Meta:
       model = Post
       fields = '__all__'

Models for the Post and Thread are as follow in models.py:

class Thread(models.Model):
    thread_subject = models.CharField(max_length=250)
    posted_on = models.DateTimeField(auto_now=True)
    category = models.CharField(max_length=250)
    forum_id = models.ForeignKey(Forum, on_delete=models.CASCADE)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Post(models.Model):
    post_message = models.TextField()
    thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE)
    parent_id = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
    posted_on = models.DateTimeField(auto_now=True)
    posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

and finally the API view is like this, in api/views.py:

class PostCreateApiView(generics.CreateAPIView):
    serializer_class = PostModelSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer, *args, **kwargs):
        thread_id = self.kwargs.get('thread_id', None)
        thread = get_object_or_404(Thread, id=thread_id)
        parent_post = get_object_or_404(Post, thread_id=thread_id, parent_id__isnull=True)

        serializer.save(posted_by=self.request.user, parent_id=parent_post, thread_id=thread)

and url route is as follow in api/urls.py :

    path('posts/<int:thread_id>/create', PostCreateApiView.as_view(), name='post_create'),

Hopefully I am able to make the problem statement clear, need help.
When I create a new post using the api url directly, example :

http://localhost:8000/api/forum/posts/4/create

I get no errors and post is successfully inserted in the database.

But when I try to insert the data using the template(ajax), example :

http://localhost:8000/forums/thread/4/

I get a bad request like following :

Bad Request: /api/forum/posts/4/create
HTTP POST /api/forum/posts/4/create 400 [0.02, 127.0.0.1:40630]

Need help, I have tried hard, but can't find the solution.
Awaiting reply. Thanks.

Body:
I had the exact same problem as you: Just a 400 Error with no further information.

Although i dont know what your Problem is exactly i can tell you that adding an error function to your ajax request will help you debug it.

The reason is that you are not actually causing a python error, you are just making a request that Django Rest Framework thinks is wrong. It will tell you what is wrong in the response which is returned under a 400 status code and thus not shown in the ajax success function but in the error function.

$("form").submit(function(event){
       event.preventDefault();

        var this_ = $(this);
        var formData =this_.serialize();
        $.ajax({
            url: "/api/forum/posts/{{ post_question.thread_id.id }}/create",
            data: formData,
            method: "POST",
            success: function (data) {
                console.log("successfully returned");
                console.log(data);
                displayPosts();

            },
            error: function (jqXhr, textStatus, errorThrown) {
                console.log('ERROR')
                console.log(jqXhr)
            },
     })


问:
Unable to start Sonarqube 6.7 on Windows 7
I am unable to run Sonarqube 6.7 on Windows 7.

I have just downloaded it from the site. I'm using JDK 1.8.0_144 as the Java runtime. When I run the "StartSonar.bat" I get the following exception:

wrapper  | --> Wrapper Started as Console
wrapper  | Launching a JVM...
jvm 1    | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
jvm 1    |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
jvm 1    |
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory C:\Tools\sonarqube-6.7\temp
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on /127.0.0.1:9001
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.s.a.p.ProcessLauncherImpl] Launch process[[key='es', ipcIndex=1, logFilenamePrefix=es]] from [C:\Tools\sonarqube-6.
7\elasticsearch]: C:\Java\jdk1.8.0_144\jre\bin\java -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+Always
PreTouch -server -Xss1m -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djna.nosys=true -Djdk.io.permissionsUseCanonicalPath=true -Dio.netty.noUnsafe=true -Dio.
netty.noKeySetOptimization=true -Dio.netty.recycler.maxCapacityPerThread=0 -Dlog4j.shutdownHookEnabled=false -Dlog4j2.disable.jmx=true -Dlog4j.skipJansi=true -X
ms512m -Xmx512m -XX:+HeapDumpOnOutOfMemoryError -Delasticsearch -Des.path.home=C:\Tools\sonarqube-6.7\elasticsearch -cp lib/* org.elasticsearch.bootstrap.Elasti
csearch -Epath.conf=C:\Tools\sonarqube-6.7\temp\conf\es
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.e.p.PluginsService] no modules loaded
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.e.p.PluginsService] loaded plugin [org.elasticsearch.transport.Netty4Plugin]
jvm 1    | 2017.12.11 14:17:22 WARN  app[][o.e.t.n.Netty4Transport] exception caught on transport layer [[id: 0xcd8d6c6a, L:/127.0.0.1:63293 - R:/127.0.0.1:9001
]], closing connection
jvm 1    | io.netty.handler.codec.DecoderException: java.io.StreamCorruptedException: invalid internal transport message format, got (48,54,54,50)
jvm 1    |      at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:459)
jvm 1    |      at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
jvm 1    |      at io.netty.handler.logging.LoggingHandler.channelRead(LoggingHandler.java:241)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
jvm 1    |      at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
jvm 1    |      at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)
jvm 1    |      at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:134)
jvm 1    |      at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644)
jvm 1    |      at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
jvm 1    |      at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
jvm 1    |      at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
jvm 1    |      at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
jvm 1    |      at java.lang.Thread.run(Thread.java:748)
jvm 1    | Caused by: java.io.StreamCorruptedException: invalid internal transport message format, got (48,54,54,50)
jvm 1    |      at org.elasticsearch.transport.TcpTransport.validateMessageHeader(TcpTransport.java:1276)
jvm 1    |      at org.elasticsearch.transport.netty4.Netty4SizeHeaderFrameDecoder.decode(Netty4SizeHeaderFrameDecoder.java:36)
jvm 1    |      at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489)
jvm 1    |      at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428)
jvm 1    |      ... 19 common frames omitted```

Any ideas as to what is happening? Thanks.

答:
I also encountered the same issue. After some troubleshooting, realized that default Elasticsearch port use by SonarQube is already in use in my windows environment

Output of netstat -ao in COMMAND prompt

```<code>Proto  Local Address          Foreign Address      State           PID
TCP    0.0.0.0:9001           UserX:0              LISTENING       4
</code>```

Here is the default Elasticsearch configuration section in sonar.properties

```<code># Elasticsearch port. Default is 9001. Use 0 to get a free port.
# As a security precaution, should be blocked by a firewall and not exposed to the Internet.
# sonar.search.port=9001
</code>```

So , I changed the Elasticsearch port in sonar.properties to 9005 and it worked like a charm. Also you can use the port 0 as instructed here to use a free port.

```<code># Elasticsearch port. Default is 9001. Use 0 to get a free port.
# As a security precaution, should be blocked by a firewall and not exposed to the Internet.
sonar.search.port=9005
</code>```

Body:
I am unable to run Sonarqube 6.7 on Windows 7.

I have just downloaded it from the site. I'm using JDK 1.8.0_144 as the Java runtime. When I run the "StartSonar.bat" I get the following exception:

wrapper  | --> Wrapper Started as Console
wrapper  | Launching a JVM...
jvm 1    | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
jvm 1    |   Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.
jvm 1    |
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory C:\Tools\sonarqube-6.7\temp
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on /127.0.0.1:9001
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.s.a.p.ProcessLauncherImpl] Launch process[[key='es', ipcIndex=1, logFilenamePrefix=es]] from [C:\Tools\sonarqube-6.
7\elasticsearch]: C:\Java\jdk1.8.0_144\jre\bin\java -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+Always
PreTouch -server -Xss1m -Djava.awt.headless=true -Dfile.encoding=UTF-8 -Djna.nosys=true -Djdk.io.permissionsUseCanonicalPath=true -Dio.netty.noUnsafe=true -Dio.
netty.noKeySetOptimization=true -Dio.netty.recycler.maxCapacityPerThread=0 -Dlog4j.shutdownHookEnabled=false -Dlog4j2.disable.jmx=true -Dlog4j.skipJansi=true -X
ms512m -Xmx512m -XX:+HeapDumpOnOutOfMemoryError -Delasticsearch -Des.path.home=C:\Tools\sonarqube-6.7\elasticsearch -cp lib/* org.elasticsearch.bootstrap.Elasti
csearch -Epath.conf=C:\Tools\sonarqube-6.7\temp\conf\es
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.e.p.PluginsService] no modules loaded
jvm 1    | 2017.12.11 14:17:21 INFO  app[][o.e.p.PluginsService] loaded plugin [org.elasticsearch.transport.Netty4Plugin]
jvm 1    | 2017.12.11 14:17:22 WARN  app[][o.e.t.n.Netty4Transport] exception caught on transport layer [[id: 0xcd8d6c6a, L:/127.0.0.1:63293 - R:/127.0.0.1:9001
]], closing connection
jvm 1    | io.netty.handler.codec.DecoderException: java.io.StreamCorruptedException: invalid internal transport message format, got (48,54,54,50)
jvm 1    |      at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:459)
jvm 1    |      at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
jvm 1    |      at io.netty.handler.logging.LoggingHandler.channelRead(LoggingHandler.java:241)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
jvm 1    |      at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1334)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
jvm 1    |      at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
jvm 1    |      at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:926)
jvm 1    |      at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:134)
jvm 1    |      at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:644)
jvm 1    |      at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:579)
jvm 1    |      at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:496)
jvm 1    |      at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:458)
jvm 1    |      at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:858)
jvm 1    |      at java.lang.Thread.run(Thread.java:748)
jvm 1    | Caused by: java.io.StreamCorruptedException: invalid internal transport message format, got (48,54,54,50)
jvm 1    |      at org.elasticsearch.transport.TcpTransport.validateMessageHeader(TcpTransport.java:1276)
jvm 1    |      at org.elasticsearch.transport.netty4.Netty4SizeHeaderFrameDecoder.decode(Netty4SizeHeaderFrameDecoder.java:36)
jvm 1    |      at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:489)
jvm 1    |      at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:428)
jvm 1    |      ... 19 common frames omitted

Any ideas as to what is happening? Thanks.

Body:
I also encountered the same issue. After some troubleshooting, realized that default Elasticsearch port use by SonarQube is already in use in my windows environment

Output of netstat -ao in COMMAND prompt

Proto  Local Address          Foreign Address      State           PID
TCP    0.0.0.0:9001           UserX:0              LISTENING       4

Here is the default Elasticsearch configuration section in sonar.properties

# Elasticsearch port. Default is 9001. Use 0 to get a free port.
# As a security precaution, should be blocked by a firewall and not exposed to the Internet.
# sonar.search.port=9001

So , I changed the Elasticsearch port in sonar.properties to 9005 and it worked like a charm. Also you can use the port 0 as instructed here to use a free port.

# Elasticsearch port. Default is 9001. Use 0 to get a free port.
# As a security precaution, should be blocked by a firewall and not exposed to the Internet.
sonar.search.port=9005


问:
How to prevent my chats from duplicating themselves whenever someone sends a message in Android Studio firebase
I am designing a simple basic chat app using firebase real time database and i've designed everything well, however, i'm facing one sllight issue. My chats keep duplicating themselves on the inbox page (the page whrere the chats are laid out for a user to select which chat he wants to open and start talking).

I've attached an image of what i mean below.
Screenshot of the phone screen

The code i am using to get the chats and display them in the recycler view is given below. I have a directory called Conversations in my DB that saves a user's Id and under it, theres a child of each and every person he chats wit, under  which is the last message and a seen boolean.

Database Structure

The code is given below

```<code> convoref = FirebaseDatabase.getInstance().getReference().child("Conversations").child(currentUid);
</code>```

and then..

```<code>  public void getConvoIds() {
    convoref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for(DataSnapshot convo : dataSnapshot.getChildren()){

                    boolean isMessageSeen = false;
                    String lastMessage = "";

                    if(convo.child("seen").getValue() != null) {
                        isMessageSeen = (boolean) convo.child("seen").getValue();
                    }else{
                        Log.i("nolastseen", "location is null");
                    }

                    if(convo.child("lastMessage").getValue() != null) {
                        lastMessage = convo.child("lastMessage").getValue().toString();
                    }else{
                        Log.i("nolastMessage", "location is null");
                    }

                    Log.i ("the_convo_partner_key", convo.getKey());
                    Log.i ("lastseenmessage", lastMessage);
                    Log.i ("seenstate", String.valueOf(isMessageSeen));
                    FetchConvoInfo(convo.getKey(), isMessageSeen, lastMessage );
                }
            }
        }
</code>```

the fetch convo information functuion is below

```<code>  public void FetchConvoInfo(final String key, final boolean isMessageSeen, final String lastMessage){
        FirebaseDatabase.getInstance().getReference().child("Users").child(key).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                boolean chatExists = false;
                String username = "";
                String thumbnail = "";
                String chatPartner;

                chatPartner = key;

                if(dataSnapshot.child("username").exists()){
                    username = dataSnapshot.child("username").getValue().toString();
                }

                if(dataSnapshot.child("thumbnail").exists()){
                    thumbnail = dataSnapshot.child("thumbnail").getValue().toString();
                }

                ConvoClass obj= new ConvoClass(chatPartner, username, thumbnail, isMessageSeen, lastMessage);
                resultConvos.add(obj);
                mConvoAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}
</code>```

Any help would be greatly appreciated. i cant seem to figure out why the chat duplicates.

答:
In your onDataChanged method, you are going through every child of the dataSnapshot. Each child of the data snapshot indicates a particular conversation of that particular currentUid guy. So when you are going through every child of the dataSnapshot you are adding all its children to the listview or recyclerview(I don't know what you are using. But you are adding it to the adapter). So you are adding the old data again and again whenever some new data must be added. Hence-duplicate data.

There are two common solutions.

The first is naive method. Do what you are doing right now. But while adding an item (chat, you will call it in your case, I think) to the adapter, check if it is already present in the container resultConvos. That will prevent you from adding duplicate chats. I am sure it is obvious to you also why this method is inefficient. You are unnecessarily having to go through every conversation of a person. It takes O(n) time for just adding one item.

The second method is the recommended method. Remove all the code of ValueEventListener. Instead use ChildEventListener. I don't know if you are aware of it. Check this.

ChildEventListener has mainly 4 methods instead of onDataChanged. Among that, what you require here is onChildAdded. Just like your onDataChanged, it has one argument- a data snapshot. But this data snapshot contains only the newly added child, whereas the data snapshot in onDataChanged contains the whole data of the conversations of that particular user (that means the whole list). So using the data snapshot provided by onChildAdded you can directly add only that chat to the adapter, which takes O(1) time.

For more about  ChildEventListener, read that link I attached

Body:
I am designing a simple basic chat app using firebase real time database and i've designed everything well, however, i'm facing one sllight issue. My chats keep duplicating themselves on the inbox page (the page whrere the chats are laid out for a user to select which chat he wants to open and start talking).

I've attached an image of what i mean below.
Screenshot of the phone screen

The code i am using to get the chats and display them in the recycler view is given below. I have a directory called Conversations in my DB that saves a user's Id and under it, theres a child of each and every person he chats wit, under  which is the last message and a seen boolean.

Database Structure

The code is given below

 convoref = FirebaseDatabase.getInstance().getReference().child("Conversations").child(currentUid);

and then..

  public void getConvoIds() {
    convoref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for(DataSnapshot convo : dataSnapshot.getChildren()){

                    boolean isMessageSeen = false;
                    String lastMessage = "";

                    if(convo.child("seen").getValue() != null) {
                        isMessageSeen = (boolean) convo.child("seen").getValue();
                    }else{
                        Log.i("nolastseen", "location is null");
                    }

                    if(convo.child("lastMessage").getValue() != null) {
                        lastMessage = convo.child("lastMessage").getValue().toString();
                    }else{
                        Log.i("nolastMessage", "location is null");
                    }

                    Log.i ("the_convo_partner_key", convo.getKey());
                    Log.i ("lastseenmessage", lastMessage);
                    Log.i ("seenstate", String.valueOf(isMessageSeen));
                    FetchConvoInfo(convo.getKey(), isMessageSeen, lastMessage );
                }
            }
        }

the fetch convo information functuion is below

  public void FetchConvoInfo(final String key, final boolean isMessageSeen, final String lastMessage){
        FirebaseDatabase.getInstance().getReference().child("Users").child(key).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                boolean chatExists = false;
                String username = "";
                String thumbnail = "";
                String chatPartner;

                chatPartner = key;

                if(dataSnapshot.child("username").exists()){
                    username = dataSnapshot.child("username").getValue().toString();
                }

                if(dataSnapshot.child("thumbnail").exists()){
                    thumbnail = dataSnapshot.child("thumbnail").getValue().toString();
                }

                ConvoClass obj= new ConvoClass(chatPartner, username, thumbnail, isMessageSeen, lastMessage);
                resultConvos.add(obj);
                mConvoAdapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}

Any help would be greatly appreciated. i cant seem to figure out why the chat duplicates.


问:
Cancan Undefined Method 'user' Problems
I'm running into problems defining user permissions in my cancan controller:

```<code>class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user

    if user.role? :admin
      can :manage, :all
    else
    can :read, :all
    can :update, User do |user|
      user.try(:user) == user
    end
    end
  end
end
</code>```

This results in a NoMethodError:

```<code>undefined method `user' for #<User:0x000001050914c8>
</code>```

When I try and edit / update a user. Everything else seems just fine.

Any help appreciated

Bob

答:
The problem is that

```<code>user.try(:user) == user
</code>```

is basically trying to execute user.user == user

Looks like you're trying to only let users update the User model attributes if the User instance in question is the logged-in user.

Try this instead:

```<code>can :update, User, :id => user.id
</code>```

Which is saying "Can update the User model when @user.id is the same as the current_user.id."

Your block notation is ambiguous since your block variable |user| is the same as the user passed in to the Ability model.

As a side-note for those still getting a grip on Ruby,

```<code>can :update, User, :id => user.id
</code>```

is the same as:

```<code>can(:update, User, { id: user.id })
</code>```

Title: Cancan Undefined Method 'user' Problems

Body:
I'm running into problems defining user permissions in my cancan controller:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user

    if user.role? :admin
      can :manage, :all
    else
    can :read, :all
    can :update, User do |user|
      user.try(:user) == user
    end
    end
  end
end

This results in a NoMethodError:

undefined method `user' for #<User:0x000001050914c8>

When I try and edit / update a user. Everything else seems just fine.

Any help appreciated

Bob

Body:
The problem is that

user.try(:user) == user

is basically trying to execute user.user == user

Looks like you're trying to only let users update the User model attributes if the User instance in question is the logged-in user.

Try this instead:

can :update, User, :id => user.id

Which is saying "Can update the User model when @user.id is the same as the current_user.id."

Your block notation is ambiguous since your block variable |user| is the same as the user passed in to the Ability model.

As a side-note for those still getting a grip on Ruby,

can :update, User, :id => user.id

is the same as:

can(:update, User, { id: user.id })


问:
Azure Synapse Analysis: Error while accessing the external table
Failed to execute query. Error: File 'https://track2gen2storage.blob.core.windows.net/\sourcedata\sample.csv' cannot be opened because it does not exist or it is used by another process.

we performed these steps:-

```<code>create database SalesdataDemo
use salesdataDemo
-----create master key
CREATE MASTER KEY ENCRYPTION BY PASSWORD = <Password>;
SELECT *
FROM sys.symmetric_keys AS SK
WHERE SK.name = '##MS_DatabaseMasterKey##';

CREATE DATABASE SCOPED CREDENTIAL ADL_User
WITH
IDENTITY = '<client_id>@<OAuth_2.0_Token_EndPoint>',Secret = <Key>

CREATE DATABASE SCOPED CREDENTIAL adls_credential
WITH IDENTITY ='SHARED ACCESS SIGNATURE',
SECRET = <azure_storage_account_key>

CREATE EXTERNAL DATA SOURCE adlsdatasource
WITH
( LOCATION = 'https://track2gen2storage.blob.core.windows.net',
CREDENTIAL = adls_credential
) ;

CREATE EXTERNAL FILE FORMAT adls_csv
WITH (
FORMAT_TYPE = DELIMITEDTEXT,
FORMAT_OPTIONS ( FIELD_TERMINATOR = ',', STRING_DELIMITER = '"', FIRST_ROW = 2 )
);

CREATE EXTERNAL TABLE sampledata ( <ColumnName><Datatype>)
WITH (
LOCATION = '/sourcedata/sample.csv',
DATA_SOURCE = adlsdatasource,
FILE_FORMAT = adls_csv
)

select * from sampledata
</code>```

答:
I think the problem is your external table location is starting with /. Try changing it to:

```<code>CREATE EXTERNAL TABLE sampledata ( <ColumnName><Datatype>)
WITH (
LOCATION = 'sourcedata/sample.csv',
DATA_SOURCE = adlsdatasource,
FILE_FORMAT = adls_csv
)
</code>```

Here is the document you can also take a look for reference:
https://learn.microsoft.com/en-us/azure/synapse-analytics/sql/create-use-external-tables

One more question, why do you need database scoped credential named ADL_User?

Body:
Failed to execute query. Error: File 'https://track2gen2storage.blob.core.windows.net/\sourcedata\sample.csv' cannot be opened because it does not exist or it is used by another process.

we performed these steps:-

create database SalesdataDemo
use salesdataDemo
-----create master key
CREATE MASTER KEY ENCRYPTION BY PASSWORD = <Password>;
SELECT *
FROM sys.symmetric_keys AS SK
WHERE SK.name = '##MS_DatabaseMasterKey##';

CREATE DATABASE SCOPED CREDENTIAL ADL_User
WITH
IDENTITY = '<client_id>@<OAuth_2.0_Token_EndPoint>',Secret = <Key>

CREATE DATABASE SCOPED CREDENTIAL adls_credential
WITH IDENTITY ='SHARED ACCESS SIGNATURE',
SECRET = <azure_storage_account_key>

CREATE EXTERNAL DATA SOURCE adlsdatasource
WITH
( LOCATION = 'https://track2gen2storage.blob.core.windows.net',
CREDENTIAL = adls_credential
) ;

CREATE EXTERNAL FILE FORMAT adls_csv
WITH (
FORMAT_TYPE = DELIMITEDTEXT,
FORMAT_OPTIONS ( FIELD_TERMINATOR = ',', STRING_DELIMITER = '"', FIRST_ROW = 2 )
);

CREATE EXTERNAL TABLE sampledata ( <ColumnName><Datatype>)
WITH (
LOCATION = '/sourcedata/sample.csv',
DATA_SOURCE = adlsdatasource,
FILE_FORMAT = adls_csv
)

select * from sampledata

Body:
I think the problem is your external table location is starting with /. Try changing it to:

CREATE EXTERNAL TABLE sampledata ( <ColumnName><Datatype>)
WITH (
LOCATION = 'sourcedata/sample.csv',
DATA_SOURCE = adlsdatasource,
FILE_FORMAT = adls_csv
)

Here is the document you can also take a look for reference:
https://learn.microsoft.com/en-us/azure/synapse-analytics/sql/create-use-external-tables

One more question, why do you need database scoped credential named ADL_User?


问:
Angular - boolean value doesn't change
I'm facing issue with my app.
I'm trying to create a list of checkboxes, when the checkbox is clicked the value should be true and when clicked again the value should be false. Simple.

Here is my html

```<code>  <li *ngFor="let checkbox of checkboxSelect">
      <div class="checkbox-style">
          <input type="checkbox" name ="{{checkbox.inputName}}"
                [checked]="checkbox.name"
                (change)="checkbox.name= !checkbox.name"/>
             <div class="state">
                 <label>{{checkbox.label}}</label>
             </div>
      </div>
  </li>
</code>```

Here is my component.ts

```<code>showFirstName = true;
showLastName = true;

checkboxSelect: any[] = [{
        label: 'First name',
        name: this.showFirstName,
        inputName: 'showFirstName'
    }, {
        label: 'Last name',
        name: this.showLastName,
        inputName: 'showLastName'

    },
];
</code>```

Everything is working except my 'name' value doesn't change to true/false when clicked.

On the other hand when I put that straight to html without *ngFor it's working

```<code>  <li>
      <div class="checkbox-style">
          <input type="checkbox" name = "firstName"
                [checked]="showFirstName"
                (change)="showFirstName = !showFirstName"/>
             <div class="state">
                 <label>First Name</label>
             </div>
      </div>
  </li>
</code>```

I wasn't so clear, my goal is to display divs depend on true/false

```<code> <div *ngIf="showFirstName" scope="col">First name</div>
<div *ngIf="showLastName" scope="col">Second name</div>
</code>```

But it doesn't change at all.

Does anyone have an idea what's wrong with my code?

答:
Why don't you use Angular ngModel? Then you don't need to define change handler.</p>

```<code><li *ngFor="let checkbox of checkboxSelect">
      <div class="checkbox-style">
          <input type="checkbox" name ="{{checkbox.inputName}}"
                [(ngModel)] ="checkbox.name"/>
             <div class="state">
                 <label>{{checkbox.label}}</label>
             </div>
      </div>
  </li>
</code>```

Title: Angular - boolean value doesn't change

Body:
I'm facing issue with my app.
I'm trying to create a list of checkboxes, when the checkbox is clicked the value should be true and when clicked again the value should be false. Simple.

Here is my html

          <input type="checkbox" name ="{{checkbox.inputName}}"
                [checked]="checkbox.name"
                (change)="checkbox.name= !checkbox.name"/>

                 {{checkbox.label}}

Here is my component.ts

showFirstName = true;
showLastName = true;

checkboxSelect: any[] = [{
        label: 'First name',
        name: this.showFirstName,
        inputName: 'showFirstName'
    }, {
        label: 'Last name',
        name: this.showLastName,
        inputName: 'showLastName'

    },
];

Everything is working except my 'name' value doesn't change to true/false when clicked.

On the other hand when I put that straight to html without *ngFor it's working

          <input type="checkbox" name = "firstName"
                [checked]="showFirstName"
                (change)="showFirstName = !showFirstName"/>

                 First Name

I wasn't so clear, my goal is to display divs depend on true/false

First name

Second name

But it doesn't change at all.

Does anyone have an idea what's wrong with my code?

Body:
Why don't you use Angular ngModel? Then you don't need to define change handler.

<li *ngFor="let checkbox of checkboxSelect">
      <div class="checkbox-style">
          <input type="checkbox" name ="{{checkbox.inputName}}"
                [(ngModel)] ="checkbox.name"/>
             <div class="state">
                 <label>{{checkbox.label}}</label>
             </div>
      </div>
  </li>


问:
Inner array total count in mongodb
I have a journal doc. Which contains details of journal_volumes, journal issues and journal articles. I have to list the journals along with the count of volumes, issues and articles in each journal.

Here is my doc:

```<code>{
"_id" : ObjectId("5c470fc3135edb4413b0ea24"),
"jnl_code" : "KEG",
"jnl_volumes" : [
    {
        "name" : "1",
        "created_date" : "2019-03-01",
        "status" : "0",
        "issue_flag" : "0",
        "jnl_issues" : [
            {
                "issue_name" : "1",
                "created_date" : "2019-03-04",
                "jnl_articles" : [
                    "test",
                    "test2"
                ]
            },
            {
                "issue_name" : "2",
                "created_date" : "2019-03-04",
                "jnl_articles" : [
                    "a"
                ]
            },
            {
                "issue_name" : "3",
                "created_date" : "2019-03-04",
                "jnl_articles" : [
                    "b"
                ]
            },
            {
                "issue_name" : "3",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "Q"
                ]
            }
        ]
    },
    {
        "name" : "2",
        "created_date" : "2019-03-01",
        "status" : "0",
        "issue_flag" : "0",
        "jnl_issues" : [
            {
                "issue_name" : "1",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "W"
                ]
            },
            {
                "issue_name" : "1",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "S"
                ]
            },
            {
                "issue_name" : "1",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "R"
                ]
            },
            {
                "issue_name" : "1",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "R"
                ]
            }
        ]
    },
    {
        "name" : "3",
        "created_date" : "2019-03-05",
        "status" : "0",
        "issue_flag" : "0"
    }
]
</code>```

}

My requirement is to get the count of jnl_volumes, total jnl_issues count and total jnl_articles count in single query..

Thanks to Neil Lunn to redirect me to the similar question (Calculate the count of nested objects with C#
). I referred the answer and wrote a query:

```<code>db.getCollection('rvh_journals').aggregate([
{
    $project: {
        "volumes" : { "$size" : { "$ifNull" : [ "$jnl_volumes", [] ] } },
        "issues" : {
            "$sum" : {
                "$map" : {
                    "input" : "$jnl_volumes",
                    "in": { "$size" : { "$ifNull" : [ "$$this.jnl_issues", [] ] } }
                }
            }
        },
        "articles" : {
            "$sum" : {
                "$map" : {
                    "input" : "$jnl_volumes.jnl_issues.jnl_articles",
                    "in" : { "$size" : { "$ifNull" : [ "$$this", [] ] } }
                }
            }
        }
    }
}
</code>```

])

This returns with an incorrect article count. Actual article count is 9 but the query returns 8

```<code>{
"_id" : ObjectId("5c470fc3135edb4413b0ea24"),
"volumes" : 3,
"issues" : 8,
"articles" : 8
</code>```

}

答:
enter image description here

.itcount() - is showing distinct count.
Need to show total count of count variable which is declare in $group
Currently it is showing based on company.

Title: Inner array total count in mongodb

Body:
I have a journal doc. Which contains details of journal_volumes, journal issues and journal articles. I have to list the journals along with the count of volumes, issues and articles in each journal.

Here is my doc:

{
"_id" : ObjectId("5c470fc3135edb4413b0ea24"),
"jnl_code" : "KEG",
"jnl_volumes" : [
    {
        "name" : "1",
        "created_date" : "2019-03-01",
        "status" : "0",
        "issue_flag" : "0",
        "jnl_issues" : [
            {
                "issue_name" : "1",
                "created_date" : "2019-03-04",
                "jnl_articles" : [
                    "test",
                    "test2"
                ]
            },
            {
                "issue_name" : "2",
                "created_date" : "2019-03-04",
                "jnl_articles" : [
                    "a"
                ]
            },
            {
                "issue_name" : "3",
                "created_date" : "2019-03-04",
                "jnl_articles" : [
                    "b"
                ]
            },
            {
                "issue_name" : "3",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "Q"
                ]
            }
        ]
    },
    {
        "name" : "2",
        "created_date" : "2019-03-01",
        "status" : "0",
        "issue_flag" : "0",
        "jnl_issues" : [
            {
                "issue_name" : "1",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "W"
                ]
            },
            {
                "issue_name" : "1",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "S"
                ]
            },
            {
                "issue_name" : "1",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "R"
                ]
            },
            {
                "issue_name" : "1",
                "created_date" : "2019-03-05",
                "jnl_articles" : [
                    "R"
                ]
            }
        ]
    },
    {
        "name" : "3",
        "created_date" : "2019-03-05",
        "status" : "0",
        "issue_flag" : "0"
    }
]

}

My requirement is to get the count of jnl_volumes, total jnl_issues count and total jnl_articles count in single query..

Thanks to Neil Lunn to redirect me to the similar question (Calculate the count of nested objects with C#
). I referred the answer and wrote a query:

db.getCollection('rvh_journals').aggregate([
{
    $project: {
        "volumes" : { "$size" : { "$ifNull" : [ "$jnl_volumes", [] ] } },
        "issues" : {
            "$sum" : {
                "$map" : {
                    "input" : "$jnl_volumes",
                    "in": { "$size" : { "$ifNull" : [ "$$this.jnl_issues", [] ] } }
                }
            }
        },
        "articles" : {
            "$sum" : {
                "$map" : {
                    "input" : "$jnl_volumes.jnl_issues.jnl_articles",
                    "in" : { "$size" : { "$ifNull" : [ "$$this", [] ] } }
                }
            }
        }
    }
}

])

This returns with an incorrect article count. Actual article count is 9 but the query returns 8

{
"_id" : ObjectId("5c470fc3135edb4413b0ea24"),
"volumes" : 3,
"issues" : 8,
"articles" : 8

}


问:
Is there a way to flip the sign bit of 32 bit float with xor?
I'm trying to flip the sign bit of the least significant float inside of xmm0. I've tried to convert -0 into another xmm register and xor it with xmm0. Unfortunately, I've achieved to flip the sign though the value of my float is gone. Is there a way to use xorps in asm in order to flip the sign bit? I've also seen some posts on stackoverflow exactly doing that but in c.

```<code># xmm0 contains 4 floats
# goal is to flip the sign of the least significant one
mov eax, -0
cvtsi2ss xmm1, eax
xorps    xmm0, xmm1
</code>```

答:
To flip the sign bit of the least significant float inside of xmm0 the solution looks like what Jester posted in the comment section of my question:

```<code>mov eax, 0x80000000
movd xmm1, eax
xorps xmm0, xmm1
</code>```

(credits to Jester and everyone else who helped me. I just wanted to mark this topic as done)

Body:
I'm trying to flip the sign bit of the least significant float inside of xmm0. I've tried to convert -0 into another xmm register and xor it with xmm0. Unfortunately, I've achieved to flip the sign though the value of my float is gone. Is there a way to use xorps in asm in order to flip the sign bit? I've also seen some posts on stackoverflow exactly doing that but in c.

# xmm0 contains 4 floats
# goal is to flip the sign of the least significant one
mov eax, -0
cvtsi2ss xmm1, eax
xorps    xmm0, xmm1

Body:
To flip the sign bit of the least significant float inside of xmm0 the solution looks like what Jester posted in the comment section of my question:

mov eax, 0x80000000
movd xmm1, eax
xorps xmm0, xmm1

(credits to Jester and everyone else who helped me. I just wanted to mark this topic as done)