问:
Pandoc Lua filters: how to specify attributes for Span element
I have a Markdown document containing raw LaTeX commands. I am trying to use a Lua filter with Pandoc (2.0.1.1) to convert the LaTeX commands into something more portable. In particular, commands that specify the language of text should be converted into spans with a lang attribute. The problem is that I don't know how to pass the attributes to the pandoc.Span constructor. This is my attempt at a filter (filter.lua):

```<code>function RawInline(elem)
  if elem.format == "tex" then
    text = string.match(elem.text, "\\textspanish{(.+)}")
    if text then
      contents = {pandoc.Str(text)}
      attrs = pandoc.Attr("",{},{lang = "es-SP"})
      return pandoc.Span(contents, attrs)
    end
  else
    return elem
  end
end
</code>```

Sample usage:

```<code>echo '\textspanish{hola}' | pandoc -f markdown -t native --lua-filter=filter.lua
</code>```

The output is [Para [Span ("",[],[]) [Str "hola"]]], with no attributes on the span.

If I pass a name and/or class to pandoc.Attr, these come through, e.g., attrs = pandoc.Attr("name",{"class"},{lang = "es-SP"}) produces [Para [Span ("name",["class"],[]) [Str "hola"]]]. But attributes I pass to the constructor never appear in the output. What is the right way to pass attributes to pandoc.Attr?

答:
This used to be one of the rough edges in the Lua filter implementation; it has since been ironed out and made more user friendly, so the above example now works as expected.

Background

Internally, pandoc uses two-element tables to hold key-value pairs. It roughly looks like this:

```<code>attrs = pandoc.Attr("", {}, {{"lang", "es-SP"}})
</code>```

Of course, this is not a great way to represent pairs.  The reason for the current implementation is two-fold:

It mirrors how way pairs (and attributes in general) are encoded in pandoc's JSON output.

These pairs have a fixed order.

The last part is important when one wants to guarantee that the order of attributes won't be changed when passing through a filter.  There is no rule in Lua which determines the order of keys in a table: the Lua table {one = 1, two = 2} could be read back into pandoc as the attribute list {one="1" two="2} or as {two="2" one="1"}.  Now, the order of attributes shouldn't matter for most applications, but we cannot be sure.  Hence the less-than-intuitive representation.

Current state (pandoc 2.16 and later)

The internal representation hasn't changed, but we have since improved the representation of Attr objects in Lua, extended the marshaling code, and added a Lua metatable. As a result, attribute tables are treated as expected. Furthermore, many users may find it more intuitive to use HTML-like attribute lists instead of "identifier, class, atttributes" triples. That is supported as well now:

attr = pandoc.Attr{id='some-id', class="one two", lang='es-SP'}
```
<p>In fact, it is not necessary to use the <code>pandoc.Attr</code> constructor at all, just passing a table will work:</p>
<pre class="lang-lua prettyprint-override"><code>  return pandoc.Span(contents, {lang='es-SP'})
</code>```

Body:
I have a Markdown document containing raw LaTeX commands. I am trying to use a Lua filter with Pandoc (2.0.1.1) to convert the LaTeX commands into something more portable. In particular, commands that specify the language of text should be converted into spans with a lang attribute. The problem is that I don't know how to pass the attributes to the pandoc.Span constructor. This is my attempt at a filter (filter.lua):

function RawInline(elem)
  if elem.format == "tex" then
    text = string.match(elem.text, "\\textspanish{(.+)}")
    if text then
      contents = {pandoc.Str(text)}
      attrs = pandoc.Attr("",{},{lang = "es-SP"})
      return pandoc.Span(contents, attrs)
    end
  else
    return elem
  end
end

Sample usage:

echo '\textspanish{hola}' | pandoc -f markdown -t native --lua-filter=filter.lua

The output is [Para [Span ("",[],[]) [Str "hola"]]], with no attributes on the span.

If I pass a name and/or class to pandoc.Attr, these come through, e.g., attrs = pandoc.Attr("name",{"class"},{lang = "es-SP"}) produces [Para [Span ("name",["class"],[]) [Str "hola"]]]. But attributes I pass to the constructor never appear in the output. What is the right way to pass attributes to pandoc.Attr?

Body:
This used to be one of the rough edges in the Lua filter implementation; it has since been ironed out and made more user friendly, so the above example now works as expected.

Background

Internally, pandoc uses two-element tables to hold key-value pairs. It roughly looks like this:

attrs = pandoc.Attr("", {}, {{"lang", "es-SP"}})

Of course, this is not a great way to represent pairs.  The reason for the current implementation is two-fold:

It mirrors how way pairs (and attributes in general) are encoded in pandoc's JSON output.

These pairs have a fixed order.

The last part is important when one wants to guarantee that the order of attributes won't be changed when passing through a filter.  There is no rule in Lua which determines the order of keys in a table: the Lua table {one = 1, two = 2} could be read back into pandoc as the attribute list {one="1" two="2} or as {two="2" one="1"}.  Now, the order of attributes shouldn't matter for most applications, but we cannot be sure.  Hence the less-than-intuitive representation.

Current state (pandoc 2.16 and later)

The internal representation hasn't changed, but we have since improved the representation of Attr objects in Lua, extended the marshaling code, and added a Lua metatable. As a result, attribute tables are treated as expected. Furthermore, many users may find it more intuitive to use HTML-like attribute lists instead of "identifier, class, atttributes" triples. That is supported as well now:

attr = pandoc.Attr{id='some-id', class="one two", lang='es-SP'}

In fact, it is not necessary to use the pandoc.Attr constructor at all, just passing a table will work:

  return pandoc.Span(contents, {lang='es-SP'})


来源: stackexchange

问:
List of possible combinations of characters with OR statement
I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. How could I achieve this ?  </p>

```<code>items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
     print(p)

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')
</code>```

答:
Created a new list items2 for d and f. Assuming that OP needs all combinations of [a,b,c,d] and [a,b,c,f]

```<code>items1 = ['a', 'b', 'c']
items2 = ['d','f']
from itertools import permutations
for x in items2:
    for p in permutations(items1+[x]):
        print(p)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I managed to generate a list of all possible combinations of characters 'a', 'b' and 'c' (code below). Now I want to add a fourth character, which can be either 'd' or 'f' but NOT both in the same combination. How could I achieve this ?

items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
     print(p)

('a', 'b', 'c')
('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

Body:
Created a new list items2 for d and f. Assuming that OP needs all combinations of [a,b,c,d] and [a,b,c,f]

items1 = ['a', 'b', 'c']
items2 = ['d','f']
from itertools import permutations
for x in items2:
    for p in permutations(items1+[x]):
        print(p)


问:
Need Eclipse Team History for a File
I have set up eclipse on a new computer and on the old one I was able to get the entire Git revision history of a file with a history tab of all changes complete with color coded line numbers in margin.

Now I only get Right click -> Team -> Show Local History.

How do I get Team -> Show In History back again?

Tried this with different perspectives and adding history view to both Navigator and Package Explorer views.

I can get revision history of an entire package resource but need it for just files.

答:
You need to make sure your file is part of a git repo you have cloned locally (there should be a .git subfolder at the root of your project)

And you need to share that project with Git (Eclipse will recognized an existing Git repo)

Title: Need Eclipse Team History for a File


问:
Webpack create output with devserver
So according to this answer here webpack will not create any output when you run the devserver, it will only handle things in memory.

However if you want the devserver to also create the files and put into a certain location while running the devserver. How can you achieve that?

答: The following plugin solved my problem: https://github.com/gajus/write-file-webpack-plugin</p>

Title: Webpack create output with devserver


问:
My flexbox divs all align in a column. I need them to align one in a column and then in the other row in two divs
I'm trying to do a flexbox with a vertical navigation on the left that has 100% height and beside that a header with 30% height and a content space taking the other 70% of the height. I'm just learning how to code sorry.

```<code><div id="wrapper">
  <nav>
  </nav>
  <div id="column2">
    <header>
    </header>
    <main>
    </main>
  </div>
</div>
</code>```

```<code>#wrapper {
  display: flex;
  flex-flow: column;
  min-height: 100em;
}

nav {
  flex: 1;
  background-color: blue;
  height: 50em;
  width:20em;
}

#column2 {
  width: 60%;
  background-color: red;
  display: flex;
  flex-direction: column;
  height: 50em;
  flex-basis: 100em;
}

header {
  background-color: red;
  flex: 1;
  height: 20em;
  justify-content: flex-end;
}

main {
  background-color: pink;
  flex: 1;
  height: 30em;
  justify-content: flex-end;
}
</code>```

答:
html, body {
  height: 100%;
}

#wrapper {
  display: flex;
  height: 100%;
}

nav {
  background-color: blue;
  flex: 0 0 30%;
}

#content {
  display: flex;
  flex: 0 0 70%;
  flex-flow: column;
}

header{
  background-color: green;
  flex: 0 0 30%;
}

main {
  background-color: red;
  flex: 0 0 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <nav>
  </nav>
  <div id="content">
    <header>
    </header>
    <main>
    </main>
  </div>
</div></code>```

Body:
I'm trying to do a flexbox with a vertical navigation on the left that has 100% height and beside that a header with 30% height and a content space taking the other 70% of the height. I'm just learning how to code sorry.

#wrapper {
  display: flex;
  flex-flow: column;
  min-height: 100em;
}

nav {
  flex: 1;
  background-color: blue;
  height: 50em;
  width:20em;
}

#column2 {
  width: 60%;
  background-color: red;
  display: flex;
  flex-direction: column;
  height: 50em;
  flex-basis: 100em;
}

header {
  background-color: red;
  flex: 1;
  height: 20em;
  justify-content: flex-end;
}

main {
  background-color: pink;
  flex: 1;
  height: 30em;
  justify-content: flex-end;
}

Body:
html, body {
  height: 100%;
}

#wrapper {
  display: flex;
  height: 100%;
}

nav {
  background-color: blue;
  flex: 0 0 30%;
}

#content {
  display: flex;
  flex: 0 0 70%;
  flex-flow: column;
}

header{
  background-color: green;
  flex: 0 0 30%;
}

main {
  background-color: red;
  flex: 0 0 70%;
}

<div id="wrapper">
  <nav>
  </nav>
  <div id="content">
    <header>
    </header>
    <main>
    </main>
  </div>
</div>


问:
How to unit test library that relies on Session object
I have several asp.net mvc websites consuming the same controller and model.

This common logic is put in seperate libraries.
These libraries use the HttpContext.Current.Session. How can I make these unit testable?
I read about the StateValue but can't completely grasp it. Where should I get this StateValue thing? Is it a lib I reference?

答: You can use mock helpers such as seen here</p>

OwnerDisplayName: boris callens

ContentLicense: CC BY-SA 2.5


问:
www being served on iis, non-www being served on apache?
Here is the problem, if you visit the site directorybest.net you will see the correct website (which is defined in apache). But if you go to the www version of the site a catch all site for and from IIS is displayed. I have no idea what this is causing this.

I have another site that already runs fine on apache from which I copied the info for DNS and vhost settings. I also have set the DNS up so that both sites point to the same ip address. Does anyone know why the www version of the site does not show the right website?

Here is the vhost information for both the working and non working site.

```<code>NameVirtualHost *

#non-working site

<VirtualHost *>
 ServerAdmin admin@email.com
 ServerName www.directorybest.net
 ServerAlias directorybest.net *.directorybest.net
 DocumentRoot "D:\WWW\DirectoryBest\2"
 DirectoryIndex index.php

 <Directory D:\WWW\DirectoryBest\2>
             AllowOverride All
 </Directory>

 # Logfiles
        ErrorLog  D:\WWW\DirectoryBest\2\logs\error.log
        CustomLog D:\WWW\DirectoryBest\2\logs\access.log combined
</VirtualHost>

#working site

<VirtualHost *>
 ServerAdmin admin@email.com
 ServerName www.directorybest.info
 ServerAlias directorybest.info *.directorybest.info
 DocumentRoot "D:\WWW\DirectoryBest\1"
 DirectoryIndex index.php

 <Directory D:\WWW\DirectoryBest\1>
             AllowOverride All
 </Directory>

 # Logfiles
        ErrorLog  D:\WWW\DirectoryBest\1\logs\error.log
        CustomLog D:\WWW\DirectoryBest\1\logs\access.log combined
</VirtualHost>
</code>```

答: Ok so I was just informed that the company has had DNS problems before. And upon further checking the local DNS had not been updated and was still resolving to the old ip address.</p>

Body:
Here is the problem, if you visit the site directorybest.net you will see the correct website (which is defined in apache). But if you go to the www version of the site a catch all site for and from IIS is displayed. I have no idea what this is causing this.

I have another site that already runs fine on apache from which I copied the info for DNS and vhost settings. I also have set the DNS up so that both sites point to the same ip address. Does anyone know why the www version of the site does not show the right website?

Here is the vhost information for both the working and non working site.

NameVirtualHost *

#non-working site

<VirtualHost *>
 ServerAdmin admin@email.com
 ServerName www.directorybest.net
 ServerAlias directorybest.net *.directorybest.net
 DocumentRoot "D:\WWW\DirectoryBest\2"
 DirectoryIndex index.php

 <Directory D:\WWW\DirectoryBest\2>
             AllowOverride All
 </Directory>

 # Logfiles
        ErrorLog  D:\WWW\DirectoryBest\2\logs\error.log
        CustomLog D:\WWW\DirectoryBest\2\logs\access.log combined
</VirtualHost>

#working site

<VirtualHost *>
 ServerAdmin admin@email.com
 ServerName www.directorybest.info
 ServerAlias directorybest.info *.directorybest.info
 DocumentRoot "D:\WWW\DirectoryBest\1"
 DirectoryIndex index.php

 <Directory D:\WWW\DirectoryBest\1>
             AllowOverride All
 </Directory>

 # Logfiles
        ErrorLog  D:\WWW\DirectoryBest\1\logs\error.log
        CustomLog D:\WWW\DirectoryBest\1\logs\access.log combined
</VirtualHost>


问:
Text blinking in Android, with most concise Kotlin
I need to make some text (currently in a TextView) blink for a few seconds. There's several answers on how to do it in java here, but since Kotlin has some syntax/language features that java doesn't, I'm asking what is the most concise way you found to make text blink on Android using Kotlin.

While I'm aiming at making a fading/smooth blink, I'm open to approaches that would make a non smooth blink too.

Note that I'm also looking at lightweight code performance wise.

Thanks for your answers!

答:
For a bit of fun, you can define an extension function:

```<code>fun View.blink(
    times: Int = Animation.INFINITE,
    duration: Long = 50L,
    offset: Long = 20L,
    minAlpha: Float = 0.0f,
    maxAlpha: Float = 1.0f,
    repeatMode: Int = Animation.REVERSE
) {
    startAnimation(AlphaAnimation(minAlpha, maxAlpha).also {
        it.duration = duration
        it.startOffset = offset
        it.repeatMode = repeatMode
        it.repeatCount = times
    })
}
</code>```

And use it like so (using the example in the question you linked):

```<code>myText.blink(3)  // Blink 3 times
yourText.blink()  // Just keep blinking
</code>```

Obviously you can change the parameters to suit your use case.

To stop the animation if needed, call clearAnimation() on the blinking view (yourText for the example above).

Body:
For a bit of fun, you can define an extension function:

fun View.blink(
    times: Int = Animation.INFINITE,
    duration: Long = 50L,
    offset: Long = 20L,
    minAlpha: Float = 0.0f,
    maxAlpha: Float = 1.0f,
    repeatMode: Int = Animation.REVERSE
) {
    startAnimation(AlphaAnimation(minAlpha, maxAlpha).also {
        it.duration = duration
        it.startOffset = offset
        it.repeatMode = repeatMode
        it.repeatCount = times
    })
}

And use it like so (using the example in the question you linked):

myText.blink(3)  // Blink 3 times
yourText.blink()  // Just keep blinking

Obviously you can change the parameters to suit your use case.

To stop the animation if needed, call clearAnimation() on the blinking view (yourText for the example above).


问:
min-height not allowing full height child
I Have a div with the following css class (generated)

```<code>min-height: {
    margin-top: 30px !important;
    margin-bottom: 30px !important;
    min-height: -webkit-calc(100% - 60px) !important;
    min-height: -moz-calc(100% - 60px) !important;
    min-height: calc(100% - 60px) !important;
}
</code>```

when I add a div inside with a height of 100% the content doesn't fill to the parent div - only when the parent div has the height attribute set not the min-height.

How can i make the  child div expand to the full size of the parent div if it only has min-height set?

```<code><div class="min-height">
    <div class="full-height">not much content<div>
</div>
</code>```

答:
The min-height class should also have a height. Then add the following rules for the full-height class:

.full-height {
  display: block;
  height: 100%;
}```

Body:
I Have a div with the following css class (generated)

min-height: {
    margin-top: 30px !important;
    margin-bottom: 30px !important;
    min-height: -webkit-calc(100% - 60px) !important;
    min-height: -moz-calc(100% - 60px) !important;
    min-height: calc(100% - 60px) !important;
}

when I add a div inside with a height of 100% the content doesn't fill to the parent div - only when the parent div has the height attribute set not the min-height.

How can i make the  child div expand to the full size of the parent div if it only has min-height set?

not much content


问:
how can I verify content based on future date?
I have a content to verify in a webpage which will change after a month or so? how can I write code for this with java in selenium that if today's date is 25th dec then verify some content. I dont want to change todays date from calendar date picker. By default when current date reaches to certain time ( for exmp 25th dec) then it will verify those content or else verify current content.

Thanks in Advance.

答:
You can use DateTime to dynamically change dates based off of your current date to get consistent results.

For instance, if you want yesterdays date in the MM/dd/yyyy format, you can call the following:

```<code>DateTime.Now.Subtract(TimeSpan.FromDays(1)).ToString("MM/dd/yyyy")
</code>```

Or if you want tomorrows date:

```<code>DateTime.Now.Add(TimeSpan.FromDays(1)).ToString("MM/dd/yyyy")
</code>```

Body:
You can use DateTime to dynamically change dates based off of your current date to get consistent results.

For instance, if you want yesterdays date in the MM/dd/yyyy format, you can call the following:

DateTime.Now.Subtract(TimeSpan.FromDays(1)).ToString("MM/dd/yyyy")

Or if you want tomorrows date:

DateTime.Now.Add(TimeSpan.FromDays(1)).ToString("MM/dd/yyyy")


问:
haml linebreaks
```<code>- if @likelist
          You like
          = @likelist.products.size
          products.
          = link_to "Likelist", likelist_path
</code>```

this results in ugly linebreaks -->

```<code>     <div id='likelist_link'>
        You like
        1
        products.
        <a href="/likelist">Likelist</a>
      </div>
</code>```

is there a way to get everything in one line?

答:
```<code>- if @likelist
  You like #{@likelist.products.size} products. #{link_to "Likelist", likelist_path}
</code>```

Title: haml linebreaks

Body:
- if @likelist
          You like
          = @likelist.products.size
          products.
          = link_to "Likelist", likelist_path

this results in ugly linebreaks -->

        You like
        1
        products.
        Likelist

is there a way to get everything in one line?


问:
Sass installation error
I use Linux Mint and I want to install sass. I have installed ruby by "sudo apt install ruby" , version 2.3 and then , when I wan to install sass by "sudo gem install sass --no-user-install" , I have the following error: </p>

```<code>Building native extensions. This could take a while...
ERROR:  Error installing sass:
    ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/ffi-1.9.18/ext/ffi_c
/usr/bin/ruby2.3 -r ./siteconf20171114-19329-157auxp.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/ffi-1.9.18 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/ffi-1.9.18/gem_make.out
</code>```

答:
Install this package:

```<code>sudo apt install ruby-dev
</code>```

The ruby-dev package contains the missing headers. You can see that the installer is looking for the headers:

```<code>/usr/lib/ruby/include/ruby.h
</code>```

Installing this package will install those headers. This is a common issue that comes up for new Ruby users when installing gems with native extensions. You may find that you have to install several packages to get the installation to complete. If you see similar errors when installing this gem or other gems, try searching for "gemname native extension prerequisites", like "sass gem native extension prerequisites", to learn which packages should be installed before installing the gem.

Title: Sass installation error

Body:
I use Linux Mint and I want to install sass. I have installed ruby by "sudo apt install ruby" , version 2.3 and then , when I wan to install sass by "sudo gem install sass --no-user-install" , I have the following error:

Building native extensions. This could take a while...
ERROR:  Error installing sass:
    ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.3.0/gems/ffi-1.9.18/ext/ffi_c
/usr/bin/ruby2.3 -r ./siteconf20171114-19329-157auxp.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/ffi-1.9.18 for inspection.
Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/ffi-1.9.18/gem_make.out

Body:
Install this package:

sudo apt install ruby-dev

The ruby-dev package contains the missing headers. You can see that the installer is looking for the headers:

/usr/lib/ruby/include/ruby.h

Installing this package will install those headers. This is a common issue that comes up for new Ruby users when installing gems with native extensions. You may find that you have to install several packages to get the installation to complete. If you see similar errors when installing this gem or other gems, try searching for "gemname native extension prerequisites", like "sass gem native extension prerequisites", to learn which packages should be installed before installing the gem.


问:
I want to output a list of every Case_Number with Code 1 that has a higher UniqueID value than its Code 2 counterpart's UniqueID value
I have a table which looks something like this:

```<code>    Case_Number  |  Code  |  UniqueID
        a             1       1372
        a             2       1352
        a             3       1325
        b             1       1642
        b             2       1651
        b             3       1623
        c             1       1743
        c             2       1739
        c             3       1720
       ...           ...        ...
</code>```

From this database I want to output a list of every Case_Number where the UniqueID value of Code 1 is higher than the UniqueID value of Code 2 (But ignoring the UniqueID value of Code 2, or any other Code x that might be in the table). Meaning that if the UniqueID value of Code 2 is higher than Code 1, which is the case with Case_Number b in the example above, it should not show up in the list.

So, querying the above table would result in this:

```<code>    Case_Number  |  Code  |  UniqueID
        a             1       1372
        c             1       1743
</code>```

答:
Hmmm . . . You seem to want:

```<code>select t.*
from t
where t.code = 1 and
      t.uniqueid > (select max(t2.uniqueid)
                    from t t2
                    where t2.case_number = t.case_number and t2.code = 2
                   );
</code>```

The max() in the subquery is simply to handle the case where there is more than one matching value.

Body:
I have a table which looks something like this:

    Case_Number  |  Code  |  UniqueID
        a             1       1372
        a             2       1352
        a             3       1325
        b             1       1642
        b             2       1651
        b             3       1623
        c             1       1743
        c             2       1739
        c             3       1720
       ...           ...        ...

From this database I want to output a list of every Case_Number where the UniqueID value of Code 1 is higher than the UniqueID value of Code 2 (But ignoring the UniqueID value of Code 2, or any other Code x that might be in the table). Meaning that if the UniqueID value of Code 2 is higher than Code 1, which is the case with Case_Number b in the example above, it should not show up in the list.

So, querying the above table would result in this:

    Case_Number  |  Code  |  UniqueID
        a             1       1372
        c             1       1743

Body:
Hmmm . . . You seem to want:

select t.*
from t
where t.code = 1 and
      t.uniqueid > (select max(t2.uniqueid)
                    from t t2
                    where t2.case_number = t.case_number and t2.code = 2
                   );

The max() in the subquery is simply to handle the case where there is more than one matching value.


问:
Lagom. Throttling for external service
I am playing with Lagom, it looks nice, but I completely lost with one issue.

Lets say I have dependency on external HTTP service, it allow only 10 requests/sec, in other case can even ban:)
I googled, but didn't found any working example. I can wrap service in untyped actor and add rate limiter to it, but I don't understand how to implement it on top of Akka Typed or Lagom service.

Maybe someone solved such task already? Thanks!

答:
You want a token bucket. Akka-Streams has this built in with Flow.throttle but it sounds like you're using raw akka so can't use that. There exists a token bucket implementation in Akka but unfortunately it doesn't give any guidance on usage, and I've not used it myself.

For my own use-cases (not Akka but using Scala Futures) I wrote my own token bucket. It allows me to refer the triggering of a Future based on the limit specified. It's coded against monix scheduler but that's very similar to the Akka schedule for this purpose:

```<code>import java.util.concurrent.ConcurrentLinkedQueue

import monix.execution.Scheduler.Implicits.global
import monix.execution.atomic.AtomicInt

import scala.concurrent.{Future, Promise}
import scala.concurrent.duration._

case class RateLimiter(duration: FiniteDuration, maxInvocations: Int) {

  @volatile var permits: Int = maxInvocations
  val queue = new ConcurrentLinkedQueue[() => Any]()

  global.scheduleAtFixedRate(duration, duration) {
    this synchronized {
      permits = maxInvocations

      while (!queue.isEmpty && permits > 0) {
        Option(queue.poll()).foreach { fun =>
          permits -= 1
          fun.apply()
        }
      }
    }
  }

  def apply[T](f: => Future[T]): Future[T] =
    this synchronized {
      if (permits > 0) {
        permits -= 1
        f
      } else {
        val res = Promise[T]()
        queue.add(() => { res.completeWith(f) })
        res.future
      }
    }
}
</code>```

Usage is

```<code>val limiter = RateLimiter(1.second, 10)

limiter {
  someWebService.asyncCall()
}
</code>```

Title: Lagom. Throttling for external service

Body:
You want a token bucket. Akka-Streams has this built in with Flow.throttle but it sounds like you're using raw akka so can't use that. There exists a token bucket implementation in Akka but unfortunately it doesn't give any guidance on usage, and I've not used it myself.

For my own use-cases (not Akka but using Scala Futures) I wrote my own token bucket. It allows me to refer the triggering of a Future based on the limit specified. It's coded against monix scheduler but that's very similar to the Akka schedule for this purpose:

import java.util.concurrent.ConcurrentLinkedQueue

import monix.execution.Scheduler.Implicits.global
import monix.execution.atomic.AtomicInt

import scala.concurrent.{Future, Promise}
import scala.concurrent.duration._

case class RateLimiter(duration: FiniteDuration, maxInvocations: Int) {

  @volatile var permits: Int = maxInvocations
  val queue = new ConcurrentLinkedQueue[() => Any]()

  global.scheduleAtFixedRate(duration, duration) {
    this synchronized {
      permits = maxInvocations

      while (!queue.isEmpty && permits > 0) {
        Option(queue.poll()).foreach { fun =>
          permits -= 1
          fun.apply()
        }
      }
    }
  }

  def apply[T](f: => Future[T]): Future[T] =
    this synchronized {
      if (permits > 0) {
        permits -= 1
        f
      } else {
        val res = Promise[T]()
        queue.add(() => { res.completeWith(f) })
        res.future
      }
    }
}

Usage is

val limiter = RateLimiter(1.second, 10)

limiter {
  someWebService.asyncCall()
}


问:
How do I figure out what is causing Data IO spikes on my Azure SQL database?
I have a Azure SQL production database that runs at around 10-20% DTU usage on average, however, I get DTU spikes that take it upwards of 100% at times. Here is a sample from the past 1 hour:

I realize this could be a rouge query, so I switched over to the Query Performance Insight tab, and I find the following from the past 24 hours:

This chart makes sense with regards to the CPU usage line. Query 3780 takes the majority of at CPU, as expected with my application. The Overall DTU (red) line seems to follow this correctly (minus the spikes).

However, in the DTU Components charts I can see large Data IO spikes occurring that coincide with the Overall DTU spikes. Switching over to the TOP 5 queries by Data IO, I see the following:

This seems to indicate that there are no queries that are using high amounts of Data IO.

How do I find out where this Data IO usage is coming from?

Finally, I see that there is this one, "odd ball" query (7966) listed under the TOP 5 queries by Data IO with only 5 executions. Selecting it shows the following:

```<code>SELECT StatMan([SC0], [SC1], [SC2], [SB0000])
    FROM (SELECT TOP 100 PERCENT [SC0], [SC1], [SC2], step_direction([SC0]) over (order by NULL) AS [SB0000]
    FROM (SELECT [UserId] AS [SC0], [Type] AS [SC1], [Id] AS [SC2] FROM [dbo].[Cipher] TABLESAMPLE SYSTEM (1.828756e+000 PERCENT)
    WITH (READUNCOMMITTED) ) AS _MS_UPDSTATS_TBL_HELPER
ORDER BY [SC0], [SC1], [SC2], [SB0000] ) AS _MS_UPDSTATS_TBL
OPTION (MAXDOP 16)
</code>```

What is this query?

This does not look like any query that my application has created/uses. The timestamps on the details chart seem to line up with the approximate times of the overall Data IO spikes (just prior to 6am) which leads me to think this query has something to do with all of this.

Are there any other tools can I use to help isolate this issue?

答: It seems that query is part of the automatic update of statistics process. To mitigate the impact of this process on production you can regularly update statistics and indexes using runbooks  as explained here. Run sp_updatestats to immediately try to mitigate the impact of this process.</p>

Body:
I have a Azure SQL production database that runs at around 10-20% DTU usage on average, however, I get DTU spikes that take it upwards of 100% at times. Here is a sample from the past 1 hour:

I realize this could be a rouge query, so I switched over to the Query Performance Insight tab, and I find the following from the past 24 hours:

This chart makes sense with regards to the CPU usage line. Query 3780 takes the majority of at CPU, as expected with my application. The Overall DTU (red) line seems to follow this correctly (minus the spikes).

However, in the DTU Components charts I can see large Data IO spikes occurring that coincide with the Overall DTU spikes. Switching over to the TOP 5 queries by Data IO, I see the following:

This seems to indicate that there are no queries that are using high amounts of Data IO.

How do I find out where this Data IO usage is coming from?

Finally, I see that there is this one, "odd ball" query (7966) listed under the TOP 5 queries by Data IO with only 5 executions. Selecting it shows the following:

SELECT StatMan([SC0], [SC1], [SC2], [SB0000])
    FROM (SELECT TOP 100 PERCENT [SC0], [SC1], [SC2], step_direction([SC0]) over (order by NULL) AS [SB0000]
    FROM (SELECT [UserId] AS [SC0], [Type] AS [SC1], [Id] AS [SC2] FROM [dbo].[Cipher] TABLESAMPLE SYSTEM (1.828756e+000 PERCENT)
    WITH (READUNCOMMITTED) ) AS _MS_UPDSTATS_TBL_HELPER
ORDER BY [SC0], [SC1], [SC2], [SB0000] ) AS _MS_UPDSTATS_TBL
OPTION (MAXDOP 16)

What is this query?

This does not look like any query that my application has created/uses. The timestamps on the details chart seem to line up with the approximate times of the overall Data IO spikes (just prior to 6am) which leads me to think this query has something to do with all of this.

Are there any other tools can I use to help isolate this issue?


问:
VBA Delete Excel column and header if all cells in column (except header) are empty?
I have some vba code that populates an excel table with specific texts.  I'm hoping to add a function to the code that deletes a column (and the header) if that column is empty (no text strings present).  I have searched for some codes but none have been able to work.  Any suggestions?</p>

答:
Below simple function will check, if given column is empty. Optional argument let you set, if empty column should include headers.

```<code>Function IsColumnEmpty(ByVal rngColumn As Range, Optional bIncludeHeaders As Boolean = True) As Boolean
    IsColumnEmpty = False
    If bIncludeHeaders = True Then
        If WorksheetFunction.CountA(rngColumn) = 1 Then
            IsColumnEmpty = True
        End If
    Else
        If WorksheetFunction.CountA(rngColumn) = 0 Then
            IsColumnEmpty = True
        End If
    End If
End Function
</code>```

To delete an empty column you can use it as below:

```<code>If IsColumnEmpty(Sheets(1).Column(1)) = true then
    Sheets(1).Column(1).Delete
End If
</code>```

Body:
Below simple function will check, if given column is empty. Optional argument let you set, if empty column should include headers.

Function IsColumnEmpty(ByVal rngColumn As Range, Optional bIncludeHeaders As Boolean = True) As Boolean
    IsColumnEmpty = False
    If bIncludeHeaders = True Then
        If WorksheetFunction.CountA(rngColumn) = 1 Then
            IsColumnEmpty = True
        End If
    Else
        If WorksheetFunction.CountA(rngColumn) = 0 Then
            IsColumnEmpty = True
        End If
    End If
End Function

To delete an empty column you can use it as below:

If IsColumnEmpty(Sheets(1).Column(1)) = true then
    Sheets(1).Column(1).Delete
End If


问:
Creating a container with a slanted edge
I have a client who requested the following in his design:

What is the easiest way to create the yellow container, with the slanted edge on the bottom? Can I do it within the interface builder or do I have to do it programatically? I'm trying to do this in swift.

答:
Maybe make a custom view that you can drop down in interface builder? This version has a property you can set in IB that determines the slant fraction so you can size it the way you want:</p>

```<code>@IBDesignable class SlantedView: UIView {

    @IBInspectable var slant: Double = 0.8

    override func prepareForInterfaceBuilder() {
        // Called when initialized in IB
        setup()
    }

    override func awakeFromNib() {
        // Called when initialized in actual app
        setup()
    }

    func setup() {
        layer.backgroundColor = UIColor.yellow.cgColor

        recalculateMask()
    }

    func recalculateMask() {
        let shapeLayer = CAShapeLayer()

        let maskPath = CGMutablePath()
        maskPath.move(to: CGPoint(x: 0, y: 0))
        maskPath.addLine(to: CGPoint(x: bounds.width, y: 0))
        maskPath.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
        maskPath.addLine(to: CGPoint(x: 0, y: bounds.height * CGFloat(slant)))

        shapeLayer.path = maskPath
        layer.mask = shapeLayer
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        recalculateMask()
    }
}
</code>```

Body:
Maybe make a custom view that you can drop down in interface builder? This version has a property you can set in IB that determines the slant fraction so you can size it the way you want:

@IBDesignable class SlantedView: UIView {

    @IBInspectable var slant: Double = 0.8

    override func prepareForInterfaceBuilder() {
        // Called when initialized in IB
        setup()
    }

    override func awakeFromNib() {
        // Called when initialized in actual app
        setup()
    }

    func setup() {
        layer.backgroundColor = UIColor.yellow.cgColor

        recalculateMask()
    }

    func recalculateMask() {
        let shapeLayer = CAShapeLayer()

        let maskPath = CGMutablePath()
        maskPath.move(to: CGPoint(x: 0, y: 0))
        maskPath.addLine(to: CGPoint(x: bounds.width, y: 0))
        maskPath.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
        maskPath.addLine(to: CGPoint(x: 0, y: bounds.height * CGFloat(slant)))

        shapeLayer.path = maskPath
        layer.mask = shapeLayer
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        recalculateMask()
    }
}


问:
col and row names in a Forest plot
I don't how to introduce columns and rows names into a forest plot. Here is the dataset:

```<code>structure(list(structure(c(5L, 6L, 4L, 3L, 2L, 1L), .Label = c("Austria",
"Denmark", "England", "France", "Portugal", "Spain"), class = "factor"),
Slope = c(-1.8511, -2.33305, -2.698, -1.46, -0.98, -1.401
), low = c(-3.3021, -4.305, -5.873, -4.86, -5.082, -2.887
), high = c(-0.4008, -0.364, -0.087, 2.98, 3.125, -0.054),
bS0 = c(-5.66, -2.709, -4.057, -1.224, -0.574, -1.43), Sf = c(0.354,
0.169, 0.253, 0.077, 0.036, 0.089), `S0-Sf` = c(0.146, 0.126,
0.169, 0.091, 0.061, 0.088)), .Names = c("", "Slope", "low",
"high", "bS0", "Sf", "S0-Sf"), class = "data.frame", row.names = c(NA,
-6L))
</code>```

And here the script to get the Forest plot:

```<code>windows()
forestplot(labeltext=data, graph.pos=3,
       mean=c(data$Slope),
       lower=c(data$low), upper=c(data$high),
       xlab="Regression Coefficient",
       txt_gp=fpTxtGp(label=gpar(cex=1),
                      ticks=gpar(cex=1),
                      xlab=gpar(cex = 1),
                      title=gpar(cex = 1)),
       col=fpColors(box="black", lines="black", zero = "gray50"),
       zero=0, cex=0.9, lineheight = "auto", boxsize=0.1,
       lwd.ci=1, ci.vertices=TRUE, ci.vertices.height = 0.1,colgap=unit(4,"mm"))
</code>```

And here is the outcome:

However, I would like to introduce the names of the countries (column 1 of my data) and the columns names. How should I do it?

答:
You need to use graph.pos argument inside the forestplot function.

For example, use graph.position=3 if you want the plot after the slope column

Title: col and row names in a Forest plot

Body:
I don't how to introduce columns and rows names into a forest plot. Here is the dataset:

structure(list(structure(c(5L, 6L, 4L, 3L, 2L, 1L), .Label = c("Austria",
"Denmark", "England", "France", "Portugal", "Spain"), class = "factor"),
Slope = c(-1.8511, -2.33305, -2.698, -1.46, -0.98, -1.401
), low = c(-3.3021, -4.305, -5.873, -4.86, -5.082, -2.887
), high = c(-0.4008, -0.364, -0.087, 2.98, 3.125, -0.054),
bS0 = c(-5.66, -2.709, -4.057, -1.224, -0.574, -1.43), Sf = c(0.354,
0.169, 0.253, 0.077, 0.036, 0.089), `S0-Sf` = c(0.146, 0.126,
0.169, 0.091, 0.061, 0.088)), .Names = c("", "Slope", "low",
"high", "bS0", "Sf", "S0-Sf"), class = "data.frame", row.names = c(NA,
-6L))

And here the script to get the Forest plot:

windows()
forestplot(labeltext=data, graph.pos=3,
       mean=c(data$Slope),
       lower=c(data$low), upper=c(data$high),
       xlab="Regression Coefficient",
       txt_gp=fpTxtGp(label=gpar(cex=1),
                      ticks=gpar(cex=1),
                      xlab=gpar(cex = 1),
                      title=gpar(cex = 1)),
       col=fpColors(box="black", lines="black", zero = "gray50"),
       zero=0, cex=0.9, lineheight = "auto", boxsize=0.1,
       lwd.ci=1, ci.vertices=TRUE, ci.vertices.height = 0.1,colgap=unit(4,"mm"))

And here is the outcome:

However, I would like to introduce the names of the countries (column 1 of my data) and the columns names. How should I do it?


问:
Upper case letters in a URL, should it be advertised that way?
Currently, our URL's look something like this:

```<code>http://helpdesk.ourdomain.com
</code>```

Recently, there has been talk of advertising these URLs (in publications, on websites, etc.) to look like this for readability purposes:

```<code>http://HelpDesk.OurDomain.com
</code>```

Our web server handles going to the URL with upper-case elements in it correctly, meaning when you go to that URL, it rewrites the URL to be all lower-case. However, I was always taught that URL's are meant to be case-sensitive. Keeping that in mind, I would think that advertising the URL's with upper-case letters would not be something that should be done.

Is advertising URL's with upper-case letters in it an okay practice? Why or why not?

答:
From the spec:

When comparing two URIs to decide if they match or not, a client SHOULD use a case-sensitive octet-by-octet comparison of the entire URIs, with these exceptions:

```<code>  - A port that is empty or not given is equivalent to the default
    port for that URI-reference;

    - Comparisons of host names MUST be case-insensitive;

    - Comparisons of scheme names MUST be case-insensitive;

    - An empty abs_path is equivalent to an abs_path of "/".
</code>```

Body:
Currently, our URL's look something like this:

http://helpdesk.ourdomain.com

Recently, there has been talk of advertising these URLs (in publications, on websites, etc.) to look like this for readability purposes:

http://HelpDesk.OurDomain.com

Our web server handles going to the URL with upper-case elements in it correctly, meaning when you go to that URL, it rewrites the URL to be all lower-case. However, I was always taught that URL's are meant to be case-sensitive. Keeping that in mind, I would think that advertising the URL's with upper-case letters would not be something that should be done.

Is advertising URL's with upper-case letters in it an okay practice? Why or why not?

Body:
From the spec:

When comparing two URIs to decide if they match or not, a client SHOULD use a case-sensitive octet-by-octet comparison of the entire URIs, with these exceptions:

  - A port that is empty or not given is equivalent to the default
    port for that URI-reference;

    - Comparisons of host names MUST be case-insensitive;

    - Comparisons of scheme names MUST be case-insensitive;

    - An empty abs_path is equivalent to an abs_path of "/".


问:
Quick way to find all permutations of a pandas DataFrame that preserves a sort?
I have a DataFrame, and I'd like find all the permutations of it that fulfill a simple ascending sort on one of the columns. (There are many ties.) For example, in the following DataFrame

```<code>df = pd.DataFrame({'name': ["Abe", "Bob", "Chris", "David", "Evan"],
                   'age': [28, 20, 21, 22, 21]})
</code>```

I'd be looking to sort by age and obtain the orders ["Bob", "Chris", "Evan", "David", "Abe"] and ["Bob", "Evan", "Chris", "David", "Abe"].

I'm new to python (and to pandas) and curious if there is a simple way to do this that I don't see.

Thanks!

答:
```<code>import pandas as pd

df.sort_values(by = 'age')
</code>```

Body:
I have a DataFrame, and I'd like find all the permutations of it that fulfill a simple ascending sort on one of the columns. (There are many ties.) For example, in the following DataFrame

df = pd.DataFrame({'name': ["Abe", "Bob", "Chris", "David", "Evan"],
                   'age': [28, 20, 21, 22, 21]})

I'd be looking to sort by age and obtain the orders ["Bob", "Chris", "Evan", "David", "Abe"] and ["Bob", "Evan", "Chris", "David", "Abe"].

I'm new to python (and to pandas) and curious if there is a simple way to do this that I don't see.

Thanks!


问:
convert a string to a list of object using Java 8
I have a string

```<code>"Red apple, blue banana, orange".
</code>```

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

```<code>   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());
</code>```

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

答:
Use map(...) method to perform transformations on the original String. Instead of calling Fruit::valueOf through a method reference, split each string on space inside map(...), and construct a combined string when you get exactly two parts:

```<code>List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
.map(s -> {
    String[] parts = s.split(" ");
    String tmp = parts.length == 2
    ? parts[0]+"_"+parts[1]
    : s;
    return Fruit.valueOf(tmp.toUpperCase());
}).collect(Collectors.toList());
</code>```

Demo.

If you need to perform any additional transformations of the result, you can do them in the same lambda code block prior to the return statement.

Body:
I have a string

"Red apple, blue banana, orange".

How could I split it by ", " first then add "_" between two words (such as Red_apple but not orange) and capitalize all letters. I read a few posts and found a solution but it only has the split part and how could I also add "_" and capitalize all letters? :

   Pattern pattern = Pattern.compile(", ");
   List<Fruit> f = pattern.splitAsStream(fruitString)
  .map(Fruit::valueOf)
  .collect(Collectors.toList());

Fruit is a enum object. So basically if I am able to convert a string to a certain format and I am able get a Enum object based on a Enum name.

Body:
Use map(...) method to perform transformations on the original String. Instead of calling Fruit::valueOf through a method reference, split each string on space inside map(...), and construct a combined string when you get exactly two parts:

List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
.map(s -> {
    String[] parts = s.split(" ");
    String tmp = parts.length == 2
    ? parts[0]+"_"+parts[1]
    : s;
    return Fruit.valueOf(tmp.toUpperCase());
}).collect(Collectors.toList());

Demo.

If you need to perform any additional transformations of the result, you can do them in the same lambda code block prior to the return statement.


问:
How to set region and zone (Google Cloud Platform) in DataProcPigOperator with Airflow
i have get problem. I will create code DataProcPigOperator before running well because default zone is running global, but i change definition region in my cluster in asia-easth1 code is not running, because DataProcPigOperator is default job running global region. Any Solution..??

```<code>t1 = DataProcPigOperator(
        task_id='abc',
        dataproc_cluster='abc-cluster-{{ ds_nodash }}',
        gcp_conn_id='abc_gcp_connection',
        query_uri='gs://abc/abc-ng/abc.pig',
        variables={'INPUT': 'gs://abc/abc-ng/summary/*', 'OUTPUT': 'gs://abc/abc-ng/output/'},
        dag=dag
    )
</code>```

How to set Region and Zone in DataProcPigOperator..??

Thanks.

答:
Thanks for bringing this up, the region field was added to Pig and a few other job types that omitted it by this pull request:

https://github.com/apache/incubator-airflow/pull/2788

Body:
i have get problem. I will create code DataProcPigOperator before running well because default zone is running global, but i change definition region in my cluster in asia-easth1 code is not running, because DataProcPigOperator is default job running global region. Any Solution..??

t1 = DataProcPigOperator(
        task_id='abc',
        dataproc_cluster='abc-cluster-{{ ds_nodash }}',
        gcp_conn_id='abc_gcp_connection',
        query_uri='gs://abc/abc-ng/abc.pig',
        variables={'INPUT': 'gs://abc/abc-ng/summary/*', 'OUTPUT': 'gs://abc/abc-ng/output/'},
        dag=dag
    )

How to set Region and Zone in DataProcPigOperator..??

Thanks.


答:
Your Enum

```<code>static enum Fruit {
    RED_APPLE, BLUE_BANANA, ORANGE
}
</code>```

Main code:

```<code>public static void main(String[] ar) throws Exception {
    Pattern pattern = Pattern.compile(", ");
    List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
            .map(YourClass::mapToFruit)
            .collect(Collectors.toList());
    System.out.println(f);
}
</code>```

Helper method to offload dirty mapping part

```<code>private static Fruit mapToFruit(String input) {
    String[] words = input.split("\\s");
    StringBuilder sb = new StringBuilder();
    if (words.length > 1) {
        for (int i = 0; i < words.length - 1; i++) {
            sb.append(words[i].toUpperCase());
            sb.append("_");
        }
        sb.append(words[words.length - 1].toUpperCase());
    } else {
        sb.append(words[0].toUpperCase());
    }
    return Fruit.valueOf(sb.toString());
}
</code>```

Title: convert a string to a list of object using Java 8

Body:
Your Enum

static enum Fruit {
    RED_APPLE, BLUE_BANANA, ORANGE
}

Main code:

public static void main(String[] ar) throws Exception {
    Pattern pattern = Pattern.compile(", ");
    List<Fruit> f = pattern.splitAsStream("Red apple, blue banana, orange")
            .map(YourClass::mapToFruit)
            .collect(Collectors.toList());
    System.out.println(f);
}

Helper method to offload dirty mapping part

private static Fruit mapToFruit(String input) {
    String[] words = input.split("\\s");
    StringBuilder sb = new StringBuilder();
    if (words.length > 1) {
        for (int i = 0; i < words.length - 1; i++) {
            sb.append(words[i].toUpperCase());
            sb.append("_");
        }
        sb.append(words[words.length - 1].toUpperCase());
    } else {
        sb.append(words[0].toUpperCase());
    }
    return Fruit.valueOf(sb.toString());
}


问:
What are the real benefits of using the Abstract Factory in the following example, instead of the factory method?
Before writing the question I read the following references:

Factory Method Vs Abstract Factory

Abstract Factory vs Factory Method (scope)

Abstract Factory, Factory Method, Builder

Factory, Abstract Factory and Factory Method

Differences between Abstract Factory Pattern and Factory Method

I see that many like me have had difficulty "grasping" the concrete differences between Abstract Factory and Factory Pattern.
I'm not familiar with the design patterns, I came across this example http://www.oracle.com/technetwork/java/dataaccessobject-138824.html and I'm trying to deepen the topic.

By comparing, I see that for 3 DTO we have:

1) Abstract Factory

1 abstract class (with 3 abstract methods and 3 switch-cases);

3 factory classes for persistence type (each with 3 methods for obtaining DTO DAOs)

3 interfaces and 9 DAOs.

2) Factory Method:

3 factory classes, one for each interface (each with 3 switch-case);

Possibly I can create 3 superclasses from which to extend the DAO classes to not duplicate the code, such as that for connecting to the database;

3 interfaces and 9 DAOs.

From the point of view of the quantity of code I do not see any substantial differences.
In cases where you need to add a new persistence support or a new interface / DTO, the differences are minimal (and complementary).

From the client's point of view:

1) Abstract Factory:

```<code>public static final int PERSISTENCE_TYPE = DAOFactory.ORACLE;

DAOFactory daoFactory = DAOFactory.getDAOFactory(PERSISTENCE_TYPE);

CustomerDAO cDAO = daoFactory.getCustomerDAO();
AccountDAO aDAO = daoFactory.getAccountDAO();
OrderDAO oDAO = daoFactory.getOrderDAO();
</code>```

2) Factory Method:

```<code>public static final int PERSISTENCE_TYPE = DAOFactory.ORACLE;

CustomerDAO cDAO = CustomerDAOFactory.getCustomerDAO(PERSISTENCE_TYPE);
AccountDAO aDAO = AccountDAOFactory.getAccountDAO(PERSISTENCE_TYPE);
OrderDAO oDAO = OrderDAOFactory.getOrderDAO(PERSISTENCE_TYPE);
</code>```

Is there an advantage in using a DAOFactory regarding the persistence type and returns all DAOs related to that support instead of using multiple DAOFactory for each DTO to get the DAO for the type of persistence used?

For now I see only aesthetic-conceptual difference in using the Abstract Factory, is there also a utility benefit that I can not grasp for my ignorance about software design??

答:
One note to previous answear You can read factory method in Efecrive Java 2nd edition .
But to imagin difference in real world between patterns please see :
For example

Factory

Imagine you are constructing a house and you approach a carpenter for a window. You give  your requirements, and he will construct a window . In this case, the carpenter is a factory of windows. Your specifications are inputs for the factory, and the window is the output from the factory.

Abstract Factory

Now, consider the same example of the window. You can go to a carpenter, or you can go to a window shop or a PVC shop. All of them are window factories. Based on the situation, you decide what kind of factory you need to approach.

So conclution - It depend on problem which you solve .

Body:
Before writing the question I read the following references:

Factory Method Vs Abstract Factory

Abstract Factory vs Factory Method (scope)

Abstract Factory, Factory Method, Builder

Factory, Abstract Factory and Factory Method

Differences between Abstract Factory Pattern and Factory Method

I see that many like me have had difficulty "grasping" the concrete differences between Abstract Factory and Factory Pattern.
I'm not familiar with the design patterns, I came across this example http://www.oracle.com/technetwork/java/dataaccessobject-138824.html and I'm trying to deepen the topic.

By comparing, I see that for 3 DTO we have:

1) Abstract Factory

1 abstract class (with 3 abstract methods and 3 switch-cases);

3 factory classes for persistence type (each with 3 methods for obtaining DTO DAOs)

3 interfaces and 9 DAOs.

2) Factory Method:

3 factory classes, one for each interface (each with 3 switch-case);

Possibly I can create 3 superclasses from which to extend the DAO classes to not duplicate the code, such as that for connecting to the database;

3 interfaces and 9 DAOs.

From the point of view of the quantity of code I do not see any substantial differences.
In cases where you need to add a new persistence support or a new interface / DTO, the differences are minimal (and complementary).

From the client's point of view:

1) Abstract Factory:

public static final int PERSISTENCE_TYPE = DAOFactory.ORACLE;

DAOFactory daoFactory = DAOFactory.getDAOFactory(PERSISTENCE_TYPE);

CustomerDAO cDAO = daoFactory.getCustomerDAO();
AccountDAO aDAO = daoFactory.getAccountDAO();
OrderDAO oDAO = daoFactory.getOrderDAO();

2) Factory Method:

public static final int PERSISTENCE_TYPE = DAOFactory.ORACLE;

CustomerDAO cDAO = CustomerDAOFactory.getCustomerDAO(PERSISTENCE_TYPE);
AccountDAO aDAO = AccountDAOFactory.getAccountDAO(PERSISTENCE_TYPE);
OrderDAO oDAO = OrderDAOFactory.getOrderDAO(PERSISTENCE_TYPE);

Is there an advantage in using a DAOFactory regarding the persistence type and returns all DAOs related to that support instead of using multiple DAOFactory for each DTO to get the DAO for the type of persistence used?

For now I see only aesthetic-conceptual difference in using the Abstract Factory, is there also a utility benefit that I can not grasp for my ignorance about software design??


问:
How to click at an element by the CSS code using Protractor?
I've been trying to click at the element using CSS Selector but it doesn't work:

```<code><button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view">
         <i _ngcontent-c16="" class="zmdi zmdi-more-vert"></i>
</button>
</code>```

I'm trying:

```<code>element.all(by.css('.btn .btn-flat .btn-no-text .btn-kebab-view')).first().click();
</code>```

Protractor gives me error:

Failed: Index out of bound. Trying to access element at index: 0, but
  there are only 0 elements that match locator By(css selector, .btn
  .btn-flat .btn-no-text .btn-kebab-view)

答:
Try to use XPath:

For the button:

```<code>//button[@class='btn btn-flat btn-no-text btn-kebab-view']
</code>```

Or for the i tag:

```<code>//i[@class='zmdi zmdi-more-vert']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been trying to click at the element using CSS Selector but it doesn't work:

<button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view">

</button>

I'm trying:

element.all(by.css('.btn .btn-flat .btn-no-text .btn-kebab-view')).first().click();

Protractor gives me error:

Failed: Index out of bound. Trying to access element at index: 0, but
  there are only 0 elements that match locator By(css selector, .btn
  .btn-flat .btn-no-text .btn-kebab-view)

Body:
Try to use XPath:

For the button:

//button[@class='btn btn-flat btn-no-text btn-kebab-view']

Or for the i tag:

//i[@class='zmdi zmdi-more-vert']


问:
How to pick one list out of many based on value in Linq?
I have an object structure which looks like this.

```<code>public class DeliveryManagerQuoteResponse
{
    public string OrderId { get; set; }
    public List<DeliveryManagerQuotes> Quotes { get; set; }
}

public class DeliveryManagerQuotes
{
    public bool IsSuccess { get; set; }
    public List<DeliveryManagerQuoteDetails> QuoteDetails { get; set; }
}

public class DeliveryManagerQuoteDetails
{
    public string QuoteId { get; set; }
    public int? DeliveryFee { get; set; }
}
</code>```

When I have DeliveryManagerQuoteResponse populated, I'll have multiple Quotesand each Quotes will have multiple QuoteDetails. What I want is, based on DeliveryFee which in DeliveryManagerQuoteDetails, I want to pick the DeliveryManagerQuoteResponse which has a minimum delivery fee. How can I do that using LINQ?

I was thinking of getting DeliveryFee first from all Quotes and then write some code/LINQ to use that to fetch quote with a minimum fee but not sure how to write it :

```<code>public void PickDeliveryQuoteBasedOnRate(DeliveryManagerQuoteResponse deliveryManagerQuoteResponse)
{

    var feeList = new List<int>();
    foreach (var quote in deliveryManagerQuoteResponse.Quotes)
    {
        if (quote.QuoteDetails != null && quote.QuoteDetails.Any())
        {
            foreach (var quoteDetail in quote.QuoteDetails)
            {
                feeList.Add(quoteDetail.DeliveryFee ?? default(int));
            }
        }
    }

    if (feeList.Any())
    {
        // This will give me minimum fee
        var minimumDeliveryFee = feeList.Min();
        // Need LINQ to use this minimum fee to pick one quote.
    }

}
</code>```

Screen Shot for better understanding:

答:
Return QuoteDetail with minimum DeliveryFee:

```<code>deliveryManagerQuoteResponse
.Quotes
.SelectMany(p=>p.QuoteDetails)
.Where(p=>p.DeliveryFee.HasValue)
.Orderby(p=>p.DeliveryFee)
.FirstOrDefault();
</code>```

Return Quote With minimum Delivery in it's Detil, So transfering Quote with each QuoteDetail to used it in the last expression for return:

```<code>deliveryManagerQuoteResponse
  .Quotes
  .SelectMany(p=>p.QuoteDetails.Select(q=>new{Quote=p,Detail=q}))
  .Where(p=>p.Detail.DeliveryFee.HasValue)
  .Orderby(p=>p.Detail.DeliveryFee)
  .FirstOrDefault()?.Quote;
</code>```

Body:
I have an object structure which looks like this.

public class DeliveryManagerQuoteResponse
{
    public string OrderId { get; set; }
    public List<DeliveryManagerQuotes> Quotes { get; set; }
}

public class DeliveryManagerQuotes
{
    public bool IsSuccess { get; set; }
    public List<DeliveryManagerQuoteDetails> QuoteDetails { get; set; }
}

public class DeliveryManagerQuoteDetails
{
    public string QuoteId { get; set; }
    public int? DeliveryFee { get; set; }
}

When I have DeliveryManagerQuoteResponse populated, I'll have multiple Quotesand each Quotes will have multiple QuoteDetails. What I want is, based on DeliveryFee which in DeliveryManagerQuoteDetails, I want to pick the DeliveryManagerQuoteResponse which has a minimum delivery fee. How can I do that using LINQ?

I was thinking of getting DeliveryFee first from all Quotes and then write some code/LINQ to use that to fetch quote with a minimum fee but not sure how to write it :

public void PickDeliveryQuoteBasedOnRate(DeliveryManagerQuoteResponse deliveryManagerQuoteResponse)
{

    var feeList = new List<int>();
    foreach (var quote in deliveryManagerQuoteResponse.Quotes)
    {
        if (quote.QuoteDetails != null && quote.QuoteDetails.Any())
        {
            foreach (var quoteDetail in quote.QuoteDetails)
            {
                feeList.Add(quoteDetail.DeliveryFee ?? default(int));
            }
        }
    }

    if (feeList.Any())
    {
        // This will give me minimum fee
        var minimumDeliveryFee = feeList.Min();
        // Need LINQ to use this minimum fee to pick one quote.
    }

}

Screen Shot for better understanding:

Body:
Return QuoteDetail with minimum DeliveryFee:

deliveryManagerQuoteResponse
.Quotes
.SelectMany(p=>p.QuoteDetails)
.Where(p=>p.DeliveryFee.HasValue)
.Orderby(p=>p.DeliveryFee)
.FirstOrDefault();

Return Quote With minimum Delivery in it's Detil, So transfering Quote with each QuoteDetail to used it in the last expression for return:

deliveryManagerQuoteResponse
  .Quotes
  .SelectMany(p=>p.QuoteDetails.Select(q=>new{Quote=p,Detail=q}))
  .Where(p=>p.Detail.DeliveryFee.HasValue)
  .Orderby(p=>p.Detail.DeliveryFee)
  .FirstOrDefault()?.Quote;


问:
how to set selected value in dropdown based on another value
are there a away i can set the selected value on my dropdown based on the key value

<add key="ReCreateSoldPart" value="false" />from my appsetting

```<code>     <label for="autoCreateSoldPart" datalabel="mydropdown">Auto genopret solgt del
        <select name="autoCreateSoldPart">
            <option value="true">Ja</option>
            <option value="false"Nej</option>
        </select></label

>
</code>```

答:
To select an option in razor, do it as follows;
Using the @Html helper;

```<code>                @Html.Label("Auto genopret solgt del  ", new {@for= "autoCreateSoldPart"})
                @{
                    var lstSelect = new List<SelectListItem>()
                    {
                        new SelectListItem() { Text="Ja",Value="true"  },
                        new SelectListItem() { Text="Ja",Value="false"  }
                    };

                    lstSelect.ForEach(o =>
                    {
                        if (o.Value== System.Configuration.ConfigurationManager.AppSettings["ReCreateSoldPart"])
                        {
                            o.Selected = true;
                        }
                    });

                }
                @Html.DropDownList("autoCreateSoldPart", lstSelect,new { @class = "form-control" })
</code>```

Use the @Html.DropDown instead. Check the selectListItem property value of each item in List, if it matches your appsetting value, set the selected property to true

Body:
are there a away i can set the selected value on my dropdown based on the key value

<add key="ReCreateSoldPart" value="false" />from my appsetting

     Auto genopret solgt del
        <select name="autoCreateSoldPart">
            <option value="true">Ja</option>
            <option value="false"Nej</option>
        </select>

Body:
To select an option in razor, do it as follows;
Using the @Html helper;

                @Html.Label("Auto genopret solgt del&nbsp;&nbsp;", new {@for= "autoCreateSoldPart"})
                @{
                    var lstSelect = new List<SelectListItem>()
                    {
                        new SelectListItem() { Text="Ja",Value="true"  },
                        new SelectListItem() { Text="Ja",Value="false"  }
                    };

                    lstSelect.ForEach(o =>
                    {
                        if (o.Value== System.Configuration.ConfigurationManager.AppSettings["ReCreateSoldPart"])
                        {
                            o.Selected = true;
                        }
                    });

                }
                @Html.DropDownList("autoCreateSoldPart", lstSelect,new { @class = "form-control" })

Use the @Html.DropDown instead. Check the selectListItem property value of each item in List, if it matches your appsetting value, set the selected property to true


问:
Set UIButton Image with SVG file
I'm trying to set the Image of my UIBUtton with a SVG file...the click on the button works fine but it appears invisible. I'm trying to use PocketSVG: https://github.com/arielelkin/PocketSVG

There's what I'm trying:

```<code>CGPathRef myPath = [PocketSVG pathFromSVGFileNamed:@"icon_convidar.svg"];

        //2: To display it on screen, you can create a CAShapeLayer
        //and set myPath as its path property:
        CAShapeLayer *myShapeLayer = [CAShapeLayer layer];
        myShapeLayer.path = myPath;

        //3: Fiddle with it using CAShapeLayer's properties:
        myShapeLayer.strokeColor = [[UIColor greenColor] CGColor];
        myShapeLayer.lineWidth = 4;
        myShapeLayer.fillColor = [[UIColor greenColor] CGColor];

        //4: Display it!
    [self.btnConvidar.layer addSublayer:myShapeLayer];
</code>```

答: You can't use SVG because iOS has no support for XML or SVG. PDF however will work. This is the best tutorial I have found on the subject: https://useyourloaf.com/blog/xcode-9-vector-images/</p>

Title: Set UIButton Image with SVG file

Body:
I'm trying to set the Image of my UIBUtton with a SVG file...the click on the button works fine but it appears invisible. I'm trying to use PocketSVG: https://github.com/arielelkin/PocketSVG

There's what I'm trying:

CGPathRef myPath = [PocketSVG pathFromSVGFileNamed:@"icon_convidar.svg"];

        //2: To display it on screen, you can create a CAShapeLayer
        //and set myPath as its path property:
        CAShapeLayer *myShapeLayer = [CAShapeLayer layer];
        myShapeLayer.path = myPath;

        //3: Fiddle with it using CAShapeLayer's properties:
        myShapeLayer.strokeColor = [[UIColor greenColor] CGColor];
        myShapeLayer.lineWidth = 4;
        myShapeLayer.fillColor = [[UIColor greenColor] CGColor];

        //4: Display it!
    [self.btnConvidar.layer addSublayer:myShapeLayer];


问:
Set minimal reasonable width for a QScrollArea
I am relatively new to Qt, which I access through PySide.

I have a longish list of content that I want to make vertically scrollable.
The horizontal size is not an issue. I tried using QScrollArea for that. Here is a minimal example:

```<code>import sys

import PySide.QtGui as gui

application = gui.QApplication(sys.argv)

window = gui.QScrollArea()
list = gui.QWidget()
layout = gui.QVBoxLayout(list)

for i in range(100):
    layout.addWidget(gui.QLabel(
        "A something longish, slightly convoluted example text."))

window.setWidget(list)

window.show()

sys.exit(application.exec_())
</code>```

What happens:

The scroll-area sets its horizontal size to the size needed for the labels

It notices that the vertical space is insufficient, so it adds a vertical scrollbar.

Due to the vertical scrollbar, the horizontal space is now insufficient as well, and so the horizontal scrollbar is also shown.

I can make the horizontal scrollbar go away with setHorizontalScrollBarPolicy, but the main problem persists: the vertical scrollbar obscures part of the labels.

How can I set the width of the scroll-area to the minimal value which does not need a horizontal scrollbar?

答:
Your example is somewhat unrealistic, because the scroll-area is made the top-level window. More typically, it would be a child widget, and its initial size would be determined by a layout, and would be indirectly constrained by the sizes of other widgets and/or layouts. As a top-level window, the constraints are different, and partly under the influence of the window-manager (the exact behaviour of which can vary between platforms).

To ensure that the scroll-area has the correct size, you must set a minimum width for it, based on its contents, and also allowing for the vertical scrollbar and the frame. It is also probably best to set the widgetResizable property to True and add an expandable spacer to the end of the contents layout.

In the example below, I have changed the background colour of the labels to make it easier to see what is going on. I have also allowed resizing the window smaller than its initial size, by resetting the minimum width after it is shown - but that is optional.

```<code>import sys

import PySide.QtGui as gui

application = gui.QApplication(sys.argv)

window = gui.QScrollArea()
window.setWidgetResizable(True)
list = gui.QWidget()
layout = gui.QVBoxLayout(list)

# just for testing
window.setStyleSheet('QLabel {background-color: red}')

for i in range(30):
    layout.addWidget(gui.QLabel(
        "A something longish, slightly convoluted example text."))

layout.addStretch()

window.setWidget(list)

window.setMinimumWidth(
    list.sizeHint().width() +
    2 * window.frameWidth() +
    window.verticalScrollBar().sizeHint().width())

window.show()

# allow resizing smaller
window.setMinimumWidth(1)

sys.exit(application.exec_())
</code>```

Body:
I am relatively new to Qt, which I access through PySide.

I have a longish list of content that I want to make vertically scrollable.
The horizontal size is not an issue. I tried using QScrollArea for that. Here is a minimal example:

import sys

import PySide.QtGui as gui

application = gui.QApplication(sys.argv)

window = gui.QScrollArea()
list = gui.QWidget()
layout = gui.QVBoxLayout(list)

for i in range(100):
    layout.addWidget(gui.QLabel(
        "A something longish, slightly convoluted example text."))

window.setWidget(list)

window.show()

sys.exit(application.exec_())

What happens:

The scroll-area sets its horizontal size to the size needed for the labels

It notices that the vertical space is insufficient, so it adds a vertical scrollbar.

Due to the vertical scrollbar, the horizontal space is now insufficient as well, and so the horizontal scrollbar is also shown.

I can make the horizontal scrollbar go away with setHorizontalScrollBarPolicy, but the main problem persists: the vertical scrollbar obscures part of the labels.

How can I set the width of the scroll-area to the minimal value which does not need a horizontal scrollbar?

Body:
Your example is somewhat unrealistic, because the scroll-area is made the top-level window. More typically, it would be a child widget, and its initial size would be determined by a layout, and would be indirectly constrained by the sizes of other widgets and/or layouts. As a top-level window, the constraints are different, and partly under the influence of the window-manager (the exact behaviour of which can vary between platforms).

To ensure that the scroll-area has the correct size, you must set a minimum width for it, based on its contents, and also allowing for the vertical scrollbar and the frame. It is also probably best to set the widgetResizable property to True and add an expandable spacer to the end of the contents layout.

In the example below, I have changed the background colour of the labels to make it easier to see what is going on. I have also allowed resizing the window smaller than its initial size, by resetting the minimum width after it is shown - but that is optional.

import sys

import PySide.QtGui as gui

application = gui.QApplication(sys.argv)

window = gui.QScrollArea()
window.setWidgetResizable(True)
list = gui.QWidget()
layout = gui.QVBoxLayout(list)

# just for testing
window.setStyleSheet('QLabel {background-color: red}')

for i in range(30):
    layout.addWidget(gui.QLabel(
        "A something longish, slightly convoluted example text."))

layout.addStretch()

window.setWidget(list)

window.setMinimumWidth(
    list.sizeHint().width() +
    2 * window.frameWidth() +
    window.verticalScrollBar().sizeHint().width())

window.show()

# allow resizing smaller
window.setMinimumWidth(1)

sys.exit(application.exec_())


问:
How to extract year and month from date in PostgreSQL without using to_char() function?
I want to select sql:
SELECT "year-month" from table group by "year-month" AND order by date, where
year-month - format for date "1978-01","1923-12".
select to_char of couse work, but not "right" order:

```<code>to_char(timestamp_column, 'YYYY-MM')
</code>```

答:
1st Option

```<code>date_trunc('month', timestamp_column)::date
</code>```

It will maintain the date format with all months starting at day one.

Example:

```<code>2016-08-01
2016-09-01
2016-10-01
2016-11-01
2016-12-01
2017-01-01
</code>```

2nd Option

```<code>to_char(timestamp_column, 'YYYY-MM')
</code>```

This solution proposed by @yairchu worked fine in my case. I really wanted to discard 'day' info.

Body:
I want to select sql:
SELECT "year-month" from table group by "year-month" AND order by date, where
year-month - format for date "1978-01","1923-12".
select to_char of couse work, but not "right" order:

to_char(timestamp_column, 'YYYY-MM')

Body:
1st Option

date_trunc('month', timestamp_column)::date

It will maintain the date format with all months starting at day one.

Example:

2016-08-01
2016-09-01
2016-10-01
2016-11-01
2016-12-01
2017-01-01

2nd Option

to_char(timestamp_column, 'YYYY-MM')

This solution proposed by @yairchu worked fine in my case. I really wanted to discard 'day' info.


问:
Update cordova-android 6.3.0->6.4.0 => Gradle not found
I upgraded from cordova-android 6.3.0 to 6.4.0 and also updated Android Studio from 2.3 to 3.0.0 (http://cordova.apache.org/announcements/2017/11/09/android-release.html)

At cordova build time, I'm no facing the error:

ANDROID_HOME=/Users/me/Library/Android/sdk
  JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home
  Error: Could not find an installed version of Gradle either in Android Studio,
  or on your system to install the gradle wrapper. Please include gradle
  in your path, or install Android Studio

Any ideas?

答:
Thx solution was found by @Sujan12 on the Ionic Framework forum.

Furthermore to the updates of the Android libs, I had to install locally Gradle (https://gradle.org/install/).

(be sure to modify the PATH variable permanently after Gradle install)

Once this done, I was able to build my app again

https://forum.ionicframework.com/t/solved-update-cordova-android-6-3-0-6-4-0-gradle-not-found/112123/4


问:
Set property "readonly" for @Html.TextBoxFor( ) dynamically based on fetched information from db
I have multiple Textboxes defined using @Html.TextBoxFor(). Now I want some of them to be only "readonly" and some of them editable, based on the role of user accessing the page.

I have tried using the following

```<code>@Html.TextBoxFor(f => f.VSSLabel, new { style = "height:19px", @Value = @ViewBag.fetchf.VSSLabel, @readonly="readonly" })
</code>```

Is there any way that we can set @readonly="false" and it becomes editable, or any other approach so I switch it to "readonly" and editable based on the Value stored in a ViewBag variable coming from controller?

答:
Unfortunately all the below mark will render a readonly textbox input

```<code><input type="text" name="s1" readonly="readonly"/>
<input type="text" name="s2" readonly="no" />
<input type="text" name="s2" readonly="reallyDoNotWant" />
<input type="text" name="s3" readonly="false" />
<input type="text" name="s4" readonly />
</code>```

The existence of readonly attribute makes the input element readonly. Value does not matter.

So you should conditionally render it

```<code>if (yourExpressionWhichGivesBooleanValue)
{
    @Html.TextBoxFor(a => a.VSSLabel)
}
else
{
    @Html.TextBoxFor(a => a.VSSLabel, new { @readonly = "readonly" })
}
</code>```

If you want to check it against a viewbag dictionary item

```<code>if (ViewBag.IsAdmin !=null && ViewBag.IsAdmin)
{
    @Html.TextBoxFor(a => a.VSSLabel)
}
else
{
    @Html.TextBoxFor(a => a.VSSLabel, new { @readonly = "readonly" })
}
</code>```

Assuming you are setting ViewBag.IsAdmin to a boolean value in your action method.

Body:
I have multiple Textboxes defined using @Html.TextBoxFor(). Now I want some of them to be only "readonly" and some of them editable, based on the role of user accessing the page.

I have tried using the following

@Html.TextBoxFor(f => f.VSSLabel, new { style = "height:19px", @Value = @ViewBag.fetchf.VSSLabel, @readonly="readonly" })

Is there any way that we can set @readonly="false" and it becomes editable, or any other approach so I switch it to "readonly" and editable based on the Value stored in a ViewBag variable coming from controller?

Body:
Unfortunately all the below mark will render a readonly textbox input

<input type="text" name="s1" readonly="readonly"/>
<input type="text" name="s2" readonly="no" />
<input type="text" name="s2" readonly="reallyDoNotWant" />
<input type="text" name="s3" readonly="false" />
<input type="text" name="s4" readonly />

The existence of readonly attribute makes the input element readonly. Value does not matter.

So you should conditionally render it

if (yourExpressionWhichGivesBooleanValue)
{
    @Html.TextBoxFor(a => a.VSSLabel)
}
else
{
    @Html.TextBoxFor(a => a.VSSLabel, new { @readonly = "readonly" })
}

If you want to check it against a viewbag dictionary item

if (ViewBag.IsAdmin !=null && ViewBag.IsAdmin)
{
    @Html.TextBoxFor(a => a.VSSLabel)
}
else
{
    @Html.TextBoxFor(a => a.VSSLabel, new { @readonly = "readonly" })
}

Assuming you are setting ViewBag.IsAdmin to a boolean value in your action method.


问:
Rearrange Logcat buttons in Android Studio
For example, I want to swap these two buttons:

Is it possible? I'm using Android Studio 3.0.

答:
You can try to create plugin which implement "com.intellij.consoleActionsPostProcessor" extension point.
According to the javadoc they can do what you want:

```<code>  /**
   * Allows to adjust actions to use within the given console instance.
   * <p/>
   * {@code 'Adjust'} here stands for 'add', 'remove', 'change order' etc.
   *
   * @param console     console instance which actions are being post-processed
   * @param actions     console actions that will be used by default
   * @return            actions to use within the given console instance (given actions may be returned by default)
   */
</code>```

For further information see sources: https://github.com/JetBrains/intellij-community/blob/master/platform/lang-api/src/com/intellij/execution/actions/ConsoleActionsPostProcessor.java

Body:
You can try to create plugin which implement "com.intellij.consoleActionsPostProcessor" extension point.
According to the javadoc they can do what you want:

  /**
   * Allows to adjust actions to use within the given console instance.
   * <p/>
   * {@code 'Adjust'} here stands for 'add', 'remove', 'change order' etc.
   *
   * @param console     console instance which actions are being post-processed
   * @param actions     console actions that will be used by default
   * @return            actions to use within the given console instance (given actions may be returned by default)
   */

For further information see sources: https://github.com/JetBrains/intellij-community/blob/master/platform/lang-api/src/com/intellij/execution/actions/ConsoleActionsPostProcessor.java


问:
Calculating the sum of values from a text file?
im trying to find the sum of the cost of all my books in my libary system from a file, could someone say where im going wrong atm. It would be great help

```<code>int sum = 0;
    File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");

    try {
        Scanner fileReader  = new Scanner (Fileobject);

        // Read and display each line of the file

        while(fileReader.hasNext())
        {
            sum+= fileReader.nextInt ( );
            line = fileReader.nextLine();
            System.out.println(line);
            System.out.println(sum);
        }
            fileReader.close();
</code>```

This is my data im reading:

```<code>The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752

OOP_programming - Graham_Winter - 32.50 – Oreilly - 0471974555

Harry_potter - Jk_Rowling - 10 - Bloomsbury- 9788700631625
</code>```

This is the errors im getting:

```<code>Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at c3500948JavaProjectAssignement1.c3500948.main(c3500948.java:80)
</code>```

答:
Asumming your file has fixed format Text (no other words has - as seperator) and position for amount value here is something you can try:

text file :

```<code>book1- author1- 100 - press1- 978846521988752
book2 - author2 - 100 - press2 - 9788928465887521
book3 - author3 - 100 - press3 - 9784659219887521
book4 - author4 - 100 - press4 - 9788928465887521
book5 - author5 - 100 - press5 - 9784659219887521
book6 - author6- 100 - press 6- 9788984659887521
</code>```

TestClass.java

```<code>import java.util.Scanner;
import java.io.*;
class TestClass
{
    public static void main(String [] args) throws Exception
    {
        FileReader file = new FileReader("test.txt");
        Scanner sc = new Scanner(file);
        double sum = 0;
        while(sc.hasNext())
        {
            String line = sc.nextLine();
            // spit the line on - char
            String [] data = line.split("-");
            // Important : assuming price is always at index 2 parse and use value
             sum = sum + Double.parseDouble(data[2].trim());
        }
        sc.close();
        System.out.println("Sum is "+sum);
    }
}
</code>```

Body:
im trying to find the sum of the cost of all my books in my libary system from a file, could someone say where im going wrong atm. It would be great help

int sum = 0;
    File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");

    try {
        Scanner fileReader  = new Scanner (Fileobject);

        // Read and display each line of the file

        while(fileReader.hasNext())
        {
            sum+= fileReader.nextInt ( );
            line = fileReader.nextLine();
            System.out.println(line);
            System.out.println(sum);
        }
            fileReader.close();

This is my data im reading:

The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752

OOP_programming - Graham_Winter - 32.50 – Oreilly - 0471974555

Harry_potter - Jk_Rowling - 10 - Bloomsbury- 9788700631625

This is the errors im getting:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at c3500948JavaProjectAssignement1.c3500948.main(c3500948.java:80)

Body:
Asumming your file has fixed format Text (no other words has - as seperator) and position for amount value here is something you can try:

text file :

book1- author1- 100 - press1- 978846521988752
book2 - author2 - 100 - press2 - 9788928465887521
book3 - author3 - 100 - press3 - 9784659219887521
book4 - author4 - 100 - press4 - 9788928465887521
book5 - author5 - 100 - press5 - 9784659219887521
book6 - author6- 100 - press 6- 9788984659887521

TestClass.java

import java.util.Scanner;
import java.io.*;
class TestClass
{
    public static void main(String [] args) throws Exception
    {
        FileReader file = new FileReader("test.txt");
        Scanner sc = new Scanner(file);
        double sum = 0;
        while(sc.hasNext())
        {
            String line = sc.nextLine();
            // spit the line on - char
            String [] data = line.split("-");
            // Important : assuming price is always at index 2 parse and use value
             sum = sum + Double.parseDouble(data[2].trim());
        }
        sc.close();
        System.out.println("Sum is "+sum);
    }
}


问:
Lazily loaded module in Angular 4 errors with "Component X is not part of any NgModule"
I have an app with loads of modules. It works perfectly. I want to make one module lazy load as it is not often hit by normal users.

So, I change the route for LazyModule to use loadChildren, the main app still loads ok, but when I try and hit one of the child routes of LazyModule, it gives me this error:

Error: Uncaught (in promise): Error: Component HomeComponent is not
  part of any NgModule or the module has not been imported into your
  module.

HomeComponent is not used in LazyModule. It is part of a different module, call it MainModule.

MainModule and LazyModule are both imported and exported to/from ComponentsModule which then gets imported into the app.module.

There is also SharedModule which is imported to all the other modules mentioned.

So my questions:

Why does LazyModule try to load components in MainModule when it has absolutely no dependencies on it?

Why does it work with normal routing, but not with lazy loading?

Thanks in advance for your help.

Modules are here:

LazyModule

```<code>import ...;

const routes: Routes = [
    {
        path: '',
        redirectTo: '/lazy-page/1',
        pathMatch: 'full'
    },
    {
        path: '1',
        component: LazyPage1Component
    }
];

@NgModule({
  imports: [
      RouterModule.forChild(routes),
      SharedModule
  ],
  declarations: [
      LazyPage1Component
  ]
})
export class LazyModule { }
</code>```

MainModule

```<code>import ...;

@NgModule({
  imports: [
      SharedModule
  ],
  declarations: [
      HomeComponent
  ],
  exports: [
      HomeComponent
  ]
})
export class MainModule { }
</code>```

ComponentsModule

```<code>import ...;

@NgModule({
  imports: [
    SharedModule,
    MainModule,
    LazyModule
  ],
  declarations: [],
  exports: [
    SharedModule,
    MainModule,
    LazyModule
  ]
})
export class ComponentsModule { }
</code>```

AppModule

```<code>import ...;

@NgModule({
  imports: [
    ComponentsModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [{provide: APP_BASE_HREF, useValue : '/' }],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

AppRoutingModule

```<code>const routes: Routes = [
{
    path: '',
    component: HomeComponent
},
{
    path: 'lazy-page',
    loadChildren: './components/lazy/lazy.module#LazyModule',
},
</code>```

EDIT: I found a hack to get around it for now, but I really want a proper solution. The hack is just to import every single module in my app into LazyModule as well as AppModule. This is a terrible solution, because the whole idea of having a lazy-loaded module is to decouple it from the rest of the app as it is separate. I don't want to import everything twice, and nor should I need to since none of the modules imported are ever used or referenced inside LazyModule.

答:
Try to use this AppRoutingModule

```<code>const routes: Routes = [
{
    path: '',
    redirectTo: '',
    pathMatch: 'full',
},
{
    path: '',
    component: AppComponent,
    children: [
        {
            path: '',
            loadChildren: './path/to/main.module#MainModule',
        }
    ]
},
{
    path: 'lazy-page',
    component: AppComponent,
    children: [
        {
            path: '',
            loadChildren: './components/lazy/lazy.module#LazyModule',
        }
    ]
}
</code>```

Your app.component

```<code><router-outlet></router-outlet>
</code>```

MainRoutingModule

```<code>{
    path: '',
    component: HomeComponent
},
</code>```

And this is your LazyModule routes

```<code>const routes: Routes = [
    {
        path: '1',
        component: LazyPage1Component
    }
];
</code>```

And remove ComponentModule

Hope it helps

Body:
I have an app with loads of modules. It works perfectly. I want to make one module lazy load as it is not often hit by normal users.

So, I change the route for LazyModule to use loadChildren, the main app still loads ok, but when I try and hit one of the child routes of LazyModule, it gives me this error:

Error: Uncaught (in promise): Error: Component HomeComponent is not
  part of any NgModule or the module has not been imported into your
  module.

HomeComponent is not used in LazyModule. It is part of a different module, call it MainModule.

MainModule and LazyModule are both imported and exported to/from ComponentsModule which then gets imported into the app.module.

There is also SharedModule which is imported to all the other modules mentioned.

So my questions:

Why does LazyModule try to load components in MainModule when it has absolutely no dependencies on it?

Why does it work with normal routing, but not with lazy loading?

Thanks in advance for your help.

Modules are here:

LazyModule

import ...;

const routes: Routes = [
    {
        path: '',
        redirectTo: '/lazy-page/1',
        pathMatch: 'full'
    },
    {
        path: '1',
        component: LazyPage1Component
    }
];

@NgModule({
  imports: [
      RouterModule.forChild(routes),
      SharedModule
  ],
  declarations: [
      LazyPage1Component
  ]
})
export class LazyModule { }

MainModule

import ...;

@NgModule({
  imports: [
      SharedModule
  ],
  declarations: [
      HomeComponent
  ],
  exports: [
      HomeComponent
  ]
})
export class MainModule { }

ComponentsModule

import ...;

@NgModule({
  imports: [
    SharedModule,
    MainModule,
    LazyModule
  ],
  declarations: [],
  exports: [
    SharedModule,
    MainModule,
    LazyModule
  ]
})
export class ComponentsModule { }

AppModule

import ...;

@NgModule({
  imports: [
    ComponentsModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [{provide: APP_BASE_HREF, useValue : '/' }],
  bootstrap: [AppComponent]
})
export class AppModule { }

AppRoutingModule

const routes: Routes = [
{
    path: '',
    component: HomeComponent
},
{
    path: 'lazy-page',
    loadChildren: './components/lazy/lazy.module#LazyModule',
},

EDIT: I found a hack to get around it for now, but I really want a proper solution. The hack is just to import every single module in my app into LazyModule as well as AppModule. This is a terrible solution, because the whole idea of having a lazy-loaded module is to decouple it from the rest of the app as it is separate. I don't want to import everything twice, and nor should I need to since none of the modules imported are ever used or referenced inside LazyModule.

Body:
Try to use this AppRoutingModule

const routes: Routes = [
{
    path: '',
    redirectTo: '',
    pathMatch: 'full',
},
{
    path: '',
    component: AppComponent,
    children: [
        {
            path: '',
            loadChildren: './path/to/main.module#MainModule',
        }
    ]
},
{
    path: 'lazy-page',
    component: AppComponent,
    children: [
        {
            path: '',
            loadChildren: './components/lazy/lazy.module#LazyModule',
        }
    ]
}

Your app.component

<router-outlet></router-outlet>

MainRoutingModule

{
    path: '',
    component: HomeComponent
},

And this is your LazyModule routes

const routes: Routes = [
    {
        path: '1',
        component: LazyPage1Component
    }
];

And remove ComponentModule

Hope it helps


问:
Disable automatic (preview) window (buffer) with a function signature
Every time I click dot, the function signature appears in a separate buffer.

```<code>import sys

sys.argv   # in this moment I have a separate buffer opened with sys.argv signature
</code>```

Then this buffer exists until manually closed.

I'd like to have it only when I press ctrl-K. Or at least it disappears when I exit insert mode...

答:
This is the default behavior of the Rope AutoCompletion used in Python-Mode.

https://github.com/python-mode/python-mode/blob/01c3131343aaa3c76f8cb656b5e9f54ac90ca04b/doc/pymode.txt#L476

If you dont like the behavior, you can turn it off using

let g:pymode_rope_complete_on_dot = 1

The reason its working when you use YouCompleteMe, is because YouCompleteMe is turning off the whole python-mode plugin altogehter. So while you can get ride of this issue, you will lose all the other features of python-mode as well.

Body:
Every time I click dot, the function signature appears in a separate buffer.

import sys

sys.argv   # in this moment I have a separate buffer opened with sys.argv signature

Then this buffer exists until manually closed.

I'd like to have it only when I press ctrl-K. Or at least it disappears when I exit insert mode...


问:
Simple Post Request with Alamofire
It's my first post here, I'm trying to do this with Alamofire:

Swift code:

```<code>let name = "Taza"
let description = "50cl"
let parameters = ["name": name, "description": description]

Alamofire.request(.POST, "http://xxxxx.es/JSONpresenter.php?op=5", parameters: parameters, encoding: .JSON);
</code>```

PHP code:

```<code>$op=$_GET['op'];

else if($op == 5)
{

    // Get user id
    $name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : “”;
    $description = isset($_POST['description']) ? mysql_real_escape_string($_POST['description']) : “”;

    add($name,$description);

}
</code>```

But only get a register with "" in all cells. What am I doing wrong?

答: You need to use the URLEncoding instead of JSONEncoding for this particular case</p>

Title: Simple Post Request with Alamofire

Body:
It's my first post here, I'm trying to do this with Alamofire:

Swift code:

let name = "Taza"
let description = "50cl"
let parameters = ["name": name, "description": description]

Alamofire.request(.POST, "http://xxxxx.es/JSONpresenter.php?op=5", parameters: parameters, encoding: .JSON);

PHP code:

$op=$_GET['op'];

else if($op == 5)
{

    // Get user id
    $name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : “”;
    $description = isset($_POST['description']) ? mysql_real_escape_string($_POST['description']) : “”;

    add($name,$description);

}

But only get a register with "" in all cells. What am I doing wrong?


问:
Delete from temporary tables takes 100% CPU for a long time
I have a pretty complex query where we make use of a temporary table (this is in Oracle running on AWS RDS service).

```<code>INSERT INTO TMPTABLE (inserts about 25.000 rows in no time)
SELECT FROM X JOIN TMPTABLE (joins with temp table also in no time)
DELETE FROM TMPTABLE (takes no time in a copy of the production database, up to 10 minutes in the production database)
</code>```

If I change the delete to a truncate it is as fast as in development.
So this change I will of course deploy. But I would like to understand why this occurs. AWS team has been quite helpful but they are a bit biased on AWS and like to tell me that my 3000 USD a month database server is not fast enough (I don't think so). I am not that fluent in Oracle administration but I have understood that if the redo logs are constantly filled, this can cause issues. I have increased the size quite substantially, but then again, this doesn't really add up.

答:
I suggest you use an Oracle Global Temporary table. They are fast, and don't need to be explicitly deleted after the session ends.

For example:

```<code>CREATE GLOBAL TEMPORARY TABLE TMP_T
  (
    ID NUMBER(32)
  )
ON COMMIT DELETE ROWS;
</code>```

See https://docs.oracle.com/cd/B28359_01/server.111/b28310/tables003.htm#ADMIN11633

Body:
I have a pretty complex query where we make use of a temporary table (this is in Oracle running on AWS RDS service).

INSERT INTO TMPTABLE (inserts about 25.000 rows in no time)
SELECT FROM X JOIN TMPTABLE (joins with temp table also in no time)
DELETE FROM TMPTABLE (takes no time in a copy of the production database, up to 10 minutes in the production database)

If I change the delete to a truncate it is as fast as in development.
So this change I will of course deploy. But I would like to understand why this occurs. AWS team has been quite helpful but they are a bit biased on AWS and like to tell me that my 3000 USD a month database server is not fast enough (I don't think so). I am not that fluent in Oracle administration but I have understood that if the redo logs are constantly filled, this can cause issues. I have increased the size quite substantially, but then again, this doesn't really add up.

Body:
I suggest you use an Oracle Global Temporary table. They are fast, and don't need to be explicitly deleted after the session ends.

For example:

CREATE GLOBAL TEMPORARY TABLE TMP_T
  (
    ID NUMBER(32)
  )
ON COMMIT DELETE ROWS;

See https://docs.oracle.com/cd/B28359_01/server.111/b28310/tables003.htm#ADMIN11633