问:
Spring boot - tests for servlet request/response, how to inject mock classes?
I'm quite new to spring boot and got a basic microservice put together (It accepts a Yelp url and scrapes the images for that restaurant). I thought it would be a good time to write some unit tests, but one thing I'm having trouble with is injecting mock classes into my tests for the servlet request/response.

The code I'm trying to test is quite simple, it looks like this. This is basically the entry point for my service, it accepts a JSON body, extracts a Yelp url from it, and thenYelpRequestController.makeYelpRequest() takes care of scraping the images and returning the image links in an ArrayList.

```<code>@RestController
public class RequestController {

    @PostMapping(value = "/")
    public ArrayList<String> index(@RequestBody String reqBodyString) {

        //my own function to parse the json string
        HashMap<String, String> requestBody = parseReqBodyString(reqBodyString);
        String yelpURL = requestBody.get("yelpURL");

        YelpRequestController yelpRequest = new YelpRequestController(yelpURL);
        ArrayList<String> yelpImgLinks = yelpRequest.makeYelpRequest();
        return yelpImgLinks;
    }

}
</code>```

This is my unit test code. It basically creates a JSON string and sends a request to my RequestController and makes sure the response is okay. It passes right now, but I want the test to just test RequestController and nothing else. Currently it sends the url from the test through YelpRequestController and starts scraping images, which is what I don't want since I just want to isolate the RequestController in this test. I've been trying to mock the YelpRequestController class and return result, but I'm really having a lot of trouble.

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RequestControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void postRequestController() throws Exception {
        ObjectMapping jsonObject = new ObjectMapping();
        jsonObject.setYelpUrl("https://www.yelp.ca/biz/l-industrie-pizzeria-brooklyn");
        Gson gson = new Gson();
        String json = gson.toJson(jsonObject);
        mvc.perform(MockMvcRequestBuilders.post("/")
                .accept(MediaType.APPLICATION_JSON)
                .content(json))
                .andExpect(status().isOk());
    }
}
</code>```

I've been reading about how to use Mockito, and understand how to mock another class and inject it into a class you are testing. But I'm really stuck trying to apply that here. Any help would be appreciated.

答:
Hi I hope my answer can help you a lot. Please see simple below,

```<code>@Autowired
private WebApplicationContext context;

private MockMvc mvc;

@Before
public void setUp() {
    this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
</code>```

Before you start to test you must to initialize the mvc. So you need to setUp your application ready before test. SoringBoot

```<code> private MockMvc mockMvc;

@InjectMocks
private UserController userController;

@Before
public void init(){
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders
            .standaloneSetup(userController)
            .addFilters(new CORSFilter())
            .build();
}
</code>```

SpringMVC you need to inject your controller.

Body:
I'm quite new to spring boot and got a basic microservice put together (It accepts a Yelp url and scrapes the images for that restaurant). I thought it would be a good time to write some unit tests, but one thing I'm having trouble with is injecting mock classes into my tests for the servlet request/response.

The code I'm trying to test is quite simple, it looks like this. This is basically the entry point for my service, it accepts a JSON body, extracts a Yelp url from it, and thenYelpRequestController.makeYelpRequest() takes care of scraping the images and returning the image links in an ArrayList.

@RestController
public class RequestController {

    @PostMapping(value = "/")
    public ArrayList<String> index(@RequestBody String reqBodyString) {

        //my own function to parse the json string
        HashMap<String, String> requestBody = parseReqBodyString(reqBodyString);
        String yelpURL = requestBody.get("yelpURL");

        YelpRequestController yelpRequest = new YelpRequestController(yelpURL);
        ArrayList<String> yelpImgLinks = yelpRequest.makeYelpRequest();
        return yelpImgLinks;
    }

}

This is my unit test code. It basically creates a JSON string and sends a request to my RequestController and makes sure the response is okay. It passes right now, but I want the test to just test RequestController and nothing else. Currently it sends the url from the test through YelpRequestController and starts scraping images, which is what I don't want since I just want to isolate the RequestController in this test. I've been trying to mock the YelpRequestController class and return result, but I'm really having a lot of trouble.

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class RequestControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void postRequestController() throws Exception {
        ObjectMapping jsonObject = new ObjectMapping();
        jsonObject.setYelpUrl("https://www.yelp.ca/biz/l-industrie-pizzeria-brooklyn");
        Gson gson = new Gson();
        String json = gson.toJson(jsonObject);
        mvc.perform(MockMvcRequestBuilders.post("/")
                .accept(MediaType.APPLICATION_JSON)
                .content(json))
                .andExpect(status().isOk());
    }
}

I've been reading about how to use Mockito, and understand how to mock another class and inject it into a class you are testing. But I'm really stuck trying to apply that here. Any help would be appreciated.

Body:
Hi I hope my answer can help you a lot. Please see simple below,

@Autowired
private WebApplicationContext context;

private MockMvc mvc;

@Before
public void setUp() {
    this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}

Before you start to test you must to initialize the mvc. So you need to setUp your application ready before test. SoringBoot

 private MockMvc mockMvc;

@InjectMocks
private UserController userController;

@Before
public void init(){
    MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders
            .standaloneSetup(userController)
            .addFilters(new CORSFilter())
            .build();
}

SpringMVC you need to inject your controller.


来源: stackexchange

问:
Compiler design, creating a language. How?
The Dragon book
is a famous book for designing a compiler. Is there another book like that or a great article about that? And what're the keywords about compilers? I wanna know how a new language is created.</p>

答:
There is a great book on implementing functional languages, just a little bit outdated: http://research.microsoft.com/en-us/um/people/simonpj/papers/pj-lester-book/

Another useful source (on languages in general, not just on compilation) is http://www.amazon.com/Theories-Programming-Languages-John-Reynolds/dp/0521594146

ContentLicense: CC BY-SA 2.5


问:
UICollectionViewCell disappears when settings contentOffset
I have created a UICollectionView that slides its items based on a certain trigger.
I'm trying to animate the cells transition by:

```<code>            UIView.animate(withDuration: 0.4,
                           delay: 0.5, animations: {

                            self.headingsCollectionView.contentOffset = CGPoint(x: x, y: 0)
                            self.headingsCollectionView.reloadItems(at: [indexPath])
            })
</code>```

The animation is successful, the problem is when I change the CollectionView contentOffset the current item disappears instead of scrolling off.

I tried reloading the current item (as suggested here) so it
would stay visible but it's still not working.

I've tried scrollToItemAtIndexPath:atScrollPosition:animated but
it's not animating the item transition.

setContentOffset:animated Tried it, it doesn't animate as well.

答:
Because you are using UIView.animate method, you have to put  self.view.layoutIfNeeded() after programmatically setting contentOffset</p>

```<code> UIView.animate(withDuration: 0.4,
                   delay: 0.5, animations: {

                    self.headingsCollectionView.contentOffset = CGPoint(x: x, y: 0)
                    self.headingsCollectionView.reloadItems(at: [indexPath])
                    self.view.layoutIfNeeded()
    })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created a UICollectionView that slides its items based on a certain trigger.
I'm trying to animate the cells transition by:

            UIView.animate(withDuration: 0.4,
                           delay: 0.5, animations: {

                            self.headingsCollectionView.contentOffset = CGPoint(x: x, y: 0)
                            self.headingsCollectionView.reloadItems(at: [indexPath])
            })

The animation is successful, the problem is when I change the CollectionView contentOffset the current item disappears instead of scrolling off.

I tried reloading the current item (as suggested here) so it
would stay visible but it's still not working.

I've tried scrollToItemAtIndexPath:atScrollPosition:animated but
it's not animating the item transition.

setContentOffset:animated Tried it, it doesn't animate as well.

Body:
Because you are using UIView.animate method, you have to put  self.view.layoutIfNeeded() after programmatically setting contentOffset

 UIView.animate(withDuration: 0.4,
                   delay: 0.5, animations: {

                    self.headingsCollectionView.contentOffset = CGPoint(x: x, y: 0)
                    self.headingsCollectionView.reloadItems(at: [indexPath])
                    self.view.layoutIfNeeded()
    })


问:
How to remove border of the navigationBar in swift?
i've been trying to remove the navigationBars border without luck. I've researched and people seem to tell to set shadowImage and BackgroundImage to nil, but this does not work in my case.

My code

```<code>    self.navigationController?.navigationBar.barTintColor = UIColor(rgba: "#4a5866")
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: ""), forBarMetrics: UIBarMetrics.Default)
    self.navigationController?.navigationBar.shadowImage = UIImage(named: "")
</code>```

illustration:

答:
Only this worked for me,

```<code>self.navigationController?.navigationBar.shadowImage = UIImage()
</code>```

Ref

ContentLicense: CC BY-SA 4.0

Body:
i've been trying to remove the navigationBars border without luck. I've researched and people seem to tell to set shadowImage and BackgroundImage to nil, but this does not work in my case.

My code

    self.navigationController?.navigationBar.barTintColor = UIColor(rgba: "#4a5866")
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: ""), forBarMetrics: UIBarMetrics.Default)
    self.navigationController?.navigationBar.shadowImage = UIImage(named: "")

illustration:

Body:
Only this worked for me,

self.navigationController?.navigationBar.shadowImage = UIImage()

Ref


问:
distinct, max and group by query in sql
I have a dataset like:

```<code>list1     list2
a          e
a          e
b          w
a          e
a          r
b          c
</code>```

I want to find most frequent item in list2 grouped by list1.

```<code>list1     list2    max
  a         e       3
  b         w       1
</code>```

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

```<code>SELECT clf1 as clf2, first(value_count) as max_value
FROM (SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc)
GROUP BY clf2
</code>```

答:
```<code>Select list1 , List2 , count(List2)  AS value_count
From table Group By list1 , List2
</code>```

Title: distinct, max and group by query in sql

Body:
I have a dataset like:

list1     list2
a          e
a          e
b          w
a          e
a          r
b          c

I want to find most frequent item in list2 grouped by list1.

list1     list2    max
  a         e       3
  b         w       1

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

SELECT clf1 as clf2, first(value_count) as max_value
FROM (SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc)
GROUP BY clf2


问:
How to swap multiple values on multiple line on notepad ++
I want to swap this value on notepad++, how can i make it simple and work ? please help me for my job with a lot of data like this.

From this

```<code>1
2
3
11
22
33
</code>```

To This

```<code>1
11
2
22
3
33
</code>```

I just wanna swap the position, like the example , please help me :)
sorry for bad english

答:
You just need to sort lines alphabeticaly:

Menu Edit → Line Operations → Sort Lines in Ascending Order

result:

```<code>1
11
2
22
3
33
</code>```

Body:
I want to swap this value on notepad++, how can i make it simple and work ? please help me for my job with a lot of data like this.

From this

1
2
3
11
22
33

To This

1
11
2
22
3
33

I just wanna swap the position, like the example , please help me :)
sorry for bad english

Body:
You just need to sort lines alphabeticaly:

Menu Edit → Line Operations → Sort Lines in Ascending Order

result:

1
11
2
22
3
33


问:
Handle Leader instance with Spring Boot and Consul
I'm currently working on a spring boot application that uses Consul as a service discovery.

Our web API has multiple instances on different Docker containers and is registered successfully with Consul.

Our main issue now is to elect a leader among our instances and have an automatic re-election in case if the former leader is down.

I have read that Consul provides a Key-Value Store and has lock on those, I was thinking that we could use a key created before hand, then the first instance to read it would have the "lock". If this instance crashes, an other one would acquire the lock and would be detected as the new leader.

I have read several examples, however I've only found command lines examples, not Java/Spring boot implementations.

Can anyone tell me if this idea could do the job and could anyone provide an example with Spring Boot or give me a link to a tutorial please?

I'm a total beginner with Spring Boot and Consul.

Thanks in advance!

答:
Have a look at java library for consul leader election,which has cooked methods for session creation,leader election etc.

https://github.com/advantageous/elekt-consul


问:
Where to put Rule Sets for MSBuild 15 (Build Tools for Visual Studio 2017)
When enabling Static Code Analysis on my builds, I get the following error thrown by MSBuild:

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Microsoft.CSharp.CurrentVersion.targets(134,9): warning MSB3884: Could not find rule set file "AllRules.ruleset". [C:\Program Files\VSTS Agent_work\PATH_TO_MY.csproj]

To get Static Code Analysis working on build agents (only MSBuild, no Visual Studio), for older versions of the build tools one would:

Copy C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Static Analysis Tools\Rule Sets\ to the build server

Add a registry entry pointing to that folder

(see also this bug report)

However, these instructions doesn't work with "Build Tools for Visual Studio 2017". I'd like to know how I resolve this, without needing to copy the rulesets into my own repository or changing anything in my csproj?

Update:

I've tried setting the following registry key, to no avail:

```<code>Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\15.0\Setup\EDev]
"StanDir"="C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\Team Tools\\Static Analysis Tools"
</code>```

Digging through the registry, I've found that the following registry keys. On my machine I've installed both VS2017 Build Tools and Test Agent, and it seems like this points to the latter, which I have installed after installed Build Tools:

```<code>Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7]
"15.0"="C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\TestAgent\\"
"14.0"="C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\"
</code>```

Update 2:

Both answers mention the file Microsoft.CodeAnalysis.Targets. However this file is not present on my build server. I've tried copying this folder over from my VS2017 installation:

```<code>from: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\CodeAnalysis
to: C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Microsoft\VisualStudio\v15.0\CodeAnalysis
</code>```

However besides the rulesets not being found, it now also throws errors about being unable to find Microsoft.WebApplication.targets:

XXX.csproj(296,11): error MSB4226: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuil
  d\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets" was not found. Also, tried to find "WebApplications\Microsoft.WebApplication.targets" in the fallback search path(s) for $(VSToo
  lsPath) - "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0" . These search paths are defined in "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe.Config".
   Confirm that the path in the  declaration is correct, and that the file exists on disk in one of the search paths.

答:
Update:

Based on my test, you don't need to change anything manually, just need to install the default components of Build Tools for VS2017, then the necessary files will be added automatically.

Old:

Regarding default folder of code analysis files, you can check Microsoft.CodeAnalysis.targets file:

```<code><PropertyGroup>
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'=='' and Exists('$(VsInstallRoot)\Team Tools\Static Analysis Tools\')">$(VsInstallRoot)\Team Tools\Static Analysis Tools\</CodeAnalysisStaticAnalysisDirectory>
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>
    <!-- If we didn't find the first registry path, assume we're in a 64bit process. -->
    <!-- read registry from Wow6432Node -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>

    <!-- if we didn't find the registry path yet, then try Win8 Express location -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Microsoft\VSWinExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>
    <!-- If we didn't find the registry path yet, then try Win8 Express 64-bit location -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VSWinExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>

    <!-- If we didn't find the registry path yet, try WP Express locations -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Microsoft\VPDExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>
    <!-- If we didn't find the registry path yet, try WP Express 64-bit locations -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VPDExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>

    <!-- If we didn't find the registry path yet, try WD Express locations -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Microsoft\WDExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>
    <!-- If we didn't find the registry path yet, try WD Express 64-bit locations -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\WDExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>

    <!-- Default rule set search paths -->
    <CodeAnalysisRuleSetDirectories Condition=
            "'$(CodeAnalysisIgnoreBuiltInRuleSets)'!='true' and
             '$(CodeAnalysisStaticAnalysisDirectory)'!=''">$(CodeAnalysisRuleSetDirectories);$(CodeAnalysisStaticAnalysisDirectory)\Rule Sets</CodeAnalysisRuleSetDirectories>

    <!--
         In scenario where we run CA from command-line , we don't get "CodeAnalysisVSSku" variable passed by the IDE, so in case of Express-only installation
         we attempt to load rule sets that are only present on Pro and above - and fail. Let's assume we're in "Express" mode if the Pro+ rule set doesn't exist.
     -->
    <CodeAnalysisVSSku Condition="'$(CodeAnalysisVSSku)'=='' and !Exists('$(CodeAnalysisStaticAnalysisDirectory)\Rule Sets\NativeRecommendedRules.ruleset')">Express</CodeAnalysisVSSku>
  </PropertyGroup>
</code>```

Based on the code, you just need to put the code analysis rule files in $(VsInstallRoot)\Team Tools\Static Analysis Tools folder and the value of $(VsInstallRoot) is C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools if you just install Build Tools for Visual Studio 2017 on the build server.

To conclude, you just need to put rule files in C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Team Tools\Static Analysis Tools folder.

Body:
When enabling Static Code Analysis on my builds, I get the following error thrown by MSBuild:

C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Microsoft.CSharp.CurrentVersion.targets(134,9): warning MSB3884: Could not find rule set file "AllRules.ruleset". [C:\Program Files\VSTS Agent_work\PATH_TO_MY.csproj]

To get Static Code Analysis working on build agents (only MSBuild, no Visual Studio), for older versions of the build tools one would:

Copy C:\Program Files (x86)\Microsoft Visual Studio 14.0\Team Tools\Static Analysis Tools\Rule Sets\ to the build server

Add a registry entry pointing to that folder

(see also this bug report)

However, these instructions doesn't work with "Build Tools for Visual Studio 2017". I'd like to know how I resolve this, without needing to copy the rulesets into my own repository or changing anything in my csproj?

Update:

I've tried setting the following registry key, to no avail:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\15.0\Setup\EDev]
"StanDir"="C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\Team Tools\\Static Analysis Tools"

Digging through the registry, I've found that the following registry keys. On my machine I've installed both VS2017 Build Tools and Test Agent, and it seems like this points to the latter, which I have installed after installed Build Tools:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7]
"15.0"="C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\TestAgent\\"
"14.0"="C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\"

Update 2:

Both answers mention the file Microsoft.CodeAnalysis.Targets. However this file is not present on my build server. I've tried copying this folder over from my VS2017 installation:

from: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\CodeAnalysis
to: C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\Microsoft\VisualStudio\v15.0\CodeAnalysis

However besides the rulesets not being found, it now also throws errors about being unable to find Microsoft.WebApplication.targets:

XXX.csproj(296,11): error MSB4226: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuil
  d\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets" was not found. Also, tried to find "WebApplications\Microsoft.WebApplication.targets" in the fallback search path(s) for $(VSToo
  lsPath) - "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v15.0" . These search paths are defined in "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\MSBuild.exe.Config".
   Confirm that the path in the  declaration is correct, and that the file exists on disk in one of the search paths.

Body:
Update:

Based on my test, you don't need to change anything manually, just need to install the default components of Build Tools for VS2017, then the necessary files will be added automatically.

Old:

Regarding default folder of code analysis files, you can check Microsoft.CodeAnalysis.targets file:

<PropertyGroup>
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'=='' and Exists('$(VsInstallRoot)\Team Tools\Static Analysis Tools\')">$(VsInstallRoot)\Team Tools\Static Analysis Tools\</CodeAnalysisStaticAnalysisDirectory>
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>
    <!-- If we didn't find the first registry path, assume we're in a 64bit process. -->
    <!-- read registry from Wow6432Node -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>

    <!-- if we didn't find the registry path yet, then try Win8 Express location -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Microsoft\VSWinExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>
    <!-- If we didn't find the registry path yet, then try Win8 Express 64-bit location -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VSWinExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>

    <!-- If we didn't find the registry path yet, try WP Express locations -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Microsoft\VPDExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>
    <!-- If we didn't find the registry path yet, try WP Express 64-bit locations -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VPDExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>

    <!-- If we didn't find the registry path yet, try WD Express locations -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Microsoft\WDExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>
    <!-- If we didn't find the registry path yet, try WD Express 64-bit locations -->
    <CodeAnalysisStaticAnalysisDirectory Condition="'$(CodeAnalysisStaticAnalysisDirectory)'==''">$(Registry:HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\WDExpress\15.0\Setup\EDev@StanDir)</CodeAnalysisStaticAnalysisDirectory>

    <!-- Default rule set search paths -->
    <CodeAnalysisRuleSetDirectories Condition=
            "'$(CodeAnalysisIgnoreBuiltInRuleSets)'!='true' and
             '$(CodeAnalysisStaticAnalysisDirectory)'!=''">$(CodeAnalysisRuleSetDirectories);$(CodeAnalysisStaticAnalysisDirectory)\Rule Sets</CodeAnalysisRuleSetDirectories>

    <!--
         In scenario where we run CA from command-line , we don't get "CodeAnalysisVSSku" variable passed by the IDE, so in case of Express-only installation
         we attempt to load rule sets that are only present on Pro and above - and fail. Let's assume we're in "Express" mode if the Pro+ rule set doesn't exist.
     -->
    <CodeAnalysisVSSku Condition="'$(CodeAnalysisVSSku)'=='' and !Exists('$(CodeAnalysisStaticAnalysisDirectory)\Rule Sets\NativeRecommendedRules.ruleset')">Express</CodeAnalysisVSSku>
  </PropertyGroup>

Based on the code, you just need to put the code analysis rule files in $(VsInstallRoot)\Team Tools\Static Analysis Tools folder and the value of $(VsInstallRoot) is C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools if you just install Build Tools for Visual Studio 2017 on the build server.

To conclude, you just need to put rule files in C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Team Tools\Static Analysis Tools folder.


问:
How to add providers to Injector dynamically?
Each component can specify new Providers using its providers property in ComponentMetadata.

Is there a way to specify providers dynamically from, say, constructor of the component?

答:
Below are 3 broader steps you need to follow to implement dynamic providers. Please note i have commented many part of the code so that we focus on the main answer. If you want to see detailed step refer this Angular tutorial

Step 1 :- Create the collection of the providers

Create the collection and you can use the push method to add DI objects dynamically.

```<code>var providerscoll:any = [];
providerscoll.push({ provide: "1", useClass: DialogLogger });
providerscoll.push({ provide: "2", useClass: ConsoleLogger });
</code>```

Step 2 :- Provide the providers collection in "NgModule" .

Please see the Square bracket syntax.

```<code>@NgModule({
    // code removed for clarity
    providers: [providerscoll]
})
export class MainModuleLibrary { }
</code>```

Step 3 :- Get the Injector object in constructor

Get injector object in the constructor using DI and you can then look up using the "Get" method and the token. So if you provide "1" then you get something and if you provide "2" you get something.

```<code>// code removed for clarity
import {  Injector } from '@angular/core';
// code removed for clarity
export class CustomerComponent {
constructor(public injector: Injector){
        this.logger = this.injector.get("2");
    }
}
</code>```

Body:
Below are 3 broader steps you need to follow to implement dynamic providers. Please note i have commented many part of the code so that we focus on the main answer. If you want to see detailed step refer this Angular tutorial

Step 1 :- Create the collection of the providers

Create the collection and you can use the push method to add DI objects dynamically.

var providerscoll:any = [];
providerscoll.push({ provide: "1", useClass: DialogLogger });
providerscoll.push({ provide: "2", useClass: ConsoleLogger });

Step 2 :- Provide the providers collection in "NgModule" .

Please see the Square bracket syntax.

@NgModule({
    // code removed for clarity
    providers: [providerscoll]
})
export class MainModuleLibrary { }

Step 3 :- Get the Injector object in constructor

Get injector object in the constructor using DI and you can then look up using the "Get" method and the token. So if you provide "1" then you get something and if you provide "2" you get something.

// code removed for clarity
import {  Injector } from '@angular/core';
// code removed for clarity
export class CustomerComponent {
constructor(public injector: Injector){
        this.logger = this.injector.get("2");
    }
}


问:
C pragma omp parallel
I'm just started with OpenMP and I need help.

I have a program and I need to parallelize it. This is what I have:

```<code>#include <stdio.h>
#include <sys/time.h>
#include <omp.h>

#define N1 3000000
#define it 5

struct timeval  t0, t1;

int i, itera_kop;

int A[N1], B[N1];

void Exe_Denbora(char * pTestu, struct timeval *pt0, struct timeval *pt1)
{
  double tej;

  tej = (pt1->tv_sec - pt0->tv_sec) + (pt1->tv_usec - pt0->tv_usec) / 1e6;
  printf("%s = %10.3f ms (%d hari)\n",pTestu, tej*1000, omp_get_max_threads());
}

void sum(char * pTestu, int *b, int n)
{
  double bat=0;
  int i;

  for (i=0; i<n; i++) bat+=b[i];
  printf ("sum: %.1f\n",bat);
}

main ()
{
  for (itera_kop=1;itera_kop<it;itera_kop++)
  {
    for(i=0; i<N1; i++)
    {
     A[i] = 1;
     B[i] = 3;
    }
    gettimeofday(&t0, 0);
    #pragma omp parallel for private(i)
    for(i=2; i<N1; i++)
    {
      A[i] = 35 / (7/B[i-1] + 2/A[i]);
      B[i] = B[i] / (A[i-1]+2) + 3 / B[i];
    }
    gettimeofday(&t1, 0);
    Exe_Denbora("T1",&t0,&t1);
    printf ("\n");
  }

  printf("\n\n");
  sum("A",A,N1);
  sum("B",B,N1);

}
</code>```

If I execute the code without using #pragma omp parallel for I get:

```<code>A sum: 9000005.5

B sum: 3000005.5
</code>```

But if I try to parallelize the code I get:

```<code>A sum: 9000284.0

B sum: 3000036.0
</code>```

using 32 threads.

I would like to know why I can't parallelize the code that way

答:
As you are likely aware, your problem is in this for loop. You have dependency between the two lines in the loop.

```<code>for(i=2; i<N1; i++)
{
  A[i] = 35 / (7/B[i-1] + 2/A[i]);
  B[i] = B[i] / (A[i-1]+2) + 3 / B[i];
}
</code>```

We cannot know the order in which any given thread reaches one of those two lines. Therefore, as an example, when the second line executes, the value in B[i] will be different depending on if A[i-1] has already been changed or not by another thread. The same can be said of A[i]'s dependency on the value of B[i-1]. A short and clear explanation of dependencies can be found at the following link. I would recommend you take a look if this still is not clear. https://scs.senecac.on.ca/~gpu621/pages/content/omp_2.html

Title: C pragma omp parallel

Body:
I'm just started with OpenMP and I need help.

I have a program and I need to parallelize it. This is what I have:

#include <stdio.h>
#include <sys/time.h>
#include <omp.h>

#define N1 3000000
#define it 5

struct timeval  t0, t1;

int i, itera_kop;

int A[N1], B[N1];

void Exe_Denbora(char * pTestu, struct timeval *pt0, struct timeval *pt1)
{
  double tej;

  tej = (pt1->tv_sec - pt0->tv_sec) + (pt1->tv_usec - pt0->tv_usec) / 1e6;
  printf("%s = %10.3f ms (%d hari)\n",pTestu, tej*1000, omp_get_max_threads());
}

void sum(char * pTestu, int *b, int n)
{
  double bat=0;
  int i;

  for (i=0; i<n; i++) bat+=b[i];
  printf ("sum: %.1f\n",bat);
}

main ()
{
  for (itera_kop=1;itera_kop<it;itera_kop++)
  {
    for(i=0; i<N1; i++)
    {
     A[i] = 1;
     B[i] = 3;
    }
    gettimeofday(&t0, 0);
    #pragma omp parallel for private(i)
    for(i=2; i<N1; i++)
    {
      A[i] = 35 / (7/B[i-1] + 2/A[i]);
      B[i] = B[i] / (A[i-1]+2) + 3 / B[i];
    }
    gettimeofday(&t1, 0);
    Exe_Denbora("T1",&t0,&t1);
    printf ("\n");
  }

  printf("\n\n");
  sum("A",A,N1);
  sum("B",B,N1);

}

If I execute the code without using #pragma omp parallel for I get:

A sum: 9000005.5

B sum: 3000005.5

But if I try to parallelize the code I get:

A sum: 9000284.0

B sum: 3000036.0

using 32 threads.

I would like to know why I can't parallelize the code that way

Body:
As you are likely aware, your problem is in this for loop. You have dependency between the two lines in the loop.

for(i=2; i<N1; i++)
{
  A[i] = 35 / (7/B[i-1] + 2/A[i]);
  B[i] = B[i] / (A[i-1]+2) + 3 / B[i];
}

We cannot know the order in which any given thread reaches one of those two lines. Therefore, as an example, when the second line executes, the value in B[i] will be different depending on if A[i-1] has already been changed or not by another thread. The same can be said of A[i]'s dependency on the value of B[i-1]. A short and clear explanation of dependencies can be found at the following link. I would recommend you take a look if this still is not clear. https://scs.senecac.on.ca/~gpu621/pages/content/omp_2.html


问:
Model Import error
I'm getting the following error when trying to import models into my google app engine app:

```<code>Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
  File "/base/data/home/apps/app/0-1.405524594589080344/main.py", line 6, in <module>
from BaseHandler import BaseHandler
  File "/base/data/home/apps/app/0-1.405524594589080344/BaseHandler.py", line 26, in <module>
from user.database import u_db
  File "/base/data/home/apps/app/0-1.405524594589080344/user/database/u_db.py", line 12, in <module>
from clubs.database import fed_db, league_db, club_db
  File "/base/data/home/apps/app/0-1.405524594589080344/clubs/database/fed_db.py", line 6, in <module>
from events.database import e_db
  File "/base/data/home/apps/app/0-1.405524594589080344/events/database/e_db.py", line 7, in <module>
from user.database import u_db
ImportError: cannot import name u_db
</code>```

I renamed the model files and their container folders, and can see this has something to do with Path.

I would really appreciate some help in fixing this as I am stuck.

Thanks.

答:
You have a circular dependency in your models, see these snippets in your traceback:

```<code>  File "/base/data/home/apps/app/0-1.405524594589080344/BaseHandler.py", line 26, in <module>
from user.database import u_db

...

  File "/base/data/home/apps/app/0-1.405524594589080344/events/database/e_db.py", line 7, in <module>
from user.database import u_db
</code>```

You need to fix that. Often it can be done simply by moving the import statements inside the functions where they are actually needed instead of just at the top of the file. But not always.

Title: Model Import error

Body:
I'm getting the following error when trying to import models into my google app engine app:

Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
  File "/base/data/home/apps/app/0-1.405524594589080344/main.py", line 6, in <module>
from BaseHandler import BaseHandler
  File "/base/data/home/apps/app/0-1.405524594589080344/BaseHandler.py", line 26, in <module>
from user.database import u_db
  File "/base/data/home/apps/app/0-1.405524594589080344/user/database/u_db.py", line 12, in <module>
from clubs.database import fed_db, league_db, club_db
  File "/base/data/home/apps/app/0-1.405524594589080344/clubs/database/fed_db.py", line 6, in <module>
from events.database import e_db
  File "/base/data/home/apps/app/0-1.405524594589080344/events/database/e_db.py", line 7, in <module>
from user.database import u_db
ImportError: cannot import name u_db

I renamed the model files and their container folders, and can see this has something to do with Path.

I would really appreciate some help in fixing this as I am stuck.

Thanks.

Body:
You have a circular dependency in your models, see these snippets in your traceback:

  File "/base/data/home/apps/app/0-1.405524594589080344/BaseHandler.py", line 26, in <module>
from user.database import u_db

...

  File "/base/data/home/apps/app/0-1.405524594589080344/events/database/e_db.py", line 7, in <module>
from user.database import u_db

You need to fix that. Often it can be done simply by moving the import statements inside the functions where they are actually needed instead of just at the top of the file. But not always.


问:
Is there a fast parallel "for" loop in Perl 6?
Given some code which does a bit of math/casting for each number from 1 to 500000, we have options:

Simple for loop: for ^500000 -> $i { my $result = ($i ** 2).Str; }. In my unscientific benchmark, this takes 2.8 seconds.

The most canonical parallel version does each bit of work in a Promise, then waits for the result. await do for ^500000 -> $i { start { my $result = ($i ** 2).Str; } } takes 19 seconds. This is slow! Creating a new promise must have too much overhead to be worthwhile for such a simple computation.

Using a parallel map operation is fairly fast. At 2.0 seconds, the operation seems barely slow enough to take advantage of parallelization: (^500000).race.map: -> $i { my $result = ($i ** 2).Str; }

The third option seems best. Unfortunately, it reads like a hack. We should not be writing map code for iteration in sink context, because others that read "map" in the source may assume the purpose is to build a list, which isn't our intent at all. It's poor communication to use map this way.

Is there any canonical fast way to use Perl 6's built in concurrency? A hyper operator would be perfect if it could accept a block instead of only functions:

```<code>(^500000)».(-> $i { my $result = ($i ** 2).Str; }) # No such method 'CALL-ME' for invocant of type 'Int'
</code>```

答:
On my PC, this is a bit (~15%) faster than the naive loop:

```<code>(^500_000).hyper(batch => 100_000).map(-> $i { my $result = ($i ** 2).Str; })
</code>```

Since the computation inside the loop is really fast, typically the cost of parallelization and synchronization dwarfs any gains you get from it. The only remedy is a large batch size.

Update: with a batch size of 200_000 I get slightly better results (another few percent faster).

Body:
Given some code which does a bit of math/casting for each number from 1 to 500000, we have options:

Simple for loop: for ^500000 -> $i { my $result = ($i ** 2).Str; }. In my unscientific benchmark, this takes 2.8 seconds.

The most canonical parallel version does each bit of work in a Promise, then waits for the result. await do for ^500000 -> $i { start { my $result = ($i ** 2).Str; } } takes 19 seconds. This is slow! Creating a new promise must have too much overhead to be worthwhile for such a simple computation.

Using a parallel map operation is fairly fast. At 2.0 seconds, the operation seems barely slow enough to take advantage of parallelization: (^500000).race.map: -> $i { my $result = ($i ** 2).Str; }

The third option seems best. Unfortunately, it reads like a hack. We should not be writing map code for iteration in sink context, because others that read "map" in the source may assume the purpose is to build a list, which isn't our intent at all. It's poor communication to use map this way.

Is there any canonical fast way to use Perl 6's built in concurrency? A hyper operator would be perfect if it could accept a block instead of only functions:

(^500000)».(-> $i { my $result = ($i ** 2).Str; }) # No such method 'CALL-ME' for invocant of type 'Int'

Body:
On my PC, this is a bit (~15%) faster than the naive loop:

(^500_000).hyper(batch => 100_000).map(-> $i { my $result = ($i ** 2).Str; })

Since the computation inside the loop is really fast, typically the cost of parallelization and synchronization dwarfs any gains you get from it. The only remedy is a large batch size.

Update: with a batch size of 200_000 I get slightly better results (another few percent faster).


问:
CDI injectionpoint @httpparam problem
I follow the Weld's doc

in the section 4.11. The InjectionPoint object

There is a very interesting example about how to obtain the http parameter using CDI

but i copy-pasted the code into netbeans, everything compiles, but has an deployment error

Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Injection point has unsatisfied dependencies.  Injection point:  parameter 1 of java.lang.String com.test.HttpParamProducer.getParamValue(javax.enterprise.inject.spi.InjectionPoint,javax.servlet.ServletRequest);  Qualifiers:  [@javax.enterprise.inject.Default()]

how to solve this problem???

```<code>public class HttpParamProducer {

   @HttpParam("")
   @Produces
   String getParamValue(
           InjectionPoint ip, ServletRequest request) {

      return request.getParameter(ip.getAnnotated().getAnnotation(HttpParam.class).value());

   }
}
</code>```

答: Every parameter on a producer method is injected, and none of your beans (including producers) provides the API type ServletRequest to satisfy this injection point.</p>

Title: CDI injectionpoint @httpparam problem

Body:
I follow the Weld's doc

in the section 4.11. The InjectionPoint object

There is a very interesting example about how to obtain the http parameter using CDI

but i copy-pasted the code into netbeans, everything compiles, but has an deployment error

Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408 Injection point has unsatisfied dependencies.  Injection point:  parameter 1 of java.lang.String com.test.HttpParamProducer.getParamValue(javax.enterprise.inject.spi.InjectionPoint,javax.servlet.ServletRequest);  Qualifiers:  [@javax.enterprise.inject.Default()]

how to solve this problem???

public class HttpParamProducer {

   @HttpParam("")
   @Produces
   String getParamValue(
           InjectionPoint ip, ServletRequest request) {

      return request.getParameter(ip.getAnnotated().getAnnotation(HttpParam.class).value());

   }
}


问:
Count and Replace Conditions in SQL
The requirements I have are as follows:
-names of all recording artists
-number of rock songs each artist sings
-list ordered so that the artist with the least number of rock songs appears first

*Note that some artists may not sing any rock songs, but should still be included in the list.

This should be done in a single query that obtains these results.

Make sure to eliminate unneeded columns from the result set, and to name your columns something user‐friendly and human readable.

This is what I have done so far:

```<code>SELECT recording_artist.artist_name AS "Artist Name", Musical_genre.musical_genre AS "Genre",
        COUNT(Song.song_id) AS "Number of Songs"
FROM Album
JOIN recording_artist
    ON recording_artist.recording_artist_id = album.recording_artist_id
JOIN musical_genre
    ON musical_genre.musical_genre_id = album.musical_genre_id
JOIN Song
    ON Album.album_id = Song.album_id
GROUP BY recording_artist.artist_name, Musical_genre.musical_genre
ORDER BY "Number of Songs" ASC
</code>```

Which shows me the 2 artist names who have rock songs, the column showing rock genre, and the number of rock songs each artist sings.

I can't figure out how to actually show those without rock songs as having 0 rock songs.

If I remove the WHERE command, it shows all songs and their count within each song genre, but still no way of setting anything but rock to 0. That's what I need help understanding.

EDIT: I'm using Microsoft SQL Server.

EDIT: This is the output with the edit in red of what I need it to be. I need the total # of songs to represent the # of rock songs, and if the singer doesn't sing rock songs, I still need to list them and their value for # of songs to be 0 or NULL.

output table

答:
You can try this.</p>

```<code>SELECT recording_artist.artist_name AS "Artist Name", Musical_genre.musical_genre AS "Genre",
        COUNT(Song.song_id) AS "Number of Songs"
FROM Album
JOIN recording_artist
    ON recording_artist.recording_artist_id = album.recording_artist_id
LEFT JOIN musical_genre
    ON musical_genre.musical_genre_id = album.musical_genre_id
       AND Musical_genre.musical_genre = 'Rock
LEFT JOIN Song
    ON Album.album_id = Song.album_id
GROUP BY recording_artist.artist_name, Musical_genre.musical_genre
ORDER BY "Number of Songs" ASC
</code>```

Title: Count and Replace Conditions in SQL

Body:
The requirements I have are as follows:
-names of all recording artists
-number of rock songs each artist sings
-list ordered so that the artist with the least number of rock songs appears first

*Note that some artists may not sing any rock songs, but should still be included in the list.

This should be done in a single query that obtains these results.

Make sure to eliminate unneeded columns from the result set, and to name your columns something user‐friendly and human readable.

This is what I have done so far:

SELECT recording_artist.artist_name AS "Artist Name", Musical_genre.musical_genre AS "Genre",
        COUNT(Song.song_id) AS "Number of Songs"
FROM Album
JOIN recording_artist
    ON recording_artist.recording_artist_id = album.recording_artist_id
JOIN musical_genre
    ON musical_genre.musical_genre_id = album.musical_genre_id
JOIN Song
    ON Album.album_id = Song.album_id
GROUP BY recording_artist.artist_name, Musical_genre.musical_genre
ORDER BY "Number of Songs" ASC

Which shows me the 2 artist names who have rock songs, the column showing rock genre, and the number of rock songs each artist sings.

I can't figure out how to actually show those without rock songs as having 0 rock songs.

If I remove the WHERE command, it shows all songs and their count within each song genre, but still no way of setting anything but rock to 0. That's what I need help understanding.

EDIT: I'm using Microsoft SQL Server.

EDIT: This is the output with the edit in red of what I need it to be. I need the total # of songs to represent the # of rock songs, and if the singer doesn't sing rock songs, I still need to list them and their value for # of songs to be 0 or NULL.

output table

Body:
You can try this.

SELECT recording_artist.artist_name AS "Artist Name", Musical_genre.musical_genre AS "Genre",
        COUNT(Song.song_id) AS "Number of Songs"
FROM Album
JOIN recording_artist
    ON recording_artist.recording_artist_id = album.recording_artist_id
LEFT JOIN musical_genre
    ON musical_genre.musical_genre_id = album.musical_genre_id
       AND Musical_genre.musical_genre = 'Rock
LEFT JOIN Song
    ON Album.album_id = Song.album_id
GROUP BY recording_artist.artist_name, Musical_genre.musical_genre
ORDER BY "Number of Songs" ASC


问:
Passing Side Input in PCollection Partition
I want to pass a sideInput in PCollection Partition and On basis of that, i need to Divide my PCollection is their anyway....

```<code>PCollectionList<TableRow> part = merged.apply(Partition.of(Pcollection Count Function Called, new PartitionFn<TableRow>(){

                                        @Override
                                        public int partitionFor(TableRow arg0, int arg1) {

                                            return 0;
                                        }

                                    }));
</code>```

Any Other Way through Which I Can Partition My PCollection

//Without Dynamic destination partitioning BigQuery table

```<code>merge.apply("write into target", BigQueryIO.writeTableRows()
                                         .to(new SerializableFunction<ValueInSingleWindow<TableRow>, TableDestination>() {
                                                @Override
                                                public TableDestination apply(ValueInSingleWindow<TableRow> value) {
                                                       TableRow row = value.getValue();
                                                       TableReference reference = new TableReference();
                                                       reference.setProjectId("XYZ");
                                                       reference.setDatasetId("ABC");
                                                       System.out.println("date of row " + row.get("authorized_transaction_date_yyyymmdd").toString());
                                                       LOG.info("date of row "+
                                                       row.get("authorized_transaction_date_yyyymmdd").toString());
                                                       String str = row.get("authorized_transaction_date_yyyymmdd").toString();
                                                       str = str.substring(0, str.length() - 2) + "01";
                                                       System.out.println("str value " + str);
                                                       LOG.info("str value " + str);
                                                       reference.setTableId("TargetTable$" + str);
                                                       return new TableDestination(reference, null);
                                                }
                                         }).withFormatFunction(new SerializableFunction<TableRow, TableRow>() {
                                                @Override
                                                public TableRow apply(TableRow input) {
                                                       LOG.info("format function:"+input.toString());

                                                       return input;
                                                }
                                         })

                                         .withSchema(schema1).withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)
                                         .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED));
</code>```

Now I have to use Dynamic Destination Any Solution.Insted Of this and have to Do Partition.

答: Based on seeing TableRow in your code, I suspect that you want to write a PCollection to BigQuery, sending different elements to different BigQuery tables. BigQueryIO.write() already provides a method to do that, using BigQueryIO.write().to(DynamicDestinations). See Writing different values to different BigQuery tables in Apache Beam.

Body:
I want to pass a sideInput in PCollection Partition and On basis of that, i need to Divide my PCollection is their anyway....

PCollectionList<TableRow> part = merged.apply(Partition.of(Pcollection Count Function Called, new PartitionFn<TableRow>(){

                                        @Override
                                        public int partitionFor(TableRow arg0, int arg1) {

                                            return 0;
                                        }

                                    }));

Any Other Way through Which I Can Partition My PCollection

//Without Dynamic destination partitioning BigQuery table

merge.apply("write into target", BigQueryIO.writeTableRows()
                                         .to(new SerializableFunction<ValueInSingleWindow<TableRow>, TableDestination>() {
                                                @Override
                                                public TableDestination apply(ValueInSingleWindow<TableRow> value) {
                                                       TableRow row = value.getValue();
                                                       TableReference reference = new TableReference();
                                                       reference.setProjectId("XYZ");
                                                       reference.setDatasetId("ABC");
                                                       System.out.println("date of row " + row.get("authorized_transaction_date_yyyymmdd").toString());
                                                       LOG.info("date of row "+
                                                       row.get("authorized_transaction_date_yyyymmdd").toString());
                                                       String str = row.get("authorized_transaction_date_yyyymmdd").toString();
                                                       str = str.substring(0, str.length() - 2) + "01";
                                                       System.out.println("str value " + str);
                                                       LOG.info("str value " + str);
                                                       reference.setTableId("TargetTable$" + str);
                                                       return new TableDestination(reference, null);
                                                }
                                         }).withFormatFunction(new SerializableFunction<TableRow, TableRow>() {
                                                @Override
                                                public TableRow apply(TableRow input) {
                                                       LOG.info("format function:"+input.toString());

                                                       return input;
                                                }
                                         })

                                         .withSchema(schema1).withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE)
                                         .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED));

Now I have to use Dynamic Destination Any Solution.Insted Of this and have to Do Partition.


问:
Is it possible to create our own threads with out using operating system threads?
I was reading an article about how database management works. in that article author has mentioned that some of the modern databases use their own threads instead of operating system threads.
Is it true? If yes how it is possible?</p>

答:
I don't think it's possible to fully replace OS threads, but a database can use other 'thread-like' facilities, like Fibers or asynchronous calls.

For example, the Microsoft SQL Server has a core component called SQL Server Operating System (SQLOS). SQLOS is responsible for low-level operations of the database like scheduling or resource-management.

SQLOS advances the core operating system thread management in order to minimize the expensive context changes and the costly user-kernel mode switching. It also uses cooperative scheduling instead of the preemptive Windows scheduler.

A database operation is executed by one of the worker threads, which are managed by one of the schedulers.

Regardless, at the very low-level the SQLOS uses Windows threads just like any other application, what differs is the thread management and scheduling.

For more information on custom thread scheduling, you can check Windows's User-mode scheduling (UMS) documentation.


问:
center button and glyphicon on different lines
As part of a small jQuery project, I'm trying to have a Bootstrap glyphicon and button centered and with a line break between them. Right now the glyphicon stays centered, but the button shifts a bit left/right depending on the container's size (at its smallest, it appears off to the left).

How can I make both elements be centered on different lines within their parent
?

The html below shows two glyphicons, but I'm using jquery to unhide one of them upon clicking the correct button.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

#questionmark {
    font-size: 15px;
    color: purple;
    border-bottom: 2px solid purple;
    padding: 0 10px 2px 10px;
}

.btn {
    font-family: Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

p {
    font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
}

.valign{
    line-height:46px;
    vertical-align:middle;
}

.glyphicon-ok-sign {
    font-size: 40px;
    color: green;
}

.glyphicon-warning-sign {
    font-size: 40px;
    color: red;
}

.hide {
    display: none;
}

#display-sentence {
    display: none;
}

.highlight {
    background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <h1 class="text-center text-primary">¿POR O PARA?</h1>
    <br>
    <div class="jumbotron">
        <br>
        <p><span id="test-sentence"></span></p>
    </div>
    <div class="col-xs-10 col-xs-offset-1">
        <div class="row">
            <div class="col-xs-4">
                <button type="button" class="btn test-btn btn-primary btn-lg" id="por-btn">por</button>
            </div>
            <div class="col-xs-4 text-center valign">
                <p class="text-center">
                    <!-- I'm trying to center the following, only one glyphicon will be desplayed at a time, along with the #reload-btn -->
                    <span class="glyphicon glyphicon-ok-sign hide"></span>
                    <span class="glyphicon glyphicon-warning-sign hide"></span>
                    <br>
                    <button type="button" class="btn btn-success pull-right btn-lg hide" id="reload-btn">¡OTRA!</button>
                </p>
            </div>
            <div class="col-xs-4">
                <button type="button" class="btn test-btn btn-primary pull-right btn-lg" id="para-btn">para</button>
            </div>
        </div>
    </div>
</div></code>```

答:
Remove the pull-right class from your hidden button. This class adds the float: right; property. If I understand correctly, this is not appropriate for your task.

There is a problem that a free space arises between  elements. You can find several solutions in this question. But I suggest turning these s into blocks. You can remove the
 tag, add the center-block class to both icons and a button and define some top margin for the button. After that, you can remove the parent
 block, if you want.

I also deleted the hide class from the first icon and the button to make the result visible:

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

#reload-btn {
  margin-top: 10px;
}

#questionmark {
  font-size: 15px;
  color: purple;
  border-bottom: 2px solid purple;
  padding: 0 10px 2px 10px;
}

.btn {
  font-family: Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

p {
  font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
}

.valign{
line-height:46px;
vertical-align:middle;}

.glyphicon-ok-sign {
  font-size: 40px;
  color: green;
}

.glyphicon-warning-sign {
  font-size: 40px;
  color: red;
}

.hide {
  display: none;
}

#display-sentence {
  display: none;
}

.highlight {
  background-color: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1 class="text-center text-primary">¿POR O PARA?</h1>
  <br>
  <div class="jumbotron">
    <br>
    <p><span id="test-sentence"></span></p>
  </div>

  <div class="col-xs-10 col-xs-offset-1">
    <div class="row">
      <div class="col-xs-4">
        <button type="button" class="btn test-btn btn-primary btn-lg" id="por-btn">por</button>
      </div>

      <div class="col-xs-4 text-center valign">

          <!-- I'm trying to center the following, only one glyphicon will be desplayed at a time, along with the #reload-btn -->
          <span class="glyphicon glyphicon-ok-sign center-block"></span>
          <span class="glyphicon glyphicon-warning-sign hide center-block"></span>
          <button type="button" class="btn btn-success btn-lg center-block" id="reload-btn">¡OTRA!</button>

      </div>

      <div class="col-xs-4">
        <button type="button" class="btn test-btn btn-primary pull-right btn-lg" id="para-btn">para</button>
      </div>
    </div>
  </div>
</div></code>```

Body:
As part of a small jQuery project, I'm trying to have a Bootstrap glyphicon and button centered and with a line break between them. Right now the glyphicon stays centered, but the button shifts a bit left/right depending on the container's size (at its smallest, it appears off to the left).

How can I make both elements be centered on different lines within their parent
?

The html below shows two glyphicons, but I'm using jquery to unhide one of them upon clicking the correct button.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

#questionmark {
    font-size: 15px;
    color: purple;
    border-bottom: 2px solid purple;
    padding: 0 10px 2px 10px;
}

.btn {
    font-family: Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

p {
    font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
}

.valign{
    line-height:46px;
    vertical-align:middle;
}

.glyphicon-ok-sign {
    font-size: 40px;
    color: green;
}

.glyphicon-warning-sign {
    font-size: 40px;
    color: red;
}

.hide {
    display: none;
}

#display-sentence {
    display: none;
}

.highlight {
    background-color: yellow;
}

¿POR O PARA?

                <button type="button" class="btn test-btn btn-primary btn-lg" id="por-btn">por</button>

                    <button type="button" class="btn btn-success pull-right btn-lg hide" id="reload-btn">¡OTRA!</button>

                <button type="button" class="btn test-btn btn-primary pull-right btn-lg" id="para-btn">para</button>

Body:
Remove the pull-right class from your hidden button. This class adds the float: right; property. If I understand correctly, this is not appropriate for your task.

There is a problem that a free space arises between <span> elements. You can find several solutions in this question. But I suggest turning these <span>s into blocks. You can remove the <br> tag, add the center-block class to both icons and a button and define some top margin for the button. After that, you can remove the parent <p> block, if you want.

I also deleted the hide class from the first icon and the button to make the result visible:

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

#reload-btn {
  margin-top: 10px;
}

#questionmark {
  font-size: 15px;
  color: purple;
  border-bottom: 2px solid purple;
  padding: 0 10px 2px 10px;
}

.btn {
  font-family: Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

p {
  font-family: "Courier New", Courier, "Lucida Sans Typewriter", "Lucida Typewriter", monospace;
}

.valign{
line-height:46px;
vertical-align:middle;}

.glyphicon-ok-sign {
  font-size: 40px;
  color: green;
}

.glyphicon-warning-sign {
  font-size: 40px;
  color: red;
}

.hide {
  display: none;
}

#display-sentence {
  display: none;
}

.highlight {
  background-color: yellow;
}

<div class="container">
  <h1 class="text-center text-primary">¿POR O PARA?</h1>
  <br>
  <div class="jumbotron">
    <br>
    <p><span id="test-sentence"></span></p>
  </div>

  <div class="col-xs-10 col-xs-offset-1">
    <div class="row">
      <div class="col-xs-4">
        <button type="button" class="btn test-btn btn-primary btn-lg" id="por-btn">por</button>
      </div>

      <div class="col-xs-4 text-center valign">

          <!-- I'm trying to center the following, only one glyphicon will be desplayed at a time, along with the #reload-btn -->
          <span class="glyphicon glyphicon-ok-sign center-block"></span>
          <span class="glyphicon glyphicon-warning-sign hide center-block"></span>
          <button type="button" class="btn btn-success btn-lg center-block" id="reload-btn">¡OTRA!</button>

      </div>

      <div class="col-xs-4">
        <button type="button" class="btn test-btn btn-primary pull-right btn-lg" id="para-btn">para</button>
      </div>
    </div>
  </div>
</div>


问:
Best way to handle error and success messages copy texts from back-end?
I have an Android application and right now I am managing error and success messages in strings.xml resource file. Now in case if I want to change these messages I need to make changes in strings.xml file and give an app update in play-store, which is a bit overhead. Instead, I want these messages to be managed from server side (back-end) so that they can be changed without any update. Can anyone please suggest me the best way to achieve this.</p>

答:
If you are use Volley then this is helpfil for you

VolleyError is really just an extended Exception, so Exception.getMessage() likely wouldn't return what you are looking for unless you override the parsing methods for parsing your VolleyError in your extended Request class. A really basic way to handle this would be to do something like:

```<code>//In your extended request class
@Override
protected VolleyError parseNetworkError(VolleyError volleyError){
        if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
                VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
                volleyError = error;
            }

        return volleyError;
    }
}
</code>```

If you add this to your extended Request classes, your getMessage() should at least not return null. I normally don't really bother with this, though, since it's easy enough to do it all from within your onErrorResponse(VolleyError e) method.

You should use a JSON library to simplify things -- I use Gson for example or you could use Apache's JSONObjects which shouldn't require an additional external library. The first step is to get the response JSON sent from your server as a String (in a similar fashion to what I just demonstrated), next you can optionally convert it to a JSONObject (using either apache's JSONObjects and JsonArrays, or another library of your choice) or just parse the String yourself. After that, you just have to display the Toast.

Here's some example code to get you started:

```<code>public void onErrorResponse(VolleyError error) {
     String json = null;

     NetworkResponse response = error.networkResponse;
     if(response != null && response.data != null){
         switch(response.statusCode){
             case 400:
                  json = new String(response.data);
                  json = trimMessage(json, "message");
                  if(json != null) displayMessage(json);
                  break;
             }
            //Additional cases
     }
}

public String trimMessage(String json, String key){
    String trimmedString = null;

    try{
        JSONObject obj = new JSONObject(json);
        trimmedString = obj.getString(key);
    } catch(JSONException e){
        e.printStackTrace();
        return null;
    }

    return trimmedString;
}

//Somewhere that has access to a context
public void displayMessage(String toastString){
    Toast.makeText(context, toastString, Toast.LENGTH_LONG).show();
}
</code>```

Body:
If you are use Volley then this is helpfil for you

VolleyError is really just an extended Exception, so Exception.getMessage() likely wouldn't return what you are looking for unless you override the parsing methods for parsing your VolleyError in your extended Request class. A really basic way to handle this would be to do something like:

//In your extended request class
@Override
protected VolleyError parseNetworkError(VolleyError volleyError){
        if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
                VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
                volleyError = error;
            }

        return volleyError;
    }
}

If you add this to your extended Request classes, your getMessage() should at least not return null. I normally don't really bother with this, though, since it's easy enough to do it all from within your onErrorResponse(VolleyError e) method.

You should use a JSON library to simplify things -- I use Gson for example or you could use Apache's JSONObjects which shouldn't require an additional external library. The first step is to get the response JSON sent from your server as a String (in a similar fashion to what I just demonstrated), next you can optionally convert it to a JSONObject (using either apache's JSONObjects and JsonArrays, or another library of your choice) or just parse the String yourself. After that, you just have to display the Toast.

Here's some example code to get you started:

public void onErrorResponse(VolleyError error) {
     String json = null;

     NetworkResponse response = error.networkResponse;
     if(response != null && response.data != null){
         switch(response.statusCode){
             case 400:
                  json = new String(response.data);
                  json = trimMessage(json, "message");
                  if(json != null) displayMessage(json);
                  break;
             }
            //Additional cases
     }
}

public String trimMessage(String json, String key){
    String trimmedString = null;

    try{
        JSONObject obj = new JSONObject(json);
        trimmedString = obj.getString(key);
    } catch(JSONException e){
        e.printStackTrace();
        return null;
    }

    return trimmedString;
}

//Somewhere that has access to a context
public void displayMessage(String toastString){
    Toast.makeText(context, toastString, Toast.LENGTH_LONG).show();
}


问:
Is it possible to manipulate the instruction pointer in 8086 assembly?
I want to know if I can manipulate (read and change the value of) the instruction pointer (IP) in 8086 assembly.

For example,

Say IP is currently storing 0200h. I would like to read this value and  change it to something else, say 4020h. How could I do that?

答:
If you wanted to set the instruction pointer to a  known value, say hex value 4020h, you could jump directly to that address:

```<code>jmp 4020h
</code>```

Or if some memory location, myVariable, held the value you wanted to store in IP you could do an indirect jump:

```<code>jmp [myVariable]
</code>```

The result of a jmp (indirect or direct) modifies the instruction pointer.

Reading the instruction pointer is problematic. Position independent code on Linux used to work by using a set of code something like:

```<code> call getIP
</code>```

with

```<code> :getIP
 mov bx, [sp] ; Read the return address into BX.
 ret
</code>```

For other methods of reading IP, see Stack Overflow: reading IP.

Body:
If you wanted to set the instruction pointer to a  known value, say hex value 4020h, you could jump directly to that address:

jmp 4020h

Or if some memory location, myVariable, held the value you wanted to store in IP you could do an indirect jump:

jmp [myVariable]

The result of a jmp (indirect or direct) modifies the instruction pointer.

Reading the instruction pointer is problematic. Position independent code on Linux used to work by using a set of code something like:

 call getIP

with

 :getIP
 mov bx, [sp] ; Read the return address into BX.
 ret

For other methods of reading IP, see Stack Overflow: reading IP.


答:
If you only want to find most frequent item in list2 grouped by list1. Below script will work.</p>

```<code>SELECT  top(1) [list1]
      ,[list2],
      count(*) as max
  FROM [dbo].[tableData]
  group by list1,list2
  order by max desc
</code>```

Title: distinct, max and group by query in sql

Body:
I have a dataset like:

list1     list2
a          e
a          e
b          w
a          e
a          r
b          c

I want to find most frequent item in list2 grouped by list1.

list1     list2    max
  a         e       3
  b         w       1

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

SELECT clf1 as clf2, first(value_count) as max_value
FROM (SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc)
GROUP BY clf2

Body:
If you only want to find most frequent item in list2 grouped by list1. Below script will work.

SELECT  top(1) [list1]
      ,[list2],
      count(*) as max
  FROM [dbo].[tableData]
  group by list1,list2
  order by max desc


问:
hive column to rows
how can I create new columns in HIVE according to the type stored in an existing column?

for example, I have :

```<code>id    ProductType
1       car
2       bike
3       truck
</code>```

and I would like to have:

```<code>id    car    bike    truck
1      1     null    null
2     null     1     null
3     null   null      1
</code>```

答:
```<code>Use `case` statement to convert values into columns:

select id, case when ProductType = 'car' then 1 end as car,
           case when ProductType = 'bike' then 1 end as bike,
           case when ProductType = 'truck' then 1 end as truck
 from your_table;

OK
id      car     bike    truck
1       1       NULL    NULL
2       NULL    1       NULL
3       NULL    NULL    1
Time taken: 35.442 seconds, Fetched: 3 row(s)
</code>```

Title: hive column to rows

Body:
how can I create new columns in HIVE according to the type stored in an existing column?

for example, I have :

id    ProductType
1       car
2       bike
3       truck

and I would like to have:

id    car    bike    truck
1      1     null    null
2     null     1     null
3     null   null      1


问:
how to pass multiple rows with a single column in a stored procedure in SQL
how to pass multiple rows using a single column in a stored procedure in SQL (SSMS)?
or
how to pass single column values in a procedure.

```<code>CREATE TYPE tblAge_Type as TABLE
(
    ID int,
    Age int
)
--------------------------------------------------------------------------------------
alter PROCEDURE spAddAge (
   @datasource tblAge_Type READONLY)
AS
    update tblAge set Age = (select Age from  @datasource ) where Id = (select ID from @datasource )

GO
------------------------------------------------------------------------------------------
DECLARE @data AS tblAge_Type

INSERT into @data VALUES(1,22) ;
INSERT into @data VALUES(2,55) ;
INSERT into @data VALUES(3,44);

EXEC spAddAge @data
</code>```

getting this error: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

答:
there is no standard way to do this.
The most common ways that this is done is:
1) make a comma delimited string, pass it as a parameter, and in the procedure, split the string into a table. There are many string splitting functions around, preferrably use one that does not use loops. I think the latest version of SQL Server has also a string splitting function.
2) pass a table valued parameter, as is explained here: How to pass a table-value parameter</p>

Body:
how to pass multiple rows using a single column in a stored procedure in SQL (SSMS)?
or
how to pass single column values in a procedure.

CREATE TYPE tblAge_Type as TABLE
(
    ID int,
    Age int
)
--------------------------------------------------------------------------------------
alter PROCEDURE spAddAge (
   @datasource tblAge_Type READONLY)
AS
    update tblAge set Age = (select Age from  @datasource ) where Id = (select ID from @datasource )

GO
------------------------------------------------------------------------------------------
DECLARE @data AS tblAge_Type

INSERT into @data VALUES(1,22) ;
INSERT into @data VALUES(2,55) ;
INSERT into @data VALUES(3,44);

EXEC spAddAge @data

getting this error: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.


问:
Type casting and inspection query
I am currently working through the basics of Type Casting and Inspection in swift 4.  I have found an example in the Apple Developer book which i need a bit of help with.

They have an exercise to create an Any type dictionary and then unwrap the values looping through the dictionary. The given solution shows the for loop with the value in brackets and each value being unwrapped. Can someone give an explanation for the solution shown? and is there another(simple) way to solve this? There is not enough information in the book.

```<code>let anythingAndEverything: [String: Any] = ["FirstBool": true,
"FalseBool": false, "Unknown": "90", "AnInteger": 12, "ADouble": 1.1]

print(anythingAndEverything)

var total: Double = 0
for (_, value) in anythingAndEverything {
    if let value = value as? Bool {
        if value {
            total += 2
        } else {
            total -= 3
        }
    } else if let value = value as? Double {
        total += value
    } else if let value = value as? Int {
        total += Double(value)
    } else if let value = value as? String {
        total += 1
    }
}

print(total)
</code>```

Many thanks for any help in advance :-)

答:
Dictionary conforms to Collection, which conforms to Sequence. This means that a dictionary can be looped through using a for...in loop.

In the definition of Dictionary, there is this line:

```<code>public typealias Element = (key: Key, value: Value)
</code>```

This means that "in the collection called a dictionary, it contains elements of type (key: Key, value: Value)". This means that you will get (key: Key, value: Value) as the type of the variable before in:

```<code>for element in someDictionary {
    // element is of type (key: Key, value: Value)
}
</code>```

Since element is a tuple, we can actually unwrap the tuple by doing this:

```<code>for (key, value) in someDictionary {}
</code>```

In your specific situation, we don't need the key bit, so we write _ to say "throw this away":

```<code>for (_, value) in someDictionary {}
</code>```

Another way to solve this is to use reduce. I wouldn't say this is necessarily simpler though:

```<code>total = anythingAndEverything.reduce(0.0) { (x, y) -> Double in
    if let value = y.value as? Bool {
        if value {
            return x + 2
        } else {
            return x - 3
        }
    } else if let value = y.value as? Double {
        return x + value
    } else if let value = y.value as? Int {
        return x + Double(value)
    } else if let value = y.value as? String {
        return x + 1
    } else {
        return x
    }
}
</code>```

Title: Type casting and inspection query

Body:
I am currently working through the basics of Type Casting and Inspection in swift 4.  I have found an example in the Apple Developer book which i need a bit of help with.

They have an exercise to create an Any type dictionary and then unwrap the values looping through the dictionary. The given solution shows the for loop with the value in brackets and each value being unwrapped. Can someone give an explanation for the solution shown? and is there another(simple) way to solve this? There is not enough information in the book.

let anythingAndEverything: [String: Any] = ["FirstBool": true,
"FalseBool": false, "Unknown": "90", "AnInteger": 12, "ADouble": 1.1]

print(anythingAndEverything)

var total: Double = 0
for (_, value) in anythingAndEverything {
    if let value = value as? Bool {
        if value {
            total += 2
        } else {
            total -= 3
        }
    } else if let value = value as? Double {
        total += value
    } else if let value = value as? Int {
        total += Double(value)
    } else if let value = value as? String {
        total += 1
    }
}

print(total)

Many thanks for any help in advance :-)

Body:
Dictionary conforms to Collection, which conforms to Sequence. This means that a dictionary can be looped through using a for...in loop.

In the definition of Dictionary, there is this line:

public typealias Element = (key: Key, value: Value)

This means that "in the collection called a dictionary, it contains elements of type (key: Key, value: Value)". This means that you will get (key: Key, value: Value) as the type of the variable before in:

for element in someDictionary {
    // element is of type (key: Key, value: Value)
}

Since element is a tuple, we can actually unwrap the tuple by doing this:

for (key, value) in someDictionary {}

In your specific situation, we don't need the key bit, so we write _ to say "throw this away":

for (_, value) in someDictionary {}

Another way to solve this is to use reduce. I wouldn't say this is necessarily simpler though:

total = anythingAndEverything.reduce(0.0) { (x, y) -> Double in
    if let value = y.value as? Bool {
        if value {
            return x + 2
        } else {
            return x - 3
        }
    } else if let value = y.value as? Double {
        return x + value
    } else if let value = y.value as? Int {
        return x + Double(value)
    } else if let value = y.value as? String {
        return x + 1
    } else {
        return x
    }
}


问:
CUDA installation on Windows
I installed CUDA Toolkit 3.2, CUDA SDK and MS Visual Studio  2008 (not necessarily in this order) on my Windows 7 that does not have an nvidia graphics card.
But when I try running my CUDA code, the CUDA keywords are'nt identified.
I am a beginner. Pls tell me what I am doing wrong here.

Thanks

答: If you don't have a NVIDIA card, you can still use the emulator but you need to install the SDK and the toolkit. Try to fix your problem by adding in your Visual Studio project settings the include and library path of CUDA.</p>

Title: CUDA installation on Windows


问:
Matlab Octave Access Struct array member without loop
I hope this question is not too embarrassing, but i didn't find a solution via google (Most likely because i don't know the matching keywords):

If i have a struct array in Matlab with an entry .data, is there a loop less solution to search in this entries for eg. the maximum value?

```<code>num = 10;
block = struct('header',cell(num,1), 'data',cell(num,1));
% Some data in block; Perhaps this can be achieved without the loop as well?
for i = 1:num
  block(i).data = rand(1, 1);
end
% How do i get the corresponding max value of all block.data entries?
</code>```

答:
Concatenate the result of block.data horizontally or vertically and then use max.

```<code>max([block.data])
</code>```

Body:
I hope this question is not too embarrassing, but i didn't find a solution via google (Most likely because i don't know the matching keywords):

If i have a struct array in Matlab with an entry .data, is there a loop less solution to search in this entries for eg. the maximum value?

num = 10;
block = struct('header',cell(num,1), 'data',cell(num,1));
% Some data in block; Perhaps this can be achieved without the loop as well?
for i = 1:num
  block(i).data = rand(1, 1);
end
% How do i get the corresponding max value of all block.data entries?

Body:
Concatenate the result of block.data horizontally or vertically and then use max.

max([block.data])


问:
Wercker deploy returns 404 for docker push
First time with Wercker and I'm using internal/docker-push. When I run my deployment step, I'm getting a 404 error from docker-hub.

```<code>ERROR Error interacting with this repository: wluce/statler-waldorf-corp-team-service PUT https://registry.hub.docker.com/v1/repositories/wluce/statler-waldorf-corp-team-service/ returned 404
</code>```

This isn't the first time I've run this step and it's worked before. The image exists and is here.

I can't figure out what could've changed.

Here is the wercker.yml file I'm using to perform the build and deploy.

```<code>box: microsoft/dotnet:2.0.0-sdk-2.0.2
no-response-timeout: 10
build:
  steps:
    - script:
        name: restore
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet restore
    - script:
        name: build
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet build

    - script:
        name: test-restore
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet restore
    - script:
        name: test-build
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet build
    - script:
        name: test-run
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet test

    - script:
        name: integration-test-restore
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet restore
    - script:
        name: integration-test-build
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet build
    - script:
        name: integration-test-run
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet test

    - script:
        name: publish
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet publish -o publish
    - script:
        name: copy binary
        cwd: src/StatlerWaldorfCorp.TeamService
        code: cp -r . $WERCKER_OUTPUT_DIR/app

deploy:
  box: microsoft/aspnetcore:2.0.0
  steps:
    - internal/docker-push:
        cwd: $WERCKER_OUTPUT_DIR/app
        username: $DOCKER_USERNAME
        password: $DOCKER_PASSWORD
        repository: wluce/statler-waldorf-corp-team-service
        registry: https://registry.hub.docker.com
        entrypoint: "/pipeline/source/app/docker_entrypoint.sh"
</code>```

答:
As discussed on Wercker slack channel and suggested @cggaldes, the solution is to set the full registry address on the step definition, like:

```<code>- internal/docker-push:
    registry: https://registry.hub.docker.com/v2   <-- This
    repository: org/repo
    username: $DOCKER_USER
    password: $DOCKER_PASS
    ...
</code>```

Apparently internal/docker-push uses v1 by default which has recently changed/broken.

Body:
First time with Wercker and I'm using internal/docker-push. When I run my deployment step, I'm getting a 404 error from docker-hub.

ERROR Error interacting with this repository: wluce/statler-waldorf-corp-team-service PUT https://registry.hub.docker.com/v1/repositories/wluce/statler-waldorf-corp-team-service/ returned 404

This isn't the first time I've run this step and it's worked before. The image exists and is here.

I can't figure out what could've changed.

Here is the wercker.yml file I'm using to perform the build and deploy.

box: microsoft/dotnet:2.0.0-sdk-2.0.2
no-response-timeout: 10
build:
  steps:
    - script:
        name: restore
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet restore
    - script:
        name: build
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet build

    - script:
        name: test-restore
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet restore
    - script:
        name: test-build
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet build
    - script:
        name: test-run
        cwd: test/StatlerWaldorfCorp.TeamService.Tests
        code: dotnet test

    - script:
        name: integration-test-restore
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet restore
    - script:
        name: integration-test-build
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet build
    - script:
        name: integration-test-run
        cwd: test/StatlerWaldorfCorp.TeamService.Tests.Integration
        code: dotnet test

    - script:
        name: publish
        cwd: src/StatlerWaldorfCorp.TeamService
        code: dotnet publish -o publish
    - script:
        name: copy binary
        cwd: src/StatlerWaldorfCorp.TeamService
        code: cp -r . $WERCKER_OUTPUT_DIR/app

deploy:
  box: microsoft/aspnetcore:2.0.0
  steps:
    - internal/docker-push:
        cwd: $WERCKER_OUTPUT_DIR/app
        username: $DOCKER_USERNAME
        password: $DOCKER_PASSWORD
        repository: wluce/statler-waldorf-corp-team-service
        registry: https://registry.hub.docker.com
        entrypoint: "/pipeline/source/app/docker_entrypoint.sh"

Body:
As discussed on Wercker slack channel and suggested @cggaldes, the solution is to set the full registry address on the step definition, like:

- internal/docker-push:
    registry: https://registry.hub.docker.com/v2   <-- This
    repository: org/repo
    username: $DOCKER_USER
    password: $DOCKER_PASS
    ...

Apparently internal/docker-push uses v1 by default which has recently changed/broken.


问:
Can you add to a VSCode language's auto complete?
We got a Ruby API for our application and I'm trying to figure out if I can make an extension for VSCode that add auto-complete for our API to the Intellisense feature of the editor.

With RubyMine I've done this by simply using stubs packaged as a gem. Adding the gem to the RubyMine project is all that I needed to have the editor provide code insight that included our API.

How can this be done for VSCode? I was hoping to build upon the existing vscode-ruby extension for Code. But I'm only finding examples of adding language extensions.

答:
Thanks to questions like this I keep up to day with new technologies and tools.

I did a quick read of the documentation, although VSCode support several language the page refers to VS Code Marketplace for extensions, and ruby is one of them.

Now, ruby extension claims to have IntelliSense and autocomplete, however if this does not detects your API, then you may need to create your own language extension. I assume that if your Ruby is an API, as you said, then VSCode has not access to the interface in order to provide the possible predictions.
Perhaps if you somehow could get the source code of the API VSCode would detect the interfaces, and life would be much easier.

Anyway, have a look to the extensionAPI7Language-support
There explain how to create

Source code snippets

Show Code completion Proposals

both of then have to be manually configured.


问:
Is there a good Fogbugz client for Mac OS X?
And/or: do I need one?

I've recently started using FogBugz for my hobby projects, and I'm very happy with things so far. Having read more about it, especially the evidence-based scheduling, I'd like to start using it for my PhD as well. (Heh; something tells me my supervisors won't be opening tickets for me, though.)

Last night I stumbled onto TimePost, which looks like a tidy app that doesn't do much but could be a real bonus to logging my time in FogBugz effectively. I tried looking around for similar apps but came up a little empty-handed. Are there any other FogBugz clients that you've used and recommend for Mac OS X? Or are you happy with the web interface?

答: I don't know of any native tool, but like Matt I am pretty happy with the web interface.</p>

OwnerDisplayName: Will Robertson

OwnerDisplayName: Dave Verwer


问:
What is the correct way to stop a checkout from an event observer in Magento?
I am verifying shipping quotes during the event checkout_controller_onepage_save_shipping_method and if the verification fails i want to send the user back to shipping method selection but I would also like to display a message saying why it failed. Does Magento have a way of doing this built in?

I am already verifying the data I just lack the redirect to shipping methods and way to display a message.

答:
(None of this is tested code, but the concepts should get you where you need to go)

Magento is a project run by a bunch of software engineers.  When you're working with a bunch of software engineers, the documentation is the code.

i.e. Whenever you need to do something common with Magento, observe how the core team has done it, taking into account that you should limit yourself to observers, overrides, and new code since you can't discuss your changes with said core team.

Take a look at the one page checkout controller's IndexAction method

```<code>app/code/core/Mage/Checkout/controllers/OnepageController.php
public function indexAction()
{
    if (!Mage::helper('checkout')->canOnepageCheckout()) {
        Mage::getSingleton('checkout/session')->addError($this->__('The onepage checkout is disabled.'));
        $this->_redirect('checkout/cart');
        return;
    }
    ...
</code>```

Magento allows you add errors to the session object, which will be processed by the messaging block on the next request.

```<code>Mage::getSingleton('checkout/session')->addError($this->__('The onepage checkout is disabled.'));
</code>```

That that handles an error.  Next, there's the redirect.  This happens here

```<code>$this->_redirect('checkout/cart');
</code>```

Since you're calling this code from an observer, you won't have access to this method.  However, if you examine the controller

```<code>/**
 * Retrieve request object
 *
 * @return Mage_Core_Controller_Request_Http
 */
public function getRequest()
{
    return $this->_request;
}
...
protected function _redirect($path, $arguments=array())
{
    $this->getResponse()->setRedirect(Mage::getUrl($path, $arguments));
    return $this;
}
</code>```

You can see its using the response object.  Magento uses a global response object (similar to Zend, and other Web frameworks) to handle what gets sent back to the browser (i.e. redirect headers).  You can get a reference to the same object via

```<code>Mage::app()->getResponse()
</code>```

and could perform a redirect with something like

```<code>Mage::app()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'));
</code>```

Body:
(None of this is tested code, but the concepts should get you where you need to go)

Magento is a project run by a bunch of software engineers.  When you're working with a bunch of software engineers, the documentation is the code.

i.e. Whenever you need to do something common with Magento, observe how the core team has done it, taking into account that you should limit yourself to observers, overrides, and new code since you can't discuss your changes with said core team.

Take a look at the one page checkout controller's IndexAction method

app/code/core/Mage/Checkout/controllers/OnepageController.php
public function indexAction()
{
    if (!Mage::helper('checkout')->canOnepageCheckout()) {
        Mage::getSingleton('checkout/session')->addError($this->__('The onepage checkout is disabled.'));
        $this->_redirect('checkout/cart');
        return;
    }
    ...

Magento allows you add errors to the session object, which will be processed by the messaging block on the next request.

Mage::getSingleton('checkout/session')->addError($this->__('The onepage checkout is disabled.'));

That that handles an error.  Next, there's the redirect.  This happens here

$this->_redirect('checkout/cart');

Since you're calling this code from an observer, you won't have access to this method.  However, if you examine the controller

/**
 * Retrieve request object
 *
 * @return Mage_Core_Controller_Request_Http
 */
public function getRequest()
{
    return $this->_request;
}
...
protected function _redirect($path, $arguments=array())
{
    $this->getResponse()->setRedirect(Mage::getUrl($path, $arguments));
    return $this;
}

You can see its using the response object.  Magento uses a global response object (similar to Zend, and other Web frameworks) to handle what gets sent back to the browser (i.e. redirect headers).  You can get a reference to the same object via

Mage::app()->getResponse()

and could perform a redirect with something like

Mage::app()->getResponse()->setRedirect(Mage::getUrl('checkout/cart'));