问:
How to insert Rich text box data using ModelForm in Django?
I've been trying to insert data into a database using a rich text field in Django using Django Rich text field
as it stands I've been able to have the field working on my form no problem but when I try and link it to my model using ModelFrom with all the other columns I have no luck.
This form is on a panel completely separate from the admin panel in which it works perfectly fine.

My model is set up to accept the form.

```<code>class Vulnerability(models.Model):
title = models.CharField(max_length=200, null=True)
CVSS = models.DecimalField(max_digits=2, decimal_places=1, null=True)
summary = RichTextField(blank=True)
remediation = RichTextField(blank=True)
impact = RichTextField(blank=True)
References = RichTextField(blank=True)
CVE = models.CharField(max_length=30, null=True)
Software = models.CharField(max_length=100, null=True)
method = RichTextField(blank=True)
Tags = models.CharField(null=True, max_length=200)
</code>```

my forms.py is set up for that field to use the correct widget (this could be where the issue lies)
I'm not entirely sure how to set up the rich text field in this fashion and I cannot find it in the documentation.

```<code>class vulnform(ModelForm):
class Meta:
    model = Vulnerability
    fields = ['Tags', 'CVSS', 'CVE', 'Software', 'title','summary']
    widgets = {
        'title': TextInput(attrs={'class': 'form-control'}),
        'CVE': TextInput(attrs={'class': 'form-control'}),
        'Software': TextInput(attrs={'class': 'form-control'}),
        'Tags': TextInput(attrs={'class': 'form-control'}),
        'CVSS': NumberInput(attrs={'class': 'form-control','max':10,'min':0}),
        'summary' : RichTextWidget()

    }
</code>```

my views. py looks like this :

class Dashboard(TemplateView):
    template_name = 'vuln_pages/Create_Vuln.html'

```<code>def get(self, request):
    Outform = {
                # 'Remediation': Remediation,
                 #'References': References,
                 #'Impact': impactform,
                 'vulnform': vulnform,

                 }
    return render(request, self.template_name, Outform)
</code>```

when being displayed the other fields in the from render correctly. i'm rendering them in my template like so:

```<code>                            <div class="col-lg-3">
                            <div class="form-group">
                                {{ vulnform.CVE }}
                            </div>
                        </div>
</code>```

and am trying to render the rich text box like so

```<code>                                {{ vulnform.summary }}
</code>```

I have had them working before but when the data is in a separate class from all the other columns in the formform.py and I was afraid that when I tried to .save them from a post request they would be saved in different rows in the database.

When I put the input box in my template HTML it renders a text box in the HTML but doesn't seem to load any JS for the rich text box.

```<code><textarea name="summary" cols="40" rows="10" class="djrichtextfield" id="id_summary"></textarea>
</code>```

I have tried linking the javascript to the page manually but it didn't work.

答:
After switching my addon to :
django-ckeditor
everything worked fine.
it seems to have been an issue with the addon.</p>

Body:
I've been trying to insert data into a database using a rich text field in Django using Django Rich text field
as it stands I've been able to have the field working on my form no problem but when I try and link it to my model using ModelFrom with all the other columns I have no luck.
This form is on a panel completely separate from the admin panel in which it works perfectly fine.

My model is set up to accept the form.

class Vulnerability(models.Model):
title = models.CharField(max_length=200, null=True)
CVSS = models.DecimalField(max_digits=2, decimal_places=1, null=True)
summary = RichTextField(blank=True)
remediation = RichTextField(blank=True)
impact = RichTextField(blank=True)
References = RichTextField(blank=True)
CVE = models.CharField(max_length=30, null=True)
Software = models.CharField(max_length=100, null=True)
method = RichTextField(blank=True)
Tags = models.CharField(null=True, max_length=200)

my forms.py is set up for that field to use the correct widget (this could be where the issue lies)
I'm not entirely sure how to set up the rich text field in this fashion and I cannot find it in the documentation.

class vulnform(ModelForm):
class Meta:
    model = Vulnerability
    fields = ['Tags', 'CVSS', 'CVE', 'Software', 'title','summary']
    widgets = {
        'title': TextInput(attrs={'class': 'form-control'}),
        'CVE': TextInput(attrs={'class': 'form-control'}),
        'Software': TextInput(attrs={'class': 'form-control'}),
        'Tags': TextInput(attrs={'class': 'form-control'}),
        'CVSS': NumberInput(attrs={'class': 'form-control','max':10,'min':0}),
        'summary' : RichTextWidget()

    }

my views. py looks like this :

class Dashboard(TemplateView):
    template_name = 'vuln_pages/Create_Vuln.html'

def get(self, request):
    Outform = {
                # 'Remediation': Remediation,
                 #'References': References,
                 #'Impact': impactform,
                 'vulnform': vulnform,

                 }
    return render(request, self.template_name, Outform)

when being displayed the other fields in the from render correctly. i'm rendering them in my template like so:

                                {{ vulnform.CVE }}

and am trying to render the rich text box like so

                                {{ vulnform.summary }}

I have had them working before but when the data is in a separate class from all the other columns in the formform.py and I was afraid that when I tried to .save them from a post request they would be saved in different rows in the database.

When I put the input box in my template HTML it renders a text box in the HTML but doesn't seem to load any JS for the rich text box.

<textarea name="summary" cols="40" rows="10" class="djrichtextfield" id="id_summary"></textarea>

I have tried linking the javascript to the page manually but it didn't work.


来源: stackexchange

问:
Displaying all results of execution
When I execute a python program, the results starts to appear quickly and I can't read it all. It just flushes over my screen.

When the execution ends, I can no longer see the first displays, because the terminal display space is limited.

How save the output, so I can read all of it?

答:
You have a few options here.

Add a breakpoint and learn how to use the debugger. Once you add this command (import pdb;pdb.set_trace() # this will take some learning so look up what pdb is online. actually, i prefer 'ipdb' instead.), the code will stop at that specific point when you execute it.

Save it to a file (python file.py > filename.txt) and then read it afterwards. Bonus: Before you ask yourself, where are my outputs? https://askubuntu.com/questions/625224/how-to-redirect-stderr-to-a-file

(More advanced) Your code is spitting out too much garbage output. You can remove some of the code or use python logging filters.

ContentLicense: CC BY-SA 4.0

Title: Displaying all results of execution


问:
Django - Fetching data works on Shell but returns " object is not iterable" on debug
I'm new to Django, and I'm trying to fetch data from different tables with ForeignKeys.

I have a model Clients and other Trip. Trip has a ForeignKey to Clients. I wanna fetch the Trips to each Client, and output on an HTML page.

When I run ls = Clients.objects.get(nif=123123123) and then ts = Trip.objects.filter(client = ls) I am able to retrieve the data I want from the Trip model.

But when I try doing so on django, I get a Exception Value: 'Clients' object is not iterable.

This is my models.py:

```<code>class Clients(models.Model):
    first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome")
    last_name = models.CharField(max_length=30, verbose_name="Apelido")
    address = models.CharField(max_length=200, verbose_name="Morada")
    nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True)
    mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])

class Trip(models.Model):
    trip_id = models.CharField(max_length=20, null=True, verbose_name="Ref. Viagem")
    client = models.ForeignKey(Clients, null=True, on_delete=models.SET_NULL, verbose_name="Cliente")
    out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida")
    hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel")
    in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso")
</code>```

This is my views.py:

```<code>from django.shortcuts import render
from django.http import HttpResponse
from .models import Clients, Hotels, Trip

def client(request, nif):
    ls= Clients.objects.get(nif=nif)
    ts= Trip.objects.filter(client = ls)
    context = {'ls': ls, 'ts' : ts}
    return render(request, "backend/client.html", context)
</code>```

This is my urls.py:

```<code>from django.urls import path
from . import views

urlpatterns = [
    path('', views.backend, name="backend"),
    path("cliente/<int:nif>", views.client, name="client"),
    path("hotel/<int:id>", views.hotel, name="hotel"),
]
</code>```

And then my client.html:

```<code>   {% for ls in ls %}

    ...

    <div class="field">
                    <p class="control is-expanded has-icons-left has-icons-right">
                    <input class="input" type="text" placeholder="Morada" value="{{ls.address}}" readonly>
                    <span class="icon is-small is-left">
                        <i class="fas fa-envelope"></i>
                    </span>
                    </p>
                </div>
                </div>
            </div>
            <div class="field is-horizontal">
                <div class="field-body">
                    <div class="field">
                        <p class="control is-expanded has-icons-left">
                        <input class="input" type="text" placeholder="Morada" value="{{ls.mobile}}" readonly>
                        <span class="icon is-small is-left">
                            <i class="fas fa-envelope"></i>
                        </span>
                        </p>
                    </div>
                <div class="field">
                    <p class="control is-expanded has-icons-left has-icons-right">
                    <input class="input" type="email" placeholder="Email" value="{{ls.nif}}" readonly>
                    <span class="icon is-small is-left">
                        <i class="far fa-id-card"></i>
                    </span>
                    </p>
                </div>
                {% for ts in ts %}
                <div class="field">
                    <p class="control is-expanded has-icons-left has-icons-right">
                    <input class="input" type="email" placeholder="Email" value="{{ts.trip_id}}" readonly>
                    <span class="icon is-small is-left">
                        <i class="far fa-id-card"></i>
                    </span>
                    </p>
                </div>
 {% endfor %}
...
 {% endfor %}
</code>```

答:
ls = Clients.objects.get() returns one object, not a list/queryset.

So {% for ls in ls %} is not possible because you have just one object.

ls is a Clients object and the error is telling you can't iterate over a Clients object.

Remove that loop.

[On a side note: {% for ts in ts %} is bad coding practice. You're overriding the ts name and it's not even clear what the object is. Rename to {% for trip in ts %} or even better rename ts to trips as well.]

Body:
I'm new to Django, and I'm trying to fetch data from different tables with ForeignKeys.

I have a model Clients and other Trip. Trip has a ForeignKey to Clients. I wanna fetch the Trips to each Client, and output on an HTML page.

When I run ls = Clients.objects.get(nif=123123123) and then ts = Trip.objects.filter(client = ls) I am able to retrieve the data I want from the Trip model.

But when I try doing so on django, I get a Exception Value: 'Clients' object is not iterable.

This is my models.py:

class Clients(models.Model):
    first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome")
    last_name = models.CharField(max_length=30, verbose_name="Apelido")
    address = models.CharField(max_length=200, verbose_name="Morada")
    nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True)
    mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])

class Trip(models.Model):
    trip_id = models.CharField(max_length=20, null=True, verbose_name="Ref. Viagem")
    client = models.ForeignKey(Clients, null=True, on_delete=models.SET_NULL, verbose_name="Cliente")
    out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida")
    hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel")
    in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso")

This is my views.py:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Clients, Hotels, Trip

def client(request, nif):
    ls= Clients.objects.get(nif=nif)
    ts= Trip.objects.filter(client = ls)
    context = {'ls': ls, 'ts' : ts}
    return render(request, "backend/client.html", context)

This is my urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.backend, name="backend"),
    path("cliente/<int:nif>", views.client, name="client"),
    path("hotel/<int:id>", views.hotel, name="hotel"),
]

And then my client.html:

   {% for ls in ls %}

    ...

                    <input class="input" type="text" placeholder="Morada" value="{{ls.address}}" readonly>

                        <input class="input" type="text" placeholder="Morada" value="{{ls.mobile}}" readonly>

                    <input class="input" type="email" placeholder="Email" value="{{ls.nif}}" readonly>

                {% for ts in ts %}

                    <input class="input" type="email" placeholder="Email" value="{{ts.trip_id}}" readonly>

 {% endfor %}
...
 {% endfor %}


问:
How to change data in XML/XLST?
how can I convert XML file like below:

```<code><?xml version="1.0"?>
<?xml-stylesheet href="file123.xsl" type="text/xsl"?>
    <ReportBody>
      <Document
        Title="Report: TESTOWY FIXEDHOL">
        <Chapter
        Tag="0"
        Name="TEST_KAL1_I0"
        Label=""
        Dimension="1">
          <TableDef>
        <ColLabel>
          <D>Type</D>
          <D>Month</D>
          <D>Day</D>
          <D>WeekDay</D>
        </ColLabel>
          </TableDef>
          <Bloc
        Tag="1"
        Level="1"
        Label="">
        <DataRow Total="false">
          <D>FLOAT</D>
          <D>May</D>
          <D>12</D>
          <D>Thurday</D>
        </DataRow>
          </Bloc>
        </Chapter>
      </Document>
    </ReportBody>
</code>```

so as to achieve like this (of course this is a shorter example):

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document UploadDate="20111021" ClientCode="AKK" Version="0">
    <HolidayRules>
        <HolidayRule>
            <Type>FIXED</Type>
            <Month>August</Month>
            <Day>2.0</Day>
            <WeekDay>Friday</WeekDay>
        </HolidayRule>
    </HolidayRules>
</UploadDocument>
</code>```

I know that probably I have to use XSLT but how can I do it ? Could you give me example of code to do it ?

Probabli it can be the solution, but how to use it? what does it mean test="position()=2"? and so on ?

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <UploadDocument>
      <xsl:for-each select="2KALROBOCZE/2VH">
        <Schedule>
          <xsl:for-each select="D">
            <xsl:if test="position() = 1">
              <Action>
                <xsl:value-of select="." />
              </Action>
            </xsl:if>
            <xsl:if test="position() = 2">
              <Name>
                <xsl:value-of select="." />
              </Name>
              <Description> </Description>
            </xsl:if>
            <xsl:if test="position() = 3">
              <DateSchedules>
                <DateSchedule>
                  <Date>
                    <xsl:value-of select="." />
                  </Date>
                </DateSchedule>
              </DateSchedules>
            </xsl:if>
          </xsl:for-each>
        </DateSchedule>
      </xsl:for-each>
    </UploadDocument>
  </xsl:template>
</xsl:stylesheet>
</code>```

答:
This simple stylesheet:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:strip-space elements="*"/>
  <xsl:key  name="ColLabel-D-by-positionn"
            match="ColLabel/D"
            use="count(preceding-sibling::D) + 1"/>

  <xsl:template match="/">
    <Document UploadDate="20111021" ClientCode="AKK" Version="0">
        <HolidayRules>
            <xsl:apply-templates/>
        </HolidayRules>
    </Document>
  </xsl:template>

  <xsl:template match="DataRow">
        <HolidayRule>
            <xsl:apply-templates/>
        </HolidayRule>
  </xsl:template>

  <xsl:template match="DataRow/D">
        <xsl:element name="{key('ColLabel-D-by-positionn', position())}">
            <xsl:value-of select="."/>
        </xsl:element>
  </xsl:template>

  <xsl:template match="text()"/>
</xsl:stylesheet>
</code>```

Output:

```<code><Document UploadDate="20111021" ClientCode="AKK" Version="0">
  <HolidayRules>
    <HolidayRule>
      <Type>FLOAT</Type>
      <Month>May</Month>
      <Day>12</Day>
      <WeekDay>Thurday</WeekDay>
    </HolidayRule>
  </HolidayRules>
</Document>
</code>```

Test in here

Do note: the empty rule for text nodes overrides the built-in rules, the xsl:strip-space is needed because xsl:apply-templates and position() semantic, the key is used for performance and convenience but it could be ../../../TableDef/ColLabel/D[position() = count(current()/preceding-sibling::D) + 1]

Title: How to change data in XML/XLST?

Body:
how can I convert XML file like below:

<?xml version="1.0"?>
<?xml-stylesheet href="file123.xsl" type="text/xsl"?>
    <ReportBody>
      <Document
        Title="Report: TESTOWY FIXEDHOL">
        <Chapter
        Tag="0"
        Name="TEST_KAL1_I0"
        Label=""
        Dimension="1">
          <TableDef>
        <ColLabel>
          <D>Type</D>
          <D>Month</D>
          <D>Day</D>
          <D>WeekDay</D>
        </ColLabel>
          </TableDef>
          <Bloc
        Tag="1"
        Level="1"
        Label="">
        <DataRow Total="false">
          <D>FLOAT</D>
          <D>May</D>
          <D>12</D>
          <D>Thurday</D>
        </DataRow>
          </Bloc>
        </Chapter>
      </Document>
    </ReportBody>

so as to achieve like this (of course this is a shorter example):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document UploadDate="20111021" ClientCode="AKK" Version="0">
    <HolidayRules>
        <HolidayRule>
            <Type>FIXED</Type>
            <Month>August</Month>
            <Day>2.0</Day>
            <WeekDay>Friday</WeekDay>
        </HolidayRule>
    </HolidayRules>
</UploadDocument>

I know that probably I have to use XSLT but how can I do it ? Could you give me example of code to do it ?

Probabli it can be the solution, but how to use it? what does it mean test="position()=2"? and so on ?

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>
  <xsl:template match="/">
    <UploadDocument>
      <xsl:for-each select="2KALROBOCZE/2VH">
        <Schedule>
          <xsl:for-each select="D">
            <xsl:if test="position() = 1">
              <Action>
                <xsl:value-of select="." />
              </Action>
            </xsl:if>
            <xsl:if test="position() = 2">
              <Name>
                <xsl:value-of select="." />
              </Name>
              <Description> </Description>
            </xsl:if>
            <xsl:if test="position() = 3">
              <DateSchedules>
                <DateSchedule>
                  <Date>
                    <xsl:value-of select="." />
                  </Date>
                </DateSchedule>
              </DateSchedules>
            </xsl:if>
          </xsl:for-each>
        </DateSchedule>
      </xsl:for-each>
    </UploadDocument>
  </xsl:template>
</xsl:stylesheet>

Body:
This simple stylesheet:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:strip-space elements="*"/>
  <xsl:key  name="ColLabel-D-by-positionn"
            match="ColLabel/D"
            use="count(preceding-sibling::D) + 1"/>

  <xsl:template match="/">
    <Document UploadDate="20111021" ClientCode="AKK" Version="0">
        <HolidayRules>
            <xsl:apply-templates/>
        </HolidayRules>
    </Document>
  </xsl:template>

  <xsl:template match="DataRow">
        <HolidayRule>
            <xsl:apply-templates/>
        </HolidayRule>
  </xsl:template>

  <xsl:template match="DataRow/D">
        <xsl:element name="{key('ColLabel-D-by-positionn', position())}">
            <xsl:value-of select="."/>
        </xsl:element>
  </xsl:template>

  <xsl:template match="text()"/>
</xsl:stylesheet>

Output:

<Document UploadDate="20111021" ClientCode="AKK" Version="0">
  <HolidayRules>
    <HolidayRule>
      <Type>FLOAT</Type>
      <Month>May</Month>
      <Day>12</Day>
      <WeekDay>Thurday</WeekDay>
    </HolidayRule>
  </HolidayRules>
</Document>

Test in here

Do note: the empty rule for text nodes overrides the built-in rules, the xsl:strip-space is needed because xsl:apply-templates and position() semantic, the key is used for performance and convenience but it could be ../../../TableDef/ColLabel/D[position() = count(current()/preceding-sibling::D) + 1]


问:
Continuous Looping Video in TVOS?
I'm just getting started with TVOS and was wondering if anyone has addressed looping in TVOS / TVJS / TVML.  I'm using this tutorial to create a simple interface for playing videos. My wrinkle is that I want these videos to play in a continuous seamless loop - basically a moving screensaver type effect - see example videos at art.chrisbaily.com.

Is there a simple way to do this, or do I need to build some kind of event listener to do the looping manually?  I'd like the videos to be fairly hi res, and the videos would be somewhere between 1 and 3 minutes.

答:
You could also set repeatMode on the playlist object

```<code>player.playlist.repeatMode = 1;
</code>```

0 = no repeat

1 = repeat all items in playlist

2 = repeat current item

ContentLicense: CC BY-SA 3.0

Title: Continuous Looping Video in TVOS?

Body:
You could also set repeatMode on the playlist object

player.playlist.repeatMode = 1;

0 = no repeat

1 = repeat all items in playlist

2 = repeat current item


问:
Angle between vectors - Python
I am a beginner in Python (a reeeal beginner) but I have a few assignments to do and I’m totally stuck with one problem. I have to count an angle between vectors. I’ve spent tons of nights trying to do that and I actually even wrote code, but. It shows only positive numbers, so it doesn’t count any negative values. How can I change it?

My data consists of eye-tracking coordinates so I’m sure there must be negative values. Sample data - {308, 394, 700, 738.6, 298.8}, {554, 718, 1270, 737.3, 352.5}, {300, 1314, 1612, 1014.3, 728.5}, {316, 1642, 1956, 844.5, 885.1}, where first 4 values are coordinates (x1, x2, y1, y2). Code I have:

```<code>def angle_between(v1, v2, deg=True):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
"""
print('First vector:', v1)
print('Second vector:', v2)

v1_u = unit_vector(v1)
v2_u = unit_vector(v2)

radians = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
result = radians

# print('radians:', result)
if deg:
    result = np.degrees([radians.real])[0]
    print(f"degrees: {result}")
return result
</code>```

Help me pls! :(

答:
Actually, that's not so a coding problem but a math problem. Not sure that's the best place to solve, I let someone more experimented to erase/deplace if any necessity.

Arc cosinus gives you a number between 0 and pi, so you can't hope to obtain an oriented angle. You need to make a distinction between negative and positive scalar product.

Let'go on on step by step.

let's first define the following function, we suppose v1 and v2 normalized for the sake of simplicity

```<code>def angle(v1,v2):
    scalar_product = v1[0]*v2[0] + v2[1]*v2[1]
    return npy.arccos( scalar_product ) # result between 0 and pi
</code>```

If we setv1 = [ 1 , 0 ] and try

```<code>angle( v1 , [ np.cos(2*np.pi/3) , np.sin(2*pi/3) )
angle( v1 , [ np.cos(4*np.pi/3) , np.sin(4*pi/3) )
</code>```

You have the same result, around 2.09, so 2*pi/3. As 2*pi/3 and 4*pi/3 have the same cos, you can't grab the difference.

So we need information from the determinant of the matrix composed of the two vectors to determine the orientation. You can use np.linalg.deton the matrix you build with the two vectors. If the determinant is positive, you keep the angle you found with the function angle, else you take the opposite. Should do the work.

Title: Angle between vectors - Python

Body:
I am a beginner in Python (a reeeal beginner) but I have a few assignments to do and I’m totally stuck with one problem. I have to count an angle between vectors. I’ve spent tons of nights trying to do that and I actually even wrote code, but. It shows only positive numbers, so it doesn’t count any negative values. How can I change it?

My data consists of eye-tracking coordinates so I’m sure there must be negative values. Sample data - {308, 394, 700, 738.6, 298.8}, {554, 718, 1270, 737.3, 352.5}, {300, 1314, 1612, 1014.3, 728.5}, {316, 1642, 1956, 844.5, 885.1}, where first 4 values are coordinates (x1, x2, y1, y2). Code I have:

def angle_between(v1, v2, deg=True):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
"""
print('First vector:', v1)
print('Second vector:', v2)

v1_u = unit_vector(v1)
v2_u = unit_vector(v2)

radians = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
result = radians

# print('radians:', result)
if deg:
    result = np.degrees([radians.real])[0]
    print(f"degrees: {result}")
return result

Help me pls! :(

Body:
Actually, that's not so a coding problem but a math problem. Not sure that's the best place to solve, I let someone more experimented to erase/deplace if any necessity.

Arc cosinus gives you a number between 0 and pi, so you can't hope to obtain an oriented angle. You need to make a distinction between negative and positive scalar product.

Let'go on on step by step.

let's first define the following function, we suppose v1 and v2 normalized for the sake of simplicity

def angle(v1,v2):
    scalar_product = v1[0]*v2[0] + v2[1]*v2[1]
    return npy.arccos( scalar_product ) # result between 0 and pi

If we setv1 = [ 1 , 0 ] and try

angle( v1 , [ np.cos(2*np.pi/3) , np.sin(2*pi/3) )
angle( v1 , [ np.cos(4*np.pi/3) , np.sin(4*pi/3) )

You have the same result, around 2.09, so 2*pi/3. As 2*pi/3 and 4*pi/3 have the same cos, you can't grab the difference.

So we need information from the determinant of the matrix composed of the two vectors to determine the orientation. You can use np.linalg.deton the matrix you build with the two vectors. If the determinant is positive, you keep the angle you found with the function angle, else you take the opposite. Should do the work.


问:
`sizeof` struct in union definition
To access a struct byte-wise, I'm using a union.

```<code>typedef struct {
    char hi;
    char lo;
} range;

union {
    range by_name;
    char as_bytes[sizeof(range)];
} U1;

char use_U1(void){
    char c = U1.as_bytes[0];
    return U1.by_name.hi;
}
</code>```

Question 1: Is it possible to skip the typedef? Like this:

```<code>union {
    struct {
        char hi;
        char lo;
    } by_name;
    char as_bytes[2]; //want sizeof()
} U2;
</code>```

A naive char as_bytes[sizeof(by_name)] doesn't compile:

error: 'by_name' undeclared here (not in a function)

Question 2: Same but with anonymous structure, to avoid typing .by_name when using.

```<code>union {
    struct {
        char hi;
        char lo;
    };
    char as_bytes[2]; //want sizeof()
} U3;

int use_U3(void){
    char c = U3.as_bytes[0];
    return U3.hi; // anonymous structure
}
</code>```

Read so far: union, struct

答:
More simple version not portable (if you plan to use non gcc or mvsc compilers):</p>

```<code>union {
    struct{
        char hi;
        char lo;
    };
    char as_bytes[0];
} U2;
</code>```

Title: `sizeof` struct in union definition

Body:
To access a struct byte-wise, I'm using a union.

typedef struct {
    char hi;
    char lo;
} range;

union {
    range by_name;
    char as_bytes[sizeof(range)];
} U1;

char use_U1(void){
    char c = U1.as_bytes[0];
    return U1.by_name.hi;
}

Question 1: Is it possible to skip the typedef? Like this:

union {
    struct {
        char hi;
        char lo;
    } by_name;
    char as_bytes[2]; //want sizeof()
} U2;

A naive char as_bytes[sizeof(by_name)] doesn't compile:

error: 'by_name' undeclared here (not in a function)

Question 2: Same but with anonymous structure, to avoid typing .by_name when using.

union {
    struct {
        char hi;
        char lo;
    };
    char as_bytes[2]; //want sizeof()
} U3;

int use_U3(void){
    char c = U3.as_bytes[0];
    return U3.hi; // anonymous structure
}

Read so far: union, struct

Body:
More simple version not portable (if you plan to use non gcc or mvsc compilers):

union {
    struct{
        char hi;
        char lo;
    };
    char as_bytes[0];
} U2;


问:
Is there a a way in Ruby to increment a Struct object variable inside an array?
```<code>Namepoints = Struct.new(:name, :points)

def arraytesting2()

  x = Namepoints.new("Seasons", 1)
  array = []
  255.times do

    unless array.include? x.name
      array << x.name
      array << x.points
    else
      array[array.index(x.points) + 1 ]
    end
  end
  print array.to_s.gsub(/[\[\]"]/, "")
end

arraytesting2
</code>```

Outcome: Seasons, 1

Expected outcome: Seasons, 255

array[array.index(x.points) + 1 ] will not increment?

Also attempting this another way: array[array.index(x.points + 1 )] receives a conversion error

答:
It’s easier to use Array#index rather than Array#include?.

Namepoints = Struct.new(:name, :points)

def arraytesting2(x)
  255.times.each_with_object([]) do |_, array|
    if found = array.index(x.name)
      array[found + 1] += 1 # points are right after
    else
      array << x.name << x.points
    end
  end
end

arraytesting2(Namepoints.new("Seasons", 1))
#⇒ ["Seasons", 255]
```

Body:
Namepoints = Struct.new(:name, :points)

def arraytesting2()

  x = Namepoints.new("Seasons", 1)
  array = []
  255.times do

    unless array.include? x.name
      array << x.name
      array << x.points
    else
      array[array.index(x.points) + 1 ]
    end
  end
  print array.to_s.gsub(/[\[\]"]/, "")
end

arraytesting2

Outcome: Seasons, 1

Expected outcome: Seasons, 255

array[array.index(x.points) + 1 ] will not increment?

Also attempting this another way: array[array.index(x.points + 1 )] receives a conversion error


问:
Count data per day between two dates
Hi i'm trying to count the total late remark per day between two dates inputs by the user.

for example:

```<code>ID  NAME    DATE_TIME         REMARKS
1   Aa  2020-01-18 09:57:56     LATE
2   Aa  2020-01-18 10:57:56     LATE
3   Aa  2020-01-19 06:52:56
4   Aa  2020-01-19 09:57:56     LATE
5   Aa  2020-01-19 09:57:56     LATE
6   Aa  2020-01-21 09:57:56     Late
</code>```

Expected result.

```<code>NAME     DATE          count
Aa     2020-01-18         2
Aa     2020-01-19         2
Aa     2020-01-20         0
Aa     2020-01-21         1
</code>```

The Data type of DATE_TIME is varhcar2

this is my attemp but i dont know how to achive it.

```<code>Select Count(REMARKS) countBT from TBLACCESSLOGS WHERE To_date(DATE_TIME,'YYYY-MM-DD') between To_date('2020-02-18','YYYY-MM-DD') and To_date('2020-02-20','YYYY-MM-DD')
</code>```

and i get error  date format picture ends before converting entire input string pointing on DATE_TIME as i execute.

Hope someone help me with this.
Thank you in advance

答:
Try this ..</p>

```<code>    SQL> select * from late_remarks;

        ID NAME DATE_TIME             REMARKS
        -- --   -------------------   ----
        1  Aa   2020-01-18 09:57:56   LATE
        2  Aa   2020-01-18 10:57:56   LATE
        3  Aa   2020-01-19 06:52:56
        4  Aa   2020-01-19 09:57:56   LATE
        5  Aa   2020-01-19 09:57:56   LATE
        6  Aa   2020-01-21 09:57:56   LATE

    6 rows selected.

    SQL> with dates as (
      2      select to_date('17-01-2020', 'DD-MM-YYYY') + level "DATE"
      3      from dual
      4      connect by level <= (to_date('21-01-2020', 'DD-MM-YYYY') - to_date('17-01-2020', 'DD-MM-YYYY'))
      5      )
      6  select 'Aa' name, d."DATE", count(lr.remarks) count from dates d
      7      left outer join late_remarks lr
      8          on d."DATE" = trunc(to_timestamp (lr.date_time, 'YYYY-MM-DD HH24:MI:SS'))
      9      group by d."DATE"
     10      order by d."DATE";

    NAME DATE           COUNT
    --   --------- ----------
    Aa   18-JAN-20          2
    Aa   19-JAN-20          2
    Aa   20-JAN-20          0
    Aa   21-JAN-20          1
</code>```

<p>.. assuming name to be constant </p>

Title: Count data per day between two dates

Body:
Hi i'm trying to count the total late remark per day between two dates inputs by the user.

for example:

ID  NAME    DATE_TIME         REMARKS
1   Aa  2020-01-18 09:57:56     LATE
2   Aa  2020-01-18 10:57:56     LATE
3   Aa  2020-01-19 06:52:56
4   Aa  2020-01-19 09:57:56     LATE
5   Aa  2020-01-19 09:57:56     LATE
6   Aa  2020-01-21 09:57:56     Late

Expected result.

NAME     DATE          count
Aa     2020-01-18         2
Aa     2020-01-19         2
Aa     2020-01-20         0
Aa     2020-01-21         1

The Data type of DATE_TIME is varhcar2

this is my attemp but i dont know how to achive it.

Select Count(REMARKS) countBT from TBLACCESSLOGS WHERE To_date(DATE_TIME,'YYYY-MM-DD') between To_date('2020-02-18','YYYY-MM-DD') and To_date('2020-02-20','YYYY-MM-DD')

and i get error  date format picture ends before converting entire input string pointing on DATE_TIME as i execute.

Hope someone help me with this.
Thank you in advance

Body:
Try this ..

    SQL> select * from late_remarks;

        ID NAME DATE_TIME             REMARKS
        -- --   -------------------   ----
        1  Aa   2020-01-18 09:57:56   LATE
        2  Aa   2020-01-18 10:57:56   LATE
        3  Aa   2020-01-19 06:52:56
        4  Aa   2020-01-19 09:57:56   LATE
        5  Aa   2020-01-19 09:57:56   LATE
        6  Aa   2020-01-21 09:57:56   LATE

    6 rows selected.

    SQL> with dates as (
      2      select to_date('17-01-2020', 'DD-MM-YYYY') + level "DATE"
      3      from dual
      4      connect by level <= (to_date('21-01-2020', 'DD-MM-YYYY') - to_date('17-01-2020', 'DD-MM-YYYY'))
      5      )
      6  select 'Aa' name, d."DATE", count(lr.remarks) count from dates d
      7      left outer join late_remarks lr
      8          on d."DATE" = trunc(to_timestamp (lr.date_time, 'YYYY-MM-DD HH24:MI:SS'))
      9      group by d."DATE"
     10      order by d."DATE";

    NAME DATE           COUNT
    --   --------- ----------
    Aa   18-JAN-20          2
    Aa   19-JAN-20          2
    Aa   20-JAN-20          0
    Aa   21-JAN-20          1

.. assuming name to be constant


问:
Handling file uploads within SVN
I'm constantly having to propset svn:ignore on my uploaded files directories simply because svn:ignore doesn't work as expected. I'm working in NetBeans and our site is constantly under heavy development. I'm sick of "ignoring" the folders because it simply doesn't work how I expect it to. We have several upload directories and would like them to be completely ignored from version control. I thought of possibly using symlinks to store the files in a separate folder on my local machine, while leaving the actual directory empty. Does this sound like a logical solution?</p>

答:
svn:ignore the entire directory, or write a svn:ignore rule to ignore everything

Beyond that, you could restructure your work flow to have a non svn controlled upload area.

It isn't clear why you would have a directory which isn't actually part of your source code checked into SVN for revisioning purposes, but perhaps there is a reason.  If at all possible, only check into SVN that which you really wish to revision.

Title: Handling file uploads within SVN


问:
NoSuchMethod while accessing Sheet API via Java
Google sheet quickstart

While following this link - https://developers.google.com/sheets/api/quickstart/java
I got this:

Exception in thread "main" java.lang.NoSuchMethodError:
  com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient$Builder.setBatchPath(Ljava/lang/String;)Lcom/google/api/client/googleapis/services/AbstractGoogleClient$Builder;
  at
  com.google.api.services.sheets.v4.Sheets$Builder.setBatchPath(Sheets.java:3143)
  at com.google.api.services.sheets.v4.Sheets$Builder.(Sheets.java:3122)
  at
  com.pansari.promoter.service.SheetQuickStart.main(SheetQuickStart.java:70)

Specifications:

```<code>Java version (java -version) 1.8
OS Mac
</code>```

POM changes:

```<code>com.google.apis
google-api-services-sheets
v4-rev516-1.23.0

com.google.api-client
google-api-client
1.23.0

com.google.oauth-client
google-oauth-client-jetty
1.23.0
</code>```

Can anyone help?

答:
I spent an embarrassing amount of time on this problem, so wanted to leave a tip. The issue with setBatchPath is that it was introduced in google-api-client 1.23.0 and later. I was including the latest builds of google-api-client in my gradle.build file, BUT there were overrides elsewhere in the project that forced the usage of google-api-client 1.22.0 which was breaking the code.

If you're having this problem, try the following:

Check what version of jar is in your build directory build/dependency for example.

Run gradle dependencyInsight --dependency com.google.api-client to see what gradle is doing if you're doing it

The fix for me was adding the following to my build.gradle in the library project and the service that was consuming the library.

```<code>dependencyManagement {
    dependencies{
        dependency 'com.google.apis:google-api-services-sheets:v4-rev607-1.25.0'
        dependency 'com.google.api-client:google-api-client:1.25.0'
    }
}
</code>```

Body:
Google sheet quickstart

While following this link - https://developers.google.com/sheets/api/quickstart/java
I got this:

Exception in thread "main" java.lang.NoSuchMethodError:
  com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient$Builder.setBatchPath(Ljava/lang/String;)Lcom/google/api/client/googleapis/services/AbstractGoogleClient$Builder;
  at
  com.google.api.services.sheets.v4.Sheets$Builder.setBatchPath(Sheets.java:3143)
  at com.google.api.services.sheets.v4.Sheets$Builder.(Sheets.java:3122)
  at
  com.pansari.promoter.service.SheetQuickStart.main(SheetQuickStart.java:70)

Specifications:

Java version (java -version) 1.8
OS Mac

POM changes:

com.google.apis
google-api-services-sheets
v4-rev516-1.23.0

com.google.api-client
google-api-client
1.23.0

com.google.oauth-client
google-oauth-client-jetty
1.23.0

Can anyone help?

Body:
I spent an embarrassing amount of time on this problem, so wanted to leave a tip. The issue with setBatchPath is that it was introduced in google-api-client 1.23.0 and later. I was including the latest builds of google-api-client in my gradle.build file, BUT there were overrides elsewhere in the project that forced the usage of google-api-client 1.22.0 which was breaking the code.

If you're having this problem, try the following:

Check what version of jar is in your build directory build/dependency for example.

Run gradle dependencyInsight --dependency com.google.api-client to see what gradle is doing if you're doing it

The fix for me was adding the following to my build.gradle in the library project and the service that was consuming the library.

dependencyManagement {
    dependencies{
        dependency 'com.google.apis:google-api-services-sheets:v4-rev607-1.25.0'
        dependency 'com.google.api-client:google-api-client:1.25.0'
    }
}


问:
Python Gurobi: How can I implement a maximum value of a decision variable in the objective function?
Hopefully someone can help me out. I am developing an optimization model where I minimize electricity costs over time (t) and over different transactions (s). (where: standard power(p)*costs of electricity (c) = electricity costs).

Now I am trying to implement a cost component in the objective function that is based on the maximum power consumption that occurred (some alike: max(P[s,t])). However, np.max() returns an error because P[s,t] is an unsupported class for np.max(). Also the Gurobi function gp.max_(P[s,t]) also gives an unsupported class error. Is there someone who has a solution?

Code:

```<code>obj = gp.quicksum(p[s, t] * Cost_elect[t]e for t in range(T) for s in range(S)) + gp.max_(p_batt_ch[s,t]*fixed_cost for t in range(T) for s in range(S))
</code>```

答:
You need to assign the max constraint to a new auxiliary variable and the put this variable into the objective instead of the actual constraint.

```<code>maxobj = model.addVar()
max_constr = model.addConstr(maxobj == gp.max_(p_batt_ch[s,t] * fixed_cost
                             for t in range(T) for s in range(S)))

obj = gp.quicksum(p[s,t] * Cost_elect[t] for t in range(T) for s in range(S)) + maxobj)

</code>```

Gurobi documentation

Body:
Hopefully someone can help me out. I am developing an optimization model where I minimize electricity costs over time (t) and over different transactions (s). (where: standard power(p)*costs of electricity (c) = electricity costs).

Now I am trying to implement a cost component in the objective function that is based on the maximum power consumption that occurred (some alike: max(P[s,t])). However, np.max() returns an error because P[s,t] is an unsupported class for np.max(). Also the Gurobi function gp.max_(P[s,t]) also gives an unsupported class error. Is there someone who has a solution?

Code:

obj = gp.quicksum(p[s, t] * Cost_elect[t]e for t in range(T) for s in range(S)) + gp.max_(p_batt_ch[s,t]*fixed_cost for t in range(T) for s in range(S))

Body:
You need to assign the max constraint to a new auxiliary variable and the put this variable into the objective instead of the actual constraint.

maxobj = model.addVar()
max_constr = model.addConstr(maxobj == gp.max_(p_batt_ch[s,t] * fixed_cost
                             for t in range(T) for s in range(S)))

obj = gp.quicksum(p[s,t] * Cost_elect[t] for t in range(T) for s in range(S)) + maxobj)

Gurobi documentation


问:
Two concurrent AsyncTasks in Android - How to handle race conditions?
I send an HTTP Post every time a button is pressed and every time it is released. It is likely that I will not have a response from the 'pressed' POST before the button is released, therefore I try to run these tasks concurrently. However, occasionally, the POST request for releasing the button is sent to the server before the request for pressing the button. How can I avoid/fix this?</p>

```<code>button = (ImageButton) findViewById((R.id.button1));
        button.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                HTTPAsyncTask task = new HTTPAsyncTask();
                if (event.getAction() == MotionEvent.ACTION_DOWN ) {
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Utilities.StringCollection.rotateRight);
                    return true;
                }
                else if (event.getAction() == MotionEvent.ACTION_UP){
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Utilities.StringCollection.stop);
                    return true;
                }
                return false;
            }
        });
</code>```

答:
Conceptually, your HTTPAsyncTask doInBackground() consists of 2 distinct actions:

Connect, and queue the request to socket

Receive the response

(after which, of course, onPostExecute() will be called.)

As you've described, you need to control the order of execution for action #1, on two different threads, while allowing action #2 to occur in parallel.

This is not possible using the generic AsyncTask mechanism, because you have not provided any way to "split the task in two"; there is no way for thread A to figure out when thread B has switched from action #1 to action #2, or vice versa.

It's possible such logic could be added, but you have not explained how you're making the socket call.

There's little point in providing that extra detail, however; the edge cases associated with the network request(s) destroy any guarantee of order you might've had. Networks are lossy; requests may fail, responses may fail. Requests may arrive out-of-order even though they were sent in order (particularly if you are using two separate sockets). Automatic re-tries may take several seconds to accomplish.

IOW, the "pressed" request may get lost by the network, and you may have to re-queue it to the socket sometime after the "unpressed" request has completed.

I would advise that you give up on the "partial conditional concurrency" you are seeking, and simply ensure that the first HTTPAsyncTask has completed before you execute the second one.

Alternatively, you could add a sequential "request ID" to each POST, or include information about the first request in the second request, so that the server is able to sort out what has happened, even if the requests arrive out-of-order.

Body:
I send an HTTP Post every time a button is pressed and every time it is released. It is likely that I will not have a response from the 'pressed' POST before the button is released, therefore I try to run these tasks concurrently. However, occasionally, the POST request for releasing the button is sent to the server before the request for pressing the button. How can I avoid/fix this?

button = (ImageButton) findViewById((R.id.button1));
        button.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                HTTPAsyncTask task = new HTTPAsyncTask();
                if (event.getAction() == MotionEvent.ACTION_DOWN ) {
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Utilities.StringCollection.rotateRight);
                    return true;
                }
                else if (event.getAction() == MotionEvent.ACTION_UP){
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, Utilities.StringCollection.stop);
                    return true;
                }
                return false;
            }
        });


问:
Restriction on length of query parameters
Do we still have any limitation on length of query params on GET operations. Earlier I think i used t be 255, which seems increased but i don't know whats that increased limitation.

The problem i am facing is
I tried GET For endpoint like http://localhost:8080/data/ids=<5000 comma seaprated ids>, it fails

but same request with 500 ids like http://localhost:8080/data/ids=<500 comma seaprated ids> succeeds and so i doubt its length issue.

Please advise

答:
I think it depends more on the configuration of the web server your application is running on.

For Apache Tomcat you can configure this value using following parameter in server.xml configuration file:

```<code><Connector port="8080" maxHttpHeaderSize="65536" protocol="HTTP/1.1" ... />
</code>```

For Jetty it should be:

```<code><Set name="requestHeaderSize">65535</Set>
</code>```

Body:
I think it depends more on the configuration of the web server your application is running on.

For Apache Tomcat you can configure this value using following parameter in server.xml configuration file:

<Connector port="8080" maxHttpHeaderSize="65536" protocol="HTTP/1.1" ... />

For Jetty it should be:

<Set name="requestHeaderSize">65535</Set>


问:
Admin panel and MVC
I'm studying MVC a little but i don't understand where the "admin control panel" fits in the MVC structure. I'm working with PHP. Maybe anyone can give me some ideas?</p>

答:
In the "MVC" structure, what you are calling the "admin control panel", is just another set of models, views, and controllers accessible by someone with administrative privileges.

Conceptually it is no different then the set of models, views, and controllers serving up content for public viewing.

This question doesn't make sense logically, similar to this question.

"I've been studying cellular structure, and want to know how a human being fits into a cell's organization"

Title: Admin panel and MVC


问:
Convert Json data into SQL table using Python
My json data looks like this:

```<code>[
    {
        "fields": {
            "bkdate": null,
            "business_credit_card_total_balances": null,
            "business_credit_card_total_limits": null,
            "business_total_monthly_debt_payments": null,
            "business_total_mortgage_monthly_payments": null,
            "created_at": "2016-08-04T00:29:03.067Z",
            "detail_results": null,
            "error_reason": "no reasons",
            "fico_v2": "695",
            "fico_v3": null,
            "loanapp_id": 194,
            "personal_credit_card_total_balances": null,
            "personal_credit_card_total_limits": null,
            "personal_total_monthly_payments": null,
            "report_type": "CreditProfile",
            "result": true,
            "role": "applicant",
            "total_mortgage_monthly_payments": null,
            "username": "cho",
            "version": "CF Microloan",
            "xml_data": "<?xml version=\"1.0\" standalone=\"no\"?><NetConnectResponse xmlns=\"http://www.experian.com/NetConnectResponse\"><CompletionCode>0000</CompletionCode>"
        },
        "model": "common.prequalresult",
        "pk": 1
    }
]
</code>```

I Want to convert it into SQL table. I tried this:

```<code>v = pd.DataFrame(data['fields'])
t = pd.io.json.json_normalize(data['fields'], ['model'], ['pk'], meta_prefix='parent_')

v.to_sql('fields', engine)
t.to_sql('fields', engine)
</code>```

But it does not work. Can someone work it and output the SQL table?

My errors looks like this:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-86-a186308b321b> in <module>()
      1
----> 2 v = pd.DataFrame(data['fields'])
      3 t = pd.io.json.json_normalize(data['fields'], ['model'], ['pk'], meta_prefix='parent_')
      4
      5 v.to_sql('fields', engine)

TypeError: list indices must be integers or slices, not str
</code>```

I want to create two tables. One include 'fields', 'model' and 'pk'.And another table include all the values in 'fields'.

The schema looks like this:
enter image description here

答:
Considering your data which you want to store in Mysql DB. You can use a One-to-One relationship for storing in DB. Instead of using pandas DataFrame it can be handled properly using SQLAlchemy ORM. The following code gives a better understanding to solve this issue. Right now I have considered only few keys from fields key.

from sqlalchemy import Column, Integer, String, Text, DateTime, Float, Boolean, ForeignKey
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import create_engine

total_data = [
    {
        "fields": {
            "bkdate": None,
            "business_credit_card_total_balances": None,
            "created_at": "2016-08-04T00:29:03.067Z",
        },
        "model": "common.prequalresult",
        "pk": 1
    },
    {
        "fields": {
            "bkdate": "2016-08-04T00:29:03.067Z",
            "business_credit_card_total_balances": 23,
            "created_at": "2016-08-04T00:29:03.067Z",
        },
        "model": "common.prequalresult",
        "pk": 2
    },
    {
        "fields": {
            "bkdate": "asdfas",
            "business_credit_card_total_balances": 1111,
            "created_at": "2016-08-04T00:29:03.067Z",
        },
        "model": "common.prequalresult",
        "pk": 3
    }
]

engine = create_engine('mysql://user:password@localhost:5432/my_data', echo=False)

Base = declarative_base()

class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    pk = Column(Integer, primary_key=False)
    model = Column(String(100), nullable=True)
    child = relationship('Comment', backref='article', uselist=False)

class Comment(Base):
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True, autoincrement=True)
    bkdate = Column(String(100), nullable=True)
    business_credit_card_total_balances = Column(Integer, nullable=True)
    created_at = Column(String(100), nullable=True)
    article_id = Column(Integer, ForeignKey('article.id'))

x = Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

for temp_data in total_data:
    pk = temp_data['pk']
    model = temp_data['model']
    bkdate = temp_data['fields']['bkdate']
    business_credit_card_total_balances = temp_data['fields']['business_credit_card_total_balances']
    created_at = temp_data['fields']['created_at']
    parent1 = Article(pk=temp_data['pk'], model=model)
    child = Comment(bkdate=bkdate,
                    business_credit_card_total_balances=business_credit_card_total_balances,
                    created_at=created_at,
                    article=parent1)

    session.add(parent1)
    session.add(child)

session.commit()
```

<p>As field pk given in each dict can be duplicated, so I have created id as a primary key. </p>

<p>Output:</p>

```mysql> select * from article;
+----+------+----------------------+
| id | pk   | model                |
+----+------+----------------------+
|  1 |    1 | common.prequalresult |
|  2 |    2 | common.prequalresult |
|  3 |    3 | common.prequalresult |
+----+------+----------------------+

mysql> select * from comment;
+----+--------------------------+-------------------------------------+--------------------------+------------+
| id | bkdate                   | business_credit_card_total_balances | created_at               | article_id |
+----+--------------------------+-------------------------------------+--------------------------+------------+
|  1 | NULL                     |                                NULL | 2016-08-04T00:29:03.067Z |          1 |
|  2 | 2016-08-04T00:29:03.067Z |                                  23 | 2016-08-04T00:29:03.067Z |          2 |
|  3 | asdfas                   |                                1111 | 2016-08-04T00:29:03.067Z |          3 |
+----+--------------------------+-------------------------------------+--------------------------+------------+
```

Body:
My json data looks like this:

[
    {
        "fields": {
            "bkdate": null,
            "business_credit_card_total_balances": null,
            "business_credit_card_total_limits": null,
            "business_total_monthly_debt_payments": null,
            "business_total_mortgage_monthly_payments": null,
            "created_at": "2016-08-04T00:29:03.067Z",
            "detail_results": null,
            "error_reason": "no reasons",
            "fico_v2": "695",
            "fico_v3": null,
            "loanapp_id": 194,
            "personal_credit_card_total_balances": null,
            "personal_credit_card_total_limits": null,
            "personal_total_monthly_payments": null,
            "report_type": "CreditProfile",
            "result": true,
            "role": "applicant",
            "total_mortgage_monthly_payments": null,
            "username": "cho",
            "version": "CF Microloan",
            "xml_data": "<?xml version=\"1.0\" standalone=\"no\"?><NetConnectResponse xmlns=\"http://www.experian.com/NetConnectResponse\"><CompletionCode>0000</CompletionCode>"
        },
        "model": "common.prequalresult",
        "pk": 1
    }
]

I Want to convert it into SQL table. I tried this:

v = pd.DataFrame(data['fields'])
t = pd.io.json.json_normalize(data['fields'], ['model'], ['pk'], meta_prefix='parent_')

v.to_sql('fields', engine)
t.to_sql('fields', engine)

But it does not work. Can someone work it and output the SQL table?

My errors looks like this:

TypeError                                 Traceback (most recent call last)
<ipython-input-86-a186308b321b> in <module>()
      1
----> 2 v = pd.DataFrame(data['fields'])
      3 t = pd.io.json.json_normalize(data['fields'], ['model'], ['pk'], meta_prefix='parent_')
      4
      5 v.to_sql('fields', engine)

TypeError: list indices must be integers or slices, not str

I want to create two tables. One include 'fields', 'model' and 'pk'.And another table include all the values in 'fields'.

The schema looks like this:
enter image description here

Body:
Considering your data which you want to store in Mysql DB. You can use a One-to-One relationship for storing in DB. Instead of using pandas DataFrame it can be handled properly using SQLAlchemy ORM. The following code gives a better understanding to solve this issue. Right now I have considered only few keys from fields key.

from sqlalchemy import Column, Integer, String, Text, DateTime, Float, Boolean, ForeignKey
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import create_engine

total_data = [
    {
        "fields": {
            "bkdate": None,
            "business_credit_card_total_balances": None,
            "created_at": "2016-08-04T00:29:03.067Z",
        },
        "model": "common.prequalresult",
        "pk": 1
    },
    {
        "fields": {
            "bkdate": "2016-08-04T00:29:03.067Z",
            "business_credit_card_total_balances": 23,
            "created_at": "2016-08-04T00:29:03.067Z",
        },
        "model": "common.prequalresult",
        "pk": 2
    },
    {
        "fields": {
            "bkdate": "asdfas",
            "business_credit_card_total_balances": 1111,
            "created_at": "2016-08-04T00:29:03.067Z",
        },
        "model": "common.prequalresult",
        "pk": 3
    }
]

engine = create_engine('mysql://user:password@localhost:5432/my_data', echo=False)

Base = declarative_base()

class Article(Base):
    __tablename__ = 'article'
    id = Column(Integer, primary_key=True, autoincrement=True)
    pk = Column(Integer, primary_key=False)
    model = Column(String(100), nullable=True)
    child = relationship('Comment', backref='article', uselist=False)

class Comment(Base):
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True, autoincrement=True)
    bkdate = Column(String(100), nullable=True)
    business_credit_card_total_balances = Column(Integer, nullable=True)
    created_at = Column(String(100), nullable=True)
    article_id = Column(Integer, ForeignKey('article.id'))

x = Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

for temp_data in total_data:
    pk = temp_data['pk']
    model = temp_data['model']
    bkdate = temp_data['fields']['bkdate']
    business_credit_card_total_balances = temp_data['fields']['business_credit_card_total_balances']
    created_at = temp_data['fields']['created_at']
    parent1 = Article(pk=temp_data['pk'], model=model)
    child = Comment(bkdate=bkdate,
                    business_credit_card_total_balances=business_credit_card_total_balances,
                    created_at=created_at,
                    article=parent1)

    session.add(parent1)
    session.add(child)

session.commit()

As field pk given in each dict can be duplicated, so I have created id as a primary key.

Output:

mysql> select * from article;
+----+------+----------------------+
| id | pk   | model                |
+----+------+----------------------+
|  1 |    1 | common.prequalresult |
|  2 |    2 | common.prequalresult |
|  3 |    3 | common.prequalresult |
+----+------+----------------------+

mysql> select * from comment;
+----+--------------------------+-------------------------------------+--------------------------+------------+
| id | bkdate                   | business_credit_card_total_balances | created_at               | article_id |
+----+--------------------------+-------------------------------------+--------------------------+------------+
|  1 | NULL                     |                                NULL | 2016-08-04T00:29:03.067Z |          1 |
|  2 | 2016-08-04T00:29:03.067Z |                                  23 | 2016-08-04T00:29:03.067Z |          2 |
|  3 | asdfas                   |                                1111 | 2016-08-04T00:29:03.067Z |          3 |
+----+--------------------------+-------------------------------------+--------------------------+------------+


问:
Accessing ViewBag variables in View
Finally giving up on asking the Google Gods...

I'm trying to access ViewBag variables in my view from the query below.

using (var context = new PrincipalContext(ContextType.Domain))
{
    var un = UserPrincipal.FindByIdentity(context, User.Identity.Name);
    var userinfo = db.Users
                     .Where(x => x.sAMAccountName == un.SamAccountName)
                     .Select(x => new
                      {
                          x.sAMAccountName,
                          x.Id
                      }).First();

    ViewBag.UserInfo = userinfo;
}
```

<p>I see the variables in VS' breakpoint watcher</p>

<p><img src="https://i.stack.imgur.com/2HNEE.png" alt="enter image description here"></p>

<p>However, when I try to access them:</p>

<p><img src="https://i.stack.imgur.com/ASWqy.png" alt="enter image description here"></p>

<p><img src="https://i.stack.imgur.com/R9TkC.png" alt="enter image description here"></p>

<p>Not 100% certain on how I'm supposed to be accessing these? I don't want to iterate through them because they're getting placed in a form as fields. As previously mentioned, the Google Gods were less than helpful.
Thanks!</p>

<p><strong>UPDATE</strong></p>

<p>I took a closer look based on the responses received, regarding casting. Ultimately what I ended up doing was retrieving the entire model and returning that in the ViewBag, and accessing it as such:</p>

```using (var context = new PrincipalContext(ContextType.Domain))
{
     var un = UserPrincipal.FindByIdentity(context, User.Identity.Name);
     User info = new User();
     info = (User)db.Users
                .Where(x => x.sAMAccountName == un.SamAccountName)
                .First();
      ViewBag.User = info;

}
```

<p>And then in the view</p>

```@ViewBag.User.Id
@ViewBag.User.sAMAccountName
```

Ultimately I was looking to access these variables without iterating over them in a loop. When I add a select statement into my query, it begins to complain that I'm trying to cast anonymous strings to a model object. Is one able to retrieve select data from a model in ASP, or do you need to return an entire model set? Now it's just curiosity.
Thank you for the guidance!

答:
With anonymous type object in ViewBag, you cannot access their properties just by using a . operator. That's because the anonymous type is generated as internal. So better approach would be to create a type with the desired properties, like so (say the type is called UserInfo). By creating a separate type that has just the properties needed for the view, you can optimize your query to select just those fields from the database (a common practice).

```<code>ViewBag.UserInfo = db.Users
                     .Where(x => x.sAMAccountName == un.SamAccountName)
                     .Select(x => new UserInfo // the object is now of type UserInfo
                     {
                         sAMAccountName = x.sAMAccountName,
                         Id = x.Id
                     }).First();
</code>```

Then in view file you can access the properties with a cast like so:

```<code>(UserInfo(ViewBag.UserInfo)).sAMAccountName
</code>```

Ugly way to access the properties with reflection in view file (don't do this):

```<code>@{
    string name = ViewBag.UserInfo.GetType().GetProperty("sAMAccountName").GetValue(ViewBag.UserInfo) as string;
}
</code>```

Title: Accessing ViewBag variables in View

Body:
Finally giving up on asking the Google Gods...

I'm trying to access ViewBag variables in my view from the query below.

using (var context = new PrincipalContext(ContextType.Domain))
{
    var un = UserPrincipal.FindByIdentity(context, User.Identity.Name);
    var userinfo = db.Users
                     .Where(x => x.sAMAccountName == un.SamAccountName)
                     .Select(x => new
                      {
                          x.sAMAccountName,
                          x.Id
                      }).First();

    ViewBag.UserInfo = userinfo;
}

I see the variables in VS' breakpoint watcher

However, when I try to access them:

Not 100% certain on how I'm supposed to be accessing these? I don't want to iterate through them because they're getting placed in a form as fields. As previously mentioned, the Google Gods were less than helpful.
Thanks!

UPDATE

I took a closer look based on the responses received, regarding casting. Ultimately what I ended up doing was retrieving the entire model and returning that in the ViewBag, and accessing it as such:

using (var context = new PrincipalContext(ContextType.Domain))
{
     var un = UserPrincipal.FindByIdentity(context, User.Identity.Name);
     User info = new User();
     info = (User)db.Users
                .Where(x => x.sAMAccountName == un.SamAccountName)
                .First();
      ViewBag.User = info;

}

And then in the view

@ViewBag.User.Id
@ViewBag.User.sAMAccountName

Ultimately I was looking to access these variables without iterating over them in a loop. When I add a select statement into my query, it begins to complain that I'm trying to cast anonymous strings to a model object. Is one able to retrieve select data from a model in ASP, or do you need to return an entire model set? Now it's just curiosity.
Thank you for the guidance!

Body:
With anonymous type object in ViewBag, you cannot access their properties just by using a . operator. That's because the anonymous type is generated as internal. So better approach would be to create a type with the desired properties, like so (say the type is called UserInfo). By creating a separate type that has just the properties needed for the view, you can optimize your query to select just those fields from the database (a common practice).

ViewBag.UserInfo = db.Users
                     .Where(x => x.sAMAccountName == un.SamAccountName)
                     .Select(x => new UserInfo // the object is now of type UserInfo
                     {
                         sAMAccountName = x.sAMAccountName,
                         Id = x.Id
                     }).First();

Then in view file you can access the properties with a cast like so:

(UserInfo(ViewBag.UserInfo)).sAMAccountName

Ugly way to access the properties with reflection in view file (don't do this):

@{
    string name = ViewBag.UserInfo.GetType().GetProperty("sAMAccountName").GetValue(ViewBag.UserInfo) as string;
}


问:
Where is the build.gradle file located for my Android project?
Where is the build.gradle file located for my Android project?

I'm trying to follow along with this tutorial, but I can't make necessary changes to my build.gradle file to use the support library.

答:
The location of build.gradle (Project) is in the root project

and the         build.gradle (app) is in the /app/build.gradle of the projet


问:
Inserts not committed until after transaction completes using PlatformTransactionManager
I need to ensure that inserts are committed during the execution of a stored procedure. Using Spring Boot Starter Data JPA 1.5, this was the default behavior for a JpaTransactionManager.  With Spring Boot 2.x, inserts are not committed until the stored procedure completes execution.

So, calling this stored procedure using Spring Boot 2.x transaction mgmt, will not insert after 1 minute:

```<code>CREATE procedure [dbo].[test_insert]
as
begin
    insert into myTempTable(col1)
    values ("1");

    WAITFOR DELAY '00:01';
end
GO
</code>```

But calling it using Spring Boot 1.5 transaction mgmt, will insert immediately which is what I need.

Here's the code. Transaction Manager:

```<code>@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory);
    return transactionManager;
}
</code>```

Repo:

```<code>public interface TestRepository extends Repository<String, Long> {

    @Procedure("test_insert")
    void testInsert();

}
</code>```

Test case:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional(transactionManager="transactionManager")
public class InsertRepositoryTest {

    @Autowired
    private TestRepository testRepo;

    @Test
    public void testInsert() throws SQLException {
        testRepo.testInsert();
    }

}
</code>```

I'm using SQL Server 2016 and its default transaction level is set to READ COMMITTED.

How can I make sure that inserts in a stored procedure are committed immediately during execution?

Update

After a bit more research, I found that with Spring's transaction manager I'm in implicit transaction mode. But when I don't use it, I'm in autocommit. In other words, select @@OPTIONS & 2 returns 2 with Spring's transaction manager and 0 without it. So, I think that explains why I'm seeing differences on when the insert commits. If that's right, then I just need to know how to set autocommit. The default mode must have changed either with Spring or the SQL Server jdbc driver (I was using 4.2 and now using 8.2.0.jre8).

Update 2

Why is it important that some other process can see the insert into mytempTable before the stored procedure completes? Because in the production stored procedure, it does the insert, calls off into some service (that I believe selects data from that row and inserts data into another table), and then the sp waitfor data to appear in the table inserted by the service. So, in the case that the service can't see insert, the stored procedure hangs waiting for the service to insert in the other table.

I think the solution is to not use an explicit transaction and just let SQL Server default to auto commit. Unfortunately, that also means no rollback if something goes wrong in the stored procedure. But given the stored procedure and the service are third party components that I can't change, I suppose that is my only option. Still wondering why the behavior was different between Spring Boot 1.5 and 2.x or the JDBC driver.

Update 3

It turns out that there is no difference in the behavior between Spring Boot 1.5 and 2.x or the JDBC driver versions. That is, the inserts never occur until after the transaction completes. The reason that I observed the difference in behavior has something to do with the fact that I was testing using Spring Boot 1.5 in an older project and that older project is a composite project with two data source and two transaction managers unlike my Spring Boot 2.x project. Not sure why that or what would make insert occur immediately in the old project but it does.

At any rate, looking at SQL Server logs, I can confirm that regardless of Spring / JDBC version, it inserts immediately when auto-commit mode is on.

答:
If executing a stored procedure follows the 'transactional-write-behind' pattern of standard entity operations then the normal behavior is for SQL statements to be queued until such time as the transaction completes.

Spring Data repositories are transactional by default so even without the explicit @Transactional(transactionManager="transactionManager") in your test a transaction is in operation.

https://vladmihalcea.com/a-beginners-guide-to-jpahibernate-flush-strategies/ (assuming you are using Hibernate here but probably similar concepts in other JPA implementations).

Try this to trigger an immediate flush:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional(transactionManager="transactionManager")
public class InsertRepositoryTest {

    @Autowired
    private TestRepository testRepo;

    @PersistenceContext
    primate EntityManager em;

    @Test
    public void testInsert() throws SQLException {
        testRepo.testInsert();
        em.flush(); //write all buffered SQL statements
    }
}
</code>```

Body:
I need to ensure that inserts are committed during the execution of a stored procedure. Using Spring Boot Starter Data JPA 1.5, this was the default behavior for a JpaTransactionManager.  With Spring Boot 2.x, inserts are not committed until the stored procedure completes execution.

So, calling this stored procedure using Spring Boot 2.x transaction mgmt, will not insert after 1 minute:

CREATE procedure [dbo].[test_insert]
as
begin
    insert into myTempTable(col1)
    values ("1");

    WAITFOR DELAY '00:01';
end
GO

But calling it using Spring Boot 1.5 transaction mgmt, will insert immediately which is what I need.

Here's the code. Transaction Manager:

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory);
    return transactionManager;
}

Repo:

public interface TestRepository extends Repository<String, Long> {

    @Procedure("test_insert")
    void testInsert();

}

Test case:

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional(transactionManager="transactionManager")
public class InsertRepositoryTest {

    @Autowired
    private TestRepository testRepo;

    @Test
    public void testInsert() throws SQLException {
        testRepo.testInsert();
    }

}

I'm using SQL Server 2016 and its default transaction level is set to READ COMMITTED.

How can I make sure that inserts in a stored procedure are committed immediately during execution?

Update

After a bit more research, I found that with Spring's transaction manager I'm in implicit transaction mode. But when I don't use it, I'm in autocommit. In other words, select @@OPTIONS & 2 returns 2 with Spring's transaction manager and 0 without it. So, I think that explains why I'm seeing differences on when the insert commits. If that's right, then I just need to know how to set autocommit. The default mode must have changed either with Spring or the SQL Server jdbc driver (I was using 4.2 and now using 8.2.0.jre8).

Update 2

Why is it important that some other process can see the insert into mytempTable before the stored procedure completes? Because in the production stored procedure, it does the insert, calls off into some service (that I believe selects data from that row and inserts data into another table), and then the sp waitfor data to appear in the table inserted by the service. So, in the case that the service can't see insert, the stored procedure hangs waiting for the service to insert in the other table.

I think the solution is to not use an explicit transaction and just let SQL Server default to auto commit. Unfortunately, that also means no rollback if something goes wrong in the stored procedure. But given the stored procedure and the service are third party components that I can't change, I suppose that is my only option. Still wondering why the behavior was different between Spring Boot 1.5 and 2.x or the JDBC driver.

Update 3

It turns out that there is no difference in the behavior between Spring Boot 1.5 and 2.x or the JDBC driver versions. That is, the inserts never occur until after the transaction completes. The reason that I observed the difference in behavior has something to do with the fact that I was testing using Spring Boot 1.5 in an older project and that older project is a composite project with two data source and two transaction managers unlike my Spring Boot 2.x project. Not sure why that or what would make insert occur immediately in the old project but it does.

At any rate, looking at SQL Server logs, I can confirm that regardless of Spring / JDBC version, it inserts immediately when auto-commit mode is on.

Body:
If executing a stored procedure follows the 'transactional-write-behind' pattern of standard entity operations then the normal behavior is for SQL statements to be queued until such time as the transaction completes.

Spring Data repositories are transactional by default so even without the explicit @Transactional(transactionManager="transactionManager") in your test a transaction is in operation.

https://vladmihalcea.com/a-beginners-guide-to-jpahibernate-flush-strategies/ (assuming you are using Hibernate here but probably similar concepts in other JPA implementations).

Try this to trigger an immediate flush:

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional(transactionManager="transactionManager")
public class InsertRepositoryTest {

    @Autowired
    private TestRepository testRepo;

    @PersistenceContext
    primate EntityManager em;

    @Test
    public void testInsert() throws SQLException {
        testRepo.testInsert();
        em.flush(); //write all buffered SQL statements
    }
}


问:
How can I remove the legend title in ggplot2?
I have a question concerning the legend in ggplot2.

Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:

```<code>carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)
</code>```

I make a simple bar plot:

```<code>require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p
</code>```

My question is: is there a way to remove the title ('Type') from the legend?

Thanks!

答:
You can use labs:

```<code>p + labs(fill="")
</code>```

Body:
I have a question concerning the legend in ggplot2.

Say I have a hypothetical dataset about mean carrot length for two different colours at two farms:

carrots<-NULL
carrots$Farm<-rep(c("X","Y"),2)
carrots$Type<-rep(c("Orange","Purple"),each=2)
carrots$MeanLength<-c(10,6,4,2)
carrots<-data.frame(carrots)

I make a simple bar plot:

require(ggplot2)
p<-ggplot(carrots,aes(y=MeanLength,x=Farm,fill=Type)) +
geom_bar(position="dodge") +
opts(legend.position="top")
p

My question is: is there a way to remove the title ('Type') from the legend?

Thanks!

Body:
You can use labs:

p + labs(fill="")


问:
Unable to display overlay template in ag-grid when url fails
I'm trying to show overlay template when the service URL fails in ag-grid.

But the overlay message is not displaying as expected.

I wanted to show Service URL failed message when the http request fails. And another overlay message Please wait data is loading when data is actually loading in the grid.

I'm unable to display the overlay message when the url gets failed. it always show's the first message

How do i fix this ?

This my link to the plunker project : https://plnkr.co/edit/MzpwnE0enLx2PVJOFUyn?p=preview

Note: to replicate the issue, give some invalid http url

this._Service.httpPost(b, a)
  .retryWhen((err) => {
    return err.scan((retryCount) => {
      retryCount += 1;
      if (retryCount < 3) {
        return;
      } else {
        this.gridOptions.overlayNoRowsTemplate = 'Problem with service link. Please try again later';
        this.gridOptions.api.showNoRowsOverlay();
        throw (err);
      }
    }, 0).delay(1000);
  })
  .catch(err => {
    console.log(err);
    return Observable.of(err);
  });```

答:
If you just want to change the message, modify the localeTextFunc of the grid API to return a different message. For this example to work you should bind gridOptions to the grid e.g. <ag-grid-angular [gridOptions]="gridOptions"..., then, on error call ShowErrorOverlay().

```<code>import { GridOptions } from '@ag-grid-community/core';
</code>```

...

```<code>gridOptions: GridOptions;
private origLocaleTextFunc: any;
private errLocaleTextFunc: any;

ngInit() {
    this.gridOptions = this.getDefaultGridOptions(this);
    this.origLocaleTextFunc = this.gridOptions.localeTextFunc;
    this.errLocaleTextFunc = (key, defaultValue) => {
        if (key === 'noRowsToShow') {
            return 'Error!';
        } else {
            return this.origLocaleTextFunc(key, defaultValue);
        }
    };
}

getDefaultGridOptions(context: any): GridOptions {
    const rv = {} as GridOptions;
    rv.localeTextFunc = (key, defaultValue) => {
        switch (key) {
            case 'noRowsToShow': return 'No rows!';
            default: return defaultValue;
        }
    };

    rv.context = { componentParent: context };
    return rv;
}

showErrorOverlay() {
    this.gridOptions.localeTextFunc = this.errLocaleTextFunc; // set error msgs
    this.gridOptions.api.showNoRowsOverlay();
    this.gridOptions.localeTextFunc = this.origLocaleTextFunc; // set default msgs
}
</code>```

If you need to style the message, look into https://www.ag-grid.com/javascript-grid-overlay-component/ or just modify your .ag-overlay-no-rows-wrapper and    .ag-overlay-no-rows-center classes

Body:
If you just want to change the message, modify the localeTextFunc of the grid API to return a different message. For this example to work you should bind gridOptions to the grid e.g. <ag-grid-angular [gridOptions]="gridOptions"..., then, on error call ShowErrorOverlay().

import { GridOptions } from '@ag-grid-community/core';

...

gridOptions: GridOptions;
private origLocaleTextFunc: any;
private errLocaleTextFunc: any;

ngInit() {
    this.gridOptions = this.getDefaultGridOptions(this);
    this.origLocaleTextFunc = this.gridOptions.localeTextFunc;
    this.errLocaleTextFunc = (key, defaultValue) => {
        if (key === 'noRowsToShow') {
            return 'Error!';
        } else {
            return this.origLocaleTextFunc(key, defaultValue);
        }
    };
}

getDefaultGridOptions(context: any): GridOptions {
    const rv = {} as GridOptions;
    rv.localeTextFunc = (key, defaultValue) => {
        switch (key) {
            case 'noRowsToShow': return 'No rows!';
            default: return defaultValue;
        }
    };

    rv.context = { componentParent: context };
    return rv;
}

showErrorOverlay() {
    this.gridOptions.localeTextFunc = this.errLocaleTextFunc; // set error msgs
    this.gridOptions.api.showNoRowsOverlay();
    this.gridOptions.localeTextFunc = this.origLocaleTextFunc; // set default msgs
}

If you need to style the message, look into https://www.ag-grid.com/javascript-grid-overlay-component/ or just modify your .ag-overlay-no-rows-wrapper and    .ag-overlay-no-rows-center classes


问:
Test Oracle SQL queries in subset of data in big table
I have some big tables in an Oracle database, representing transactions etc.

Is there a way in Oracle/SQL to try a query on a subset of the data? Just to speed up the time it takes to try different queries and feel confident that you’ve got the logic right? Once I feel confident that my query is correct I want to run it on the full dataset.

答:
You can limit your result set by the pseudo column ROWNUM.
In your where clause, add:

```<code>and rownum < 100  -- or any number you want
</code>```

And this will put a hard stop at that number of rows.

Body:
You can limit your result set by the pseudo column ROWNUM.
In your where clause, add:

and rownum < 100  -- or any number you want

And this will put a hard stop at that number of rows.


问:
Material pagination dropdown out of place

Issue

I am currently implementing a <mat-table> with a <mat-paginator> attached to it. The only problem is that the dropdown for items per page is being offset to the left. For what seems like outside of the Bootstrap container.

Here is an image of what is happening. You can see the location of the dropdown and the location of the items are completely wrong.

Code

My entire site is inside of a bootstrap container so my app.component.html basically looks like this:

```<code><app-header></app-header>
<div class="container mt-3">
  <router-outlet></router-outlet>
</div>
<app-footer></app-footer>
</code>```

The page in questions is just a simple material table with the pagination added to the bottom.

```<code><div class="row">
  <div class="col-md-12">
    <mat-table *ngIf="items" [dataSource]="items" matSort>

      <!-- ID Column -->
      <ng-container matColumnDef="type">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Type </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.type}} </mat-cell>
      </ng-container>

      <!-- Provider Column -->
      <ng-container matColumnDef="provider">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Provider </mat-header-cell>
        <mat-cell *matCellDef="let row"> <a href="https://eosauthority.com/account/{{row.provider}}" target="_blank">{{row.provider}}</a> </mat-cell>
      </ng-container>

      <!-- Name Column -->
      <ng-container matColumnDef="url">
        <mat-header-cell *matHeaderCellDef mat-sort-header> URL </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.url}} </mat-cell>
      </ng-container>

      <!-- Color Column -->
      <ng-container matColumnDef="country">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Country </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.country}} - <span class="flag-icon flag-icon-{{row.country | lowercase}}"></span> </mat-cell>
      </ng-container>

      <!-- Color Column -->
      <ng-container matColumnDef="updated_on">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Updated </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.updated_on}} </mat-cell>
      </ng-container>

      <mat-header-row *matHeaderRowDef="['type', 'provider', 'url', 'country', 'updated_on']"></mat-header-row>
      <mat-row *matRowDef="let row; columns: ['type', 'provider', 'url', 'country', 'updated_on']">
      </mat-row>
    </mat-table>

    <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
  </div>
</div>
</code>```

答:
In most projects, be it boostrap-themed or material-themed, there is usually a theme folder, you would have files like theme-variable.scss and theme.scss for Bootstrap projects, while in material projects, you'd find material-theme.css or material-theme.scss.

The last two files are very important for angular-material components to be rendered properly, even after importing the modules responsible for the component, you need the files mentioned above.

After ensuring you have those two files, you want to import them in your styles.css file with this line: @import './theme/material-theme.css';

Once the above steps are taken, the table or whichever angular-material component will render properly.

Body:
Issue

I am currently implementing a <mat-table> with a <mat-paginator> attached to it. The only problem is that the dropdown for items per page is being offset to the left. For what seems like outside of the Bootstrap container.

Here is an image of what is happening. You can see the location of the dropdown and the location of the items are completely wrong.

Code

My entire site is inside of a bootstrap container so my app.component.html basically looks like this:

<app-header></app-header>

  <router-outlet></router-outlet>

<app-footer></app-footer>

The page in questions is just a simple material table with the pagination added to the bottom.

    <mat-table *ngIf="items" [dataSource]="items" matSort>

      <ng-container matColumnDef="type">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Type </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.type}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="provider">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Provider </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.provider}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="url">
        <mat-header-cell *matHeaderCellDef mat-sort-header> URL </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.url}} </mat-cell>
      </ng-container>

      <ng-container matColumnDef="country">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Country </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.country}} -  </mat-cell>
      </ng-container>

      <ng-container matColumnDef="updated_on">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Updated </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.updated_on}} </mat-cell>
      </ng-container>

      <mat-header-row *matHeaderRowDef="['type', 'provider', 'url', 'country', 'updated_on']"></mat-header-row>
      <mat-row *matRowDef="let row; columns: ['type', 'provider', 'url', 'country', 'updated_on']">
      </mat-row>
    </mat-table>

    <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>


问:
jQuery, optimal usage question
I don't know how jQuery works under the hood, but let's say that at some point I create a jQuery object:

```<code>var thingy = $('#thingy');
</code>```

Further down in the code, is there any difference in reusing thingy:

```<code>thingy.empty();
</code>```

versus just making the jQuery again? :

```<code>$('#thingy').empty();
</code>```

I guess in the second case, we have to create another jQuery object, but I suspect that is trivial.  What I'm trying to avoid by just reusing the variable is doing a DOM search for matching elements.  Perhaps this search occurs in either case anyway?

My initial assumption was that the the document is scanned upon the creation of the $ object.  But then it occurred to me that the $ object might just be an iterator that scans the document again every time you execute one of its methods.  I guess this is the crux of my question.

答:
The answers to these SO questions indicate that it will be faster if you reuse the jQuery object :

Is referencing a selector faster in jquery than actually calling the selector? if so, how much does it make a difference?

Most efficient way to re-use jQuery-selected elements

Title: jQuery, optimal usage question

Body:
I don't know how jQuery works under the hood, but let's say that at some point I create a jQuery object:

var thingy = $('#thingy');

Further down in the code, is there any difference in reusing thingy:

thingy.empty();

versus just making the jQuery again? :

$('#thingy').empty();

I guess in the second case, we have to create another jQuery object, but I suspect that is trivial.  What I'm trying to avoid by just reusing the variable is doing a DOM search for matching elements.  Perhaps this search occurs in either case anyway?

My initial assumption was that the the document is scanned upon the creation of the $ object.  But then it occurred to me that the $ object might just be an iterator that scans the document again every time you execute one of its methods.  I guess this is the crux of my question.


问:
Dividing within a column based on values of other columns in SQL Server
Having some trouble solving this.

```<code>store key  promotion key  sales year  average weekly sales          *Desired Output Column*
1               1           2007             100                        1 (100 / by itself)
1               1           2008             120                        1 (120 / by itself)
1               2           2008             240                        2 (240 / 120)
1               3           2007              50                        0.5 (50 / 100)
1               4           2007              70                        0.7 (70 / 100)
1               5           2007              80                        0.8 (80 / 100)
1               3           2008              180                       1.5 (180 / 120)
2               1           2009              150                       1 (150 / by itself)
2               2           2009              200                       1.3 (200 / 150)
2               3           2007              300                       Null (no baseline value in 2007)
</code>```

Each store key and sales year has a baseline value indicated by promotion key 1. All other promotion keys reflect entries I want divided into the baseline value for the same store key and sales year.

So in the above example, I want all entries with store key 1 and year 2007 divided by the baseline value for that year and store (i.e., promotion key 1 for the same store key of 1 and sales year of 2007). Similarly, all entries with store key 1 and year 2008 divided by the baseline value for that year (promotion key 1 for store 1 and sales year 2008). Likewise for store 2, I want store key 2 and year 2009 for promotion key 2 divided by the baseline value (promotion key 1, store key 2, and year 2009). As there is no baseline value (promotion key 1) for store key 2 in 2007, that entry will produce a null.

答:
I think you want:</p>

```<code>select t.*,
       (avgweeklysales  * 1.0 /
        max(case when promotionkey = 1 then avgweeklysales end) over (partition by storekey, salesyear)
       ) as desired_output
from t;
</code>```

Body:
Having some trouble solving this.

store key  promotion key  sales year  average weekly sales          *Desired Output Column*
1               1           2007             100                        1 (100 / by itself)
1               1           2008             120                        1 (120 / by itself)
1               2           2008             240                        2 (240 / 120)
1               3           2007              50                        0.5 (50 / 100)
1               4           2007              70                        0.7 (70 / 100)
1               5           2007              80                        0.8 (80 / 100)
1               3           2008              180                       1.5 (180 / 120)
2               1           2009              150                       1 (150 / by itself)
2               2           2009              200                       1.3 (200 / 150)
2               3           2007              300                       Null (no baseline value in 2007)

Each store key and sales year has a baseline value indicated by promotion key 1. All other promotion keys reflect entries I want divided into the baseline value for the same store key and sales year.

So in the above example, I want all entries with store key 1 and year 2007 divided by the baseline value for that year and store (i.e., promotion key 1 for the same store key of 1 and sales year of 2007). Similarly, all entries with store key 1 and year 2008 divided by the baseline value for that year (promotion key 1 for store 1 and sales year 2008). Likewise for store 2, I want store key 2 and year 2009 for promotion key 2 divided by the baseline value (promotion key 1, store key 2, and year 2009). As there is no baseline value (promotion key 1) for store key 2 in 2007, that entry will produce a null.

Body:
I think you want:

select t.*,
       (avgweeklysales  * 1.0 /
        max(case when promotionkey = 1 then avgweeklysales end) over (partition by storekey, salesyear)
       ) as desired_output
from t;