问:
Python page count down print (len(elem_href1-(number)))
How do I create a page count down for python for each page it navigates to.  I have included my attempts below.  How do I get desired result?

I am using (len(elem_href1) so I can try and create page count down so easily informed of where my script is progressing. Trying to do that - a value each loop.

```<code>driver = webdriver.Chrome()

driver.get('https://stackoverflow.com/questions')
elements = driver.find_elements_by_css_selector("#questions .question-hyperlink")
elem_href1 = [element.get_attribute("href") for element in elements]
print(elem_href1)
print (len(elem_href1))
shuffle(elem_href1)
for link in elem_href1:#(2)
    driver.get(link)
    print(len(link))
    import numbers

    #number = number -= 1
    #print (len(elem_href1-(number)))

print (len(elem_href1)) gives total number of pages to navigate to.

print(len(link)) gives random number due to shuffle.
</code>```

Current output:

```<code>15
83
101
112
72
107
106
84
</code>```

Desired:

```<code>50 #When at page 50
49 #when at page 49..
48 #when at page 48..
42 #Counting down...
..
</code>```

Maybe then:

```<code>    number = number -= 1
    print (len(elem_href1-(number)))
#SyntaxError: invalid syntax
</code>```

Or:

```<code>count = len(elem_href1)
def countdownList(l):  # 3. prints number of files left to process
    global count
    count = count - 1
    print(count, " pages left to go.")
    if count == 0:
</code>```

Output:

```<code>    15
   43
</code>```

Any ideas how this might be achieved

答:
if you looking for the len of the strings and sorting it out, try this.

```<code>driver.get('https://stackoverflow.com/questions')
elements = [x.get_attribute("href") for x in
driver.find_elements_by_css_selector("#questions .question-hyperlink")]
print(len(elements))

numbers = sorted([len(e) for e in elements], reverse=True)
print(numbers)
</code>```

update

```<code>def page_counter():
  for x in range(1000):
      yield x

count = page_counter()

driver.get('https://stackoverflow.com/questions')
elements = [x.get_attribute("href") for x in
driver.find_elements_by_css_selector("#questions .question-hyperlink")]
print(len(elements))

links = dict((next(count) + 1, e) for e in elements)

for key, value in links.items():
   driver.get(value)
   print(f'At Page: {key}')
</code>```

2nd update

```<code>import operator

links = dict((next(count) + 1, e) for e in elements)
desc_links = sorted(links.items(), key=operator.itemgetter(1))

for link in desc_links:
    driver.get(link[1])
    print(f'At Page: {link[0]}')
</code>```

Body:
How do I create a page count down for python for each page it navigates to.  I have included my attempts below.  How do I get desired result?

I am using (len(elem_href1) so I can try and create page count down so easily informed of where my script is progressing. Trying to do that - a value each loop.

driver = webdriver.Chrome()

driver.get('https://stackoverflow.com/questions')
elements = driver.find_elements_by_css_selector("#questions .question-hyperlink")
elem_href1 = [element.get_attribute("href") for element in elements]
print(elem_href1)
print (len(elem_href1))
shuffle(elem_href1)
for link in elem_href1:#(2)
    driver.get(link)
    print(len(link))
    import numbers

    #number = number -= 1
    #print (len(elem_href1-(number)))

print (len(elem_href1)) gives total number of pages to navigate to.

print(len(link)) gives random number due to shuffle.

Current output:

15
83
101
112
72
107
106
84

Desired:

50 #When at page 50
49 #when at page 49..
48 #when at page 48..
42 #Counting down...
..

Maybe then:

    number = number -= 1
    print (len(elem_href1-(number)))
#SyntaxError: invalid syntax

Or:

count = len(elem_href1)
def countdownList(l):  # 3. prints number of files left to process
    global count
    count = count - 1
    print(count, " pages left to go.")
    if count == 0:

Output:

    15
   43

Any ideas how this might be achieved

Body:
if you looking for the len of the strings and sorting it out, try this.

driver.get('https://stackoverflow.com/questions')
elements = [x.get_attribute("href") for x in
driver.find_elements_by_css_selector("#questions .question-hyperlink")]
print(len(elements))

numbers = sorted([len(e) for e in elements], reverse=True)
print(numbers)

update

def page_counter():
  for x in range(1000):
      yield x

count = page_counter()

driver.get('https://stackoverflow.com/questions')
elements = [x.get_attribute("href") for x in
driver.find_elements_by_css_selector("#questions .question-hyperlink")]
print(len(elements))

links = dict((next(count) + 1, e) for e in elements)

for key, value in links.items():
   driver.get(value)
   print(f'At Page: {key}')

2nd update

import operator

links = dict((next(count) + 1, e) for e in elements)
desc_links = sorted(links.items(), key=operator.itemgetter(1))

for link in desc_links:
    driver.get(link[1])
    print(f'At Page: {link[0]}')


来源: stackexchange

问:
implementing contravariance in interface in c#
i have been going through many blogs to learn about contravariance, the more i learn the more i am getting confused on this.

my question is, suppose i have an interface and the implementation as following

```<code>interface ICovariant<in T>
    {
        void add(T _object);
    }
    public class sample<T> : ICovariant<T>
    {
        List<T> lists = new List<T>();
        public void add(T _object)
        {
            lists.Add(_object);
        }
    }
    public class baseClass
    {
        public string name { get; set; }
        public void print()
        {
            Console.WriteLine("one method");
        }
    }
    public class derivedClass : baseClass
    {
        public string address { get; set; }
        public void print()
        {
            Console.WriteLine("one more method");
        }
    }
</code>```

i implement contravariance like this

```<code>ICovariant<derivedClass> derivedClass = new sample<baseClass>();
</code>```

in the above line, i am able to define the least derived class on the most derived class but when i do this i am getting an error

```<code>derivedClass.add(new baseClass());
</code>```

why should i be getting an error?

i have mentioned T as contravariance while defining in the interface.

when i am able to intialize the sample class with the least inherited type then why am i not able to do the same while calling the add method.

am i missing something

答:
when I am able to initialize the sample class with the least inherited type then why am I not able to do the same while calling the add method?

Because you cast the object to ICovariant<derivedClass>.  An ICovariant<derivedClass> has an add method that only accepts derivedClass instances, and baseClass isn't a derivedClass instance.  If you didn't cast sample<baseClass> to ICovariant<derivedClass>, and instead left it as sample<baseClass> (or even ICovariant<baseClass>) then the add method would accept a baseClass, not a derivedClass and you could pass in any baseClass instance to it.

ContentLicense: CC BY-SA 3.0

Body:
i have been going through many blogs to learn about contravariance, the more i learn the more i am getting confused on this.

my question is, suppose i have an interface and the implementation as following

interface ICovariant<in T>
    {
        void add(T _object);
    }
    public class sample<T> : ICovariant<T>
    {
        List<T> lists = new List<T>();
        public void add(T _object)
        {
            lists.Add(_object);
        }
    }
    public class baseClass
    {
        public string name { get; set; }
        public void print()
        {
            Console.WriteLine("one method");
        }
    }
    public class derivedClass : baseClass
    {
        public string address { get; set; }
        public void print()
        {
            Console.WriteLine("one more method");
        }
    }

i implement contravariance like this

ICovariant<derivedClass> derivedClass = new sample<baseClass>();

in the above line, i am able to define the least derived class on the most derived class but when i do this i am getting an error

derivedClass.add(new baseClass());

why should i be getting an error?

i have mentioned T as contravariance while defining in the interface.

when i am able to intialize the sample class with the least inherited type then why am i not able to do the same while calling the add method.

am i missing something


问:
Service Connection
From the Android doc:

Android system creates the connection between the client and service,
  it calls onServiceConnected() on the ServiceConnection. The
  onServiceConnected() method includes an IBinder argument, which the
  client then uses to communicate with the bound service.

Does the Android system call onServiceConnected() using the client thread message queue?

答:
Diving around a little bit in the source code, the handler that is used to post the connection runnable callback is running on the main thread.

Source code

Also the java doc in the top of the class says

Like many callbacks from the system, the methods on this class are called from the main thread of your process.

Title: Service Connection


问:
How to check the extension of a Java 7 Path
I'd like to check if a Path (introduced in Java 7) ends with a  certain extension. I tried the endsWith() method like so:

```<code>Path path = Paths.get("foo/bar.java")
if (path.endsWith(".java")){
    //Do stuff
}
</code>```

However, this doesn't seem to work because path.endsWith(".java") returns false. It seems the endsWith() method only returns true if there is a complete match for everything after the final directory separator (e.g. bar.java), which isn't practical for me.

So how can I check the file extension of a Path?

答:
Simple solution:

```<code>if( path.toString().endsWith(".java") ) //Do something
</code>```

You have to be carefull, when using the Path.endsWith method. As you stated, the method will return true only if it matches with a subelement of your Path object.
For example:

```<code>Path p = Paths.get("C:/Users/Public/Mycode/HelloWorld.java");
System.out.println(p.endsWith(".java")); // false
System.out.println(p.endsWith("HelloWorld.java")); // true
</code>```

Body:
I'd like to check if a Path (introduced in Java 7) ends with a  certain extension. I tried the endsWith() method like so:

Path path = Paths.get("foo/bar.java")
if (path.endsWith(".java")){
    //Do stuff
}

However, this doesn't seem to work because path.endsWith(".java") returns false. It seems the endsWith() method only returns true if there is a complete match for everything after the final directory separator (e.g. bar.java), which isn't practical for me.

So how can I check the file extension of a Path?

Body:
Simple solution:

if( path.toString().endsWith(".java") ) //Do something

You have to be carefull, when using the Path.endsWith method. As you stated, the method will return true only if it matches with a subelement of your Path object.
For example:

Path p = Paths.get("C:/Users/Public/Mycode/HelloWorld.java");
System.out.println(p.endsWith(".java")); // false
System.out.println(p.endsWith("HelloWorld.java")); // true

ContentLicense: CC BY-SA 4.0


问:
Find all instances of 'old' in a webpage and replace each with 'new', using a javascript bookmarklet
What I want to do is replace all instances of 'old' in a webpage with 'new' in a JS bookmarklet or a greasemonkey script. How can I do this? I suppose jQuery or other frameworks are okay, as there're hacks to include them in both bookmarklets as well as greasemonkey scripts.</p>

答:
I'm trying to slightly modify this so that it prompts for the text to search for, followed by the text to replace with, and when all done processing, show a dialog box letting me know it's done.

I plan to use it on a phpmyadmin database edit page that'll have any number of textboxes filled with text (which is what I need it to search and replace in). Also, the text to search for and replace may or may not be multi-line, so I've added the 'm' param in the regex, and also, since I'll be doing searches/replaces that may contain html, they'll often have quotes/double quotes in them. ex:

Search for:

```<code><img height="76" width="92" src="http://www.gifs.net/Animation11/Hobbies_and_Entertainment/Games_and_Gambling/Slot_machine.gif" /></div>
<div class="rtecenter"> <strong><em><font color="#ff0000">Vegas Baby!<br />
</font></em></strong></div>
</code>```

and maybe replace with nothing (just to erase all that code), or some other html. So far this is the bookmarklet I've come up with, (javascript, and especially bookmarklets aren't something I mess with often) however, it does nothing as far as finding/replacing, although it does do the prompting correctly.

```<code>javascript:var%20scrEl=document.createElement('script');scrEl.setAttribute('language','javascript');scrEl.setAttribute('type','text/javascript');scrEl.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js');function%20htmlreplace(a,b,element){if(!element)element=document.body;var%20nodes=$(element).contents().each(function(){if(this.nodeType==Node.TEXT_NODE){var%20r=new%20RegExp(a,'gim');this.textContent=this.textContent.replace(r,b);}else{htmlreplace(a,b,this);alert('Done%20processing.');}});}htmlreplace(prompt('Text%20to%20find:',''),prompt('Replace%20with:',''));
</code>```

Anyone have any ideas?

OwnerDisplayName: Fooby

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to slightly modify this so that it prompts for the text to search for, followed by the text to replace with, and when all done processing, show a dialog box letting me know it's done.

I plan to use it on a phpmyadmin database edit page that'll have any number of textboxes filled with text (which is what I need it to search and replace in). Also, the text to search for and replace may or may not be multi-line, so I've added the 'm' param in the regex, and also, since I'll be doing searches/replaces that may contain html, they'll often have quotes/double quotes in them. ex:

Search for:

<img height="76" width="92" src="http://www.gifs.net/Animation11/Hobbies_and_Entertainment/Games_and_Gambling/Slot_machine.gif" /></div>
<div class="rtecenter"> <strong><em><font color="#ff0000">Vegas Baby!<br />
</font></em></strong></div>

and maybe replace with nothing (just to erase all that code), or some other html. So far this is the bookmarklet I've come up with, (javascript, and especially bookmarklets aren't something I mess with often) however, it does nothing as far as finding/replacing, although it does do the prompting correctly.

javascript:var%20scrEl=document.createElement('script');scrEl.setAttribute('language','javascript');scrEl.setAttribute('type','text/javascript');scrEl.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js');function%20htmlreplace(a,b,element){if(!element)element=document.body;var%20nodes=$(element).contents().each(function(){if(this.nodeType==Node.TEXT_NODE){var%20r=new%20RegExp(a,'gim');this.textContent=this.textContent.replace(r,b);}else{htmlreplace(a,b,this);alert('Done%20processing.');}});}htmlreplace(prompt('Text%20to%20find:',''),prompt('Replace%20with:',''));

Anyone have any ideas?


问:
Where is bootstrap/autoload.php in Laravel 5.5?
In previous versions of Laravel there was a file autoload.php. After I installed Laravel 5.5, that file is not found. Is it moved or deleted?

答:
This file was removed in this commit :

https://github.com/laravel/laravel/commit/8914be5fc864ebc6877be38ff3502997e0c62761

he is now in vendor/autoload.php


问:
WPF overload custom binding constructor
Here is my code:

```<code>public class MyBinding : Binding {

    public MyBinding(string path, bool value) : base(path) { /*...*/ }

    public MyBinding(string path, int value) : base(path) { /*...*/ }

}
</code>```

I can do this:

```<code><Control Property="{MyBinding Variable, True}" />
</code>```

But can't do this:

```<code><Control Property="{MyBinding Variable, 123}" />
</code>```

It seems like only the first constructor is taken into account. Why?

答:
The XAML processor tries to invoke the first constructor it finds. If works if you change the order of the constuctors or if you remove the first one:

```<code>public class MyBinding : Binding
{
    public MyBinding(string path, int value) : base(path) { } //primary
    public MyBinding(string path, bool value) : base(path) { } //secondary
}
</code>```

In XAML values such as 'True' and '123' are nothing but strings. The conversion to a bool or int is performed by the parser at runtime.

XAML is not a strongly-type programming language. It's a XML (text) based markup language.

The tooltip in Visual Studio will display Int32 even if you type:

```<code>{MyBinding Variable, xyz}
</code>```

That doesn't mean that converting xyz to a System.Int32 will succeed at runtime. It obviously won't.

Title: WPF overload custom binding constructor

Body:
Here is my code:

public class MyBinding : Binding {

    public MyBinding(string path, bool value) : base(path) { /*...*/ }

    public MyBinding(string path, int value) : base(path) { /*...*/ }

}

I can do this:

<Control Property="{MyBinding Variable, True}" />

But can't do this:

<Control Property="{MyBinding Variable, 123}" />

It seems like only the first constructor is taken into account. Why?

Body:
The XAML processor tries to invoke the first constructor it finds. If works if you change the order of the constuctors or if you remove the first one:

public class MyBinding : Binding
{
    public MyBinding(string path, int value) : base(path) { } //primary
    public MyBinding(string path, bool value) : base(path) { } //secondary
}

In XAML values such as 'True' and '123' are nothing but strings. The conversion to a bool or int is performed by the parser at runtime.

XAML is not a strongly-type programming language. It's a XML (text) based markup language.

The tooltip in Visual Studio will display Int32 even if you type:

{MyBinding Variable, xyz}

That doesn't mean that converting xyz to a System.Int32 will succeed at runtime. It obviously won't.


问:
The html td is not updating via jquery
I have this little method which, on the first load, created a
 and some 's. That works.  But if the underlying data changes, the 's are not updated. I'm not sure why.

```<code>    function ParseJson(json, isFirstLoad)
    {
        json = $.parseJSON(json);
        var tr;
        for (var i = 0; i < json.length; i++) {
            if (isFirstLoad === 1)
            {
                tr = $('<tr/>');
                tr.append("<td id='" + json[i].LocationName + "'>" + json[i].LocationName + "</td>");
                tr.append("<td id='" + json[i].LocationName + "Count'>" + json[i].Count + "</td>");
                $('#MainTable').append(tr);
            }
            else
            {
                var td =  $("#" + json[i].LocationName + "Count");
                td.html = json[i].Count;
            }
        }
</code>```

When isFirstLoad is 1, the html is rendered as I would expect. Example:

```<code><tr>
    <td id="ChemLab">ChemLab</td>
    <td id="ChemLabCount">24</td>
</tr>
</code>```

But the next time around, if the data has changed and someone has left the Chem Lab, the html for ChemLabCount does not change.

I have verified that the json being passed into this method is correct.  Meaning, the count DOES indeed change.  It just doesn't get displayed on the screen.

答:
The problem comes from td.html = json[i].Count; because it's not the right way of using html() method.

To set the Count to your td you could use .text() instead :

```<code>td.text( json[i].Count );
</code>```

Else if you want to set an HTML code the you could use .html() :

```<code>td.html( json[i].Count );
</code>```

Title: The html td is not updating via jquery

Body:
I have this little method which, on the first load, created a
 and some 's. That works.  But if the underlying data changes, the 's are not updated. I'm not sure why.

    function ParseJson(json, isFirstLoad)
    {
        json = $.parseJSON(json);
        var tr;
        for (var i = 0; i < json.length; i++) {
            if (isFirstLoad === 1)
            {
                tr = $('
');
                tr.append("" + json[i].LocationName + "	");
                tr.append("" + json[i].Count + "	");
                $('#MainTable').append(tr);
            }
            else
            {
                var td =  $("#" + json[i].LocationName + "Count");
                td.html = json[i].Count;
            }
        }

When isFirstLoad is 1, the html is rendered as I would expect. Example:

    ChemLab
    24

But the next time around, if the data has changed and someone has left the Chem Lab, the html for ChemLabCount does not change.

I have verified that the json being passed into this method is correct.  Meaning, the count DOES indeed change.  It just doesn't get displayed on the screen.

Body:
The problem comes from td.html = json[i].Count; because it's not the right way of using html() method.

To set the Count to your td you could use .text() instead :

td.text( json[i].Count );

Else if you want to set an HTML code the you could use .html() :

td.html( json[i].Count );


问:
MYSQL Table design help
I have  a table called teams (id, name, ...)   I have a table called divisions (id, name, ......)   I want the diviosn to hold the teams.id  for each team in a divsion  and Teams can be in more than one divsion.  How do I set this up?</p>

答:
Assuming your tables looked like this

```<code>teams
-teamId
-teamName

divisions
-divisionId
-divisionName
</code>```

I think what you are looking for is a many-to-many link table

```<code>membership
-divisionId
-teamId
</code>```

This would allow you to find all the teams in a division with

```<code>select teamId
from team t
join membership m
  on m.teamId = t.teamId
where m.divisionId = 'theIdYouWant'
</code>```

It would also allow as many teams as you want to belong to a division and as many divisions as you want to contain the same teams. It's a many to many relationship table.

Title: MYSQL Table design help

Body:
Assuming your tables looked like this

teams
-teamId
-teamName

divisions
-divisionId
-divisionName

I think what you are looking for is a many-to-many link table

membership
-divisionId
-teamId

This would allow you to find all the teams in a division with

select teamId
from team t
join membership m
  on m.teamId = t.teamId
where m.divisionId = 'theIdYouWant'

It would also allow as many teams as you want to belong to a division and as many divisions as you want to contain the same teams. It's a many to many relationship table.


问:
<input type="text"> does not allow resizing
I can't figure out why my input does not allow me to resize it.

<input type="text">

Example of the problem

I only want to have a working resize on my biginput class.

答:
That's simply because <input type="text"> is ment for a single line.

You'll need to use <textarea></textarea> for this.

<input type="text" placeholder="I can't be resized"></input>
<textarea>I can be resized</textarea>```

In order to do this in Google Forms, use the option 'Paragraph Text' instead of 'Text' when selecting an answer.

Body:
That's simply because <input type="text"> is ment for a single line.

You'll need to use <textarea></textarea> for this.

<input type="text" placeholder="I can't be resized"></input>
<textarea>I can be resized</textarea>

In order to do this in Google Forms, use the option 'Paragraph Text' instead of 'Text' when selecting an answer.


问:
Not allowed to set the device owner
I know question has been asked but i can't get device ownership.

I'm with a samsung xcover 4 with android 7.0.

I launch this command :

```<code>C:\Users\xxx\AppData\Local\Android\Sdk\platform-tools>adb shell dpm set-device-owner org.wso2.iot.system.service/.ServiceDeviceAdminReceiver
</code>```

I get this error :

```<code>java.lang.IllegalStateException: Not allowed to set the device owner because the
re are already some accounts on the device
        at android.os.Parcel.readException(Parcel.java:1701)
        at android.os.Parcel.readException(Parcel.java:1646)
        at android.app.admin.IDevicePolicyManager$Stub$Proxy.setDeviceOwner(IDev
icePolicyManager.java:6067)
        at com.android.commands.dpm.Dpm.runSetDeviceOwner(Dpm.java:148)
        at com.android.commands.dpm.Dpm.onRun(Dpm.java:96)
        at com.android.internal.os.BaseCommand.run(BaseCommand.java:51)
        at com.android.commands.dpm.Dpm.main(Dpm.java:41)
        at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
        at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:316)
</code>```

factory reset done.
I also disable and uninstall all applications but still no luck. Any solution?
Thanks.

答:
As the error states

because there are already some accounts on the device

Go to Settings -> Accounts and remove all accounts (like Gmail, Facebook, ...). When there are no more accounts, try again.

Title: Not allowed to set the device owner

Body:
I know question has been asked but i can't get device ownership.

I'm with a samsung xcover 4 with android 7.0.

I launch this command :

C:\Users\xxx\AppData\Local\Android\Sdk\platform-tools>adb shell dpm set-device-owner org.wso2.iot.system.service/.ServiceDeviceAdminReceiver

I get this error :

java.lang.IllegalStateException: Not allowed to set the device owner because the
re are already some accounts on the device
        at android.os.Parcel.readException(Parcel.java:1701)
        at android.os.Parcel.readException(Parcel.java:1646)
        at android.app.admin.IDevicePolicyManager$Stub$Proxy.setDeviceOwner(IDev
icePolicyManager.java:6067)
        at com.android.commands.dpm.Dpm.runSetDeviceOwner(Dpm.java:148)
        at com.android.commands.dpm.Dpm.onRun(Dpm.java:96)
        at com.android.internal.os.BaseCommand.run(BaseCommand.java:51)
        at com.android.commands.dpm.Dpm.main(Dpm.java:41)
        at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
        at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:316)

factory reset done.
I also disable and uninstall all applications but still no luck. Any solution?
Thanks.


问:
How to add a margin to a table row

I have a table containing many rows. Some of these rows are class="highlight" and signify a row that needs to be styled differently and highlighted. What I'm trying to do is add some extra spacing before and after these rows so they appear slightly separated from the other rows.

I thought I could get this done with margin-top:10px;margin-bottom:10px; but it's not working. Anyone knows how to get this done, or if it could be done? Here's the HTML and I've set the 2nd tr in the tbody to class highlight.

```<code><table>
<thead>
  <tr>
     <th>Header 1</th>
     <th>Header 2</th>
  </tr>
</thead>
<tbody>
  <tr>
     <td>Value1</td>
     <td>Value2</td>
  </tr>
  <tr class="highlight">
     <td>Value1</td>
     <td>Value2</td>
  </tr>
  <tr>
     <td>Value1</td>
     <td>Value2</td>
  </tr>
  <tr>
     <td>Value1</td>
     <td>Value2</td>
  </tr>
</tbody>
</table>
</code>```

答:
First of all, don't try to put a margin to a
 or a  because it won't work in modern rendering.

Solution 1

Although margin doesn't work, padding does work :

```<code>td{
    padding-bottom: 10px;
    padding-top: 10px;
}
</code>```

Warning : This will also push the border further away from the element, if your border is visible, you might want to use solution 2 instead.

Solution 2

To keep the border close to the element and mimic the margin, put another
 between each of your reel table's
 like so :

```<code><tr style="height: 20px;"> <!-- Mimic the margin -->
</tr>
</code>```

Title: How to add a margin to a table row <tr>

Body:
I have a table containing many rows. Some of these rows are class="highlight" and signify a row that needs to be styled differently and highlighted. What I'm trying to do is add some extra spacing before and after these rows so they appear slightly separated from the other rows.

I thought I could get this done with margin-top:10px;margin-bottom:10px; but it's not working. Anyone knows how to get this done, or if it could be done? Here's the HTML and I've set the 2nd tr in the tbody to class highlight.

     Header 1
     Header 2

     Value1
     Value2

     Value1
     Value2

     Value1
     Value2

     Value1
     Value2

Body:
First of all, don't try to put a margin to a <tr> or a <td> because it won't work in modern rendering.

Solution 1

Although margin doesn't work, padding does work :

td{
    padding-bottom: 10px;
    padding-top: 10px;
}

Warning : This will also push the border further away from the element, if your border is visible, you might want to use solution 2 instead.

Solution 2

To keep the border close to the element and mimic the margin, put another <tr> between each of your reel table's <tr> like so :

<tr style="height: 20px;"> <!-- Mimic the margin -->
</tr>


问:
Help with intro to Java procedure call
I have a school project in Java assigned to do the following:

Write an application to be used in a
  college admission's office.   To be
  admitted to this school, the student
  must have either:   •A grade point
  average of 3.0 or higher and an
  entrance score of 60 or higher •An
  entrance score of 85 or higher and any
  grade point average   To make things
  more user friendly, write some code to
  do some error checking of the data.

  That is, if the grade point average is
  not between 0.0 and 4.0 or if the
  entrance score is not between 0 and
  100, then print an appropriate error
  message to the screen telling the user
  that they entered invalid data.   Use
  the above criteria to write a
  procedure called, accepted, that takes
  the grade point average and entrance
  score as parameters and returns no
  value.   This procedure will print
  either "Accept" or "Reject",
  accordingly. Finally, write a main
  procedure that prompts the user for a
  grade point average and an entrance
  score.   This procedure should then
  call the accepted method to display
  the result.

Although I foolishly wrote the following code below without thoroughly reading the directions. My problem is I am not sure how call a procedure. Also how do I pass variables to this called procedure? Any help or other examples would be helpful. Below is the code I written while it works it doesn't feature an Accept procedure that gets called.

```<code>import java.util.Scanner;
class College {

    public static void main(String[] args) {
         double testGPA;
         int testScore;

        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Student Admisions");
        System.out.println("Please student prospects GPA: ");
        testGPA = input.nextDouble();

        System.out.println("Now enter prospect students Test Score: ");
        testScore = input.nextInt();
        System.out.println("-----------------------");

        if (testGPA >= 0.0 && testGPA <= 4.0 && testScore >= 0 && testScore <= 100){
            if(testGPA >= 3.0 && testScore >= 60 || testScore >= 85){
                System.out.println("Student is ACCEPTED to university!");
                System.out.println("Students GPA is a " + testGPA + " and students test score is a " + testScore + "%");
                }
            else {
                System.out.println("Student is NOT ACCEPTED to university!");
                System.out.println("Students GPA is a " + testGPA + " and students test score is a " + testScore + "%");
            }
        }
        else{
            System.out.println("Please Check GPA and Test score input!");
            System.out.println("Your inputs were:");
            System.out.println(testGPA + " = GPA should be between 0.0 and 4.0.");
            System.out.println(testScore + " = Test Score should be between 0 and 100");
        }
    }
}
</code>```

答:
A very simple procedure call demo here.

```<code>public class Demo {
    private static void prn(int x) {
        System.out.println(x);
    }
    public static void main(String[] args) {
        prn(2);
        prn(3);
    }
}
</code>```

Got it?

Title: Help with intro to Java procedure call

Body:
I have a school project in Java assigned to do the following:

Write an application to be used in a
  college admission's office.   To be
  admitted to this school, the student
  must have either:   •A grade point
  average of 3.0 or higher and an
  entrance score of 60 or higher •An
  entrance score of 85 or higher and any
  grade point average   To make things
  more user friendly, write some code to
  do some error checking of the data.

  That is, if the grade point average is
  not between 0.0 and 4.0 or if the
  entrance score is not between 0 and
  100, then print an appropriate error
  message to the screen telling the user
  that they entered invalid data.   Use
  the above criteria to write a
  procedure called, accepted, that takes
  the grade point average and entrance
  score as parameters and returns no
  value.   This procedure will print
  either "Accept" or "Reject",
  accordingly. Finally, write a main
  procedure that prompts the user for a
  grade point average and an entrance
  score.   This procedure should then
  call the accepted method to display
  the result.

Although I foolishly wrote the following code below without thoroughly reading the directions. My problem is I am not sure how call a procedure. Also how do I pass variables to this called procedure? Any help or other examples would be helpful. Below is the code I written while it works it doesn't feature an Accept procedure that gets called.

import java.util.Scanner;
class College {

    public static void main(String[] args) {
         double testGPA;
         int testScore;

        Scanner input = new Scanner(System.in);
        System.out.println("Welcome to Student Admisions");
        System.out.println("Please student prospects GPA: ");
        testGPA = input.nextDouble();

        System.out.println("Now enter prospect students Test Score: ");
        testScore = input.nextInt();
        System.out.println("-----------------------");

        if (testGPA >= 0.0 && testGPA <= 4.0 && testScore >= 0 && testScore <= 100){
            if(testGPA >= 3.0 && testScore >= 60 || testScore >= 85){
                System.out.println("Student is ACCEPTED to university!");
                System.out.println("Students GPA is a " + testGPA + " and students test score is a " + testScore + "%");
                }
            else {
                System.out.println("Student is NOT ACCEPTED to university!");
                System.out.println("Students GPA is a " + testGPA + " and students test score is a " + testScore + "%");
            }
        }
        else{
            System.out.println("Please Check GPA and Test score input!");
            System.out.println("Your inputs were:");
            System.out.println(testGPA + " = GPA should be between 0.0 and 4.0.");
            System.out.println(testScore + " = Test Score should be between 0 and 100");
        }
    }
}

Body:
A very simple procedure call demo here.

public class Demo {
    private static void prn(int x) {
        System.out.println(x);
    }
    public static void main(String[] args) {
        prn(2);
        prn(3);
    }
}

Got it?


问:
Customized strikethrough on title
I'm creating a website to school project and i want to put a strikethrough behind my title like in this image. I want that green lines behind text

I am working with HTML and CSS , someone know the code to get that beautiful strikethrough?

答:
I did it (Image example) but when i change resolution this happen: not responsive... How can i put it to be responsive? here is my HTML and here is my CSS... Thank you for all resolution but i'm using panther's example

#titulo1{
    font-size: 5vw;
    font-weight: 400;
    color:#f5dc9f;
    font-family: 'Moon Light' , sans-serif;
    float: right;
    margin-bottom: 0;
    margin-top: 15vw;
    margin-right: 15vw;
    display: flex;

}

#titulo2{
    color: #f5dc9f;
    font-size:6.7vw;
    font-family: 'Moon Bold', sans-serif;
    clear: right;
    float: right;
    margin-top: 0;
    margin-bottom: 0;
    margin-right: 13vw;

}

#titulo3{
    font-size: 4.8vw;
    font-weight: 400;
    color:#f5dc9f;
    font-family: 'Moon Light' , sans-serif;
    float: right;
    margin-top: 0;
    margin-right: 3vw;

}

#titulo2:before, #titulo2:after {
    content: '';
    background: rgba(0,0,255,0.3);;
    border-radius: 40px;
    position: absolute;
    top: calc(53% - 1vw);
    width: 50%;
    height: 5%;
    z-index: -1
}

#titulo2:before{
    left: 54vw;
    width: 15vw;
}
#titulo2:after{
    right: 11vw;
    width: 26vw;
}

#titulo1:before, #titulo1:after {
    content: '';
    background: rgba(0,0,255,0.3);;
    border-radius: 40px;
    position: absolute;
    top: calc(40% - 20px);
    width: 50%;
    height: 5%;
    z-index: -1
}

#titulo1:before{
    left: 52vw;
    width: 17vw;
    height: 2vw;
}
#titulo1:after{
    right: 15vw;
    width: 20vw;
    height: 2vw;
}

#titulo3:before, #titulo3:after {
    content: '';
    background: rgba(0,0,255,0.3);;
    border-radius: 40px;
    position: absolute;
    top: calc(66% - 20px);
    width: 50%;
    height: 5%;
    z-index: -1
}

#titulo3:before{
    width: 3em;
    height: 0.4em;
}
#titulo3:after{
    right: 0.5em;
    width: 9em;
    height: 0.4em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <h2 id="titulo1">Aqui vai ser</h2><br>
        <h1 id="titulo2">o titulo</h1><br>
        <h2 id="titulo3">do nosso trabalho!</h2><br></code>```

here is the snippet but is very diferent from what i see on my browser

Title: Customized strikethrough on title

Body:
I did it (Image example) but when i change resolution this happen: not responsive... How can i put it to be responsive? here is my HTML and here is my CSS... Thank you for all resolution but i'm using panther's example

#titulo1{
    font-size: 5vw;
    font-weight: 400;
    color:#f5dc9f;
    font-family: 'Moon Light' , sans-serif;
    float: right;
    margin-bottom: 0;
    margin-top: 15vw;
    margin-right: 15vw;
    display: flex;

}

#titulo2{
    color: #f5dc9f;
    font-size:6.7vw;
    font-family: 'Moon Bold', sans-serif;
    clear: right;
    float: right;
    margin-top: 0;
    margin-bottom: 0;
    margin-right: 13vw;

}

#titulo3{
    font-size: 4.8vw;
    font-weight: 400;
    color:#f5dc9f;
    font-family: 'Moon Light' , sans-serif;
    float: right;
    margin-top: 0;
    margin-right: 3vw;

}

#titulo2:before, #titulo2:after {
    content: '';
    background: rgba(0,0,255,0.3);;
    border-radius: 40px;
    position: absolute;
    top: calc(53% - 1vw);
    width: 50%;
    height: 5%;
    z-index: -1
}

#titulo2:before{
    left: 54vw;
    width: 15vw;
}
#titulo2:after{
    right: 11vw;
    width: 26vw;
}

#titulo1:before, #titulo1:after {
    content: '';
    background: rgba(0,0,255,0.3);;
    border-radius: 40px;
    position: absolute;
    top: calc(40% - 20px);
    width: 50%;
    height: 5%;
    z-index: -1
}

#titulo1:before{
    left: 52vw;
    width: 17vw;
    height: 2vw;
}
#titulo1:after{
    right: 15vw;
    width: 20vw;
    height: 2vw;
}

#titulo3:before, #titulo3:after {
    content: '';
    background: rgba(0,0,255,0.3);;
    border-radius: 40px;
    position: absolute;
    top: calc(66% - 20px);
    width: 50%;
    height: 5%;
    z-index: -1
}

#titulo3:before{
    width: 3em;
    height: 0.4em;
}
#titulo3:after{
    right: 0.5em;
    width: 9em;
    height: 0.4em;
}

        <h2 id="titulo1">Aqui vai ser</h2><br>
        <h1 id="titulo2">o titulo</h1><br>
        <h2 id="titulo3">do nosso trabalho!</h2><br>

here is the snippet but is very diferent from what i see on my browser


问:
How to fetch the Public IP of the newly launched machine using Terraform
I have created two instances (Instance-1 and Instance-2) in AWS using Terraform. I installed Ansible on Instance-1 in the same script and I want to push a playbook to Instance-2 from Instance-1.

I want to specify the public-IP, username and key path to the Ansible Host file inside Instance-1 where I installed Ansible.

How can I fetch the public-IP of Instance-2 for specifying the aforementioned attributes in the Ansible host file ?

答:
If you're like me, with terraform and ansible runs as separate steps in a bigger orchestration, use terraform outputs to save off the IP address(es) you need during ansible. For example, we provision a whole cluster with terraform, only allowing SSH from a bastion host. I use the following to save off the bastion's IP address (it's behind an elastic IP):

```<code>output "bastion.ip" {
  value = "${aws_eip.bastion.public_ip}"
}
</code>```

Then to retrieve it after terraform apply:

```<code>bash-4.3# terraform output bastion.ip
52.1.2.3
</code>```

Body:
If you're like me, with terraform and ansible runs as separate steps in a bigger orchestration, use terraform outputs to save off the IP address(es) you need during ansible. For example, we provision a whole cluster with terraform, only allowing SSH from a bastion host. I use the following to save off the bastion's IP address (it's behind an elastic IP):

output "bastion.ip" {
  value = "${aws_eip.bastion.public_ip}"
}

Then to retrieve it after terraform apply:

bash-4.3# terraform output bastion.ip
52.1.2.3


问:
Why does my background music stop when the player object gets destroyed?
I work with Unity 5.5.4 and I'm still learning.

My problem is when the player(object) gets destroyed(destroy(gameobject)), my backgroud music stops playing, even if I place my music in Arenamanager(gameobject), not in player(gameobject).

I don't have a function like audio.stop or something like that in my script and I already untagged the player(gameobject) and I still can't solve it.

Here is my death function:

```<code>Void Death() {
    Instantiate(explosion, transform.position, transform.rotation);
    Destroy(this.gameobject);
}
</code>```

答:
Your player is most likely holding the AudioListener.

So when you destroy, there is nothing left to listen to your music.

Body:
I work with Unity 5.5.4 and I'm still learning.

My problem is when the player(object) gets destroyed(destroy(gameobject)), my backgroud music stops playing, even if I place my music in Arenamanager(gameobject), not in player(gameobject).

I don't have a function like audio.stop or something like that in my script and I already untagged the player(gameobject) and I still can't solve it.

Here is my death function:

Void Death() {
    Instantiate(explosion, transform.position, transform.rotation);
    Destroy(this.gameobject);
}


问:
Shuffling the items in a ListBox
I have a system that contains integers in a ListBox. I have included a 'Shuffle' Button, which should shuffle the stored items in the ListBox into a random order, when clicked by the user.

However, the code I am using is not working for this. Has anyone got any suggestions on how to generate a shuffle button to randomize the data within a ListBox?

答:
I don't know why you store this in a variable of type buttonShuffle.ObjectCollection.

Just access the Items property of the ListBox:

```<code>while (n > 1)
{
    n--;
    int k = rng.Next(n + 1);
    object value = listBoxAddedIntegers.Items[k];
    listBoxAddedIntegers.Items[k] = listBoxAddedIntegers.Items[n];
    listBoxAddedIntegers.Items[n] = value;
}
</code>```

If you did it because you wanted a shorter name, use ListBox.ObjectCollection or var:

```<code>var items = this.listBoxAddedIntegers.Items;

while (n > 1)
{
    n--;
    int k = rng.Next(n + 1);
    object value = items[k];
    items[k] = items[n];
    items[n] = value;
}
</code>```

Title: Shuffling the items in a ListBox

Body:
I don't know why you store this in a variable of type buttonShuffle.ObjectCollection.

Just access the Items property of the ListBox:

while (n > 1)
{
    n--;
    int k = rng.Next(n + 1);
    object value = listBoxAddedIntegers.Items[k];
    listBoxAddedIntegers.Items[k] = listBoxAddedIntegers.Items[n];
    listBoxAddedIntegers.Items[n] = value;
}

If you did it because you wanted a shorter name, use ListBox.ObjectCollection or var:

var items = this.listBoxAddedIntegers.Items;

while (n > 1)
{
    n--;
    int k = rng.Next(n + 1);
    object value = items[k];
    items[k] = items[n];
    items[n] = value;
}


问:
How do you use the Java word boundary with apostrophes?
I am trying to delete all the occurrences of a word in a list, but I am having trouble when there are apostrophes in the words.

```<code>String phrase="bob has a bike and bob's bike is red";
String word="bob";
phrase=phrase.replaceAll("\\b"+word+"\\b","");
System.out.println(phrase);
</code>```

output:

has a bike and 's bike is red

What I want is

has a bike and bob's bike is red

I have a limited understanding of regex so I'm guessing there is a solution, but I do not now enough to create the regex to handle apostrophes.  Also I would like it to work with dashes so the phrase the new mail is e-mail would only replace the first occurrence of mail.

答:
```<code>\b\S*(bob|mail)\S*\b
</code>```

Be careful with false positives, this could match more than you want. If you need "prefixes" or "sufixes" of no more than 2 characters (that would be things like "'s" or "e-"), use \S{0,2} instead of \S*.

The regex says:

```<code>\b           # a word boundary
\S*          # any number of non-spaces
(            # match group 1 (to enable a choice)
  bob|mail   #   "bob" or "mail"
)            # end match group 1
\S*          # any number of non-spaces
\b           # a word boundary
</code>```

So, in Java:

```<code>phrase = phrase.replaceAll("\\b\\S*(bob|mail)\\S*\\b", "");
</code>```

Be careful with things like

```<code>phrase = phrase.replaceAll("\\b" + word + "\\b", "");
</code>```

That should be

```<code>phrase = phrase.replaceAll("\\b" + Pattern.quote(word) + "\\b", "");
</code>```

since whenever word contains regex meta characters, your regex will break unless you properly escape the string beforehand using Pattern.quote().

Body:
I am trying to delete all the occurrences of a word in a list, but I am having trouble when there are apostrophes in the words.

String phrase="bob has a bike and bob's bike is red";
String word="bob";
phrase=phrase.replaceAll("\\b"+word+"\\b","");
System.out.println(phrase);

output:

has a bike and 's bike is red

What I want is

has a bike and bob's bike is red

I have a limited understanding of regex so I'm guessing there is a solution, but I do not now enough to create the regex to handle apostrophes.  Also I would like it to work with dashes so the phrase the new mail is e-mail would only replace the first occurrence of mail.

Body:
\b\S*(bob|mail)\S*\b

Be careful with false positives, this could match more than you want. If you need "prefixes" or "sufixes" of no more than 2 characters (that would be things like "'s" or "e-"), use \S{0,2} instead of \S*.

The regex says:

\b           # a word boundary
\S*          # any number of non-spaces
(            # match group 1 (to enable a choice)
  bob|mail   #   "bob" or "mail"
)            # end match group 1
\S*          # any number of non-spaces
\b           # a word boundary

So, in Java:

phrase = phrase.replaceAll("\\b\\S*(bob|mail)\\S*\\b", "");

Be careful with things like

phrase = phrase.replaceAll("\\b" + word + "\\b", "");

That should be

phrase = phrase.replaceAll("\\b" + Pattern.quote(word) + "\\b", "");

since whenever word contains regex meta characters, your regex will break unless you properly escape the string beforehand using Pattern.quote().


问:
Usage of pascal variant record
I need help from those who know the pascal very well.

I need (teachers requirement) to use a variant record. Those variant record are defined like this:

```<code>Temperature = record
   case scale :   TemperatureScale of
   celsius : (celsius_value : ScaleCelsius);
   kelvin : (kelvin_value : ScaleKelvin);
end;
</code>```

According to primary sources I found during my research about this topic, I could not find how to use variant record, only how to declare it.

My primary sources: google search(found nothing), Case-Freepascal and Record-Freepascal

Edit for those who wonder what i  must use in implementation it is exacly this:

```<code> type
  UkPolozka = ^Polozka;
  UkHodnota = ^Hodnota;
  TypUdaj=(typretez, typcele, typrealne, typlogik, typpole, typobjekt);

  VarZaznam = record
  case Udaj: TypUdaj of
    typretez:  (retez: string);
    typcele:   (cele: word);
    typrealne: (realne: single);
    typlogik:  (logik: boolean);
    typpole:   (pole: UkHodnota);
    typobjekt: (objekt: UkPolozka);
 end;

 Polozka = record
    Nazev: string;
    Hodn:  VarZaznam;
    Dalsi: UkPolozka
 end;
 Hodnota = record
    Hodn:  VarZaznam;
    Dalsi: UkHodnota
 end;
</code>```

答:
Consider example record from Delphi Help. I modified it with tag.

Tag usage is optional and usually is not used and doesn't provide useful information.

Note that the first line outputs radius with the same value as height - they share the same memory.

Then I explicitly set tag (but fields stay the same)

Also note size difference for no-tag record and tagged one.

Note again - in most cases programmers don't define or use tag value. It might be unsafe to rely on tag (until you follow strict rules in assigning tags). I did not set rectangle tag, but program consider zero tag as the first variant.

Just assign needed field by name. Just read needed field by name. For your example varVarZaznam.retez:= 'test';

```<code>type
   TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
   TFigure = record
     case shape: TShapeList of
       Rectangle: (Height, Width: Real);
       Triangle: (Side1, Side2, Angle: Real);
       Circle: (Radius: Real);
       Ellipse, Other: ();
   end;

   TFigureNoTag = record
     case TShapeList of
       Rectangle: (Height, Width: Real);
       Triangle: (Side1, Side2, Angle: Real);
       Circle: (Radius: Real);
       Ellipse, Other: ();
   end;

var
   Fig: TFigure;
begin
  Fig.Height := 5;
  Fig.Width := 3;
  //default tag is zero = Rectangle
  if Fig.shape = Rectangle then
    Writeln('Rect ', Fig.Height:3:0, Fig.Width:3:0, Fig.Radius:3:0)
  else
    Writeln('not Rect');

  Fig.shape := Circle;
  if Fig.shape <> Rectangle then
    Writeln('not Rect');

  Writeln('Fig size ', SizeOf(TFigure), ' noTag size ', SizeOf(TFigureNoTag));
  Readln;
</code>```

output in Delphi:

```<code>Rect   5  3  5
not Rect
Fig size 32 noTag size 24
</code>```

Title: Usage of pascal variant record

Body:
I need help from those who know the pascal very well.

I need (teachers requirement) to use a variant record. Those variant record are defined like this:

Temperature = record
   case scale :   TemperatureScale of
   celsius : (celsius_value : ScaleCelsius);
   kelvin : (kelvin_value : ScaleKelvin);
end;

According to primary sources I found during my research about this topic, I could not find how to use variant record, only how to declare it.

My primary sources: google search(found nothing), Case-Freepascal and Record-Freepascal

Edit for those who wonder what i  must use in implementation it is exacly this:

 type
  UkPolozka = ^Polozka;
  UkHodnota = ^Hodnota;
  TypUdaj=(typretez, typcele, typrealne, typlogik, typpole, typobjekt);

  VarZaznam = record
  case Udaj: TypUdaj of
    typretez:  (retez: string);
    typcele:   (cele: word);
    typrealne: (realne: single);
    typlogik:  (logik: boolean);
    typpole:   (pole: UkHodnota);
    typobjekt: (objekt: UkPolozka);
 end;

 Polozka = record
    Nazev: string;
    Hodn:  VarZaznam;
    Dalsi: UkPolozka
 end;
 Hodnota = record
    Hodn:  VarZaznam;
    Dalsi: UkHodnota
 end;

Body:
Consider example record from Delphi Help. I modified it with tag.

Tag usage is optional and usually is not used and doesn't provide useful information.

Note that the first line outputs radius with the same value as height - they share the same memory.

Then I explicitly set tag (but fields stay the same)

Also note size difference for no-tag record and tagged one.

Note again - in most cases programmers don't define or use tag value. It might be unsafe to rely on tag (until you follow strict rules in assigning tags). I did not set rectangle tag, but program consider zero tag as the first variant.

Just assign needed field by name. Just read needed field by name. For your example varVarZaznam.retez:= 'test';

type
   TShapeList = (Rectangle, Triangle, Circle, Ellipse, Other);
   TFigure = record
     case shape: TShapeList of
       Rectangle: (Height, Width: Real);
       Triangle: (Side1, Side2, Angle: Real);
       Circle: (Radius: Real);
       Ellipse, Other: ();
   end;

   TFigureNoTag = record
     case TShapeList of
       Rectangle: (Height, Width: Real);
       Triangle: (Side1, Side2, Angle: Real);
       Circle: (Radius: Real);
       Ellipse, Other: ();
   end;

var
   Fig: TFigure;
begin
  Fig.Height := 5;
  Fig.Width := 3;
  //default tag is zero = Rectangle
  if Fig.shape = Rectangle then
    Writeln('Rect ', Fig.Height:3:0, Fig.Width:3:0, Fig.Radius:3:0)
  else
    Writeln('not Rect');

  Fig.shape := Circle;
  if Fig.shape <> Rectangle then
    Writeln('not Rect');

  Writeln('Fig size ', SizeOf(TFigure), ' noTag size ', SizeOf(TFigureNoTag));
  Readln;

output in Delphi:

Rect   5  3  5
not Rect
Fig size 32 noTag size 24


问:
Centralized Logging of methods: framework to implement it
I suspect that one of the c# method is never called (because of if codintions); but the software is a client and it's distributed to 1000 users.
So I would like to call some remote API to log every time the method is accessed.

This kind of tracking has got a name? Is it possible to use Google Analytics through c# as a workaround?

答:
It's pretty easy to achieve using Google Analytics.

Is there any way to post events to Google Analytics via server-side API?

A c# wrapper has already been provided:

https://gist.github.com/0liver/11229128


问:
Handling async request with React, Redux and Axios?
I am new to React JS and Redux and it has been too overwhelming to get going. I am trying to make a POST request using Axios, but I am unable to make it. May be I am missing something in the container file. Below is the code. Check plnkr

Update:  I am getting @@redux-form/SET_SUBMIT_SUCCEEDED message after submitting. But when I am checking in the network tab, I don't see the call to API. And also when I am consoling the submitted values, I see only name and fullname values. It doesn't consist of logo and details. What am I missing?

Component file

```<code>   import React, { PureComponent } from 'react'
   import PropTypes from 'prop-types'
   import { Field,reduxForm } from 'redux-form'
   import {   Columns,Column, TextArea, Label,Button  } from 'bloomer'
   import FormField from 'FormField'

   const validate = (values) => {
     const errors = {}
    const requiredFields =
      ['organizationName','organizationFullName','organizationDetails']

    requiredFields.forEach((field) => {
     if (!values[field]) {
     errors[field] = 'This field can\'t be empty!'
    }
  })
     return errors
}

  const formConfig = {
   validate,
   form: 'createOrganization',
   enableReinitialize: true
   }

  export class CreateOrganization extends PureComponent {
   static propTypes = {
     isLoading:PropTypes.bool.isRequired,
     handleSubmit: PropTypes.func.isRequired, // from react-redux
     submitting: PropTypes.bool.isRequired // from react-redux
    }
   onSubmit = data => {
     console.log(data)
   }
  render () {
     const { handleSubmit,submitting,isLoading } = this.props
      return (
        <Columns isCentered>
        <form onSubmit={handleSubmit(this.onSubmit.bind(this))} >

          <Column isSize='3/6' >
            <Label>Organization Name</Label>
            <Field
              name="organizationName"
              component={FormField}
              type="text"
              placeholder="Organization Name"
            />
          </Column>

          <Column isSize='3/6'>
            <Label>Organization Full Name</Label>
            <Field
              name="organizationFullName"
              component={FormField}
              type="text"
              placeholder="Organization Full Name"
            />
          </Column>

           <Column isSize='3/6'>
            <Label>Organization Logo</Label>
            <Input
              name="organizationLogo"
              type="file"
              placeholder="Logo"
            />
          </Column>

          <Column isSize='3/6'>
            <Label>Organization Details</Label>
                <TextArea placeholder={'Enter Details'} />
          </Column>

          <Column >
            <span className="create-button">
              <Button type="submit" isLoading={submitting || isLoading} isColor='primary'>
                Submit
              </Button>
            </span>
              <Button type="button" isColor='danger'>
                Cancel
              </Button>
          </Column>

        </form>
      </Columns>
    )
  }
}

  export default reduxForm(formConfig)(CreateOrganization)
</code>```

Container File

```<code>   import React, { PureComponent } from 'react'
   import PropTypes from 'prop-types'
   import { connect } from 'react-redux'
   import Loader from 'Loader'
   import organization from 'state/organization'
   import CreateOrganization from '../components/createOrganization'

   export class Create extends PureComponent {
   static propTypes = {
     error: PropTypes.object,
     isLoaded: PropTypes.bool.isRequired,
     create: PropTypes.func.isRequired,
    }
    onSubmit = data => {
      this.props.create(data)
    }

    render () {
      const { isLoaded, error } = this.props
    return (
       <CreateOrganization onSubmitForm={this.onSubmit} isLoading=
         {isLoading} />
     )
   }
 }

   const mapStateToProps = state => ({
     error: organization.selectors.getError(state),
     isLoading: organization.selectors.isLoading(state)
   })

    const mapDispatchToProps = {
      create: organization.actions.create
    }

  export default connect(mapStateToProps, mapDispatchToProps)(Create)
</code>```

答:
I would suggest using redux-promise-middleware. This library requires that the action have a property named payload that is a promise and this is easy with axios. It then integrates with Redux to suffix the root action type (e.g. GET_CUSTOMERS) with PENDING, FULFILLED, and REJECTED and fires those actions.

Firing the action is the same as any other action.

Store

```<code>import {applyMiddleware, compose, createStore} from 'redux';
import promiseMiddleware from 'redux-promise-middleware';
import reducer from './reducers';

let middleware = applyMiddleware(promiseMiddleware());
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const enhancer = composeEnhancers(middleware);

export default createStore(reducer, enhancer);
</code>```

Action

```<code>export function getCustomers() {
  return {
    type: 'GET_CUSTOMERS',
    payload: axios.get('url/to/api')
      .then(res => {
        if (!res.ok) throw new Error('An error occurred.');
        return res;
      })
      .then(res => res.json())
      .catch(err => console.warn(err));
  };
}
</code>```

Reducer

```<code>export default function(state = initialState, action) => {
  switch (action.type) {
    case 'GET_CUSTOMERS_PENDING':
      // this means the call is pending in the browser and has not
      // yet returned a response
      ...
    case 'GET_CUSTOMERS_FULFILLED':
      // this means the call is successful and the response has been set
      // to action.payload
      ...
    case 'GET_CUSTOMERS_REJECTED':
      // this means the response was unsuccessful so you can handle that
      // error here
      ...
    default:
      return state;
  }
}
</code>```

Body:
I am new to React JS and Redux and it has been too overwhelming to get going. I am trying to make a POST request using Axios, but I am unable to make it. May be I am missing something in the container file. Below is the code. Check plnkr

Update:  I am getting @@redux-form/SET_SUBMIT_SUCCEEDED message after submitting. But when I am checking in the network tab, I don't see the call to API. And also when I am consoling the submitted values, I see only name and fullname values. It doesn't consist of logo and details. What am I missing?

Component file

   import React, { PureComponent } from 'react'
   import PropTypes from 'prop-types'
   import { Field,reduxForm } from 'redux-form'
   import {   Columns,Column, TextArea, Label,Button  } from 'bloomer'
   import FormField from 'FormField'

   const validate = (values) => {
     const errors = {}
    const requiredFields =
      ['organizationName','organizationFullName','organizationDetails']

    requiredFields.forEach((field) => {
     if (!values[field]) {
     errors[field] = 'This field can\'t be empty!'
    }
  })
     return errors
}

  const formConfig = {
   validate,
   form: 'createOrganization',
   enableReinitialize: true
   }

  export class CreateOrganization extends PureComponent {
   static propTypes = {
     isLoading:PropTypes.bool.isRequired,
     handleSubmit: PropTypes.func.isRequired, // from react-redux
     submitting: PropTypes.bool.isRequired // from react-redux
    }
   onSubmit = data => {
     console.log(data)
   }
  render () {
     const { handleSubmit,submitting,isLoading } = this.props
      return (
        <Columns isCentered>
        <form onSubmit={handleSubmit(this.onSubmit.bind(this))} >

          <Column isSize='3/6' >
            Organization Name
            <Field
              name="organizationName"
              component={FormField}
              type="text"
              placeholder="Organization Name"
            />
          </Column>

          <Column isSize='3/6'>
            Organization Full Name
            <Field
              name="organizationFullName"
              component={FormField}
              type="text"
              placeholder="Organization Full Name"
            />
          </Column>

           <Column isSize='3/6'>
            Organization Logo
            <Input
              name="organizationLogo"
              type="file"
              placeholder="Logo"
            />
          </Column>

          <Column isSize='3/6'>
            Organization Details
                <TextArea placeholder={'Enter Details'} />
          </Column>

          <Column >

              <Button type="submit" isLoading={submitting || isLoading} isColor='primary'>
                Submit
              </Button>

              <Button type="button" isColor='danger'>
                Cancel
              </Button>
          </Column>

        </form>
      </Columns>
    )
  }
}

  export default reduxForm(formConfig)(CreateOrganization)

Container File

   import React, { PureComponent } from 'react'
   import PropTypes from 'prop-types'
   import { connect } from 'react-redux'
   import Loader from 'Loader'
   import organization from 'state/organization'
   import CreateOrganization from '../components/createOrganization'

   export class Create extends PureComponent {
   static propTypes = {
     error: PropTypes.object,
     isLoaded: PropTypes.bool.isRequired,
     create: PropTypes.func.isRequired,
    }
    onSubmit = data => {
      this.props.create(data)
    }

    render () {
      const { isLoaded, error } = this.props
    return (
       <CreateOrganization onSubmitForm={this.onSubmit} isLoading=
         {isLoading} />
     )
   }
 }

   const mapStateToProps = state => ({
     error: organization.selectors.getError(state),
     isLoading: organization.selectors.isLoading(state)
   })

    const mapDispatchToProps = {
      create: organization.actions.create
    }

  export default connect(mapStateToProps, mapDispatchToProps)(Create)

Body:
I would suggest using redux-promise-middleware. This library requires that the action have a property named payload that is a promise and this is easy with axios. It then integrates with Redux to suffix the root action type (e.g. GET_CUSTOMERS) with PENDING, FULFILLED, and REJECTED and fires those actions.

Firing the action is the same as any other action.

Store

import {applyMiddleware, compose, createStore} from 'redux';
import promiseMiddleware from 'redux-promise-middleware';
import reducer from './reducers';

let middleware = applyMiddleware(promiseMiddleware());
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const enhancer = composeEnhancers(middleware);

export default createStore(reducer, enhancer);

Action

export function getCustomers() {
  return {
    type: 'GET_CUSTOMERS',
    payload: axios.get('url/to/api')
      .then(res => {
        if (!res.ok) throw new Error('An error occurred.');
        return res;
      })
      .then(res => res.json())
      .catch(err => console.warn(err));
  };
}

Reducer

export default function(state = initialState, action) => {
  switch (action.type) {
    case 'GET_CUSTOMERS_PENDING':
      // this means the call is pending in the browser and has not
      // yet returned a response
      ...
    case 'GET_CUSTOMERS_FULFILLED':
      // this means the call is successful and the response has been set
      // to action.payload
      ...
    case 'GET_CUSTOMERS_REJECTED':
      // this means the response was unsuccessful so you can handle that
      // error here
      ...
    default:
      return state;
  }
}


问:
Why can't PHP create a directory with 777 permissions?
I'm trying to create a directory on my server using PHP with the command:

```<code>mkdir("test", 0777);
</code>```

But it doesn't give full permissions, only these:

```<code>rwxr-xr-x
</code>```

答:
For those who tried

mkdir('path', 777);

and it did not work.

It is because, apparently, the 0 preceding the file mode is very important which tells chmod to interpret the passed number as an Octal instead of a decimal.

Reference

Ps. This is not a solution to the question but only an add-on to the accepted anwser

Body:
I'm trying to create a directory on my server using PHP with the command:

mkdir("test", 0777);

But it doesn't give full permissions, only these:

rwxr-xr-x


问:
regexp_substr Finding two letter words
I have a address field in Oracle from where I need o extract the State Code.

```<code>select  '111 BROADWAY ~ ST LOUIS, WA 58585' from dual
union
select  '111 BROADWAY ~ ST LOUIS, WA' from dual
union
select  '111 BROADWAY ~ ST LOUIS,58585 WA' from dual
</code>```

Sometimes the state code WA is before Postal Code and some times after.
Also in some cases the Postal code is not present.

Need help to extract WA in all these cases.

答:
Here is how you can find the last substring consisting of exactly two letters, preceded by a space and followed by a space OR the end of the string:

```<code>select ....,
       regexp_substr(address, '.*( ([[:alpha:]]{2})( |$))', 1, 1, null, 2) as state_code
...........
</code>```

The regular expression looks for a single space followed by two letters followed by a space or the end of the string. Preceding that by .* guarantees that we find the LAST such occurrence. Then the REGEXP function returns just the two letters (the part of the pattern in the second pair of parentheses, counting from the left; that is the meaning of the last argument to REGEXP_SUBSTR).

Title: regexp_substr Finding two letter words

Body:
I have a address field in Oracle from where I need o extract the State Code.

select  '111 BROADWAY ~ ST LOUIS, WA 58585' from dual
union
select  '111 BROADWAY ~ ST LOUIS, WA' from dual
union
select  '111 BROADWAY ~ ST LOUIS,58585 WA' from dual

Sometimes the state code WA is before Postal Code and some times after.
Also in some cases the Postal code is not present.

Need help to extract WA in all these cases.

Body:
Here is how you can find the last substring consisting of exactly two letters, preceded by a space and followed by a space OR the end of the string:

select ....,
       regexp_substr(address, '.*( ([[:alpha:]]{2})( |$))', 1, 1, null, 2) as state_code
...........

The regular expression looks for a single space followed by two letters followed by a space or the end of the string. Preceding that by .* guarantees that we find the LAST such occurrence. Then the REGEXP function returns just the two letters (the part of the pattern in the second pair of parentheses, counting from the left; that is the meaning of the last argument to REGEXP_SUBSTR).


问:
Constructors and Advanced Exception Throwing C++
I have to analyze this C++ code which involves exceptions, but I’m not used to analyzing what code is supposed to do. There’s several things about it I don’t understand. Additionally, I don’t have experience with a buffer data structure or advanced details of throwing exceptions in C++.

What is the max size of the data structure?

That is to say, if a Seq_Buffer is made with size_ = 100, how many
elements can be stored?

My intuition tells me that if you create    something with size 100,
it’s max size will be 100, but I can’t be    sure with facts.

Constructors can throw exceptions in c++?

Can the constructor for Seq_Buffer throw an exception?

Assuming this is true, why does that work without explicating
stating a try, catch, or throw block? I thought that was the only way to get exceptions

I’ve tried searching for these two questions, but I’m really quite lost. Thank you for taking the time to read.I’ve tried searching for these two questions, but I’m really quite lost. Thank you for taking the time to read.

The code for the Seq_Buffer class with its constructor is below:

```<code>#ifndef SEQBUFFER_H
#define SEQBUFFER_H

#include <memory>
#include <experimental/optional>

#include "optional.h"

// Exceptions classes
struct full_buffer {};
struct empty_buffer {};

// Sequential buffer for values of type T
template <typename T>
class seq_buffer {
public:
  // Constructs a buffer for n elements
  seq_buffer(int n) :
    size_{n},
    buf_{new item_type[size_]}
  {
  }

  // Default destructor
  ~seq_buffer() = default;

  // Size of buffer
  int size() const noexcept {
    return size_;
  }

  // Is buffer empty?
  bool empty() const noexcept {
    return next_read_ == next_write_;
  }

  // Is buffer full?
  bool full() const noexcept {
    const int next = next_position(next_write_);
    return next == next_read_;
  }

  // Put element x into buffer with marker last.
  // An empty element signals end of buffer.
  void put(const optional<T> & x);

  // Gets a pair with next element and last indication.
  // Pair is accessed through members first and second
  optional<T> get();

private:
  // Compute next position after p following circular order
  int next_position(int p) const noexcept {
    return p + ((p+1>=size_)?(1-size_):1);
  }

private:
  // Size of buffer
  const int size_;

  using item_type = optional<T>;

  // Unique pointer to buffer of size_ elements.
  std::unique_ptr<item_type[]> buf_;

  // Next position to read
  int next_read_ = 0;

  // Next position to write
  int next_write_ = 0;
};

template <typename T>
void seq_buffer<T>::put(const optional<T> & x)
{
  const int next = next_position(next_write_);
  if (next == next_read_) throw full_buffer{};
  if (!x) {
    buf_[next_write_] = {};
  }
  else {
    buf_[next_write_] = *x;
  }
  next_write_ = next;
}

template <typename T>
optional<T> seq_buffer<T>::get()
{
  if (empty()) throw empty_buffer{};
  auto res = buf_[next_read_];
  next_read_ = next_position(next_read_);
  return res;
}

#endif
</code>```

答:
Yes we can throw exceptions from constructors.It is the best way of dealing with constructor failures or class initialization error.Take this code example

```<code>class bar
{
public:
  bar()
  {
    std::cout << "bar() called" << std::endl;
  }

  ~bar()
  {
    std::cout << "~bar() called" << std::endl;

  }
};
class foo
{
public:
  foo()
    : b(new bar())
  {
    std::cout << "foo() called" << std::endl;
    throw "throw something";
  }

  ~foo()
  {
    delete b;
    std::cout << "~foo() called" << std::endl;
  }

private:
  bar *b;
};

int main(void)
{
  try {
    std::cout << "heap: new foo" << std::endl;
    foo *f = new foo();
  } catch (const char *e) {
    std::cout << "heap exception: " << e << std::endl;
  }

  try {
    std::cout << "stack: foo" << std::endl;
    foo f;
  } catch (const char *e) {
    std::cout << "stack exception: " << e << std::endl;
  }

  return 0;
}
</code>```

Here you are throwing exception from the constructor itself.But there are situations where you allocate memory(heap) in the constructor.In those situation it is not much useful to throw exception in the constructor as this will lead to memory leak.Because if the class fails to initialize then there will be no destructor called for the class as there is already exception thrown(assuming that in the destructor the allocated memory is freed using free).So throwing exception in constructor depends on the scenario or the use case.Not every situation benefits from throwing exception in the constructor.

Body:
I have to analyze this C++ code which involves exceptions, but I’m not used to analyzing what code is supposed to do. There’s several things about it I don’t understand. Additionally, I don’t have experience with a buffer data structure or advanced details of throwing exceptions in C++.

What is the max size of the data structure?

That is to say, if a Seq_Buffer is made with size_ = 100, how many
elements can be stored?

My intuition tells me that if you create    something with size 100,
it’s max size will be 100, but I can’t be    sure with facts.

Constructors can throw exceptions in c++?

Can the constructor for Seq_Buffer throw an exception?

Assuming this is true, why does that work without explicating
stating a try, catch, or throw block? I thought that was the only way to get exceptions

I’ve tried searching for these two questions, but I’m really quite lost. Thank you for taking the time to read.I’ve tried searching for these two questions, but I’m really quite lost. Thank you for taking the time to read.

The code for the Seq_Buffer class with its constructor is below:

#ifndef SEQBUFFER_H
#define SEQBUFFER_H

#include <memory>
#include <experimental/optional>

#include "optional.h"

// Exceptions classes
struct full_buffer {};
struct empty_buffer {};

// Sequential buffer for values of type T
template <typename T>
class seq_buffer {
public:
  // Constructs a buffer for n elements
  seq_buffer(int n) :
    size_{n},
    buf_{new item_type[size_]}
  {
  }

  // Default destructor
  ~seq_buffer() = default;

  // Size of buffer
  int size() const noexcept {
    return size_;
  }

  // Is buffer empty?
  bool empty() const noexcept {
    return next_read_ == next_write_;
  }

  // Is buffer full?
  bool full() const noexcept {
    const int next = next_position(next_write_);
    return next == next_read_;
  }

  // Put element x into buffer with marker last.
  // An empty element signals end of buffer.
  void put(const optional<T> & x);

  // Gets a pair with next element and last indication.
  // Pair is accessed through members first and second
  optional<T> get();

private:
  // Compute next position after p following circular order
  int next_position(int p) const noexcept {
    return p + ((p+1>=size_)?(1-size_):1);
  }

private:
  // Size of buffer
  const int size_;

  using item_type = optional<T>;

  // Unique pointer to buffer of size_ elements.
  std::unique_ptr<item_type[]> buf_;

  // Next position to read
  int next_read_ = 0;

  // Next position to write
  int next_write_ = 0;
};

template <typename T>
void seq_buffer<T>::put(const optional<T> & x)
{
  const int next = next_position(next_write_);
  if (next == next_read_) throw full_buffer{};
  if (!x) {
    buf_[next_write_] = {};
  }
  else {
    buf_[next_write_] = *x;
  }
  next_write_ = next;
}

template <typename T>
optional<T> seq_buffer<T>::get()
{
  if (empty()) throw empty_buffer{};
  auto res = buf_[next_read_];
  next_read_ = next_position(next_read_);
  return res;
}

#endif

Body:
Yes we can throw exceptions from constructors.It is the best way of dealing with constructor failures or class initialization error.Take this code example

class bar
{
public:
  bar()
  {
    std::cout << "bar() called" << std::endl;
  }

  ~bar()
  {
    std::cout << "~bar() called" << std::endl;

  }
};
class foo
{
public:
  foo()
    : b(new bar())
  {
    std::cout << "foo() called" << std::endl;
    throw "throw something";
  }

  ~foo()
  {
    delete b;
    std::cout << "~foo() called" << std::endl;
  }

private:
  bar *b;
};

int main(void)
{
  try {
    std::cout << "heap: new foo" << std::endl;
    foo *f = new foo();
  } catch (const char *e) {
    std::cout << "heap exception: " << e << std::endl;
  }

  try {
    std::cout << "stack: foo" << std::endl;
    foo f;
  } catch (const char *e) {
    std::cout << "stack exception: " << e << std::endl;
  }

  return 0;
}

Here you are throwing exception from the constructor itself.But there are situations where you allocate memory(heap) in the constructor.In those situation it is not much useful to throw exception in the constructor as this will lead to memory leak.Because if the class fails to initialize then there will be no destructor called for the class as there is already exception thrown(assuming that in the destructor the allocated memory is freed using free).So throwing exception in constructor depends on the scenario or the use case.Not every situation benefits from throwing exception in the constructor.


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答: Read up on the halting problem (which is about the difficulty of proving something as simple as whether a program completes or not).  Fundamentally the problem is related to Gödel's incompleteness theorem.</p>

Title: Why can't programs be proven?

OwnerDisplayName: timday


问:
Syntax when calling Typescript class from Javascript
I've written a typescript class that will be called in legacy javascript.  I import it via:

const ConfigurationManager = require('./ConfigurationManager');

After the transpile I end up with:

```<code>var ConfigurationManager = /** @class */ (function () {
    function ConfigurationManager
</code>```

so it must be called with:

new ConfigurationManager.ConfigurationManager(...)

to create a new instance.  Is there a way to clean this up so the javascript side is a little less verbose?

答:
There are several options:

You could just define another variable in which you put the class:

Code:

```<code>const ConfigurationManagerModule = require('./ConfigurationManager');
const ConfigurationManager = ConfigurationManagerModule.ConfigurationManager;
new ConfigurationManager(...);
</code>```

You could set the whole export of the module as the class if the module exports nothing but this class.

Code:

```<code>export = class ConfigurationManager  {

}
const ConfigurationManager = require('./ConfigurationManager');

new ConfigurationManager();
</code>```

For the second option, the difference between export class .. and export = class ..., is that in the first case we specify something to add to the export, in the second we specify that the whole export is the class. In terms of the generated JS, the first options generates this:

```<code>var ConfigurationManager = /** @class */ (function () {
    function ConfigurationManager() {
    }
    return ConfigurationManager;
}());
exports.ConfigurationManager = ConfigurationManager;
</code>```

while the second generates this:

```<code>module.exports = /** @class */ (function () {
    function ConfigurationManager() {
    }
    return ConfigurationManager;
}());
</code>```

Body:
I've written a typescript class that will be called in legacy javascript.  I import it via:

const ConfigurationManager = require('./ConfigurationManager');

After the transpile I end up with:

var ConfigurationManager = /** @class */ (function () {
    function ConfigurationManager

so it must be called with:

new ConfigurationManager.ConfigurationManager(...)

to create a new instance.  Is there a way to clean this up so the javascript side is a little less verbose?

Body:
There are several options:

You could just define another variable in which you put the class:

Code:

const ConfigurationManagerModule = require('./ConfigurationManager');
const ConfigurationManager = ConfigurationManagerModule.ConfigurationManager;
new ConfigurationManager(...);

You could set the whole export of the module as the class if the module exports nothing but this class.

Code:

export = class ConfigurationManager  {

}
const ConfigurationManager = require('./ConfigurationManager');

new ConfigurationManager();

For the second option, the difference between export class .. and export = class ..., is that in the first case we specify something to add to the export, in the second we specify that the whole export is the class. In terms of the generated JS, the first options generates this:

var ConfigurationManager = /** @class */ (function () {
    function ConfigurationManager() {
    }
    return ConfigurationManager;
}());
exports.ConfigurationManager = ConfigurationManager;

while the second generates this:

module.exports = /** @class */ (function () {
    function ConfigurationManager() {
    }
    return ConfigurationManager;
}());


问:
CSS: Making two complementary diagonal divs
this is what I'm trying to do:

This is how I was trying to do it:
  The first div 'subCont1' works fine, even if it's getting out of the page. If I do the same thing with the second, this time scroll activates for the same reason.

.subCont1{

    background-color: blueviolet;
    position:absolute;
    left:-20%;
    top:0;

    width:70%;
    height:100%;
    transform: skew(-20deg);

    border:2px solid yellow;
}

.subCont2{

      width:50%;
      height:100%;

      border:2px solid grey;

      z-index:1000;

      overflow:hidden;
  }```

答:
You can use a background gradient to fake it:

.mybox {
  border: solid;
  background: linear-gradient(100deg, blue 49.75%, black 50%, black calc(50% + 3px), green calc(50% + 4px));
  display: flex;
  margin:1em;
}

.mybox div {
  padding: 1em 2%;
  flex:1;
  color:white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=mybox>
  <div> div one </div>
  <div> div two</div>
</div>

<div class=mybox>
  <div> div one <br> line two </div>
  <div> div two</div>
</div></code>```

Body:
You can use a background gradient to fake it:

.mybox {
  border: solid;
  background: linear-gradient(100deg, blue 49.75%, black 50%, black calc(50% + 3px), green calc(50% + 4px));
  display: flex;
  margin:1em;
}

.mybox div {
  padding: 1em 2%;
  flex:1;
  color:white;
}

<div class=mybox>
  <div> div one </div>
  <div> div two</div>
</div>

<div class=mybox>
  <div> div one <br> line two </div>
  <div> div two</div>
</div>


问:
Should I Ajax or should I store the whole collection into a variable ?
I am building a single page app.
The app has a list of 7000 ports stored in a MongoDB database.
I need to be able to search for those ports with autocomplete on the search.

Should I Ajax the autocomplete results ?

OR

Should I retrieve the whole collection of ports, store it in a variable, plug my autocomplete on this array ?

What's the best practice ?
What's the smartest performance wise ?

答:
Because you said the list can grow I would not load the whole list into your app. This could lead to performance issues if your list becomes too big.

I would solve this problem in this way:

Make a route on your webservice, which returns lets say the top 10-20 results matching your search.

On input send a GET request to your endpoint.

To improve performance you could cache the list in an in-memory database like Redis to avoid slow database-access on every request.


问:
How to create a color picker in html?
How to make a color picker, like we see in different websites where users can scroll down different colors and on click can get the color code?

I have tried of making a rows and columns but it was not so comfortable so want it to be like a color picker

You can take a look at the color box how i am trying it to be:

I have gone through different questions but I'm not able to solve this issue.

答:
You can simply create a color picker by  with type as color. But it works only in modern browsers.

DON'T USE Color Picker. It is ultra random as to what it does, older browsers turn it into a regular input, newer ones are random as it gets. Your best bet is to do as I am and either pick a Javascript color picker or create your own. I am forced to create my own because all of the current pickers are too project specific.

Title: How to create a color picker in html?


问:
Accessing ASP.NET controls dynamically from JavaScript
here's what I mean:

I have a few controls, for example,

```<code><asp:DropDownList ID="ddlDate1" runat="server" />
<asp:DropDownList ID="ddlDate2" runat="server" />
<asp:DropDownList ID="ddlDate3" runat="server" />
</code>```

in my javascript, I want to do something like this:

```<code>for (i = 1; i <= count; i++) {
    something[i] = document.getElementById("<%= ddlDateRange" + i + ".ClientID %>");
}
</code>```

any way I can make this work, or any alternatives?

答:
Why not use jQuery and just do something like:

```<code><asp:DropDownList CssClass="ddl" ID="ddlDate1" runat="server" />
<asp:DropDownList CssClass="ddl" ID="ddlDate2" runat="server" />
<asp:DropDownList CssClass="ddl" ID="ddlDate3" runat="server" />
</code>```

```<code>$('.ddl').each(function(){
    var ddl = $(this);
});
</code>```

Body:
here's what I mean:

I have a few controls, for example,

<asp:DropDownList ID="ddlDate1" runat="server" />
<asp:DropDownList ID="ddlDate2" runat="server" />
<asp:DropDownList ID="ddlDate3" runat="server" />

in my javascript, I want to do something like this:

for (i = 1; i <= count; i++) {
    something[i] = document.getElementById("<%= ddlDateRange" + i + ".ClientID %>");
}

any way I can make this work, or any alternatives?

Body:
Why not use jQuery and just do something like:

<asp:DropDownList CssClass="ddl" ID="ddlDate1" runat="server" />
<asp:DropDownList CssClass="ddl" ID="ddlDate2" runat="server" />
<asp:DropDownList CssClass="ddl" ID="ddlDate3" runat="server" />

$('.ddl').each(function(){
    var ddl = $(this);
});


问:
Can we able to display multiple ads in same screen using AdMob
I have one app in which I want to display multiple ads in same screen.

App has one recycler view & which is scrollable more than 200 items. After in each 6 items, I have planed display the ads from admob. Are we able to do this using admob.?

I have tried with single ad unit id, with this all displaying ads are same.
How to get different ads in same screen with more secure way & without violating policies ?

Please help!!

答:
You can have more than one ad in the same Activity, but only one should be on the screen at any given time. If you're using a RecyclerView and mixing ads with content, just make sure you have enough space between ads that they don't share the screen.

Because display sizes vary so much from device to device (especially from phone to tablet), you should check the device dimensions and use them to decide how far apart to space your ads.


问:
How to run virus scanner script from host machine from Docker container
I've got a java program where user can upload photos etc. It is running on docker container in Linux. I can have a plenty of containers and I don't want to pay many licenses to Mcafee, so is there a good solution for executing uvscan on host machine and scan uploaded files and buy only one license instead of 30?</p>

答:
One way is to mount files to host directory and perform scan.

There is a blog which explains scanning malicious files, but it uses Linux Malware Detection (LMD) and CalmAV, go through if it helpful

https://www.linkedin.com/pulse/virus-malware-scanning-service-docker-dietrich-rordorf


问:
Validation strategy
I'm trying to build a series of attribute classes to make it easier for our development team to validate objects. The objects are POCO classes like this.

```<code>public class User
{
    public string Name { get; set; }
    public string Company { get; set; }
}
</code>```

I want to decorate this model with a custom attribute.

```<code>public class User
{
    [MustHaveValue]
    public string Name { get; set; }
    public string Company { get; set; }
}
</code>```

Then I would create my own class implementing ValidationAttribute, the base class in .NET Framework, which belongs to System.ComponentModel.DataAnnotations.

```<code>public class MustHaveValueAttribute : ValidationAttribute
{
    .
    .
    public override IsValid(object value)
    {
        // validation logic.
    }
}
</code>```

And then I can validate the User model whenever I want by making the set of instances like ValidationContext, List<ValidationResult>.

But in an enterprise environment, problems just can't be solved by a specific class. My validation scenario requires more complex and more flexible ways. Imagine that one of the required validation scenarios would something like this.

```<code>public class User
{
    public string Name { get; set; }
    public string Company { get; set; }

    // Check if an item exists in this list.
    [MustHaveMoreThanOneItem]
    public IList<Client> Clients { get; set; }
}
</code>```

Then I would need to make another attribute class

```<code>public class MustHaveMoreThanOneItemAttribute : ValidationAttribute
{
    .
    .
    public override IsValid(object value)
    {
        // Let's assume this value is List<Client> for now.
        // I know the exact type, so I'm going to cast it to List<Client> without further considerations
        List<Client> clients = value as List<Client>;
        if(clients.Count > 0) {
            return true;
        } else {
            return false;
        }
    }
}
</code>```

But the problem is that there are a lot of other models that have a nested list items. Try to imagine the time when I want to reuse the MustHaveMoreThanOneItem in one of the other models like...

```<code>public class Department
{
    public string Name { get; set; }

    [MustHaveMoreThanOneItem]
    public IList<Employee> { get; set; }
}
</code>```

You already know that it's not going to work because it was strongly typed only for List<Client>. So I decided to use Generic there to solve this problem.

But to my disappointment, the _Attribute interface doesn't support Generic. There's no additional implementation like _Attribute<T> : Attribute and therefore, no ValidationAttribute<T> alas!! I just cannot use Generic here !!

```<code>public class Department
{
    public string Name { get; set; }

    // No way to use this syntax.
    [MustHaveMoreThanOneItem<Employee>]
    public IList<Employee> { get; set; }
}
</code>```

So I made a conclusion that Attribute must have been designed for a fixed set of validations like email format, card format, null check, and etc IMAO.

But I still want to use an attribute and give a lot of flexibilities in it to prevent the duplicated, verbose validation codes like this.

```<code>if(model.Clients.Count > 0) ...
if(model.Name != null) ...
if(model.Clients.GroupBy(x => x.Country == Country.USA).Count >= 1) ...
if(model.Clients.Where(x => x.CompanyName == Company.Google).ToList().Count > 1 ) ...
.
.
.
</code>```

I want to pose two questions here.

If Attirbute supports Generic, this problem will be solved?

Is there any way to implement Generic Attribute? in order to use
[MustHaveMoreThanOneItem<Employee>] annotation on a class member?

答:
You can generically check any object that implements IEnumerable like this:

```<code>public class MustHaveMoreThanOneItemAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // omitted null checking
        var enumerable = value as IEnumerable;
        var enumerator = enumerable.GetEnumerator();
        if (!enumerator.MoveNext())
        {
            return false;
        }

        if (!enumerator.MoveNext())
        {
            return false;
        }

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

Title: Validation strategy

Body:
I'm trying to build a series of attribute classes to make it easier for our development team to validate objects. The objects are POCO classes like this.

public class User
{
    public string Name { get; set; }
    public string Company { get; set; }
}

I want to decorate this model with a custom attribute.

public class User
{
    [MustHaveValue]
    public string Name { get; set; }
    public string Company { get; set; }
}

Then I would create my own class implementing ValidationAttribute, the base class in .NET Framework, which belongs to System.ComponentModel.DataAnnotations.

public class MustHaveValueAttribute : ValidationAttribute
{
    .
    .
    public override IsValid(object value)
    {
        // validation logic.
    }
}

And then I can validate the User model whenever I want by making the set of instances like ValidationContext, List<ValidationResult>.

But in an enterprise environment, problems just can't be solved by a specific class. My validation scenario requires more complex and more flexible ways. Imagine that one of the required validation scenarios would something like this.

public class User
{
    public string Name { get; set; }
    public string Company { get; set; }

    // Check if an item exists in this list.
    [MustHaveMoreThanOneItem]
    public IList<Client> Clients { get; set; }
}

Then I would need to make another attribute class

public class MustHaveMoreThanOneItemAttribute : ValidationAttribute
{
    .
    .
    public override IsValid(object value)
    {
        // Let's assume this value is List<Client> for now.
        // I know the exact type, so I'm going to cast it to List<Client> without further considerations
        List<Client> clients = value as List<Client>;
        if(clients.Count > 0) {
            return true;
        } else {
            return false;
        }
    }
}

But the problem is that there are a lot of other models that have a nested list items. Try to imagine the time when I want to reuse the MustHaveMoreThanOneItem in one of the other models like...

public class Department
{
    public string Name { get; set; }

    [MustHaveMoreThanOneItem]
    public IList<Employee> { get; set; }
}

You already know that it's not going to work because it was strongly typed only for List<Client>. So I decided to use Generic there to solve this problem.

But to my disappointment, the _Attribute interface doesn't support Generic. There's no additional implementation like _Attribute<T> : Attribute and therefore, no ValidationAttribute<T> alas!! I just cannot use Generic here !!

public class Department
{
    public string Name { get; set; }

    // No way to use this syntax.
    [MustHaveMoreThanOneItem<Employee>]
    public IList<Employee> { get; set; }
}

So I made a conclusion that Attribute must have been designed for a fixed set of validations like email format, card format, null check, and etc IMAO.

But I still want to use an attribute and give a lot of flexibilities in it to prevent the duplicated, verbose validation codes like this.

if(model.Clients.Count > 0) ...
if(model.Name != null) ...
if(model.Clients.GroupBy(x => x.Country == Country.USA).Count >= 1) ...
if(model.Clients.Where(x => x.CompanyName == Company.Google).ToList().Count > 1 ) ...
.
.
.

I want to pose two questions here.

If Attirbute supports Generic, this problem will be solved?

Is there any way to implement Generic Attribute? in order to use
[MustHaveMoreThanOneItem<Employee>] annotation on a class member?

Body:
You can generically check any object that implements IEnumerable like this:

public class MustHaveMoreThanOneItemAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        // omitted null checking
        var enumerable = value as IEnumerable;
        var enumerator = enumerable.GetEnumerator();
        if (!enumerator.MoveNext())
        {
            return false;
        }

        if (!enumerator.MoveNext())
        {
            return false;
        }

        return true;
    }
}


问:
SSIS Flat file column delimiter
I have a csv file that I process and import into a database. the problem is the delimiter needs to be " but within SSIS is this possible as currently the default options are :-

答: Just write it by yourself in the text box. Your choice is not limited with the values listed in the drop down list.</p>

Title: SSIS Flat file column delimiter