问:
CSS/HTML fit any resolution
I am relatively new to the css/html world. I am trying to create a website. I noticed though that even though everything looks great on my screen when i try to view it on lower resolution screens everything is messed up. Is there a way to make it display correctly through css?

Here is an image of what i'm trying to achieve and make it possible for lower resolutions as well: image
here is my css so far (the first part is a reseter. i got it as it is from watching a youtube tutorial) :

html,body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary, time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

body {
  line-height: 1;
}

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

nav ul {
  list-style: none;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}

a {
  margin: 0;
  padding: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

/* change colours to suit your needs */

ins {
  background-color: #ff9;
  color: #000;
  text-decoration: none;
}

/* change colours to suit your needs */

mark {
  background-color: #ff9;
  color: #000;
  font-style: italic;
  font-weight: bold;
}

del {
  text-decoration: line-through;
}

abbr[title],
dfn[title] {
  border-bottom: 1px dotted;
  cursor: help;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* change border colour to suit your needs */

hr {
  display: block;
  height: 1px;
  border: 0;
  border-top: 1px solid #cccccc;
  margin: 1em 0;
  padding: 0;
}

input,
select {
  vertical-align: middle;
}

/*!!!!!END OF RESET!!!!!*/

/*MY CSS*/

body {
  width: 100%;
  height: 100%;
}

#logo1 {
  padding-left: 25px;
}

#logo2 {
  padding-left: 260px;
}

#eternal {
  padding-top: 15px;
  display: block;
  position: absolute;
  left: 0;
}

#prwtoetis {
  padding-top: 20px;
  float: right;
  position: absolute;
  bottom: 0%;
  left: 0;
}

#akyri {
  padding-top: 5px;
  display: block;
  position: absolute;
  right: 0%;
}

#akyri2 {
  padding-top: 5px;
  display: block;
  bottom: 0%;
  right: 0%;
  position: absolute;
}

#quote {
  text-align: center;
  padding: 13%;
  font-family: Calibri;
  font-size: 35px;
}

a {
  color: #000;
  text-decoration: none;
}

body {
  background-color: #e1e8ea;
  width: 100%;
  min-width: 600px;
  max-width: 2000px
}

header {
  background-color: #b5c4c9;
  padding-top: 8px;
  padding-bottom: 10px;
  width: 100%;
  height: 159px;
}

header img {
  float: left;
}

nav {
  float: left;
}

nav ul {
  margin-top: 86px;
  margin-left: 200px;
}

nav ul li {
  display: inline-block;
  margin-left: 20px;
}

nav ul li a {
  font-family: Calibri;
  font-size: 22px;
}

a.ex5:hover,
a.ex5:active {
  text-decoration: underline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>RateYourProfessor</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">
</head>

<body>
  <div id="site-wrapper">

    <header>
      <div>
        <img id="logo1" src="images/logo.png">
        <nav>
          <ul>
            <li>HOME</li>
            <li>CREATE PROFESSOR</li>
            <li>RATE PROFESSOR</li>
            <li>SCOREBOARD</li>
            <li>TOP 5</li>
          </ul>
        </nav>
        <img id="logo2" src="images/logo.png">
      </div>
    </header>

    <section>
      <div>
        <img id="eternal" src="images/eternal.png">
        <img id="prwtoetis" src="images/prwtoetis.png">
        <img id="akyri" src="images/akyri.png">
        <img id="akyri2" src="images/akyri2.png">
      </div>
      <div id="quote"><br> There is no end to education. <br>It is not that you read a book, pass an examination, and finish with education. <br>The whole of life, from the moment you are born to the moment you die, is a process of learning.
        <br>- <i>Jiddu Krishnamurti</i>
      </div>
    </section>
  </div>

</body>

</html></code>```

答:
Hi its always a good idea to build your application responsive using a framework such as bootstrap. That'll help your application great on all types of screens.

you can learn it from this website.

https://www.w3schools.com/bootstrap/

https://www.youtube.com/watch?v=qIULMnbH2-o

http://getbootstrap.com/getting-started/

If you dont use any framework like this one, making responsive websites will be a tedious task. Bootstrap is easy to learn and will save you lots of time.

If you decide not to use a framework like bootstrap you'll have to use media queries to resize your elements according to the screen size.

https://www.w3schools.com/css/css3_mediaqueries_ex.asp

Title: CSS/HTML fit any resolution

Body:
I am relatively new to the css/html world. I am trying to create a website. I noticed though that even though everything looks great on my screen when i try to view it on lower resolution screens everything is messed up. Is there a way to make it display correctly through css?

Here is an image of what i'm trying to achieve and make it possible for lower resolutions as well: image
here is my css so far (the first part is a reseter. i got it as it is from watching a youtube tutorial) :

html,body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary, time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

body {
  line-height: 1;
}

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

nav ul {
  list-style: none;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}

a {
  margin: 0;
  padding: 0;
  font-size: 100%;
  vertical-align: baseline;
  background: transparent;
}

/* change colours to suit your needs */

ins {
  background-color: #ff9;
  color: #000;
  text-decoration: none;
}

/* change colours to suit your needs */

mark {
  background-color: #ff9;
  color: #000;
  font-style: italic;
  font-weight: bold;
}

del {
  text-decoration: line-through;
}

abbr[title],
dfn[title] {
  border-bottom: 1px dotted;
  cursor: help;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* change border colour to suit your needs */

hr {
  display: block;
  height: 1px;
  border: 0;
  border-top: 1px solid #cccccc;
  margin: 1em 0;
  padding: 0;
}

input,
select {
  vertical-align: middle;
}

/*!!!!!END OF RESET!!!!!*/

/*MY CSS*/

body {
  width: 100%;
  height: 100%;
}

#logo1 {
  padding-left: 25px;
}

#logo2 {
  padding-left: 260px;
}

#eternal {
  padding-top: 15px;
  display: block;
  position: absolute;
  left: 0;
}

#prwtoetis {
  padding-top: 20px;
  float: right;
  position: absolute;
  bottom: 0%;
  left: 0;
}

#akyri {
  padding-top: 5px;
  display: block;
  position: absolute;
  right: 0%;
}

#akyri2 {
  padding-top: 5px;
  display: block;
  bottom: 0%;
  right: 0%;
  position: absolute;
}

#quote {
  text-align: center;
  padding: 13%;
  font-family: Calibri;
  font-size: 35px;
}

a {
  color: #000;
  text-decoration: none;
}

body {
  background-color: #e1e8ea;
  width: 100%;
  min-width: 600px;
  max-width: 2000px
}

header {
  background-color: #b5c4c9;
  padding-top: 8px;
  padding-bottom: 10px;
  width: 100%;
  height: 159px;
}

header img {
  float: left;
}

nav {
  float: left;
}

nav ul {
  margin-top: 86px;
  margin-left: 200px;
}

nav ul li {
  display: inline-block;
  margin-left: 20px;
}

nav ul li a {
  font-family: Calibri;
  font-size: 22px;
}

a.ex5:hover,
a.ex5:active {
  text-decoration: underline;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>RateYourProfessor</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">

HOME

CREATE PROFESSOR

RATE PROFESSOR

SCOREBOARD

TOP 5

 There is no end to education.
It is not that you read a book, pass an examination, and finish with education.
The whole of life, from the moment you are born to the moment you die, is a process of learning.

- Jiddu Krishnamurti


来源: stackexchange

问:
Domain Driven Design question
I would like to ask for a reccomended solution for this:

 We have a list of Competitions.

 Each competition has defined fee that a participatior has to pay

We have Participators

I have to know has a Participator that is on a Competition paid the fee or not. I am thinking about 2 solutions and the thing is it has to be the most appropriate solution in Domain Driven Design.
First is to create a Dictionary in Competition instead of a List, the dictionary would have be of type <Participator, bool>.
The secont is perhaps create a different class that has 2 fields, a participator and feePaid. And in Competiton I would have a list of object of that new class.

Thank you

答: The way I would handle this is to have Competitions, Participants, and Registrations.  A Participant would register for a Competition, creating a Registration.  A Registration would consist of the Competition id, Participant id, a flag indicating whether the fee was paid or not, and any other registration-specific data (like the date of registration).  This would be modeled in the database as a "join table" (with the additional data).  On the app side, a Participant would have a list of Registrations, each Registration would have an associated Participant and a Competition.  Likewise, each Competition would have a list of Registrations.</p>

OwnerDisplayName: gljivar

ContentLicense: CC BY-SA 2.5

Title: Domain Driven Design question

LastEditorDisplayName: tvanfosson

OwnerDisplayName: tvanfosson


问:
SPSS bizarre glitch when importing from excel
I am trying to run down the source of a bizzare data glitch I am getting in SPSS. when I import my data, the cases for every other line (all the odds from 33-63) in column 2 show up blank (not missing, but blank). After 65 that it starts showing 3 blanks in a row, then a record, then 3 more blanks and so on up to 100 records (the file ends at 100 records.)

It looks like this:

```<code>N   ID_1    F_Name  L_Name  ID_2
1   ABC1    First   Last    p1234567
2   ABC2    First   Last    p1234567
3   ABC3    First   Last    p1234567
4   ABC4    First   Last    p1234567
5   ABC5    First   Last    p1234567
6   ABC6    First   Last    p1234567
7   ABC7    First   Last    p1234567
8   ABC8    First   Last    p1234567
9   ABC9    First   Last    p1234567
10  ABC10   First   Last    p1234567
11  ABC11   First   Last    p1234567
12  ABC12   First   Last    p1234567
13  ABC13   First   Last    p1234567
14  ABC14   First   Last    p1234567
15  ABC15   First   Last    p1234567
16  ABC16   First   Last    p1234567
17  ABC17   First   Last    p1234567
18  ABC18   First   Last    p1234567
19  ABC19   First   Last    p1234567
20  ABC20   First   Last    p1234568
21  ABC21   First   Last    p1234569
22  ABC22   First   Last    p1234570
23  ABC23   First   Last    p1234571
24  ABC24   First   Last    p1234572
25  ABC25   First   Last    p1234573
26  ABC26   First   Last    p1234574
27  ABC27   First   Last    p1234575
28  ABC28   First   Last    p1234576
29  ABC29   First   Last    p1234577
30  ABC30   First   Last    p1234578
31  ABC31   First   Last    p1234579
32  ABC32   First   Last    p1234580
33          First   Last    p1234581
34  ABC34   First   Last    p1234582
35          First   Last    p1234583
36  ABC36   First   Last    p1234584
37          First   Last    p1234585
38  ABC38   First   Last    p1234586
39          First   Last    p1234587
40  ABC40   First   Last    p1234588
41          First   Last    p1234589
42  ABC42   First   Last    p1234590
43          First   Last    p1234591
44  ABC44   First   Last    p1234592
45          First   Last    p1234593
46  ABC46   First   Last    p1234594
47          First   Last    p1234595
48  ABC48   First   Last    p1234596
49          First   Last    p1234597
50  ABC50   First   Last    p1234598
51          First   Last    p1234599
52  ABC52   First   Last    p1234600
53          First   Last    p1234601
54  ABC54   First   Last    p1234602
55          First   Last    p1234603
56  ABC56   First   Last    p1234604
57          First   Last    p1234605
58  ABC58   First   Last    p1234606
59          First   Last    p1234607
60  ABC60   First   Last    p1234608
61          First   Last    p1234609
62  ABC62   First   Last    p1234610
63          First   Last    p1234611
64  ABC64   First   Last    p1234612
65          First   Last    p1234613
66          First   Last    p1234614
67          First   Last    p1234615
68  ABC68   First   Last    p1234616
69          First   Last    p1234617
70          First   Last    p1234618
71          First   Last    p1234619
72  ABC72   First   Last    p1234620
73          First   Last    p1234621
74          First   Last    p1234622
75          First   Last    p1234623
76  ABC76   First   Last    p1234624
77          First   Last    p1234625
78          First   Last    p1234626
79          First   Last    p1234627
80  ABC80   First   Last    p1234628
81          First   Last    p1234629
82          First   Last    p1234630
83          First   Last    p1234631
84  ABC84   First   Last    p1234632
85          First   Last    p1234633
86          First   Last    p1234634
87          First   Last    p1234635
88  ABC88   First   Last    p1234636
89          First   Last    p1234637
90          First   Last    p1234638
91          First   Last    p1234639
92  ABC92   First   Last    p1234640
93          First   Last    p1234641
94          First   Last    p1234642
95          First   Last    p1234643
96  ABC96   First   Last    p1234644
97          First   Last    p1234645
98          First   Last    p1234646
99          First   Last    p1234647
100 ABC100  First   Last    p1234648
</code>```

I am using a standard import syntax:

```<code>GET DATA
  /TYPE=XLS
  /FILE='Y:\RESEARCH UNIT\RESEARCH UNIT PROJECTS\DATA\2016\Quarter 1 (Jan - Mar 2016)\Working Files\WK-FILE ONE.xls'
  /SHEET=name 'Demographics'
  /CELLRANGE=full
  /READNAMES=on
  /ASSUMEDSTRWIDTH=32767.
</code>```

The only clue I have is the excel formula that creates the ID_1 is "=CONCATENATE(G1,F1,A1)". SPSS hasn't had any issues with importing other formula based values, but maybe I am missing something.

Thanks in advance for anyone with a theory on what is happening and a way to fix it that doesn't involve manually altering the original excel files!

答: What version of Statistics are you using?  Have you installed the latest fixpack for it?  Excel files are endlessly tricky.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run down the source of a bizzare data glitch I am getting in SPSS. when I import my data, the cases for every other line (all the odds from 33-63) in column 2 show up blank (not missing, but blank). After 65 that it starts showing 3 blanks in a row, then a record, then 3 more blanks and so on up to 100 records (the file ends at 100 records.)

It looks like this:

N   ID_1    F_Name  L_Name  ID_2
1   ABC1    First   Last    p1234567
2   ABC2    First   Last    p1234567
3   ABC3    First   Last    p1234567
4   ABC4    First   Last    p1234567
5   ABC5    First   Last    p1234567
6   ABC6    First   Last    p1234567
7   ABC7    First   Last    p1234567
8   ABC8    First   Last    p1234567
9   ABC9    First   Last    p1234567
10  ABC10   First   Last    p1234567
11  ABC11   First   Last    p1234567
12  ABC12   First   Last    p1234567
13  ABC13   First   Last    p1234567
14  ABC14   First   Last    p1234567
15  ABC15   First   Last    p1234567
16  ABC16   First   Last    p1234567
17  ABC17   First   Last    p1234567
18  ABC18   First   Last    p1234567
19  ABC19   First   Last    p1234567
20  ABC20   First   Last    p1234568
21  ABC21   First   Last    p1234569
22  ABC22   First   Last    p1234570
23  ABC23   First   Last    p1234571
24  ABC24   First   Last    p1234572
25  ABC25   First   Last    p1234573
26  ABC26   First   Last    p1234574
27  ABC27   First   Last    p1234575
28  ABC28   First   Last    p1234576
29  ABC29   First   Last    p1234577
30  ABC30   First   Last    p1234578
31  ABC31   First   Last    p1234579
32  ABC32   First   Last    p1234580
33          First   Last    p1234581
34  ABC34   First   Last    p1234582
35          First   Last    p1234583
36  ABC36   First   Last    p1234584
37          First   Last    p1234585
38  ABC38   First   Last    p1234586
39          First   Last    p1234587
40  ABC40   First   Last    p1234588
41          First   Last    p1234589
42  ABC42   First   Last    p1234590
43          First   Last    p1234591
44  ABC44   First   Last    p1234592
45          First   Last    p1234593
46  ABC46   First   Last    p1234594
47          First   Last    p1234595
48  ABC48   First   Last    p1234596
49          First   Last    p1234597
50  ABC50   First   Last    p1234598
51          First   Last    p1234599
52  ABC52   First   Last    p1234600
53          First   Last    p1234601
54  ABC54   First   Last    p1234602
55          First   Last    p1234603
56  ABC56   First   Last    p1234604
57          First   Last    p1234605
58  ABC58   First   Last    p1234606
59          First   Last    p1234607
60  ABC60   First   Last    p1234608
61          First   Last    p1234609
62  ABC62   First   Last    p1234610
63          First   Last    p1234611
64  ABC64   First   Last    p1234612
65          First   Last    p1234613
66          First   Last    p1234614
67          First   Last    p1234615
68  ABC68   First   Last    p1234616
69          First   Last    p1234617
70          First   Last    p1234618
71          First   Last    p1234619
72  ABC72   First   Last    p1234620
73          First   Last    p1234621
74          First   Last    p1234622
75          First   Last    p1234623
76  ABC76   First   Last    p1234624
77          First   Last    p1234625
78          First   Last    p1234626
79          First   Last    p1234627
80  ABC80   First   Last    p1234628
81          First   Last    p1234629
82          First   Last    p1234630
83          First   Last    p1234631
84  ABC84   First   Last    p1234632
85          First   Last    p1234633
86          First   Last    p1234634
87          First   Last    p1234635
88  ABC88   First   Last    p1234636
89          First   Last    p1234637
90          First   Last    p1234638
91          First   Last    p1234639
92  ABC92   First   Last    p1234640
93          First   Last    p1234641
94          First   Last    p1234642
95          First   Last    p1234643
96  ABC96   First   Last    p1234644
97          First   Last    p1234645
98          First   Last    p1234646
99          First   Last    p1234647
100 ABC100  First   Last    p1234648

I am using a standard import syntax:

GET DATA
  /TYPE=XLS
  /FILE='Y:\RESEARCH UNIT\RESEARCH UNIT PROJECTS\DATA\2016\Quarter 1 (Jan - Mar 2016)\Working Files\WK-FILE ONE.xls'
  /SHEET=name 'Demographics'
  /CELLRANGE=full
  /READNAMES=on
  /ASSUMEDSTRWIDTH=32767.

The only clue I have is the excel formula that creates the ID_1 is "=CONCATENATE(G1,F1,A1)". SPSS hasn't had any issues with importing other formula based values, but maybe I am missing something.

Thanks in advance for anyone with a theory on what is happening and a way to fix it that doesn't involve manually altering the original excel files!


问:
How to enable hibernate query timings for logging
I am trying to add timing stats mechanism for hibernate queries. Our application.properties file already has entries like this :

```<code>logging.level.org.hibernate.SQL=DEBUG
spring.jpa.hibernate.ddl-auto=validate
</code>```

So I tried to add : logging.level.org.hibernate.stat=DEBUG. But this is not providing me with any timing info. Anyone know why?

edit :
I also added this to pom.xml :

```<code><properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>1.8</java.version>
  <hibernate.generate_statistics>true</hibernate.generate_statistics>
</properties>
</code>```

still doesn't work.

答:
You also need to set hibernate system property as well: hibernate.generate_statistics=true

One way you can set the System property is by using VM argument. In your case: -Dhibernate.generate_statistics=true

Body:
I am trying to add timing stats mechanism for hibernate queries. Our application.properties file already has entries like this :

logging.level.org.hibernate.SQL=DEBUG
spring.jpa.hibernate.ddl-auto=validate

So I tried to add : logging.level.org.hibernate.stat=DEBUG. But this is not providing me with any timing info. Anyone know why?

edit :
I also added this to pom.xml :

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>1.8</java.version>
  <hibernate.generate_statistics>true</hibernate.generate_statistics>
</properties>

still doesn't work.


问:
Xamarin Forms listview out of memory error
In Xamarin Forms i have the following listview:

```<code><ListView x:Name="StudentView"  RowHeight="55"  SeparatorVisibility="None" CachingStrategy="RecycleElement">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="55"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>

                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="0" Aspect="AspectFill"></Image>
                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="1" Aspect="AspectFill"></Image>
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

In the code behind i have declared an array of 1000 items.

The problem is that if i scroll up and down the listview, everytime i see in the xamarin profile that the memory usage increase and seems that CachingStrategy="RecycleElement" not work properly (tested on real android device).

After scroll some times, the program crash with out of memory.

What's the problem? How can i resolve it?

答:
Not sure how you are setting the ItemSource of the list view, or what it is. It would be useful to also show some of the code-behind file for this.

As a blind guess there can be performance issues with the recycling if your source is not indexable. The recommendation from Xamarin is to use an IList for the itemsource, using something like an IEnumerable will cause performance issues for a large array because it essentially has to keep looping through the data to find the right item for display.

Body:
In Xamarin Forms i have the following listview:

<ListView x:Name="StudentView"  RowHeight="55"  SeparatorVisibility="None" CachingStrategy="RecycleElement">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="55"></RowDefinition>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                    </Grid.ColumnDefinitions>

                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="0" Aspect="AspectFill"></Image>
                    <Image Source="{Binding Image}" Grid.Row="0" Grid.Column="1" Aspect="AspectFill"></Image>
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

In the code behind i have declared an array of 1000 items.

The problem is that if i scroll up and down the listview, everytime i see in the xamarin profile that the memory usage increase and seems that CachingStrategy="RecycleElement" not work properly (tested on real android device).

After scroll some times, the program crash with out of memory.

What's the problem? How can i resolve it?


问:
Oracle - Extract multiple substrings from a string
I need to extract all e-mail accounts mentioned on a single string, so far I've tried with SUBSTR and INSTR, but with no success, here an example:

The string looks like this:

```<code>()
string = "User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};

select SUBSTR(string ,INSTR(string ,'<',-1,2)) EMAIL
from dual;
</code>```

What I need is something like this:

```<code>user_1@domain.com;user_2@domain.com;user_3@domain.com;user_4@domain.com;
</code>```

Body:
I need to extract all e-mail accounts mentioned on a single string, so far I've tried with SUBSTR and INSTR, but with no success, here an example:

The string looks like this:

()
string = "User_1" {user_1@domain.com};"User_2" {user_2@domain.com};"User_3" {user_3@domain.com};"User_4" {user_4@domain.com};

select SUBSTR(string ,INSTR(string ,'<',-1,2)) EMAIL
from dual;

What I need is something like this:

user_1@domain.com;user_2@domain.com;user_3@domain.com;user_4@domain.com;

Body:
From this site I found this nasty bit of regex:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

But, it seems to work!  I cannot break down what it's doing for you though :P

Here's an example on regexr

EDIT:  That is giving errors in Oracle, so I've written up a new one:

([a-zA-Z0-9.\-_])+\@[a-zA-Z]+\.[a-zA-Z.]+

Here's an example of the new one in regexr


问:
What's the purpose of @ in this c# code?
I have seen a sample C# code that looked like this:

```<code>private static string GetCommandLine(Process process)
{
    string cmd = "";
    using (var s = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
    {
        foreach (var @object in s.Get())
        {
            if (cmd.Length > 0) cmd += " ";
            cmd += @object["CommandLine"];
        }
    }
    return cmd;
}
</code>```

What is the purpose of the @ in the loop variable?

答: If you want to use reserved words as variable names, you prefix them with the @ sign.</p>

Body:
I have seen a sample C# code that looked like this:

private static string GetCommandLine(Process process)
{
    string cmd = "";
    using (var s = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
    {
        foreach (var @object in s.Get())
        {
            if (cmd.Length > 0) cmd += " ";
            cmd += @object["CommandLine"];
        }
    }
    return cmd;
}

What is the purpose of the @ in the loop variable?


问:
Understanding SAS output data sets
SAS has several forms it uses to create output data sets from within a procedure.  It is not always clear whether or not a particular procedure can generate a data set and, if it seems to be able to, it's not always clear how.

Off the top of my head, here are some examples of how widely the syntax can differ.

Example 1

```<code>proc sort data = sashelp.baseball out = baseball_sorted;
  by
    league
    division
  ;
run;
</code>```

Example 2

```<code>proc means noprint data = baseball_sorted;
  by
    league
    division
  ;
  var nHits;
  output
    out = baseball_avg_hits (drop = _TYPE_ _FREQ_)
    mean = mean_hits
  ;
run;
</code>```

Example 3

```<code>ods exclude all;
ods output
  statistics  = baseball_statistics
  equality    = baseball_ftest
;
proc ttest data = baseball_sorted;
  class league;
  var nHits;
run;
ods exclude none;
</code>```

Example 4

The PROC ANOVA OUTSTAT= option.

It seems almost as if SAS has implemented each of these willy-nilly.  Is the SAS syntax dictating how to create a data set directed by some consistent approach I am not seeing or is it truly capricious and arbitrary?

答:
The way I see it there are four main ways to specify the output data sets.

In the PROC statement you may be able to specify some type of output statements or options, such as OUT= OUTEST=.

In the main statement of the procedure, ie MODEL/TABLE can have options that allow for output. ie PROC FREQ has an OUT= on the TABLE statement.

An explicit OUTPUT statement within a procedure. These are typically from older procedures. ie PROC MEANS

ODS tables which are relatively newer method, more frequently used these days since the format aligns with what you'd expect to see.

Yes, there are multiple places to check, but fortunately the SAS documentation for procedures is relatively clear with the options and how to use/specify the outputs.

If I've missed anything that seems different post in the comments and I can update this.

PS. Although SAS is definitely bad, trying to navigate different packages/modules in Python to export an XLSX file isn't straight forward either. Some packages support some options others don't. I've given up on asking why these days and just accept it as peculiarities of the different languages at this point.

Title: Understanding SAS output data sets

Body:
SAS has several forms it uses to create output data sets from within a procedure.  It is not always clear whether or not a particular procedure can generate a data set and, if it seems to be able to, it's not always clear how.

Off the top of my head, here are some examples of how widely the syntax can differ.

Example 1

proc sort data = sashelp.baseball out = baseball_sorted;
  by
    league
    division
  ;
run;

Example 2

proc means noprint data = baseball_sorted;
  by
    league
    division
  ;
  var nHits;
  output
    out = baseball_avg_hits (drop = _TYPE_ _FREQ_)
    mean = mean_hits
  ;
run;

Example 3

ods exclude all;
ods output
  statistics  = baseball_statistics
  equality    = baseball_ftest
;
proc ttest data = baseball_sorted;
  class league;
  var nHits;
run;
ods exclude none;

Example 4

The PROC ANOVA OUTSTAT= option.

It seems almost as if SAS has implemented each of these willy-nilly.  Is the SAS syntax dictating how to create a data set directed by some consistent approach I am not seeing or is it truly capricious and arbitrary?


问:
Tranpose the table rows to column
I have a table which looks like this:

```<code>id  response_id     name        value
6   13          gender         female
5   13          workingArea    Sch
3   12          workingArea    IT
4   12          gender         male
</code>```

and I wish to convert into something like this:

```<code>response_id          workingArea   gender
12                IT           male
13                Sch          female
</code>```

May I know how to do this?

答:
Assuming your first table is SOURCETABLE and your second table is TARGETTABLE</p>

```<code>INSERT INTO TARGETTABLE(response_id, workingArea, gender)
SELECT a.response_id response_id,
       a.value workingArea,
       b.value gender
  FROM SOURCETABLE a, SOURCETABLE b
 WHERE a.response_id = b.response_id
   AND a.name <> b.name
   AND a.name = 'workingArea'
   AND b.name = 'gender'
</code>```

Title: Tranpose the table rows to column

Body:
I have a table which looks like this:

id  response_id     name        value
6   13          gender         female
5   13          workingArea    Sch
3   12          workingArea    IT
4   12          gender         male

and I wish to convert into something like this:

response_id          workingArea   gender
12                IT           male
13                Sch          female

May I know how to do this?

Body:
Assuming your first table is SOURCETABLE and your second table is TARGETTABLE

INSERT INTO TARGETTABLE(response_id, workingArea, gender)
SELECT a.response_id response_id,
       a.value workingArea,
       b.value gender
  FROM SOURCETABLE a, SOURCETABLE b
 WHERE a.response_id = b.response_id
   AND a.name <> b.name
   AND a.name = 'workingArea'
   AND b.name = 'gender'


问:
Angular2 Controlling Focus And Select programmatically
I need to set the focus of a specific input field after the component initialization, and I'd like to have the inside text fully selected.
Looking on the internet for some hint, I ended up writing a speficic directive, this way:

```<code>@Directive({
selector: '[focusControl]'})
export class FocusDirective {
@Input('focusControl') focusEvent: EventEmitter<boolean>;

constructor( @Inject(ElementRef) private element: ElementRef, private renderer: Renderer) {
}

ngOnInit() {
    this.focusEvent.subscribe(event => {
        this.renderer.invokeElementMethod(this.element.nativeElement, 'focus', []);
        if (this.element.nativeElement.tagName == "INPUT") {
            this.renderer.invokeElementMethod(this.element.nativeElement, 'select', []);
        }
    });
}}
</code>```

In the template, obviously I set the directive on the element:

```<code> <input type="text" class="form-control" tabindex="1" [focusControl]="userIdFocus" maxlength="32">
</code>```

Then, after the component's views are initialized, in the AfterViewInit callback, I try to set focus and select:

```<code>ngAfterViewInit() {
    this.userIdFocus.emit(true);
}
</code>```

The problem is the field gets the focus, but the text is NOT selected. If I try to set the focus behind a click on a button, then the whole thing works corretcly.

I could I fix that?

答:
Are you using Chrome? As found in: https://stackoverflow.com/a/19498477

In Chrome the selection via .select() doesn't stick - adding a slight timeout resolves this issue.

Based on your code, something like this should work:

```<code>setTimeout(() => {
  this.renderer.invokeElementMethod(this.element.nativeElement, 'select', []);
}, 0);
</code>```

Seems that slight delay in execution allows the browser to detect the focus, allowing select() to then be called.

Hope that helps! Just encountered the problem myself.

Body:
I need to set the focus of a specific input field after the component initialization, and I'd like to have the inside text fully selected.
Looking on the internet for some hint, I ended up writing a speficic directive, this way:

@Directive({
selector: '[focusControl]'})
export class FocusDirective {
@Input('focusControl') focusEvent: EventEmitter<boolean>;

constructor( @Inject(ElementRef) private element: ElementRef, private renderer: Renderer) {
}

ngOnInit() {
    this.focusEvent.subscribe(event => {
        this.renderer.invokeElementMethod(this.element.nativeElement, 'focus', []);
        if (this.element.nativeElement.tagName == "INPUT") {
            this.renderer.invokeElementMethod(this.element.nativeElement, 'select', []);
        }
    });
}}

In the template, obviously I set the directive on the element:

 <input type="text" class="form-control" tabindex="1" [focusControl]="userIdFocus" maxlength="32">

Then, after the component's views are initialized, in the AfterViewInit callback, I try to set focus and select:

ngAfterViewInit() {
    this.userIdFocus.emit(true);
}

The problem is the field gets the focus, but the text is NOT selected. If I try to set the focus behind a click on a button, then the whole thing works corretcly.

I could I fix that?

Body:
Are you using Chrome? As found in: https://stackoverflow.com/a/19498477

In Chrome the selection via .select() doesn't stick - adding a slight timeout resolves this issue.

Based on your code, something like this should work:

setTimeout(() => {
  this.renderer.invokeElementMethod(this.element.nativeElement, 'select', []);
}, 0);

Seems that slight delay in execution allows the browser to detect the focus, allowing select() to then be called.

Hope that helps! Just encountered the problem myself.


问:
how to set callback URL using HybridAuth social login
I using extensions HybridAuth version 2.8.2 for function login social.
How to set callback URL redirect to another page not homepage after login success.
Thank you so much.</p>

答: You can set the login redirect URi in the Hybridauth settings under Other Settings.</p>


问:
Faster way of polygon intersection with shapely
I have a large number of polygons (~100000) and try to find a smart way of calculating their intersecting area with a regular grid cells.

Currently, I am creating the polygons and the grid cells using shapely (based on their corner coordinates). Then, using a simple for-loop I go through each polygon and compare it to nearby grid cells.

Just a small example to illustrate the polygons/grid cells.

```<code>from shapely.geometry import box, Polygon
# Example polygon
xy = [[130.21001, 27.200001], [129.52, 27.34], [129.45, 27.1], [130.13, 26.950001]]
polygon_shape = Polygon(xy)
# Example grid cell
gridcell_shape = box(129.5, -27.0, 129.75, 27.25)
# The intersection
polygon_shape.intersection(gridcell_shape).area
</code>```

(BTW: the grid cells have the dimensions 0.25x0.25 and the polygons 1x1 at max)

Actually this is quite fast for an individual polygon/grid cell combo with around 0.003 seconds. However, running this code on a huge amount of polygons (each one could intersect dozens of grid cells) takes around 15+ minutes (up to 30+ min depending on the number of intersecting grid cells)  on my machine which is not acceptable. Unfortunately, I have no idea how it is possible to write a code for polygon intersection to get the area of overlap. Do you have any tips? Is there an alternative to shapely?

答:
Since 2013/2014 Shapely has
STRtree. I have used it and it seems to work well.

Here is a snippet from the docstring:

STRtree is an R-tree that is created using the Sort-Tile-Recursive
algorithm. STRtree takes a sequence of geometry objects as initialization
parameter. After initialization the query method can be used to make a
spatial query over those objects.

```<code>>>> from shapely.geometry import Polygon
>>> from shapely.strtree import STRtree
>>> polys = [Polygon(((0, 0), (1, 0), (1, 1))), Polygon(((0, 1), (0, 0), (1, 0))), Polygon(((100, 100), (101, 100), (101, 101)))]
>>> s = STRtree(polys)
>>> query_geom = Polygon([(-1, -1), (2, 0), (2, 2), (-1, 2)])
>>> result = s.query(query_geom)
>>> polys[0] in result
True
</code>```

Body:
I have a large number of polygons (~100000) and try to find a smart way of calculating their intersecting area with a regular grid cells.

Currently, I am creating the polygons and the grid cells using shapely (based on their corner coordinates). Then, using a simple for-loop I go through each polygon and compare it to nearby grid cells.

Just a small example to illustrate the polygons/grid cells.

from shapely.geometry import box, Polygon
# Example polygon
xy = [[130.21001, 27.200001], [129.52, 27.34], [129.45, 27.1], [130.13, 26.950001]]
polygon_shape = Polygon(xy)
# Example grid cell
gridcell_shape = box(129.5, -27.0, 129.75, 27.25)
# The intersection
polygon_shape.intersection(gridcell_shape).area

(BTW: the grid cells have the dimensions 0.25x0.25 and the polygons 1x1 at max)

Actually this is quite fast for an individual polygon/grid cell combo with around 0.003 seconds. However, running this code on a huge amount of polygons (each one could intersect dozens of grid cells) takes around 15+ minutes (up to 30+ min depending on the number of intersecting grid cells)  on my machine which is not acceptable. Unfortunately, I have no idea how it is possible to write a code for polygon intersection to get the area of overlap. Do you have any tips? Is there an alternative to shapely?

Body:
Since 2013/2014 Shapely has
STRtree. I have used it and it seems to work well.

Here is a snippet from the docstring:

STRtree is an R-tree that is created using the Sort-Tile-Recursive
algorithm. STRtree takes a sequence of geometry objects as initialization
parameter. After initialization the query method can be used to make a
spatial query over those objects.

>>> from shapely.geometry import Polygon
>>> from shapely.strtree import STRtree
>>> polys = [Polygon(((0, 0), (1, 0), (1, 1))), Polygon(((0, 1), (0, 0), (1, 0))), Polygon(((100, 100), (101, 100), (101, 101)))]
>>> s = STRtree(polys)
>>> query_geom = Polygon([(-1, -1), (2, 0), (2, 2), (-1, 2)])
>>> result = s.query(query_geom)
>>> polys[0] in result
True

ContentLicense: CC BY-SA 4.0


问:
Reduce space between ticks in horizontal bar-chart chartJS
I am using the horizontal bar chart from chartjs. Right now my Chart seems to be very big, and the space between the ticks on the xAxis is very high. ( I attached picture of that), can anyone tell me how to reduce this space and scale the chart in total better?

My css properties:

```<code>#myChart {
  width: 90% !important;
  height: 100% !important;
  padding-left: 0;
  padding-right: 0;
  margin-left: auto;
  margin-right: auto;
  display: block;
  padding-bottom: 5%;
}
</code>```

My chart options:

```<code>modelChart = new Chart(ctx, {
      type: 'horizontalBar',
      data: data,
      options: {
        scales: {
          yAxes: [{
            ticks: {
              suggestedMin: 0,
              fontSize: 18
            }
          }],
          xAxes: [{
            ticks: {
              autoSkip: false,
              fontSize: 18,
              beginAtZero: true
            }
          }]
        },
        legend: {
          display: false
        },
        tooltips: {
          footerFontSize: 22,
          bodyFontSize: 22,
          titleFontSize: 18
        },
        hover: {
          animationDuration: 0
        }
      }
    });
</code>```

答: Try using chartArea: {width: '30%'}. Adjust percentage as per requirement. It will compress the width of the chart. Just a thought !!!! I used in horizontal bar graphs to adjust my graph size. </p>

Body:
I am using the horizontal bar chart from chartjs. Right now my Chart seems to be very big, and the space between the ticks on the xAxis is very high. ( I attached picture of that), can anyone tell me how to reduce this space and scale the chart in total better?

My css properties:

#myChart {
  width: 90% !important;
  height: 100% !important;
  padding-left: 0;
  padding-right: 0;
  margin-left: auto;
  margin-right: auto;
  display: block;
  padding-bottom: 5%;
}

My chart options:

modelChart = new Chart(ctx, {
      type: 'horizontalBar',
      data: data,
      options: {
        scales: {
          yAxes: [{
            ticks: {
              suggestedMin: 0,
              fontSize: 18
            }
          }],
          xAxes: [{
            ticks: {
              autoSkip: false,
              fontSize: 18,
              beginAtZero: true
            }
          }]
        },
        legend: {
          display: false
        },
        tooltips: {
          footerFontSize: 22,
          bodyFontSize: 22,
          titleFontSize: 18
        },
        hover: {
          animationDuration: 0
        }
      }
    });


问:
Multiple instances of QWebView (qt jambi)
Good day,
How I can use QWebView with method load() in threads?
I have create QWebView in main(!) thread, but I can't use load() with QWebView (used signals/slots from other threads to do it):

QWebView wv = new QWebView(); //ok
QUrl url = new QUrl("http://somesite.com/"); //ok
wv.load(url); //ERROR: QObject: Cannot create children for a parent that is in a different thread.

In c++ it work. Please, help me!

p.s. sorry for my English

答:
I know this is an old question but for anyone else interested, the problem is creating children on a different thread. To marshal back to the owning thread, do something like the following:</p>

```<code>public void loadURL(String url) {
    QApplication.invokeLater(new LoadURL(url));
}

private class LoadURL implements Runnable {
    private String url;
    public LoadURL(String url) {
        this.url = url;
    }
    public void run() {
        QNetworkRequest nreq = new QNetworkRequest(new QUrl(this.url));
        load(nreq);
    }
}
</code>```

Body:
I know this is an old question but for anyone else interested, the problem is creating children on a different thread. To marshal back to the owning thread, do something like the following:

public void loadURL(String url) {
    QApplication.invokeLater(new LoadURL(url));
}

private class LoadURL implements Runnable {
    private String url;
    public LoadURL(String url) {
        this.url = url;
    }
    public void run() {
        QNetworkRequest nreq = new QNetworkRequest(new QUrl(this.url));
        load(nreq);
    }
}


问:
get proportion of each group's value counts after group_by dplyr R
In python pandas I was able to simply do df.groupby(x,y).value_counts(normalize=True) to get the proportion of each value in a group. However I've been unable to find a way to do this in R.

I've grouped my df by x and y and have summarized to calculate the frequency,
as such df %>% group_by(x,y) %>% summarize(count=n()) but I'd like to instead see the proportion of each y for each x.

```<code>x   y  count
1   A   22
1   B   65
1   C   94
1   D   40
2   D   34
2   E   1
2   F   6
3   E   4
3   F   13
</code>```

for example, the new column of proportions should have

```<code>x   y   proportion
1   A   0.0995475
1   B   0.2941176
1   C   0.4253393
1   D   0.1809955
2   D   0.8292683
2   E   0.024390
2   F   0.1463415
3   E   0.2352941
3   F   0.7647059
</code>```

答:
I think you need to group by x to get the results in your example. Assuming the data frame is named df1:

```<code>library(dplyr)
  df1 %>%
  group_by(x) %>%
  mutate(proportion = count/sum(count))
</code>```

Body:
In python pandas I was able to simply do df.groupby(x,y).value_counts(normalize=True) to get the proportion of each value in a group. However I've been unable to find a way to do this in R.

I've grouped my df by x and y and have summarized to calculate the frequency,
as such df %>% group_by(x,y) %>% summarize(count=n()) but I'd like to instead see the proportion of each y for each x.

x   y  count
1   A   22
1   B   65
1   C   94
1   D   40
2   D   34
2   E   1
2   F   6
3   E   4
3   F   13

for example, the new column of proportions should have

x   y   proportion
1   A   0.0995475
1   B   0.2941176
1   C   0.4253393
1   D   0.1809955
2   D   0.8292683
2   E   0.024390
2   F   0.1463415
3   E   0.2352941
3   F   0.7647059

Body:
I think you need to group by x to get the results in your example. Assuming the data frame is named df1:

library(dplyr)
  df1 %>%
  group_by(x) %>%
  mutate(proportion = count/sum(count))


问:
VSCode PowerShell 0.11.0 Debug Console is no longer used - How do I "correctly" use VSCode now?
I am still a relatively new PowerShell coder, and I have been successfully using the PowerShell extension v0.8.0 for Visual Studio Code.  I could write a script, press F5, and happily see my output.

Today I noticed there was an upgrade to v0.11.0, so I clicked the install believing that newer = better.

Unfortunately, now whenever I press F5 to execute my script, I get this error:

"The Debug Console is no longer used for PowerShell debugging.  Please
  use the 'PowerShell Integrated Console' to execute commands in the
  debugger.  Run the 'PowerShell: Show Integrated Console' command to
  open it."

I can't say I've been smart enough to learn more than basics, and never really knew how to use the debugger, but I was getting by.  With this error, however, does this mean that every time I want to execute my script, I have to press CTRL+` and then type out things like I was at a console window?  For now, I've found a workaround by clicking in the editor window and pressing CTRL+a, F8.  I was hoping to start reading an article on debugging, but it seems like the extension update has rendered the material obsolete.

This seems like a huge step back in terms of usability, but I'm not sure if it's really a bug for the extension developer, or I'm just not skillfull enough to use the extension?

答:
All that happens now is the output is to the powershell integrated terminal. So make sure that the Terminal tab is active. Then hitting F5 works as normal (before).

My launch.json looks like:

```<code>{
    "type": "PowerShell",
    "request": "launch",
    "name": "PowerShell Launch (current file)",
    "script": "${file}",
    "args": [],
    "cwd": "${file}"
}
</code>```

Body:
All that happens now is the output is to the powershell integrated terminal. So make sure that the Terminal tab is active. Then hitting F5 works as normal (before).

My launch.json looks like:

{
    "type": "PowerShell",
    "request": "launch",
    "name": "PowerShell Launch (current file)",
    "script": "${file}",
    "args": [],
    "cwd": "${file}"
}


问:
Cannot write to a Microsoft Access file using SQL (OLEDB) C#
I understand that this may be considered a duplicate question, but I am at an impasse and i do not know what it is I am doing wrong, I need help. The duplicate question said to use OLEDB in order to write to the Microsoft Access file, where as before I was using the SQL connection to accomplish my task. As far as i can tell there are no syntax, logic, or runtime errors and Visual Studios doesnt have an issue either.

When i run the code and go to add a new entry to the Microsoft Access Database Table, it says it worked, but when I go and look at the file there is NOTHING there. Someone please help me, I have goe through all the links, all the web pages, all the search engines, and I dont know what is wrong. I would love to learn what is wrong and how to fix it so I wont ever have to ask for help again.

Currently I am a college student and I am working on a team assignment. Our task, is to create a window that will take input from a user and then add it as a entry into an Microsoft Access File as if it were a SQL database.

The issue we are having is that we are trying to add the new entry to a local Microsoft Access file under the table named Artist. I have connected to an actual SQL server before and no one else in my group has, even worse no one has done this with using a Microsoft Access file on our PC either.

I have added the Database (Microsoft Access File) in Visual Studios using the Database Configuration Wizard. At first I was using straight SQL do to this and then i was told i need to use OLEDB in order to do this. SO I have implemented in the code and for some reason I still cannot get it to work. If anyone can give me a hand and tell me what it is I am doing wrong, I would greatly appreciate it.

Details that I believe are important for anyone to help me:

The name of the table I am attempting to write a new entry to: Artist

Name of the Microsoft Access File: Kays.accdb

Location of the Microsoft Access file: C:\KayDB\Kays.accdb (local machine)

Once again I would greatly appreciate any help that anyone can give me. I really am curious as to why the code is not working, please help me understand.

My code is as follows:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace Kay
{
public partial class Kay_Green : Form
{

    string Username,Fname, Mname, Lname, streetaddress, city, phonenumber, emailaddress, zipcode, taxIDnummber, state;

    string[,] SQLTable = new string[0, 10];

    public Kay_Green()
    {
        InitializeComponent();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {//Save Button

        /*Upon clicking the save button, gather all info and save it into an temp array.
          Then send it to the SQL database.*/

        /*The order of the data in the array will be the same order in the SQL table.*/

        Fname = tbFirstName.Text;
        Mname = tbMiddleInitial.Text;
        Lname = tbLastName.Text;
        streetaddress = tbStreet.Text;
        city = tbCity.Text;
        state = cbState.Text;
        phonenumber = tbPhoneNumber.Text;
        emailaddress = tbEmailAddress.Text;
        zipcode = tbZipCode.Text;
        taxIDnummber = tbTaxID.Text;
        Username = tbUserName.Text;

        /*SQLTable[0,0] = taxIDnummber;
        SQLTable[0,1] = Fname;
        SQLTable[0,2] = Mname;
        SQLTable[0,3] = Lname;
        SQLTable[0,4] = streetaddress;
        SQLTable[0,5] = city;
        SQLTable[0,6] = state;
        SQLTable[0,7] = zipcode;
        SQLTable[0,8] = phonenumber;
        SQLTable[0,9] = emailaddress;*/

        /*Below is the details for the SQL connection*/

        string connectstring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\KayDB\\Kays.accdb";
        OleDbConnection connection=new OleDbConnection(connectstring);
        OleDbCommand command;
        OleDbDataAdapter adapter;
        DataTable dt = new DataTable();

        string sql ="Insert into ARTIST values ('" + taxIDnummber + "','"
            + emailaddress + "','" + Fname + "','" + Mname + "','"
            + Lname + "','" + phonenumber+"','"+ Username + "','"
            + streetaddress + "','" + city + "','" +state+ "','"
            + zipcode + "')";

        try
        {

            connection.Open();

            command = new OleDbCommand(sql, connection);

            MessageBox.Show("Connection Open And data added to table! ");

            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Can not open connection ! " + ex.StackTrace.ToString());

        }
        /*Above is the details for the SQL connection*/

    }

    private void btnCancel_Click(object sender, EventArgs e)
    {//Cancel Button
        tbCity.Clear();
        tbEmailAddress.Clear();
        tbFirstName.Clear();
        tbLastName.Clear();
        tbMiddleInitial.Clear();
        tbPhoneNumber.Clear();
        tbStreet.Clear();
        tbTaxID.Clear();
        tbZipCode.Clear();
        tbUserName.Clear();

        Close();//Go back to switchboard from here

    }

    private void btnClear_Click(object sender, EventArgs e)
    {//Clear button

        tbCity.Clear();
        tbEmailAddress.Clear();
        tbFirstName.Clear();
        tbLastName.Clear();
        tbMiddleInitial.Clear();
        tbPhoneNumber.Clear();
        tbStreet.Clear();
        tbTaxID.Clear();
        tbZipCode.Clear();
        tbUserName.Clear();
    }

}
</code>```

}

答:
This code

```<code>command = new OleDbCommand(sql, connection);
</code>```

sets up a command but does not run it

you need to run this afterwards:

```<code>command.ExecuteNonQuery();
</code>```

This has nothing to do with connection strings

Body:
I understand that this may be considered a duplicate question, but I am at an impasse and i do not know what it is I am doing wrong, I need help. The duplicate question said to use OLEDB in order to write to the Microsoft Access file, where as before I was using the SQL connection to accomplish my task. As far as i can tell there are no syntax, logic, or runtime errors and Visual Studios doesnt have an issue either.

When i run the code and go to add a new entry to the Microsoft Access Database Table, it says it worked, but when I go and look at the file there is NOTHING there. Someone please help me, I have goe through all the links, all the web pages, all the search engines, and I dont know what is wrong. I would love to learn what is wrong and how to fix it so I wont ever have to ask for help again.

Currently I am a college student and I am working on a team assignment. Our task, is to create a window that will take input from a user and then add it as a entry into an Microsoft Access File as if it were a SQL database.

The issue we are having is that we are trying to add the new entry to a local Microsoft Access file under the table named Artist. I have connected to an actual SQL server before and no one else in my group has, even worse no one has done this with using a Microsoft Access file on our PC either.

I have added the Database (Microsoft Access File) in Visual Studios using the Database Configuration Wizard. At first I was using straight SQL do to this and then i was told i need to use OLEDB in order to do this. SO I have implemented in the code and for some reason I still cannot get it to work. If anyone can give me a hand and tell me what it is I am doing wrong, I would greatly appreciate it.

Details that I believe are important for anyone to help me:

The name of the table I am attempting to write a new entry to: Artist

Name of the Microsoft Access File: Kays.accdb

Location of the Microsoft Access file: C:\KayDB\Kays.accdb (local machine)

Once again I would greatly appreciate any help that anyone can give me. I really am curious as to why the code is not working, please help me understand.

My code is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace Kay
{
public partial class Kay_Green : Form
{

    string Username,Fname, Mname, Lname, streetaddress, city, phonenumber, emailaddress, zipcode, taxIDnummber, state;

    string[,] SQLTable = new string[0, 10];

    public Kay_Green()
    {
        InitializeComponent();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {//Save Button

        /*Upon clicking the save button, gather all info and save it into an temp array.
          Then send it to the SQL database.*/

        /*The order of the data in the array will be the same order in the SQL table.*/

        Fname = tbFirstName.Text;
        Mname = tbMiddleInitial.Text;
        Lname = tbLastName.Text;
        streetaddress = tbStreet.Text;
        city = tbCity.Text;
        state = cbState.Text;
        phonenumber = tbPhoneNumber.Text;
        emailaddress = tbEmailAddress.Text;
        zipcode = tbZipCode.Text;
        taxIDnummber = tbTaxID.Text;
        Username = tbUserName.Text;

        /*SQLTable[0,0] = taxIDnummber;
        SQLTable[0,1] = Fname;
        SQLTable[0,2] = Mname;
        SQLTable[0,3] = Lname;
        SQLTable[0,4] = streetaddress;
        SQLTable[0,5] = city;
        SQLTable[0,6] = state;
        SQLTable[0,7] = zipcode;
        SQLTable[0,8] = phonenumber;
        SQLTable[0,9] = emailaddress;*/

        /*Below is the details for the SQL connection*/

        string connectstring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\KayDB\\Kays.accdb";
        OleDbConnection connection=new OleDbConnection(connectstring);
        OleDbCommand command;
        OleDbDataAdapter adapter;
        DataTable dt = new DataTable();

        string sql ="Insert into ARTIST values ('" + taxIDnummber + "','"
            + emailaddress + "','" + Fname + "','" + Mname + "','"
            + Lname + "','" + phonenumber+"','"+ Username + "','"
            + streetaddress + "','" + city + "','" +state+ "','"
            + zipcode + "')";

        try
        {

            connection.Open();

            command = new OleDbCommand(sql, connection);

            MessageBox.Show("Connection Open And data added to table! ");

            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Can not open connection ! " + ex.StackTrace.ToString());

        }
        /*Above is the details for the SQL connection*/

    }

    private void btnCancel_Click(object sender, EventArgs e)
    {//Cancel Button
        tbCity.Clear();
        tbEmailAddress.Clear();
        tbFirstName.Clear();
        tbLastName.Clear();
        tbMiddleInitial.Clear();
        tbPhoneNumber.Clear();
        tbStreet.Clear();
        tbTaxID.Clear();
        tbZipCode.Clear();
        tbUserName.Clear();

        Close();//Go back to switchboard from here

    }

    private void btnClear_Click(object sender, EventArgs e)
    {//Clear button

        tbCity.Clear();
        tbEmailAddress.Clear();
        tbFirstName.Clear();
        tbLastName.Clear();
        tbMiddleInitial.Clear();
        tbPhoneNumber.Clear();
        tbStreet.Clear();
        tbTaxID.Clear();
        tbZipCode.Clear();
        tbUserName.Clear();
    }

}

}

Body:
This code

command = new OleDbCommand(sql, connection);

sets up a command but does not run it

you need to run this afterwards:

command.ExecuteNonQuery();

This has nothing to do with connection strings


问:
Haml "Illegal Nesting" problem; how to place multiple code elements in the same tag?
```<code>- @subjects.each do |s|
  %tr
  %td= s.position
  %td= s.name
  %td= s.visible ? "Yes" : "No"
  %td= s.pages.size
  %td= link_to("Show", {:action => "show", :id => s.id}, :class => "action show")
    = link_to("Edit", {:action => "edit", :id => s.id}, :class => "action edit")
    = link_to("Delete", {:action => "delete", :id => s.id}, :class => "action delete")
</code>```

error_msg:

Illegal nesting: content can't be both given on the same line as %td and nested within it.

I want those three links--show, edit, and delete--in the same td; how can I do it?

答: FYI - I ran into this issue too but the culprit was a trailing space after my , which is content for HAML.

Body:
- @subjects.each do |s|
  %tr
  %td= s.position
  %td= s.name
  %td= s.visible ? "Yes" : "No"
  %td= s.pages.size
  %td= link_to("Show", {:action => "show", :id => s.id}, :class => "action show")
    = link_to("Edit", {:action => "edit", :id => s.id}, :class => "action edit")
    = link_to("Delete", {:action => "delete", :id => s.id}, :class => "action delete")

error_msg:

Illegal nesting: content can't be both given on the same line as %td and nested within it.

I want those three links--show, edit, and delete--in the same td; how can I do it?

Body: FYI - I ran into this issue too but the culprit was a trailing space after my <td>, which is content for HAML.


问:
How do you use gettext when you have link into the translated text?
I use gettext to translate my web site.

It would be nice to have link in text translated but I don't want to write html tags in gettext files because these translations may be used elsewhere.

I could create text for web site only (with links) and text for all purpose.

I'll have to maintain 2 versions. :-(

I could also write a custom parser to insert links in text but it seems overkill and I'm affraid of The Danger of Naïveté

For those who had the same problem, how did you handle that ?

答:
Another solution here: https://zargony.com/2008/01/24/links-in-gettext-translated-strings.

It suggests using {curly brackets} for links. As for example:

```<code>_("Please click {here} or {here}")
</code>```

And then write your own function linkify that replaces things in curly brackets with the parameters given.

```<code>linkify(
    _("Please click {here} or {here}"),
    "</a>",
    "<a href='www.example1.com'>",
    "<a href='www.example2.com'>"
)
</code>```

Definition in PHP:

```<code>function linkify($string, $closingTag) {
    $arguments = func_get_args();
    return preg_replace_callback(
        '/{(.*?)}/', // Ungreedy (*?)
        function($matches) use ($arguments, $closingTag) {
            static $i = 1;
            $i++;
            return $arguments[$i] . $matches[1] . $closingTag;
        },
        $string
    );
}
</code>```

PS: You can also easily substitute the {} for [], as I've noticed that in POEdit these curly brackets give warnings to the translators and recommend them not to be translated.

Body:
Another solution here: https://zargony.com/2008/01/24/links-in-gettext-translated-strings.

It suggests using {curly brackets} for links. As for example:

_("Please click {here} or {here}")

And then write your own function linkify that replaces things in curly brackets with the parameters given.

linkify(
    _("Please click {here} or {here}"),
    "</a>",
    "<a href='www.example1.com'>",
    "<a href='www.example2.com'>"
)

Definition in PHP:

function linkify($string, $closingTag) {
    $arguments = func_get_args();
    return preg_replace_callback(
        '/{(.*?)}/', // Ungreedy (*?)
        function($matches) use ($arguments, $closingTag) {
            static $i = 1;
            $i++;
            return $arguments[$i] . $matches[1] . $closingTag;
        },
        $string
    );
}

PS: You can also easily substitute the {} for [], as I've noticed that in POEdit these curly brackets give warnings to the translators and recommend them not to be translated.


问:
Troubleshooting failed packer build
I am just getting started with Packer, and have had several instances where my build is failing and I'd LOVE to log in to the box to investigate the cause.  However, there doesn't seem to be a packer login or similar command to give me a shell.  Instead, the run just terminates and tears down the box before I have a chance to investigate.

I know I can use the --debug flag to pause execution at each stage, but I'm curios if there is a way to just pause after a failed run (and prior to cleanup) and then runt he cleanup after my debugging is complete.

Thanks.

答:
This was my top annoyance with packer. Thankfully, packer build now has an option -on-error that gives you options.

packer build -on-error=ask ... to the rescue.

From the packer build docs:

-on-error=cleanup (default), -on-error=abort, -on-error=ask - Selects what to do when the build fails. cleanup cleans up after the previous steps, deleting temporary files and virtual machines. abort exits without any cleanup, which might require the next build to use -force. ask presents a prompt and waits for you to decide to clean up, abort, or retry the failed step.

Title: Troubleshooting failed packer build


问:
What is the difference between $state.go(app.location) and $location.path("app/location")?
I have recently started using ionic framework, it has angular js in it. To navigate between screens, I was using $location.path and it's working great. However, in an example I've downloaded, I saw $state.go being used to redirect to some page. I would like to know the difference between the two. </p>

答: I use ionic and one of the differences that I have observed but not yet figured out why is that $location.path is much slower than $state.go


问:
Conditional matching of a string at the end of the line using regex
I need to create a Regex pattern in C# where it is able to take in a string, capture 3 groups, where the final group only captures if the string ends with 'NoClause'. I've provided below a sample input and what I'd like the 3 capture groups to contain.

Sample Input:

Header:Select * From TableName WHERE ColumnName = '53 : ABC' ORDER BY NoClause : NoClause

Desired Output:

```<code>Group1: 'Header'
Group2: 'Select * From TableName WHERE ColumnName = '53 : ABC''
Group3: 'NoClause'
</code>```

The pattern I have so far is:

(\w+):{1}(.+)\s*:\s*(NoClause)

Now for when the string is formatted as the sample input, this does work but the issue I have is when the input string doesn't contain ': NoClause', in these scenarios that capture group should contain nothing. I've provided examples below of when this doesn't work but needs to.

```<code>Header:select * from TableName where ColumnName = '1 ABC'
Header:select * from TableName where ColumnName = '1: ABC'
Header:select * from TableName where ColumnName = '1: ABC' OR ColumnName = '2: DFG' OR ColumnName = '3: HIJ'
</code>```

When using the above pattern, nothing captures at all. I've attempted to use the '?' as a conditional but am unable to have it match all cases.

I've been fiddling with this all at https://regex101.com/r/wG3aM3/261.

Things to consider

When using this pattern, only one string of input will be processed
at a time, not for example, four separate inputs processed at once

I have the C# code all ready to go, just need the Regex pattern to make it
work

The input string will sometimes contain 0 or more semi-colons (:)
but it is only after the final semi-colon do I want it to capture
the 'NoClause'

This needs to support the edge case, where a ColumnName or value is 'NoClause', very unlikely but needs to support this case regardless.

For interest, the below is my C# code.

```<code>Match parameters = Regex.Match(inputString, @"(\w+):{1}(.+)\s*:\s*(NoClause)", RegexOptions.IgnoreCase);

var group1 = parameters.Groups[1].Value;
var group2 = parameters.Groups[2].Value;
bool group3 = parameters.Groups[3].Success;
</code>```

答:
Have a try with this one:

```<code>^(\w+):(.+?)(?:\s*:\s*(NoClause|NoWhereClause))?$
</code>```

You need to make the last part optional. Also you need to use lazy matching in the middle to avoid capturing the content of the last group into the middle one.

Body:
I need to create a Regex pattern in C# where it is able to take in a string, capture 3 groups, where the final group only captures if the string ends with 'NoClause'. I've provided below a sample input and what I'd like the 3 capture groups to contain.

Sample Input:

Header:Select * From TableName WHERE ColumnName = '53 : ABC' ORDER BY NoClause : NoClause

Desired Output:

Group1: 'Header'
Group2: 'Select * From TableName WHERE ColumnName = '53 : ABC''
Group3: 'NoClause'

The pattern I have so far is:

(\w+):{1}(.+)\s*:\s*(NoClause)

Now for when the string is formatted as the sample input, this does work but the issue I have is when the input string doesn't contain ': NoClause', in these scenarios that capture group should contain nothing. I've provided examples below of when this doesn't work but needs to.

Header:select * from TableName where ColumnName = '1 ABC'
Header:select * from TableName where ColumnName = '1: ABC'
Header:select * from TableName where ColumnName = '1: ABC' OR ColumnName = '2: DFG' OR ColumnName = '3: HIJ'

When using the above pattern, nothing captures at all. I've attempted to use the '?' as a conditional but am unable to have it match all cases.

I've been fiddling with this all at https://regex101.com/r/wG3aM3/261.

Things to consider

When using this pattern, only one string of input will be processed
at a time, not for example, four separate inputs processed at once

I have the C# code all ready to go, just need the Regex pattern to make it
work

The input string will sometimes contain 0 or more semi-colons (:)
but it is only after the final semi-colon do I want it to capture
the 'NoClause'

This needs to support the edge case, where a ColumnName or value is 'NoClause', very unlikely but needs to support this case regardless.

For interest, the below is my C# code.

Match parameters = Regex.Match(inputString, @"(\w+):{1}(.+)\s*:\s*(NoClause)", RegexOptions.IgnoreCase);

var group1 = parameters.Groups[1].Value;
var group2 = parameters.Groups[2].Value;
bool group3 = parameters.Groups[3].Success;

Body:
Have a try with this one:

^(\w+):(.+?)(?:\s*:\s*(NoClause|NoWhereClause))?$

You need to make the last part optional. Also you need to use lazy matching in the middle to avoid capturing the content of the last group into the middle one.


问:
How do I rewrite a 'for loop' as a 'while loop' in python?
This is the loop:

```<code>for c in "Hi there":
     print(c.upper())
</code>```

This is my attempt of rewriting as a while loop:

```<code>phrase = "Hi there"
while len.phrase > 0
    print (c.upper())
</code>```

答:
There's a couple things I see wrong here.

First off, you're forgetting to use a colon at the end of the while statement.

```<code>while len.phrase > 0:
</code>```

Second, a much more efficient way of performing this task is the following:

```<code>while 1:
</code>```

as 1 will always be true (in the case of Python) and it will perform an infinite loop like your previous attempt seems to be intending to do.

Body:
This is the loop:

for c in "Hi there":
     print(c.upper())

This is my attempt of rewriting as a while loop:

phrase = "Hi there"
while len.phrase > 0
    print (c.upper())

Body:
There's a couple things I see wrong here.

First off, you're forgetting to use a colon at the end of the while statement.

while len.phrase > 0:

Second, a much more efficient way of performing this task is the following:

while 1:

as 1 will always be true (in the case of Python) and it will perform an infinite loop like your previous attempt seems to be intending to do.


问:
Centralized handling for HTTP errors in Angular 4
I want to inform the user if an HTTP request fails, without having to write additional code for every HTTP request.

I had a working prototype for angular 2:

```<code>@Injectable()
export class MyErrorHandler extends ErrorHandler {

  constructor() {
    super(false);
  }

  handleError(error: any) {
    this.tellUser(error);
    super.handleError(error);
  }

  tellUser(error: any) {
    // dig for the root cause
    if (error.rejection) {
      error = error.rejection;
    }
    if (error instanceof ViewWrappedError) {
       error = error.originalError;
    }

    let message;
    if (error instanceof Response) {
      // TODO: localize and display nicely
      const messages = {
        0: "Could not connect to server",
      }
      message = messages[error.status] || ("The server reported a system error (HTTP " + error.status + ")");
    } else {
      message = "A system error occurred.";
    }
    console.warn(message);
  }
}
</code>```

but the ViewWrappedError has been replaced in Angular 4 by

```<code>export function viewWrappedDebugError(err: any, context: DebugContext): Error {
  if (!(err instanceof Error)) {
    // errors that are not Error instances don't have a stack,
    // so it is ok to wrap them into a new Error object...
    err = new Error(err.toString());
  }
  _addDebugContext(err, context);
  return err;
}
</code>```

Which, by virtue of invoking toString on the HttpResponse, makes it hard to query the status code ...

I'd have expected angular to provide a public, well supported API for centralized error handling. Is there really no way to centrally handle HTTP errors other than parsing error messages?

Update: I'd prefer if a component could easily override the centralized error handling.

答:
Another option is simply having a service that delegates to the Http service while adding whatever custom error handling, debugging logic, extra headers etc that you need to interact with your API.

This service then becomes your centralized point for interacting with anything Http related and as such you can centralize your error handling right there. In any project I develop, I ALWAYS create such a class because practically every single API you interact with has some common configuration that has to happen with every request (even if that configuration is as little as specifying the base url to use).

Example of such a class:

```<code>export class ApiGateway {

  baseURL = "https://myapi.com";  // or sometimes pulled from another file
  constructor(private http: Http) { }

  get(path, params) {
    showLoadingIndicator();

    let headers = this.createMySpecialHeaders();
    let options = { headers: headers } // and whatever else you need to generalize
    let fullUrl = this.baseUrl + path + '?' + this.urlEncode(params)`;
    return this.get(path, params, options)
               .do(() => hideLoadingIndicator())
               .map(res => res.json())
               .catch(err => {
                    hideLoadingIndicator();
                  // show error message or whatever the app does with API errors etc
                  // sometimes rethrow the error, depending on the use case
                })
  }
}
</code>```

To me, this is basic OOP principles - you wrap your interactions with things outside your control in an adapter class to allow you some protection against external changes and to change the API of that external thing to something you prefer, if necessary.

With such a class in place, if, for eg, you upgraded to Angular 4 and the means of receiving errors change, you only have one place to change to handle the new error technique.

Body:
I want to inform the user if an HTTP request fails, without having to write additional code for every HTTP request.

I had a working prototype for angular 2:

@Injectable()
export class MyErrorHandler extends ErrorHandler {

  constructor() {
    super(false);
  }

  handleError(error: any) {
    this.tellUser(error);
    super.handleError(error);
  }

  tellUser(error: any) {
    // dig for the root cause
    if (error.rejection) {
      error = error.rejection;
    }
    if (error instanceof ViewWrappedError) {
       error = error.originalError;
    }

    let message;
    if (error instanceof Response) {
      // TODO: localize and display nicely
      const messages = {
        0: "Could not connect to server",
      }
      message = messages[error.status] || ("The server reported a system error (HTTP " + error.status + ")");
    } else {
      message = "A system error occurred.";
    }
    console.warn(message);
  }
}

but the ViewWrappedError has been replaced in Angular 4 by

export function viewWrappedDebugError(err: any, context: DebugContext): Error {
  if (!(err instanceof Error)) {
    // errors that are not Error instances don't have a stack,
    // so it is ok to wrap them into a new Error object...
    err = new Error(err.toString());
  }
  _addDebugContext(err, context);
  return err;
}

Which, by virtue of invoking toString on the HttpResponse, makes it hard to query the status code ...

I'd have expected angular to provide a public, well supported API for centralized error handling. Is there really no way to centrally handle HTTP errors other than parsing error messages?

Update: I'd prefer if a component could easily override the centralized error handling.

Body:
Another option is simply having a service that delegates to the Http service while adding whatever custom error handling, debugging logic, extra headers etc that you need to interact with your API.

This service then becomes your centralized point for interacting with anything Http related and as such you can centralize your error handling right there. In any project I develop, I ALWAYS create such a class because practically every single API you interact with has some common configuration that has to happen with every request (even if that configuration is as little as specifying the base url to use).

Example of such a class:

export class ApiGateway {

  baseURL = "https://myapi.com";  // or sometimes pulled from another file
  constructor(private http: Http) { }

  get(path, params) {
    showLoadingIndicator();

    let headers = this.createMySpecialHeaders();
    let options = { headers: headers } // and whatever else you need to generalize
    let fullUrl = this.baseUrl + path + '?' + this.urlEncode(params)`;
    return this.get(path, params, options)
               .do(() => hideLoadingIndicator())
               .map(res => res.json())
               .catch(err => {
                    hideLoadingIndicator();
                  // show error message or whatever the app does with API errors etc
                  // sometimes rethrow the error, depending on the use case
                })
  }
}

To me, this is basic OOP principles - you wrap your interactions with things outside your control in an adapter class to allow you some protection against external changes and to change the API of that external thing to something you prefer, if necessary.

With such a class in place, if, for eg, you upgraded to Angular 4 and the means of receiving errors change, you only have one place to change to handle the new error technique.


问:
Want to update a column with a number value following specific query
So this is my first question and first day here. Thanks in advance.

I want to perform the following query -

Put the fine on books_return if the duration is violated, otherwise put zero.
The duration is in book_issue. SO I figured out that I can calculate the difference between return_date and issue_date and if it is greater than 10 then fine_amount will update to 20; otherwise will update to zero. However, I am having trouble with the query statement which is the following -

```<code>UPDATE (
    SELECT brt.fine_amount
    FROM book_return brt, book_issue bi
    WHERE brt.book_id = bi.book_id
        AND brt.return_date - bi.issue_date > bi.issue_duration
) SET fine_amount = 20;
</code>```

```<code>error - ORA-01779: cannot modify a column which maps to a non key-preserved table
</code>```

How can I pull off this query?

EDIT: book_id and borrower_id are the composite primary keys of both tables.

related tables -

答:
You can do what you want with merge.  If you use update, you can use exists:

```<code>UPDATE book_return brt
    SET fine_amount = 20
    WHERE EXISTS (SELECT 1
                  FROM book_issue bi
                  WHERE brt.book_id = bi.book_id AND
                        brt.return_date - bi.issue_date > bi.issue_duration
                 );
</code>```

Body:
So this is my first question and first day here. Thanks in advance.

I want to perform the following query -

Put the fine on books_return if the duration is violated, otherwise put zero.
The duration is in book_issue. SO I figured out that I can calculate the difference between return_date and issue_date and if it is greater than 10 then fine_amount will update to 20; otherwise will update to zero. However, I am having trouble with the query statement which is the following -

UPDATE (
    SELECT brt.fine_amount
    FROM book_return brt, book_issue bi
    WHERE brt.book_id = bi.book_id
        AND brt.return_date - bi.issue_date > bi.issue_duration
) SET fine_amount = 20;

error - ORA-01779: cannot modify a column which maps to a non key-preserved table

How can I pull off this query?

EDIT: book_id and borrower_id are the composite primary keys of both tables.

related tables -

Body:
You can do what you want with merge.  If you use update, you can use exists:

UPDATE book_return brt
    SET fine_amount = 20
    WHERE EXISTS (SELECT 1
                  FROM book_issue bi
                  WHERE brt.book_id = bi.book_id AND
                        brt.return_date - bi.issue_date > bi.issue_duration
                 );


问:
Nokogiri: apply class to element that has a certain descendant
Let's say I have this html that has various depths of descendants and a mixture of element types:

```<code><div class="foo">
    <div class="bar"></div>
</div>
<div class="foo">
    <div class="baz"></div>
</div>
<div class="foo">
    <u><span class="duh">
        <div class="bar"></div>
    </span></u>
</div>
<div class="foo">
    <div class="baz"></div>
</div>
</code>```

And I want to apply a class of bex to all the foos that contain classes of bar so it looks like:

```<code><div class="bex">
    <div class="bar"></div>
</div>
<div class="foo">
    <div class="baz"></div>
</div>
<div class="bex">
    <u><span class="duh">
        <div class="bar"></div>
    </span></u>
</div>
<div class="foo">
    <div class="baz"></div>
</div>
</code>```

How wld I do that with ruby/nokogiri? Tried all sorts of things and can't quite get it. Thanks.

Edit: closed the duh, oops.

答:
I spent a long time wondering why the second foo wasn't found.
Your data is broken, "duh isn't closed.

To select the nodes, you can use :

```<code>doc.xpath("//div[@class='foo' and .//div[@class='bar']]")
</code>```

As an example :

```<code>data = %q(<div class="foo">
    <div class="bar"></div>
</div>
<div class="foo">
    <div class="baz"></div>
</div>
<div class="foo">
    <u><span class="duh">
        <div class="bar"></div>
    </span></u>
</div>
<div class="foo">
    <div class="baz"></div>
</div>)

require 'nokogiri'

doc = Nokogiri.HTML(data)

doc.xpath("//div[@class='foo' and .//div[@class='bar']]").each do |node|
  node["class"] = 'bex'
end

puts doc
</code>```

Body:
Let's say I have this html that has various depths of descendants and a mixture of element types:

And I want to apply a class of bex to all the foos that contain classes of bar so it looks like:

How wld I do that with ruby/nokogiri? Tried all sorts of things and can't quite get it. Thanks.

Edit: closed the duh, oops.

Body:
I spent a long time wondering why the second foo wasn't found.
Your data is broken, "duh isn't closed.

To select the nodes, you can use :

doc.xpath("//div[@class='foo' and .//div[@class='bar']]")

As an example :

data = %q(<div class="foo">
    <div class="bar"></div>
</div>
<div class="foo">
    <div class="baz"></div>
</div>
<div class="foo">
    <u><span class="duh">
        <div class="bar"></div>
    </span></u>
</div>
<div class="foo">
    <div class="baz"></div>
</div>)

require 'nokogiri'

doc = Nokogiri.HTML(data)

doc.xpath("//div[@class='foo' and .//div[@class='bar']]").each do |node|
  node["class"] = 'bex'
end

puts doc


问:
Print effective arguments
I run a python program with a long argument list (> 20 arguments). Arguments have all a default values (if not overriden by user). At the program's startup, I print the effective argument to have a trace of how the program has been started. Today I print using a dumb routine:

```<code>def print_config(args):
    print("Configuration:")
    print("  shoes:   {}".format(args.shoes))
    print("  socket:  {}".format(args.socket))
    [...]
</code>```

How can I print this using a smart iterator?

答:
args is a argparse.Namespace object.  That class, or rather its super has a repr method.  That's what you see when you do

```<code>print(args)
</code>```

The relevant lines of the repr (which you can find in the argparse.py file) are:

```<code>    arg_strings = []
    for name, value in sorted(self.__dict__.items()):
        arg_strings.append('%s=%r' % (name, value))
    return '%s(%s)' % (type_name, ', '.join(arg_strings))
</code>```

If you joined with '\n' instead of ', ', it would give something close to your version.

vars(args) gives the same dictionary as args.__dict__.items().

print(parser.parse_args([])) will show all the defaults, without any user input.  Of course that won't work if there are required inputs.

Title: Print effective arguments

Body:
I run a python program with a long argument list (> 20 arguments). Arguments have all a default values (if not overriden by user). At the program's startup, I print the effective argument to have a trace of how the program has been started. Today I print using a dumb routine:

def print_config(args):
    print("Configuration:")
    print("  shoes:   {}".format(args.shoes))
    print("  socket:  {}".format(args.socket))
    [...]

How can I print this using a smart iterator?

Body:
args is a argparse.Namespace object.  That class, or rather its super has a repr method.  That's what you see when you do

print(args)

The relevant lines of the repr (which you can find in the argparse.py file) are:

    arg_strings = []
    for name, value in sorted(self.__dict__.items()):
        arg_strings.append('%s=%r' % (name, value))
    return '%s(%s)' % (type_name, ', '.join(arg_strings))

If you joined with '\n' instead of ', ', it would give something close to your version.

vars(args) gives the same dictionary as args.__dict__.items().

print(parser.parse_args([])) will show all the defaults, without any user input.  Of course that won't work if there are required inputs.


问:
Create a ts R object from a CSV file with dates as a column with multivariate series
I have a CSV file with the format

```<code>ref_date;wings;airfoil;turbines
2015-03-31;123,22;22,77;99,0
2015-04-30;123,22;28,77;99,0
2015-05-31;123,22;22,177;02,0
2015-06-30;56,288;22,77;99,0
</code>```

and I want to use the forecast package to predict the next values of this time series. The forecast package only accepts a ts object, but so far all my attempts to create one failed. I tried to

1) Use zoo package

```<code>df = read.zoo(data_file, sep=';', dec=',', format="%Y-%m-%d", header=T)
</code>```

but the data is truncated at the decimal point.

2) Use the zoo package with xts

```<code>df = read.zoo(datafile, sep=';', dec=',', format="%Y-%m-%d", header=T)
df_ts = ts(df)
</code>```

The dates are nowhere to be seen, the index is just a sequence of numbers, like

```<code>1 123.22 22.77 99
</code>```

3) Use read.csv and ts

```<code>df = read.zoo(datafile, sep=';', dec=',', format="%Y-%m-%d", header=T)
df_ts = ts(df)
</code>```

4) Try using xts

```<code>df = read.csv(data_file, sep=';', header=T, dec=',')
tt = as.xts(df[,-1],order.by = as.Date(as.character(df[,1]), format = "%Y-%m-%d"))
forecast(tt)
Error in `tsp<-`(`*tmp*`, value = tsp.y) :
  invalid time series parameters specified
</code>```

the result looses all information about the date, including the ref_date column, and now the forecast package gives nonsense as result.

What is the correct approach to create the object that the forecast library is waiting and can generate a forecast, maintaining the dates, including in the plots?

答:
I have been wrestling CSV data into ZOO/XTS objects and sympathize -- painful.

Suggest using as_xts() in the tidyquant package

```<code>as_xts(read_csv(file),ref_date)
</code>```

You may need to coerce the resulting coredata() in the XTS object back to numeric.

Body:
I have a CSV file with the format

ref_date;wings;airfoil;turbines
2015-03-31;123,22;22,77;99,0
2015-04-30;123,22;28,77;99,0
2015-05-31;123,22;22,177;02,0
2015-06-30;56,288;22,77;99,0

and I want to use the forecast package to predict the next values of this time series. The forecast package only accepts a ts object, but so far all my attempts to create one failed. I tried to

1) Use zoo package

df = read.zoo(data_file, sep=';', dec=',', format="%Y-%m-%d", header=T)

but the data is truncated at the decimal point.

2) Use the zoo package with xts

df = read.zoo(datafile, sep=';', dec=',', format="%Y-%m-%d", header=T)
df_ts = ts(df)

The dates are nowhere to be seen, the index is just a sequence of numbers, like

1 123.22 22.77 99

3) Use read.csv and ts

df = read.zoo(datafile, sep=';', dec=',', format="%Y-%m-%d", header=T)
df_ts = ts(df)

4) Try using xts

df = read.csv(data_file, sep=';', header=T, dec=',')
tt = as.xts(df[,-1],order.by = as.Date(as.character(df[,1]), format = "%Y-%m-%d"))
forecast(tt)
Error in `tsp<-`(`*tmp*`, value = tsp.y) :
  invalid time series parameters specified

the result looses all information about the date, including the ref_date column, and now the forecast package gives nonsense as result.

What is the correct approach to create the object that the forecast library is waiting and can generate a forecast, maintaining the dates, including in the plots?

Body:
I have been wrestling CSV data into ZOO/XTS objects and sympathize -- painful.

Suggest using as_xts() in the tidyquant package

as_xts(read_csv(file),ref_date)

You may need to coerce the resulting coredata() in the XTS object back to numeric.


问:
Gem/Bundler load error: can't activate...already activated
I ran bundle update to update my gems. now I get this when I try to start up the local, development server. Anyone know how to fix? </p>

```<code>hostname:myapp username$ rails s
/Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:238:in `activate': can't activate i18n (~> 0.4.1, runtime) for ["mail-2.2.10", "actionmailer-3.0.3", "rails-3.0.3"], already activated i18n-0.5.0 for ["activemodel-3.0.3", "actionpack-3.0.3", "rails-3.0.3"] (Gem::LoadError)
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:1065:in `gem'
    from /Users/username/.rvm/gems/ruby-1.9.2-p0@rails3/bin/rails:18:in `<main>'
</code>```

答:
This worked for me too:
Instead of
gem uninstall i18n
your best bet is
gem uninstall i18n -v=0.5.0

Here's why it matters: If you don't specify the version you are uninstalling, it will ask you if you want to uninstall a specific version or all of them. This isn't actually a problem, inherently, but I made the mistake of uninstalling all of them. No need to do that.

To get out of the bind I was in at that point (no i18n at all!) I did
 gem install i18n -v0.4.2
and all was well again.

Body:
I ran bundle update to update my gems. now I get this when I try to start up the local, development server. Anyone know how to fix?

hostname:myapp username$ rails s
/Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:238:in `activate': can't activate i18n (~> 0.4.1, runtime) for ["mail-2.2.10", "actionmailer-3.0.3", "rails-3.0.3"], already activated i18n-0.5.0 for ["activemodel-3.0.3", "actionpack-3.0.3", "rails-3.0.3"] (Gem::LoadError)
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:254:in `block in activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `each'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:253:in `activate'
    from /Users/username/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems.rb:1065:in `gem'
    from /Users/username/.rvm/gems/ruby-1.9.2-p0@rails3/bin/rails:18:in `'


问:
How are Windows symbolic links treated by the apps?
I thought that symbolic links in Windows 10 behave similarly to Linux symlinks, i.e., they are transparent to the apps. However, I'm confused by the actual behavior.

As an example, I've both softlinked and hardlinked the same CSS file:

```<code>$ mklink softlinked.css Default.css
symbolic link created for softlinked.css <<===>> Default.css

$ mklink /H hardlinked.css Default.css
Hardlink created for hardlinked.css <<===>> Default.css
</code>```

The hardlink behaves predictably (is indistinguishable from the original file) but I don't understand the soft linked one. See for example this:

Also, when the CSS is consumed by the Caret editor, the hardlinked stylesheet works fine:

while the softlinked is broken:

The questions are:

How do the symbolic links actually behave on Windows?

Can soft links be made transparent to the apps? By transparent, I mean the app would always see the file as being on the symlinked path (...\symlinked.css) and never resolve to the original path (...\Default.css). Is there some Windows registry settings or something?

答:
Symlinks are transparent to applications that are using the underlying file system, e.g., CreateFile() and friends, unless the application makes a specific effort to be aware of them.

However, they are not transparent to applications that are using the shell namespace (for example the standard Open File dialog) because the shell treats symlinks as if they were shortcuts, even to the point of modifying the displayed icon.   Whether this was a sensible decision on Microsoft's part is a moot point at this stage, since it isn't about to change.  So far as I'm aware, it is not configurable.

In practice this usually means that symlinks will behave transparently for non-GUI applications and for internal files (DLLs, built-in templates, configuration files, etc.) in GUI applications, but not for the user's documents.

So your first two examples (the way Explorer displays the files and the behaviour of Notepad++) are features rather than bugs; like it or not, this is the way Windows is designed to work.

Your last example does appear to be a bug (or at best an undesirable design limitation) in the application in question.  It might be worth contacting the vendor.

You should also be aware that creating a symlink requires administrative privilege, and by default they don't work at all over network shares.  Personally, given all these limitations, I've never found them very useful.  For most user tasks I would use shortcuts instead, and for most system administration tasks junction points are more reliable.

Body:
I thought that symbolic links in Windows 10 behave similarly to Linux symlinks, i.e., they are transparent to the apps. However, I'm confused by the actual behavior.

As an example, I've both softlinked and hardlinked the same CSS file:

$ mklink softlinked.css Default.css
symbolic link created for softlinked.css <<===>> Default.css

$ mklink /H hardlinked.css Default.css
Hardlink created for hardlinked.css <<===>> Default.css

The hardlink behaves predictably (is indistinguishable from the original file) but I don't understand the soft linked one. See for example this:

Also, when the CSS is consumed by the Caret editor, the hardlinked stylesheet works fine:

while the softlinked is broken:

The questions are:

How do the symbolic links actually behave on Windows?

Can soft links be made transparent to the apps? By transparent, I mean the app would always see the file as being on the symlinked path (...\symlinked.css) and never resolve to the original path (...\Default.css). Is there some Windows registry settings or something?