问:
CSS3 opacity property to one of the background image
```<code>background: url('./images/pattern.png'), linear-gradient(to bottom right, rgb(62,131,255), rgb(64,126,253), rgb(99,22,203), rgb(122,5,240));
</code>```

this is the above code where I want to apply opacity to the png image only and not the linear-gradient colour. Is it possible to do so?

Thanks in advance.

答:
You can use ::after pseudo-element.

```<code>div#bg {
    /* Assuming other properties are set */
    background: linear-gradient(to bottom right, rgb(62,131,255), rgb(64,126,253), rgb(99,22,203), rgb(122,5,240));
}

div#bg::after {
    content: '';
    display: block;
    width: 100%;
    height: 100%;
    background: url('./images/pattern.png');
    opacity: 0.5;
}
</code>```

Working example.

Read about CSS pesudo-element.

Body:
background: url('./images/pattern.png'), linear-gradient(to bottom right, rgb(62,131,255), rgb(64,126,253), rgb(99,22,203), rgb(122,5,240));

this is the above code where I want to apply opacity to the png image only and not the linear-gradient colour. Is it possible to do so?

Thanks in advance.

Body:
You can use ::after pseudo-element.

div#bg {
    /* Assuming other properties are set */
    background: linear-gradient(to bottom right, rgb(62,131,255), rgb(64,126,253), rgb(99,22,203), rgb(122,5,240));
}

div#bg::after {
    content: '';
    display: block;
    width: 100%;
    height: 100%;
    background: url('./images/pattern.png');
    opacity: 0.5;
}

Working example.

Read about CSS pesudo-element.


来源: stackexchange

问:
Tampermonkey script to wait for elements then fill them in
I'm trying to finish a script that fills out a checkout form. It needs to click a button with no id or name then fill out the rest of the form that appears. The code I have to click the button is:

```<code>document.querySelector('input[type="submit"][value="continue"]').click();
</code>```

but that is not working for me, the other elements will appear after that, my script:

```<code>// ==UserScript==
// @name         Script
// @include      https://checkout.bigcartel.com/*
// @include      http://*.bigcartel.com/product
// @include      http://*.bigcartel.com/cart
// @grant        none
// ==/UserScript==

// on "/cart" page click checkout button
if (window.location.origin !== "https://checkout.bigcartel.com") document.getElementsByName("checkout")[0].click();
else {
    // fill first three form fields
    document.getElementById("buyer_first_name").value = "John";
    document.getElementById("buyer_last_name").value = "Smith";
    document.getElementById("buyer_email").value = "john@doe.com";
    //click button for next section
    document.querySelector('input[type="submit"][value="continue"]').click();
}
</code>```

答:
Refer to Choosing and activating the right controls on an AJAX-driven site, and use a utility like waitForKeyElements().

Here's how to wait for elements and chain states (in case it's needed) for the submit click:

```<code>// ==UserScript==
// @name     _Wait for elements overkill and on separate pages
// @match    https://checkout.bigcartel.com/*
// @match    *://*.bigcartel.com/product*
// @match    *://*.bigcartel.com/cart*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

//-- Track form field state, just in case. *Might* be needed for multistage forms...
var glblFlags = {firstFlld: false, lastFlld: false, emailFlld: false};

if (location.hostname === "checkout.bigcartel.com") {
    /*-- Fill first three form fields.
        Use separate WFKE's for multistage.  (Fun overkill for simpler forms.)
    */
    waitForKeyElements ("#buyer_first_name", jNd => {SetValue (jNd, "firstFlld", "John"); }, true);
    waitForKeyElements ("#buyer_last_name",  jNd => {SetValue (jNd, "lastFlld",  "Smith"); }, true);
    waitForKeyElements ("#buyer_email",      jNd => {SetValue (jNd, "emailFlld", "john@doe.com"); }, true);

    //-- Click button for next section
    waitForKeyElements (
        "form[action='/shipping'] button:contains('Next')",
        clickWhenFormIsReady, true
    );
}
else if (location.pathname === "/cart") {
    //-- On "/cart" page click checkout button
    waitForKeyElements ("[name='checkout']", clickNode, true);
}

function clickNode (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

function SetValue (jNode, flagVarName, newValue) {
    jNode.val (newValue);
    glblFlags[flagVarName] = true;
}

function clickWhenFormIsReady (jNode) {
    //-- Keep waiting if all flags are not true (form not yet filled out):
    for (let prpName in glblFlags) {
        if (glblFlags.hasOwnProperty (prpName) ) {
            if (glblFlags[prpName] === false)
                return true;
        }
    }
    clickNode (jNode);
}
</code>```

To add additional form fields, you would:

Add a new "filled" property to the glblFlagsobject.  For example:

```<code>var glblFlags = {firstFlld: false, lastFlld: false, emailFlld: false, phoneFlld: false};
</code>```

Add a new waitForKeyElements line to the first if section.  For example:

```<code>    waitForKeyElements ("#buyer_phone", jNd => {SetValue (jNd, "phoneFlld", "800-867-5309"); }, true);
</code>```

The second parameter to SetValue() is the name of the property you added in step 1.

The third parameter to SetValue() is the value you wish to fill in the form field with.

Some form controls may require special handling.  That's beyond the scope of this question.  Search around and then open a new question, if needed.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to finish a script that fills out a checkout form. It needs to click a button with no id or name then fill out the rest of the form that appears. The code I have to click the button is:

document.querySelector('input[type="submit"][value="continue"]').click();

but that is not working for me, the other elements will appear after that, my script:

// ==UserScript==
// @name         Script
// @include      https://checkout.bigcartel.com/*
// @include      http://*.bigcartel.com/product
// @include      http://*.bigcartel.com/cart
// @grant        none
// ==/UserScript==

// on "/cart" page click checkout button
if (window.location.origin !== "https://checkout.bigcartel.com") document.getElementsByName("checkout")[0].click();
else {
    // fill first three form fields
    document.getElementById("buyer_first_name").value = "John";
    document.getElementById("buyer_last_name").value = "Smith";
    document.getElementById("buyer_email").value = "john@doe.com";
    //click button for next section
    document.querySelector('input[type="submit"][value="continue"]').click();
}

Body:
Refer to Choosing and activating the right controls on an AJAX-driven site, and use a utility like waitForKeyElements().

Here's how to wait for elements and chain states (in case it's needed) for the submit click:

// ==UserScript==
// @name     _Wait for elements overkill and on separate pages
// @match    https://checkout.bigcartel.com/*
// @match    *://*.bigcartel.com/product*
// @match    *://*.bigcartel.com/cart*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
//- The @grant directive is needed to restore the proper sandbox.

//-- Track form field state, just in case. *Might* be needed for multistage forms...
var glblFlags = {firstFlld: false, lastFlld: false, emailFlld: false};

if (location.hostname === "checkout.bigcartel.com") {
    /*-- Fill first three form fields.
        Use separate WFKE's for multistage.  (Fun overkill for simpler forms.)
    */
    waitForKeyElements ("#buyer_first_name", jNd => {SetValue (jNd, "firstFlld", "John"); }, true);
    waitForKeyElements ("#buyer_last_name",  jNd => {SetValue (jNd, "lastFlld",  "Smith"); }, true);
    waitForKeyElements ("#buyer_email",      jNd => {SetValue (jNd, "emailFlld", "john@doe.com"); }, true);

    //-- Click button for next section
    waitForKeyElements (
        "form[action='/shipping'] button:contains('Next')",
        clickWhenFormIsReady, true
    );
}
else if (location.pathname === "/cart") {
    //-- On "/cart" page click checkout button
    waitForKeyElements ("[name='checkout']", clickNode, true);
}

function clickNode (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

function SetValue (jNode, flagVarName, newValue) {
    jNode.val (newValue);
    glblFlags[flagVarName] = true;
}

function clickWhenFormIsReady (jNode) {
    //-- Keep waiting if all flags are not true (form not yet filled out):
    for (let prpName in glblFlags) {
        if (glblFlags.hasOwnProperty (prpName) ) {
            if (glblFlags[prpName] === false)
                return true;
        }
    }
    clickNode (jNode);
}

To add additional form fields, you would:

Add a new "filled" property to the glblFlagsobject.  For example:

var glblFlags = {firstFlld: false, lastFlld: false, emailFlld: false, phoneFlld: false};

Add a new waitForKeyElements line to the first if section.  For example:

    waitForKeyElements ("#buyer_phone", jNd => {SetValue (jNd, "phoneFlld", "800-867-5309"); }, true);

The second parameter to SetValue() is the name of the property you added in step 1.

The third parameter to SetValue() is the value you wish to fill in the form field with.

Some form controls may require special handling.  That's beyond the scope of this question.  Search around and then open a new question, if needed.


问:
read remote xml from server using c#
Hello i am trying to get simple xml file from server and to read the data so i can convert it to list. I was try few lib and code with no success so far. I am getting the xml content in one line without any tags <> and the count is always 0 zero. The XML string. I need to get the data that inside camp tag

```<code><campaigns>
 <mainPage>http://example.com</mainPage>
 <orderPage>https://www.example.co.il/adver/</orderPage>
 <totalCount>3</totalCount>
 <onLineCount>2</onLineCount>
  <campaignList>
   <camp id="557">
    <name>test1</name>
    <status>on</status>
    <rating>5</rating>
    <url>http://example.com/557</url>
  </camp>
  <camp id="559">
   <name>test1</name>
   <status>on</status>
   <rating>5</rating>
   <url>http://example.com/559</url>
 </camp>
 <camp id="660">
  <name>test1</name>
  <status>off</status>
  <rating>5</rating>
  <url>http://example.com/660</url>
 </camp>
</campaignList>
</code>```

And the c# code i am trying so far

```<code>XElement xelement = XElement.Load("http://example.com/test.xml");

    var name = from nm in xelement.Elements("camp")
               where (string)nm.Element("status") == "on"
               select nm;

    Response.Write(name.Count());

    foreach (XElement xEle in name)
    {
        Response.Write(xEle);
    }
</code>```

答: XElement.Elements() means search in children tags. I think what you need is Descendants() or xelement.Element("campaigns").Element("campaignList").Elements("camp")

Title: read remote xml from server using c#

Body:
Hello i am trying to get simple xml file from server and to read the data so i can convert it to list. I was try few lib and code with no success so far. I am getting the xml content in one line without any tags <> and the count is always 0 zero. The XML string. I need to get the data that inside camp tag

<campaigns>
 <mainPage>http://example.com</mainPage>
 <orderPage>https://www.example.co.il/adver/</orderPage>
 <totalCount>3</totalCount>
 <onLineCount>2</onLineCount>
  <campaignList>
   <camp id="557">
    <name>test1</name>
    <status>on</status>
    <rating>5</rating>
    <url>http://example.com/557</url>
  </camp>
  <camp id="559">
   <name>test1</name>
   <status>on</status>
   <rating>5</rating>
   <url>http://example.com/559</url>
 </camp>
 <camp id="660">
  <name>test1</name>
  <status>off</status>
  <rating>5</rating>
  <url>http://example.com/660</url>
 </camp>
</campaignList>

And the c# code i am trying so far

XElement xelement = XElement.Load("http://example.com/test.xml");

    var name = from nm in xelement.Elements("camp")
               where (string)nm.Element("status") == "on"
               select nm;

    Response.Write(name.Count());

    foreach (XElement xEle in name)
    {
        Response.Write(xEle);
    }


问:
how to set textview horizontally inside linearlayout
```<code>  <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="2">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorSlate"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/hello"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#5d737e"
                        android:padding="20dp"
                        android:text="₹ 250.00"
                        android:textColor="@color/colorWhite" />

                </LinearLayout>

                <LinearLayout
                    android:id="@+id/world"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorTurquoiseBlue"
                    android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
                    android:orientation="horizontal"
                    android:padding="20dp"
                    android:weightSum="1">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight=".5"
                        android:fontFamily="sans-serif-medium"
                        android:letterSpacing="-0.03"
                        android:text="Go premium"
                        android:textColor="@color/colorWhite"
                        android:textSize="14.4sp"
                        android:textStyle="normal" />

                    <ImageView
                        android:layout_width="8dp"
                        android:layout_height="14dp"
                        android:layout_gravity="center"
                        android:layout_weight=".5"
                        app:srcCompat="@drawable/ic_arrow_white"

                        />
                </LinearLayout>
            </LinearLayout>

        </RelativeLayout>
</code>```

This is my xml i am trying to display text horizontally in first linear-layout but when i try to insert another text-view below text-view inside linear-layout i am my first linear-layout get increase not fit with second layout please suggest me how to achieve this  i want set text below 200 in given screen

答:
Use the layout below . I have changes some attributes to default you can reset them as per your requirement.</p>

```<code> <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="2">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@color/blue_end"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/hello"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="₹ 250.00"
            android:textColor="#FFFFFF" />

        <TextView
            android:id="@+id/subscription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="4dp"
            android:text="Subscription"
            android:textColor="#FFFFFF" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/world"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@color/transparent_black"
        android:orientation="horizontal"
        android:padding="20dp"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:fontFamily="sans-serif-medium"
            android:letterSpacing="-0.03"
            android:text="Go premium"
            android:textSize="14.4sp"
            android:textStyle="normal" />

        <ImageView
            android:layout_width="8dp"
            android:layout_height="14dp"
            android:layout_gravity="center"
            android:layout_weight=".5"
            android:src="@mipmap/ic_launcher" />
    </LinearLayout>
</LinearLayout>
</code>```

Body:
  <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="2">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorSlate"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/hello"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#5d737e"
                        android:padding="20dp"
                        android:text="₹ 250.00"
                        android:textColor="@color/colorWhite" />

                </LinearLayout>

                <LinearLayout
                    android:id="@+id/world"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorTurquoiseBlue"
                    android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
                    android:orientation="horizontal"
                    android:padding="20dp"
                    android:weightSum="1">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight=".5"
                        android:fontFamily="sans-serif-medium"
                        android:letterSpacing="-0.03"
                        android:text="Go premium"
                        android:textColor="@color/colorWhite"
                        android:textSize="14.4sp"
                        android:textStyle="normal" />

                    <ImageView
                        android:layout_width="8dp"
                        android:layout_height="14dp"
                        android:layout_gravity="center"
                        android:layout_weight=".5"
                        app:srcCompat="@drawable/ic_arrow_white"

                        />
                </LinearLayout>
            </LinearLayout>

        </RelativeLayout>

This is my xml i am trying to display text horizontally in first linear-layout but when i try to insert another text-view below text-view inside linear-layout i am my first linear-layout get increase not fit with second layout please suggest me how to achieve this  i want set text below 200 in given screen

Body:
Use the layout below . I have changes some attributes to default you can reset them as per your requirement.

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="2">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@color/blue_end"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/hello"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="₹ 250.00"
            android:textColor="#FFFFFF" />

        <TextView
            android:id="@+id/subscription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="4dp"
            android:text="Subscription"
            android:textColor="#FFFFFF" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/world"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@color/transparent_black"
        android:orientation="horizontal"
        android:padding="20dp"
        android:weightSum="1">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:fontFamily="sans-serif-medium"
            android:letterSpacing="-0.03"
            android:text="Go premium"
            android:textSize="14.4sp"
            android:textStyle="normal" />

        <ImageView
            android:layout_width="8dp"
            android:layout_height="14dp"
            android:layout_gravity="center"
            android:layout_weight=".5"
            android:src="@mipmap/ic_launcher" />
    </LinearLayout>
</LinearLayout>


问:
Celery does not registering tasks

Hello! I just started to use Celery with Django. I've a task that i need to be periodic. In admin interface I can see my task in dropdown list named "Task (registered):". But when Celery Beat tries to execute it NotRegistered exception is thrown.

Python 3.5.2, Django 1.11.4, Celery 4.1, django-celery-beat 1.1.0, django-celery-results 1.0.1

Part of settings.py related to celery:

```<code>CELERY_BROKER_URL = 'amqp://user:*****@192.168.X.X/proj'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_RESULT_BACKEND = 'django-db'
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Europe/Moscow'
</code>```

celery.py and proj/__init__.py are identical to documentation examples.

proj/celery.py:

```<code>from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

app = Celery('proj')

app.config_from_object(settings, namespace='CELERY')

app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))
</code>```

proj/__init__.py:

```<code>from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app

__all__ = ['celery_app']
</code>```

tasks.py:

```<code>from celery import shared_task
from core.backend.files import SFTP

@shared_task
def load_files_from_sftp():
    ftp = SFTP()
    ftp.get_files()
</code>```

I get the following json result:
{"exc_message": "'core.tasks.load_files_from_sftp'", "exc_type": "NotRegistered"}

If I try to use celery.task.control.inspect() from shell, it is only debug_task() there. Just stuck! ( I'll be grateful for any help.

答:
As @MuhammadShoaib wrote, it's just one thing:

```<code>from django.apps import apps

app.config_from_object(settings)
app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])
</code>```

instead of

```<code>app.autodiscover_tasks()
</code>```

why this is not in the documentation?...

Title: Celery does not registering tasks

Body:
Hello! I just started to use Celery with Django. I've a task that i need to be periodic. In admin interface I can see my task in dropdown list named "Task (registered):". But when Celery Beat tries to execute it NotRegistered exception is thrown.

Python 3.5.2, Django 1.11.4, Celery 4.1, django-celery-beat 1.1.0, django-celery-results 1.0.1

Part of settings.py related to celery:

CELERY_BROKER_URL = 'amqp://user:*****@192.168.X.X/proj'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_RESULT_BACKEND = 'django-db'
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Europe/Moscow'

celery.py and proj/__init__.py are identical to documentation examples.

proj/celery.py:

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

app = Celery('proj')

app.config_from_object(settings, namespace='CELERY')

app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

proj/__init__.py:

from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app

__all__ = ['celery_app']

tasks.py:

from celery import shared_task
from core.backend.files import SFTP

@shared_task
def load_files_from_sftp():
    ftp = SFTP()
    ftp.get_files()

I get the following json result:
{"exc_message": "'core.tasks.load_files_from_sftp'", "exc_type": "NotRegistered"}

If I try to use celery.task.control.inspect() from shell, it is only debug_task() there. Just stuck! ( I'll be grateful for any help.

Body:
As @MuhammadShoaib wrote, it's just one thing:

from django.apps import apps

app.config_from_object(settings)
app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])

instead of

app.autodiscover_tasks()

why this is not in the documentation?...


问:
Does Keen.io have a limit keyword or equivalent?
All,

Using Keen.io to pull some analytics.  I allow user input to specify start and end times, but I'm not able to find something equivalent to a "limit" parameter such as can be found for SQL queries.  If a user specifies a large enough range, this can result in way too much data coming back.

Does Keen.io have a way to pull back the first "x" records?

bower.json

"keen-js": "^3.4.1",

答:
Looking at the docs it looks like the simplest way to limit results over a timeframe is to group results into [interval][1]s.

It's not a perfect solution in that you end up with grouped data instead of individual records, but does give a guarantee that the results are limited


问:
I want to Block url in webview
Heres the acitivity of my code I want to like to block external link like if someone click on another webpage he or she cannot go to that webpage.

```<code>public class NewsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        String url = "https://www.example.com";
        WebView web = (WebView) findViewById(R.id.webView4);
        web.loadUrl(url);

        final WebView mWebView = (WebView) findViewById(R.id.webView4);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSaveFormData(true);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(false);
        mWebView.getSettings().setLightTouchEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                mWebView.loadUrl("javascript:(function() { " +

                        "document.getElementsByClassName('header_wrapper')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-contact')[0].style.display='none'; " +
                        "document.getElementsByClassName('navbar-header')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-social')[0].style.display='none'; " +
                        "document.getElementById('footer_bottom').style.display='none'; " +
                        "document.getElementById('footer_content').style.display='none'; " +
                        "document.getElementById('core_mobile_menu').style.display='none'; " +
                        "document.getElementById('catapult-cookie-bar').style.display='none'; " +

                        "})()");
            }
        });
        mWebView.loadUrl("https://www.example.com");

    }
}
</code>```

答:
Try this code this will also handle shouldOverrideUrlLoading deprecation in Nougat and above

```<code>mWebview.setWebViewClient(new WebViewClent() {

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().equals("http://www.example.com")) {
            // This is my web site, so do not override; let my WebView load the page
            return false;
        }
        // reject anything other by returning true
        return true;
    }

    @RequiresApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    String url=request.getUrl().toString();
        if (Uri.parse(url).getHost().equals("http://www.example.com")) {
            // This is my web site, so do not override; let my WebView load the page
            return false;
        }

        // reject anything other
        return true;
    }
}
</code>```

Title: I want to Block url in webview

Body:
Heres the acitivity of my code I want to like to block external link like if someone click on another webpage he or she cannot go to that webpage.

public class NewsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        String url = "https://www.example.com";
        WebView web = (WebView) findViewById(R.id.webView4);
        web.loadUrl(url);

        final WebView mWebView = (WebView) findViewById(R.id.webView4);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setSavePassword(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSaveFormData(true);
        mWebView.getSettings().setSupportZoom(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(false);
        mWebView.getSettings().setLightTouchEnabled(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                mWebView.loadUrl("javascript:(function() { " +

                        "document.getElementsByClassName('header_wrapper')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-contact')[0].style.display='none'; " +
                        "document.getElementsByClassName('navbar-header')[0].style.display='none'; " +
                        "document.getElementsByClassName('footer-social')[0].style.display='none'; " +
                        "document.getElementById('footer_bottom').style.display='none'; " +
                        "document.getElementById('footer_content').style.display='none'; " +
                        "document.getElementById('core_mobile_menu').style.display='none'; " +
                        "document.getElementById('catapult-cookie-bar').style.display='none'; " +

                        "})()");
            }
        });
        mWebView.loadUrl("https://www.example.com");

    }
}

Body:
Try this code this will also handle shouldOverrideUrlLoading deprecation in Nougat and above

mWebview.setWebViewClient(new WebViewClent() {

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().equals("http://www.example.com")) {
            // This is my web site, so do not override; let my WebView load the page
            return false;
        }
        // reject anything other by returning true
        return true;
    }

    @RequiresApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    String url=request.getUrl().toString();
        if (Uri.parse(url).getHost().equals("http://www.example.com")) {
            // This is my web site, so do not override; let my WebView load the page
            return false;
        }

        // reject anything other
        return true;
    }
}


问:
Case-insensitive search by EmailAddress (Oracle Sales Cloud REST API)
Does OSC REST API support case insensitive search possibility?

For example there is a Contact with EmailAddress: "Person@Company.com"

This contact is not found when I querying like: ```/contacts?q=EmailAddress='<strong>p</strong>erson@<strong>c</strong>ompany.com'```

Any solution here?

答:
I am trying in Release 12 of OSC, my testing from POSTMAN works fine. The Search is case-insensitive.

/crmCommonApi/resources/latest/contacts?q=EmailAddress LIKE 'Test2@Gsd.com'&fields=PartyId, PatyNumber,AccountName,EmailAddress

Response:

....

"AccountName": "Oracle_o",

"EmailAddress": "test2@gsd.com",

....

See in my above query; I have used Test2@Gsd.com while actual data is 'test2@gsd.com'. I also tried testing with 'TEST2@GSD.COM' as stated in request below, the results are as desired.

/crmCommonApi/resources/latest/contacts?q=EmailAddress='TEST2@GSD.COM'&fields=PartyId, PatyNumber,AccountName,EmailAddress

Body:
Does OSC REST API support case insensitive search possibility?

For example there is a Contact with EmailAddress: "Person@Company.com"

This contact is not found when I querying like:
/contacts?q=EmailAddress='person@company.com'

Any solution here?


Title: SQL Return distinct rows based on two columns by rounding column to nearest value

Body:
Following is the Table:

ID  C1  C2  C3  Date    C5  C6  Name
1   ### ### ### 9.53    ### ### ron
1   ### ### ### 9.57    ### ### ron
1   ### ### ### 9.87    ### ### ron
1   ### ### ### 10.2    ### ### jess
1   ### ### ### 10.2    ### ### jess
1   ### ### ### 11.3    ### ### mike
1   ### ### ### 11.3    ### ### mike
2   ### ### ### 16.58   ### ### ron
2   ### ### ### 16.33   ### ### ron
2   ### ### ### 16.45   ### ### ron
2   ### ### ### 22.43   ### ### jess
2   ### ### ### 22.88   ### ### jess
2   ### ### ### 19.2    ### ### mike
2   ### ### ### 19.51   ### ### mike

Following is what i am expecting:

Gettting distinct rows based on ID and Name, grouping by Date to nearest round number.

ID  C1  C2  C3  Date    C5  C6  Name
1   ### ### ### 9      ###  ### ron
1   ### ### ### 10     ###  ### jess
1   ### ### ### 11     ###  ### mike
2   ### ### ### 16     ###  ### ron
2   ### ### ### 22     ###  ### jess
2   ### ### ### 19     ###  ### mike

Can anyone help me on this?

Body:
CREATE TABLE #Table1
    ([ID] int, [C1] varchar(3), [C2] varchar(3), [C3] varchar(3), [Date] numeric(10,4), [C5] varchar(3), [C6] varchar(3), [Name] varchar(4))
;

INSERT INTO #Table1
    ([ID], [C1], [C2], [C3], [Date], [C5], [C6], [Name])
VALUES
    (1, '###', '###', '###', 9.53, '###', '###', 'ron'),
    (1, '###', '###', '###', 9.57, '###', '###', 'ron'),
    (1, '###', '###', '###', 9.87, '###', '###', 'ron'),
    (1, '###', '###', '###', 10.2, '###', '###', 'jess'),
    (1, '###', '###', '###', 10.2, '###', '###', 'jess'),
    (1, '###', '###', '###', 11.3, '###', '###', 'mike'),
    (1, '###', '###', '###', 11.3, '###', '###', 'mike'),
    (2, '###', '###', '###', 16.58, '###', '###', 'ron'),
    (2, '###', '###', '###', 16.33, '###', '###', 'ron'),
    (2, '###', '###', '###', 16.45, '###', '###', 'ron'),
    (2, '###', '###', '###', 22.43, '###', '###', 'jess'),
    (2, '###', '###', '###', 22.88, '###', '###', 'jess'),
    (2, '###', '###', '###', 19.2, '###', '###', 'mike'),
    (2, '###', '###', '###', 19.51, '###', '###', 'mike')
;
select  distinct [ID], [C1], [C2], [C3], cast(date as int), [C5], [C6], [Name]  from #Table1


问:
Swift 3 escaping closure changes not sticking

I'm attempting to write a Game of Thrones episode compendium using OMDb API. I'm getting the information just fine from the server, but I'm having a difficult time sending that data to my UITableView.

This is both the function calling the closure and the one defining it:

```<code>func getAllForSeason(season: Int) {
    let uri = "\(baseURL)\(urlId)&season=\(season)"
    var episodeList = [EpisodeModel]()
    let url = URL(string: uri)
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
      if error != nil {
        print("Error retrieving information. No season found")
      } else {
        if let content = data {
          do {
            let seasonJSON = try JSONSerialization.jsonObject(with: content, options: .mutableContainers) as? [String: Any]
            let episodesFound = seasonJSON?["Episodes"] as! [[String: String]]
            for episodeJSON in episodesFound {
              let number = Int(episodeJSON["Episode"] ?? "0") ?? 0
              var episodeToAdd = EpisodeModel()
              self.getTemporaryEpisode(season: season, number: number, completion: {(result:EpisodeModel) in
                episodeToAdd = result
                print(episodeToAdd.season)
              })
              print(episodeToAdd.season)
              episodeList.append(episodeToAdd)
            }
            DispatchQueue.main.async {
              self.delegate?.didGetSeason(episodes: episodeList)
            }
          } catch {
            print ("Error retrieving information. No seasons found")
          }
        }
      }
    }
    task.resume()
  }

private func getTemporaryEpisode(season: Int, number: Int, completion: @escaping(_ response:EpisodeModel)->Void) {
    let episode = EpisodeModel()
    let uri = "\(baseURL)\(urlId)&season=\(season)&episode=\(number)"
    let url = URL(string: uri)
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
      if error != nil {
        print("Error downloading episode information. Empty Episode returned")
      } else {
        if let content = data {
          do {
            let episodeJSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]
            episode.title = (episodeJSON?["Title"] as? String)?.description ?? ""
            let dateString = (episodeJSON?["Released"] as? String)?.description ?? ""
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy MMM dd"
            episode.releaseDate = dateFormatter.date(from: dateString) ?? Date()
            episode.rating = (episodeJSON?["Rated"] as? String)?.description ?? ""
            episode.season = Int(episodeJSON?["Season"] as? String ?? "") ?? 0
            episode.number = Int(episodeJSON?["Episode"] as? String ?? "") ?? 0
            let runtimeString = (episodeJSON?["Runtime"] as? String)?.description ?? "0 min"
            let spaceIndex = runtimeString.index(of: " ") ?? runtimeString.endIndex
            let minuteString = runtimeString[runtimeString.startIndex..<spaceIndex]
            episode.minutes = Int(minuteString) ?? 0
            episode.director = (episodeJSON?["Director"] as? String)?.description ?? ""
            episode.writer = (episodeJSON?["Writer"] as? String)?.description ?? ""
            let actorsString = (episodeJSON?["Actors"] as? String)?.description ?? ""
            episode.actors = actorsString.components(separatedBy: ", ")
            episode.plot = (episodeJSON?["Plot"] as? String)?.description ?? ""
          } catch {
            print("Error downloading episode information. Empty or incomplete episode returned")
          }
        }
      }
      completion(episode)
    }
    task.resume()
  }
</code>```

I have done similar work with the SW API (Star Wars) using the exact same methodology and it worked then.

The print statements placed for testing should both print the season number of the episode obtained with getTemporaryEpisode

However, I find instead that while the first print statement prints properly (from within the closure), the second one right outside the closure prints 0 (the default I set in to make sure the value is initialized), meaning that episodeToAdd no longer contains the result.

For example: Winter Is Coming will print 1 within the enclosure, but 0 out of it.

It prints the 0s first, so I'm sure it's a threading issue and the completion just hasn't happened by the time the second print statement gets called. I'm just not sure how to solve it.

Edit: I did realize I stupidly placed my call to the main thread inside the loop, but fixing that did not fix this issue.

答:
Your function getTemporaryEpisode is asynchronous, so you notify the delegate with an array of empty episodes.

You then reassign the episodeToAdd variable to refer to a properly set up episode, but that doesn’t have any effect on the contents of episodeList. You probably want to wait to populate episodeList until you have retrieved the proper contents. You can use a DispatchGroup for this.

However, if you simply use a DispatchGroup, the episodes are not required to come back in the expected order, because they’ll each be requested at the same time, independently. The easiest solution would be to gather them in an array and then sort the array by episode number before informing your delegate.

Body:
I'm attempting to write a Game of Thrones episode compendium using OMDb API. I'm getting the information just fine from the server, but I'm having a difficult time sending that data to my UITableView.

This is both the function calling the closure and the one defining it:

func getAllForSeason(season: Int) {
    let uri = "\(baseURL)\(urlId)&season=\(season)"
    var episodeList = [EpisodeModel]()
    let url = URL(string: uri)
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
      if error != nil {
        print("Error retrieving information. No season found")
      } else {
        if let content = data {
          do {
            let seasonJSON = try JSONSerialization.jsonObject(with: content, options: .mutableContainers) as? [String: Any]
            let episodesFound = seasonJSON?["Episodes"] as! [[String: String]]
            for episodeJSON in episodesFound {
              let number = Int(episodeJSON["Episode"] ?? "0") ?? 0
              var episodeToAdd = EpisodeModel()
              self.getTemporaryEpisode(season: season, number: number, completion: {(result:EpisodeModel) in
                episodeToAdd = result
                print(episodeToAdd.season)
              })
              print(episodeToAdd.season)
              episodeList.append(episodeToAdd)
            }
            DispatchQueue.main.async {
              self.delegate?.didGetSeason(episodes: episodeList)
            }
          } catch {
            print ("Error retrieving information. No seasons found")
          }
        }
      }
    }
    task.resume()
  }

private func getTemporaryEpisode(season: Int, number: Int, completion: @escaping(_ response:EpisodeModel)->Void) {
    let episode = EpisodeModel()
    let uri = "\(baseURL)\(urlId)&season=\(season)&episode=\(number)"
    let url = URL(string: uri)
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
      if error != nil {
        print("Error downloading episode information. Empty Episode returned")
      } else {
        if let content = data {
          do {
            let episodeJSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]
            episode.title = (episodeJSON?["Title"] as? String)?.description ?? ""
            let dateString = (episodeJSON?["Released"] as? String)?.description ?? ""
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy MMM dd"
            episode.releaseDate = dateFormatter.date(from: dateString) ?? Date()
            episode.rating = (episodeJSON?["Rated"] as? String)?.description ?? ""
            episode.season = Int(episodeJSON?["Season"] as? String ?? "") ?? 0
            episode.number = Int(episodeJSON?["Episode"] as? String ?? "") ?? 0
            let runtimeString = (episodeJSON?["Runtime"] as? String)?.description ?? "0 min"
            let spaceIndex = runtimeString.index(of: " ") ?? runtimeString.endIndex
            let minuteString = runtimeString[runtimeString.startIndex..<spaceIndex]
            episode.minutes = Int(minuteString) ?? 0
            episode.director = (episodeJSON?["Director"] as? String)?.description ?? ""
            episode.writer = (episodeJSON?["Writer"] as? String)?.description ?? ""
            let actorsString = (episodeJSON?["Actors"] as? String)?.description ?? ""
            episode.actors = actorsString.components(separatedBy: ", ")
            episode.plot = (episodeJSON?["Plot"] as? String)?.description ?? ""
          } catch {
            print("Error downloading episode information. Empty or incomplete episode returned")
          }
        }
      }
      completion(episode)
    }
    task.resume()
  }

I have done similar work with the SW API (Star Wars) using the exact same methodology and it worked then.

The print statements placed for testing should both print the season number of the episode obtained with getTemporaryEpisode

However, I find instead that while the first print statement prints properly (from within the closure), the second one right outside the closure prints 0 (the default I set in to make sure the value is initialized), meaning that episodeToAdd no longer contains the result.

For example: Winter Is Coming will print 1 within the enclosure, but 0 out of it.

It prints the 0s first, so I'm sure it's a threading issue and the completion just hasn't happened by the time the second print statement gets called. I'm just not sure how to solve it.

Edit: I did realize I stupidly placed my call to the main thread inside the loop, but fixing that did not fix this issue.


问:
ggplot2 hell with rpy2-2.0.7 + python 2.6 + r 2.11 (windows 7)
i am using rpy2-2.0.7 (i need this to work with windows 7, and compiling the binaries for the newer rpy2 versions is a mess) to push a two-column dataframe into r, create a few layers in ggplot2, and output the image into a <.png>.

i have wasted countless hours fidgeting around with the syntax; i did manage to output the files i needed at one point, but (stupidly) did not notice and continued fidgeting around with my code ...

i would sincerely appreciate any help; below is a (trivial) example for demonstration.  Thank you very much for your help!!!   ~  Eric Butter

```<code>import rpy2.robjects as rob
from rpy2.robjects import r
import rpy2.rlike.container as rlc
from array import array

r.library("grDevices")    # import r graphics package with rpy2
r.library("lattice")
r.library("ggplot2")
r.library("reshape")

picpath = 'foo.png'

d1 = ["cat","dog","mouse"]
d2 = array('f',[1.0,2.0,3.0])

nums = rob.RVector(d2)
name = rob.StrVector(d1)

tl = rlc.TaggedList([nums, name], tags = ('nums', 'name'))
dataf = rob.RDataFrame(tl)

## r['png'](file=picpath, width=300, height=300)
## r['ggplot'](data=dataf)+r['aes_string'](x='nums')+r['geom_bar'](fill='name')+r['stat_bin'](binwidth=0.1)
r['ggplot'](data=dataf)
r['aes_string'](x='nums')
r['geom_bar'](fill='name')
r['stat_bin'](binwidth=0.1)
r['ggsave']()
## r['dev.off']()
</code>```

*The output is just a blank image (181 b).

here are a couple common errors R itself throws as I fiddle around in ggplot2:

```<code>r['png'](file=picpath, width=300, height=300)
r['ggplot']()
r['layer'](dataf, x=nums, fill=name, geom="bar")
r['geom_histogram']()
r['stat_bin'](binwidth=0.1)
r['ggsave'](file=picpath)
r['dev.off']()
</code>```

*RRuntimeError: Error: No layers in plot

```<code>r['png'](file=picpath, width=300, height=300)
r['ggplot'](data=dataf)
r['aes'](geom="bar")
r['geom_bar'](x=nums, fill=name)
r['stat_bin'](binwidth=0.1)
r['ggsave'](file=picpath)
r['dev.off']()
</code>```

*RRuntimeError: Error: When setting aesthetics, they may only take one value. Problems: fill,x

答:
You have to engage the dev() before you shut it off, which means that you have to print() (like JD guesses above) prior to throwing dev.off(). </p>

```<code>from rpy2 import robjects
r = robjects.r
r.library("ggplot2")
robjects.r('p = ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()')
r.ggsave('/stackBar.jpeg')
robjects.r('print(p)')
r['dev.off']()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i am using rpy2-2.0.7 (i need this to work with windows 7, and compiling the binaries for the newer rpy2 versions is a mess) to push a two-column dataframe into r, create a few layers in ggplot2, and output the image into a <.png>.

i have wasted countless hours fidgeting around with the syntax; i did manage to output the files i needed at one point, but (stupidly) did not notice and continued fidgeting around with my code ...

i would sincerely appreciate any help; below is a (trivial) example for demonstration.  Thank you very much for your help!!!   ~  Eric Butter

import rpy2.robjects as rob
from rpy2.robjects import r
import rpy2.rlike.container as rlc
from array import array

r.library("grDevices")    # import r graphics package with rpy2
r.library("lattice")
r.library("ggplot2")
r.library("reshape")

picpath = 'foo.png'

d1 = ["cat","dog","mouse"]
d2 = array('f',[1.0,2.0,3.0])

nums = rob.RVector(d2)
name = rob.StrVector(d1)

tl = rlc.TaggedList([nums, name], tags = ('nums', 'name'))
dataf = rob.RDataFrame(tl)

## r['png'](file=picpath, width=300, height=300)
## r['ggplot'](data=dataf)+r['aes_string'](x='nums')+r['geom_bar'](fill='name')+r['stat_bin'](binwidth=0.1)
r['ggplot'](data=dataf)
r['aes_string'](x='nums')
r['geom_bar'](fill='name')
r['stat_bin'](binwidth=0.1)
r['ggsave']()
## r['dev.off']()

*The output is just a blank image (181 b).

here are a couple common errors R itself throws as I fiddle around in ggplot2:

r['png'](file=picpath, width=300, height=300)
r['ggplot']()
r['layer'](dataf, x=nums, fill=name, geom="bar")
r['geom_histogram']()
r['stat_bin'](binwidth=0.1)
r['ggsave'](file=picpath)
r['dev.off']()

*RRuntimeError: Error: No layers in plot

r['png'](file=picpath, width=300, height=300)
r['ggplot'](data=dataf)
r['aes'](geom="bar")
r['geom_bar'](x=nums, fill=name)
r['stat_bin'](binwidth=0.1)
r['ggsave'](file=picpath)
r['dev.off']()

*RRuntimeError: Error: When setting aesthetics, they may only take one value. Problems: fill,x

Body:
You have to engage the dev() before you shut it off, which means that you have to print() (like JD guesses above) prior to throwing dev.off().

from rpy2 import robjects
r = robjects.r
r.library("ggplot2")
robjects.r('p = ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()')
r.ggsave('/stackBar.jpeg')
robjects.r('print(p)')
r['dev.off']()


问:
Hibernate: @ManyToOne(fetch = FetchType.LAZY) does not work on non-primary key referenced column
I have 2 tables: Order [OrderId(PK), OrderShipmentCode, ...] and Shipment[ShipmentId(PK), ShipmentCode, ...].

In Order class, I declared shipment field as follows:

```<code>@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "OrderShipmentCode", referencedColumnName = "ShipmentCode", insertable = false, updatable = false, nullable = false)
private Shipment shipment;
</code>```

When I get the list of Order, the Shipment is also loaded (I saw many separate SELECT queries). But I want the Shipment to be lazy loaded, not to be fetched together with Order.

For other tables, if the referenced column is primary key then the results are as expected (Lazy-loading is used). In my case, ShipmentCode is not Primary Key of Shipment table, and lazy-loading is not used by Hibernate.

Could you show me how to accomplish that goal?

EDIT:
The Query code is as bellow:

```<code>Criteria criteria = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(Order.class);
List result = criteria.list();
</code>```

SQL queries are: 1 SELECT statement for Order table and a bunch of SELECT statement for Shipment

答:
Try this:</p>

```<code>Criteria criteria = HibernateUtil.getSessionFactory()
                                 .getCurrentSession()
                                 .createCriteria(Order.class)
                                 .setFetchMode("shipment", FetchMode.LAZY);
</code>```

Body:
I have 2 tables: Order [OrderId(PK), OrderShipmentCode, ...] and Shipment[ShipmentId(PK), ShipmentCode, ...].

In Order class, I declared shipment field as follows:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "OrderShipmentCode", referencedColumnName = "ShipmentCode", insertable = false, updatable = false, nullable = false)
private Shipment shipment;

When I get the list of Order, the Shipment is also loaded (I saw many separate SELECT queries). But I want the Shipment to be lazy loaded, not to be fetched together with Order.

For other tables, if the referenced column is primary key then the results are as expected (Lazy-loading is used). In my case, ShipmentCode is not Primary Key of Shipment table, and lazy-loading is not used by Hibernate.

Could you show me how to accomplish that goal?

EDIT:
The Query code is as bellow:

Criteria criteria = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(Order.class);
List result = criteria.list();

SQL queries are: 1 SELECT statement for Order table and a bunch of SELECT statement for Shipment

Body:
Try this:

Criteria criteria = HibernateUtil.getSessionFactory()
                                 .getCurrentSession()
                                 .createCriteria(Order.class)
                                 .setFetchMode("shipment", FetchMode.LAZY);


答:
You can use this code,</p>

```<code>select ID, C1, C2, C3, floor(Date) as RDate, C5, C6, Name
from your_table_name
group by ID, Name, RDate
</code>```

Body:
You can use this code,

select ID, C1, C2, C3, floor(Date) as RDate, C5, C6, Name
from your_table_name
group by ID, Name, RDate


问:
JS Array.every alway return false on comparing strings
I'm trying to complete an assignment using every, I tried everything and after and after 1 hour I decided to ask your help.

This function should return true if all the words in the array start with a case-insensitive but always return false, no matter what.

Thank you

var allStartingWithA = function(words){
  return words.length !== 0? words.every((word) => {word[0] === /"a"/i }) : true;
};

allStartingWithA(["abbb","aee", "aee", "avvv"]);```

答:
Your approach is correct for the problem. Whereas you did small mistakes with your arrow function usage and use of regex

Firstly  (word) => {word[0] === /"a"/i } function doesn't return anything

You can use

(word) => {return word[0] === /"a"/i } or (word) => word[0] === /"a"/i

And secondly you are doing just comparison. Then if you add //i it will become regex then you need to use test method.

So use return word[0] === "a" simply for comparison

var allStartingWithA = function(words){
  return words.length !== 0? words.every((word) => word[0] === "a") : true;
};

console.log(allStartingWithA(["abbb","aee", "aee", "avvv"]));```


问:
Blitting / Loading PNG image in Pyglet resulting in "blotchy" image with an odd alpha layer
I'm trying to display a PNG image in pyglet. The PNG image is this:

However, when I attempt to render this using the following code:

```<code>if fullscreen:
    window = pyglet.window.Window(caption = "Forsaken Light, by Damian Heaton",
                                  fullscreen = True)
else:
    window = pyglet.window.Window(caption = "Forsaken Light, by Damian Heaton",
                                  fullscreen = False,
                                  width = 500, height = 250)
window.set_icon(pyglet.image.load('icon.ico'))

logo = pyglet.image.load(
    os.path.join("res", "graphics", "temp", "misc", "logo.png"))

class MenuEventHandler(object):
    def on_draw(self):
        window.clear()
        logo.blit((window.width / 2) - (logo.width / 2),
                  window.height - logo.height)

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE:
            sys.exit(0)
        return True

    def on_mouse_press(self, x, y, button, modifiers):
        print("Mouse button pressed in menu")
        return True

menu_handlers = MenuEventHandler()

window.push_handlers(menu_handlers)

def stop_game():
    window.pop_handlers()

pyglet.app.run()
</code>```

It shows as this:

I've tried searching for what my problem is, but all example scripts using Pyglet rendering a PNG image seem to suggest my code is correct...

Any help would be appreciated, and thank you in advance.

答:
Add this to beginning of the on_draw function:</p>

```<code>glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
</code>```

Body:
I'm trying to display a PNG image in pyglet. The PNG image is this:

However, when I attempt to render this using the following code:

if fullscreen:
    window = pyglet.window.Window(caption = "Forsaken Light, by Damian Heaton",
                                  fullscreen = True)
else:
    window = pyglet.window.Window(caption = "Forsaken Light, by Damian Heaton",
                                  fullscreen = False,
                                  width = 500, height = 250)
window.set_icon(pyglet.image.load('icon.ico'))

logo = pyglet.image.load(
    os.path.join("res", "graphics", "temp", "misc", "logo.png"))

class MenuEventHandler(object):
    def on_draw(self):
        window.clear()
        logo.blit((window.width / 2) - (logo.width / 2),
                  window.height - logo.height)

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE:
            sys.exit(0)
        return True

    def on_mouse_press(self, x, y, button, modifiers):
        print("Mouse button pressed in menu")
        return True

menu_handlers = MenuEventHandler()

window.push_handlers(menu_handlers)

def stop_game():
    window.pop_handlers()

pyglet.app.run()

It shows as this:

I've tried searching for what my problem is, but all example scripts using Pyglet rendering a PNG image seem to suggest my code is correct...

Any help would be appreciated, and thank you in advance.

Body:
Add this to beginning of the on_draw function:

glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)


问:
laravel redirect to shows a message in white screen
In my project only one section that is the date booking taking section , when the appointment is booked the redirect message

"redirecting to <url>" shows in a white screen.

This happens only in this function. I have already checked the layout used in this page for any space before the Doctype but it was fine, and also checked any space before <?php and ?> in the head.blade.php . But nothing noticed.

This started showing suddenly from yesterday where i just wrote a php code in head for checking and displaying meta title and meta description.
The redirect code used in the end of controller function is:

```<code>return Redirect::to('/home/my-profile/'.$d_id.'#menu5');
</code>```

Can anyone please tell me how to avoid this message from displaying like this.?

答:
I also experienced same issue once,
I fixed it by removing whitespaces before <?php in one of my routes file.
Check your all routes and controller file if there is any whitespaces before opening PHP tag.

Body:
In my project only one section that is the date booking taking section , when the appointment is booked the redirect message

"redirecting to <url>" shows in a white screen.

This happens only in this function. I have already checked the layout used in this page for any space before the Doctype but it was fine, and also checked any space before <?php and ?> in the head.blade.php . But nothing noticed.

This started showing suddenly from yesterday where i just wrote a php code in head for checking and displaying meta title and meta description.
The redirect code used in the end of controller function is:

return Redirect::to('/home/my-profile/'.$d_id.'#menu5');

Can anyone please tell me how to avoid this message from displaying like this.?


问:
Programming style of method declaration of get/set method variables in C++?
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp. </p>

答: I would say that header files should be about interface, not implementation.  I'd put them in the .cpp.</p>

LastEditorDisplayName: Eddie Parker


问:
TClientDataSet faulted with message
got a small situation here, I haven't used TClientDataSet until recently(it requires midas.dll) so now I'm facing a very awkward error, not very descriptive:

Debugger Fault Notification

Project E:\Work\XXX\binary\XXX.exe faulted with message: 'access violation at 0x00678827: write of address 0x00030a38'. Process Stopped. Use Step or Run to continue.

this happens whenever I try to set the value of a field in the clientdataset(I'm using it as a in-memory dataset) as so:

```<code>with ADataModule do begin
  cdsTest.Append;
  cdsTestAField.AsString := ATableField.AsString;
  // ...
end;
</code>```

both fields are TStringField, cdsTestAField has size 64 and ATableField has size 32

Note: that I'm calling the CreateDataSet method before anything else, also this happens only with the string fields, any help would be highly appreciated.

Thank you for your time.

答:
And where does ATableField come from? Could it be that it is an invalid reference to an object that is already freed?

Also, you can include midaslib.pas in your project to eliminate the use of an external midaslib.dll. It will make your project slightly larger, though, because you are basically compiling the dll in you exe.

Title: TClientDataSet faulted with message

Body:
got a small situation here, I haven't used TClientDataSet until recently(it requires midas.dll) so now I'm facing a very awkward error, not very descriptive:

Debugger Fault Notification

Project E:\Work\XXX\binary\XXX.exe faulted with message: 'access violation at 0x00678827: write of address 0x00030a38'. Process Stopped. Use Step or Run to continue.

this happens whenever I try to set the value of a field in the clientdataset(I'm using it as a in-memory dataset) as so:

with ADataModule do begin
  cdsTest.Append;
  cdsTestAField.AsString := ATableField.AsString;
  // ...
end;

both fields are TStringField, cdsTestAField has size 64 and ATableField has size 32

Note: that I'm calling the CreateDataSet method before anything else, also this happens only with the string fields, any help would be highly appreciated.

Thank you for your time.


问:
How "parameterized queries/prepared statements" better in SQL injection than escaping user input
There are many articles telling to use parametrized queries instead of escaping user input. But doesn't show any examples. I would like to know a real example where “parameterized queries/prepared statements” prevents SQL injections, while escaping user input can’t. Can you give an example that parameterized query prevent the SQL injection attack when a user input to the query still contains a special character to cause harm? For example, a query that parameterized queries can take care of but the escaping user input can't take care of

Query like = ' or 1=1-- //I would like to know if there is a similar query that "parameterized queries/prepared statements" can prevent from SQL injection, but "escaping user input" can't

答:
Q:  Can you give an example that parameterized query prevent the SQL injection attack when a user input to the query still contains a special character to cause harm?

A: There have been some multibyte character exploits in code that doesn't properly account for character sets, resulting in holes in the escaping mechanism.  (Where the "escape string" thinks it's working on a string in particular encoding, but the actual bytes are in a different encoding, and sneakily sliding single quotes into the SQL text.)

But I don't really think that's the strongest argument for prepared statements with bind placeholders.

A strong argument is that when we look at the code, we see static SQL text, not dynamically generated...

```<code> $sql = 'SELECT fee, fi FROM fo WHERE fum = ?';
 $dbh->prepare($sql);
</code>```

We see that code, and we look at that SQL text... and we recognize immediately, there is no way that the SQL text is going to be other than what we see. We don't have to look anywhere else in the code; we see it right there on two lines.

When we see this:

```<code> $sql = "SELECT fee, fi FROM fo WHERE fum = $fumval";
</code>```

That's double quotes, there's variable interpretation going on. Is $fumval guaranteed  to be safe for inclusion in the SQL text, where did $fumval come from? Should there be single quotes around $fumval, or are we guaranteed that it's already enclosed in single quotes?

Okay, maybe there's a line right before that:

```<code> $fumval = $dbh->quote($unsafe_fumval);
</code>```

If that line isn't right above the generation of the SQL text, we need to go check... are we guaranteed the $fumval is safe?

The point is this... the SQL is being dynamically constructed. It might be better if it was done like this:

```<code>$sql = 'SELECT fee, fi FROM fo WHERE fum = ' . $dbh->quote($unsafe_fumval);
</code>```

For a simple statement, maybe it's six of one and half a dozen of the other. But when SQL statements get larger, involving multiple tables and dozens of column references and values, the dynamic construction gets harder to verify that there are not any problems in it.

Is it possible to write secure code using dynamically generated SQL and "escape string" processing on values?  YES.

Is it possible to write vulnerable code that uses prepared statements with dynamically generated SQL text? YES.

It's really the  pattern of static SQL text, passing values provided through bind placeholders is what gets us the bang for our buck... code that is written in a way in which we can identify as not vulnerable to SQL injection.

Body:
Q:  Can you give an example that parameterized query prevent the SQL injection attack when a user input to the query still contains a special character to cause harm?

A: There have been some multibyte character exploits in code that doesn't properly account for character sets, resulting in holes in the escaping mechanism.  (Where the "escape string" thinks it's working on a string in particular encoding, but the actual bytes are in a different encoding, and sneakily sliding single quotes into the SQL text.)

But I don't really think that's the strongest argument for prepared statements with bind placeholders.

A strong argument is that when we look at the code, we see static SQL text, not dynamically generated...

 $sql = 'SELECT fee, fi FROM fo WHERE fum = ?';
 $dbh->prepare($sql);

We see that code, and we look at that SQL text... and we recognize immediately, there is no way that the SQL text is going to be other than what we see. We don't have to look anywhere else in the code; we see it right there on two lines.

When we see this:

 $sql = "SELECT fee, fi FROM fo WHERE fum = $fumval";

That's double quotes, there's variable interpretation going on. Is $fumval guaranteed  to be safe for inclusion in the SQL text, where did $fumval come from? Should there be single quotes around $fumval, or are we guaranteed that it's already enclosed in single quotes?

Okay, maybe there's a line right before that:

 $fumval = $dbh->quote($unsafe_fumval);

If that line isn't right above the generation of the SQL text, we need to go check... are we guaranteed the $fumval is safe?

The point is this... the SQL is being dynamically constructed. It might be better if it was done like this:

$sql = 'SELECT fee, fi FROM fo WHERE fum = ' . $dbh->quote($unsafe_fumval);

For a simple statement, maybe it's six of one and half a dozen of the other. But when SQL statements get larger, involving multiple tables and dozens of column references and values, the dynamic construction gets harder to verify that there are not any problems in it.

Is it possible to write secure code using dynamically generated SQL and "escape string" processing on values?  YES.

Is it possible to write vulnerable code that uses prepared statements with dynamically generated SQL text? YES.

It's really the  pattern of static SQL text, passing values provided through bind placeholders is what gets us the bang for our buck... code that is written in a way in which we can identify as not vulnerable to SQL injection.


问:
Decimal fields are not working properly after publishing in MVC view
I have some decimal fields to show and edit in my view in a table.

```<code><td>@Html.EditorFor(model => model[i].Score, new { htmlAttributes = new { @class = "form-control" } })</td>
<td>@Html.EditorFor(model => model[i].Cost, new { htmlAttributes = new { @class = "form-control", @type = "text" } })</td>**
</code>```

They work all great before I publish it on my server. However when I publish the project on the server there is a /00 character at the end of each field and user have to delete them before submit the form.
What should I do?

答:
I should add

```<code>    <globalization culture="en-us" uiCulture="en-us" />
</code>```

to Web.config in <system.web>

Body:
I have some decimal fields to show and edit in my view in a table.

@Html.EditorFor(model => model[i].Score, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model[i].Cost, new { htmlAttributes = new { @class = "form-control", @type = "text" } })	**

They work all great before I publish it on my server. However when I publish the project on the server there is a /00 character at the end of each field and user have to delete them before submit the form.
What should I do?

Body:
I should add

    <globalization culture="en-us" uiCulture="en-us" />

to Web.config in <system.web>


问:
Tooltip in table header
I have a scrollable table with fixed header and columns, and tooltips in the header.  There is also a rowspan in the header.  I have tried for a long time now to get the tooltips in the header rows to show over top of the header cells in the following rows.  I can not seem to find a solution even after reading everything I can find on stacking contexts and z-index, including the W3C specs.

CSS:

```<code>.gradebooktable {
  overflow: auto;
  height: 200px;
  width: 400px
}

table {
  table-layout: fixed;
  border-width: 0;
  border-spacing: 0;
}

td {
  position:relative;
  padding: 3px;
  white-space: nowrap;
  border-right: 1px solid #ccc;
}

th {
  position:relative;
  z-index:20;
  background: #999;
}

th.pinned {
  position: relative;
  z-index: 40;
  background: #ccc;
}

td.pinned {
  position: relative;
  z-index: 30;
  background: #eee;
}

.tooltip{
  position:relative;
}

.tooltiptext{
  display:none;
  position:absolute;
  z-index:10;
  border:1px;
  background-color:#eee;
  border-style:solid;
  border-width:1px;
  border-color:blue;
  border-radius: 6px;
  padding:3px;
  color:blue;
  top:20px;
  left:20px;
}

.tooltip:hover span.tooltiptext{
  display:block;
}
</code>```

HTML:

```<code><BODY>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<SCRIPT>
$( function() {
$('#gradebooktable').scroll( function() {
      var translate = "translate(0," + this.scrollTop + "px)";
      $("table thead th:not(.pinned)").css('transform', translate);

      translate = "translate(" + this.scrollLeft + "px,0)";
      $("table tbody .pinned").css('transform', translate);

      translate = "translate(" + this.scrollLeft + "px," + this.scrollTop + "px)";
      $("table thead th.pinned").css('transform', translate);
    }
);
});
</SCRIPT>
  <div id="gradebooktable" class="gradebooktable">
    <table>
      <thead>
        <tr>
          <th class="pinned" rowspan=3>Col 0</th>
          <th class="pinned" rowspan=3>Col 1</th>
          <th class="tooltip">Col 2A
               <span class="tooltiptext">Tooltip for header cell</span></th>
          <th class="tooltip">Col 3A
               <span class="tooltiptext">Tooltip for header cell</span></th>
          <th class="tooltip">Col 4A
               <span class="tooltiptext">Tooltip for header cell</span></th>
          <th class="tooltip">Col 5A
               <span class="tooltiptext">Tooltip for header cell</span></th>
          <th class="tooltip">Col 6A
               <span class="tooltiptext">Tooltip for header cell</span></th>
          <th class="tooltip">Col 7A
               <span class="tooltiptext">Tooltip for header cell</span></th>
          <th class="tooltip">Col 8A
               <span class="tooltiptext">Tooltip for header cell</span></th>
          <th class="tooltip">Col 9A
               <span class="tooltiptext">Tooltip for header cell</span></th>
        </tr>
        <tr>
          <th>Col 2B</th>
          <th>Col 3B</th>
          <th>Col 4B</th>
          <th>Col 5B</th>
          <th>Col 6B</th>
          <th>Col 7B</th>
          <th>Col 8B</th>
          <th>Col 9B</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td class="tooltip">Another Cell
                  <span class="tooltiptext">Tooltip for body cell</span></td>
          <td class="tooltip">Another Cell
                  <span class="tooltiptext">Tooltip for body cell</span></td>
          <td class="tooltip">Another Cell
                  <span class="tooltiptext">Tooltip for body cell</span></td>
          <td class="tooltip">Another Cell
                  <span class="tooltiptext">Tooltip for body cell</span></td>
          <td class="tooltip">Another Cell
                  <span class="tooltiptext">Tooltip for body cell</span></td>
          <td class="tooltip">Another Cell
                  <span class="tooltiptext">Tooltip for body cell</span></td>
          <td class="tooltip">Another Cell
                  <span class="tooltiptext">Tooltip for body cell</span></td>
          <td class="tooltip">Another Cell
                  <span class="tooltiptext">Tooltip for body cell</span></td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
        <tr>
          <td class="pinned">First Cell</td>
          <td class="pinned">Second Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
          <td>Another Cell</td>
        </tr>
      </tbody>
    </table>
    </div>
</BODY>
</code>```

Fiddle here: https://jsfiddle.net/k42myms3/5/

The goal is to get the tooltips in the top row of the spanned header rows to show on top of the cells on the bottom row of the spanned header rows. I can find ways to get the tooltips to show, for example by removing position:absolute from the .tooltiptext css, but not without either causing positioning problems or breaking the table cells scrolling behind the fixed headers and columns.

答:
Never mind, fixed it: https://jsfiddle.net/k42myms3/10/

Code added:

```<code>th.tooltip{
  position:relative;
  z-index: 35;
}
</code>```

... and a few other things.

Title: Tooltip in table header

Body:
I have a scrollable table with fixed header and columns, and tooltips in the header.  There is also a rowspan in the header.  I have tried for a long time now to get the tooltips in the header rows to show over top of the header cells in the following rows.  I can not seem to find a solution even after reading everything I can find on stacking contexts and z-index, including the W3C specs.

CSS:

.gradebooktable {
  overflow: auto;
  height: 200px;
  width: 400px
}

table {
  table-layout: fixed;
  border-width: 0;
  border-spacing: 0;
}

td {
  position:relative;
  padding: 3px;
  white-space: nowrap;
  border-right: 1px solid #ccc;
}

th {
  position:relative;
  z-index:20;
  background: #999;
}

th.pinned {
  position: relative;
  z-index: 40;
  background: #ccc;
}

td.pinned {
  position: relative;
  z-index: 30;
  background: #eee;
}

.tooltip{
  position:relative;
}

.tooltiptext{
  display:none;
  position:absolute;
  z-index:10;
  border:1px;
  background-color:#eee;
  border-style:solid;
  border-width:1px;
  border-color:blue;
  border-radius: 6px;
  padding:3px;
  color:blue;
  top:20px;
  left:20px;
}

.tooltip:hover span.tooltiptext{
  display:block;
}

HTML:

          Col 0
          Col 1
          Col 2A
               Tooltip for header cell
          Col 3A
               Tooltip for header cell
          Col 4A
               Tooltip for header cell
          Col 5A
               Tooltip for header cell
          Col 6A
               Tooltip for header cell
          Col 7A
               Tooltip for header cell
          Col 8A
               Tooltip for header cell
          Col 9A
               Tooltip for header cell

          Col 2B
          Col 3B
          Col 4B
          Col 5B
          Col 6B
          Col 7B
          Col 8B
          Col 9B

          First Cell
          Second Cell
          Another Cell
                  Tooltip for body cell
          Another Cell
                  Tooltip for body cell
          Another Cell
                  Tooltip for body cell
          Another Cell
                  Tooltip for body cell
          Another Cell
                  Tooltip for body cell
          Another Cell
                  Tooltip for body cell
          Another Cell
                  Tooltip for body cell
          Another Cell
                  Tooltip for body cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

          First Cell
          Second Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell
          Another Cell

Fiddle here: https://jsfiddle.net/k42myms3/5/

The goal is to get the tooltips in the top row of the spanned header rows to show on top of the cells on the bottom row of the spanned header rows. I can find ways to get the tooltips to show, for example by removing position:absolute from the .tooltiptext css, but not without either causing positioning problems or breaking the table cells scrolling behind the fixed headers and columns.

Body:
Never mind, fixed it: https://jsfiddle.net/k42myms3/10/

Code added:

th.tooltip{
  position:relative;
  z-index: 35;
}

... and a few other things.


问:
Does Apple allows force update to newer version for iOS Applications?
Does Apple allows any category of iOS application (i.e games or any type) to force users for new version update, without update later or cancel button (if user don't want to do or intend to do it later)

Apple used to reject applications on such scenarios, Please correct me if I am wrong.

An application which currenly forced me to update is as follows:
https://itunes.apple.com/us/app/farmville-2-country-escape/id824318267?mt=8

Please find screenshot attached.

After new version release whenever I open this application, it has only one button which says "Upgrade Now".

I am unable to use until I click upgrade button.

I am wondering is it mistake on Apple review process or is it really
allowed to do now?

答:
This process never really went through the apple verification process.
The logic for this probably is...

-) On launch check for update

-) If a update exists, show prompt and lock the application

If the application was being reviewed, then the reviewer never saw such scenario. I am pretty sure if the reviewer saw such locking mechanism, they would simply reject the application. Either way if you really want to force a user to a specific version, this seems to be the best way forward.


问:
'eslint' is not recognized as an internal or external command
I'm trying to install eslint & run it in vs code.  I ran this command:

```<code>npm i -g eslint
</code>```

and it seemed to work, but I keep getting an error when I try to run
eslint :

"'eslint' is not recognized as an internal or external command,
operable program or batch file".

What gives?

http://eslint.org/docs/user-guide/command-line-interface

http://eslint.org/docs/user-guide/getting-started

答:
The eslint module must not be installed into global.

instead, you should install eslint-cli module into global.

So, first install eslint-cli gloablly:

```<code>npm -g i eslint-cli
</code>```

then in the project folder: install eslint locally

```<code>npm i eslint --save-dev
</code>```

Then in the project folder you can run someting like: (on Windows)

```<code>eslint .\
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to install eslint & run it in vs code.  I ran this command:

npm i -g eslint

and it seemed to work, but I keep getting an error when I try to run
eslint :

"'eslint' is not recognized as an internal or external command,
operable program or batch file".

What gives?

http://eslint.org/docs/user-guide/command-line-interface

http://eslint.org/docs/user-guide/getting-started

Body:
The eslint module must not be installed into global.

instead, you should install eslint-cli module into global.

So, first install eslint-cli gloablly:

npm -g i eslint-cli

then in the project folder: install eslint locally

npm i eslint --save-dev

Then in the project folder you can run someting like: (on Windows)

eslint .\


问:
how to set textview horizontally inside linearlayout
```<code>  <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="2">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorSlate"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/hello"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#5d737e"
                        android:padding="20dp"
                        android:text="₹ 250.00"
                        android:textColor="@color/colorWhite" />

                </LinearLayout>

                <LinearLayout
                    android:id="@+id/world"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorTurquoiseBlue"
                    android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
                    android:orientation="horizontal"
                    android:padding="20dp"
                    android:weightSum="1">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight=".5"
                        android:fontFamily="sans-serif-medium"
                        android:letterSpacing="-0.03"
                        android:text="Go premium"
                        android:textColor="@color/colorWhite"
                        android:textSize="14.4sp"
                        android:textStyle="normal" />

                    <ImageView
                        android:layout_width="8dp"
                        android:layout_height="14dp"
                        android:layout_gravity="center"
                        android:layout_weight=".5"
                        app:srcCompat="@drawable/ic_arrow_white"

                        />
                </LinearLayout>
            </LinearLayout>

        </RelativeLayout>
</code>```

This is my xml i am trying to display text horizontally in first linear-layout but when i try to insert another text-view below text-view inside linear-layout i am my first linear-layout get increase not fit with second layout please suggest me how to achieve this  i want set text below 200 in given screen

答:
```<code><LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">

        <LinearLayout
            android:padding="10dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:background="#5d737e"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/hello"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="₹ 250.00"
                android:textColor="#FFFFFF" />

            <TextView
                android:id="@+id/hello2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Yearly Subscription"
                android:textColor="#FFFFFF" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/world"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"

            android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
            android:orientation="horizontal"
            android:padding="20dp"
            android:weightSum="1">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight=".5"
                android:fontFamily="sans-serif-medium"
                android:letterSpacing="-0.03"
                android:text="Go premium"
                android:textColor="#000"
                android:textSize="14.4sp"
                android:textStyle="normal" />

            <ImageView
                android:layout_width="8dp"
                android:layout_height="14dp"
                android:layout_gravity="center"
                android:layout_weight=".5"
                app:srcCompat="@drawable/ic_arrow_white"

                />
        </LinearLayout>
    </LinearLayout>
</code>```

try this. :)

Body:
  <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="2">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorSlate"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/hello"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="#5d737e"
                        android:padding="20dp"
                        android:text="₹ 250.00"
                        android:textColor="@color/colorWhite" />

                </LinearLayout>

                <LinearLayout
                    android:id="@+id/world"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:background="@color/colorTurquoiseBlue"
                    android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
                    android:orientation="horizontal"
                    android:padding="20dp"
                    android:weightSum="1">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_weight=".5"
                        android:fontFamily="sans-serif-medium"
                        android:letterSpacing="-0.03"
                        android:text="Go premium"
                        android:textColor="@color/colorWhite"
                        android:textSize="14.4sp"
                        android:textStyle="normal" />

                    <ImageView
                        android:layout_width="8dp"
                        android:layout_height="14dp"
                        android:layout_gravity="center"
                        android:layout_weight=".5"
                        app:srcCompat="@drawable/ic_arrow_white"

                        />
                </LinearLayout>
            </LinearLayout>

        </RelativeLayout>

This is my xml i am trying to display text horizontally in first linear-layout but when i try to insert another text-view below text-view inside linear-layout i am my first linear-layout get increase not fit with second layout please suggest me how to achieve this  i want set text below 200 in given screen

Body:
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">

        <LinearLayout
            android:padding="10dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:background="#5d737e"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:id="@+id/hello"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="₹ 250.00"
                android:textColor="#FFFFFF" />

            <TextView
                android:id="@+id/hello2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Yearly Subscription"
                android:textColor="#FFFFFF" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/world"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"

            android:onClick="@{()->upgradeViewModel.gotoPremimum()}"
            android:orientation="horizontal"
            android:padding="20dp"
            android:weightSum="1">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight=".5"
                android:fontFamily="sans-serif-medium"
                android:letterSpacing="-0.03"
                android:text="Go premium"
                android:textColor="#000"
                android:textSize="14.4sp"
                android:textStyle="normal" />

            <ImageView
                android:layout_width="8dp"
                android:layout_height="14dp"
                android:layout_gravity="center"
                android:layout_weight=".5"
                app:srcCompat="@drawable/ic_arrow_white"

                />
        </LinearLayout>
    </LinearLayout>

try this. :)


问:
Removing last empty row of dataGridView
I have some empty datagridview which uses data source is List through BindingSource. Because AllowUserToAddRows = true, initially the datagridview has one empty row. When I just select this row and close the form then datagridview creates new empty object. Why it does it? How to prevent this?
Thanks.

Selecting of empty row:

And I get this:

Conclusion: After many attempts to find a solution I decided to create UI control with datagridview and two buttons (add row and delete row). At this point I stopped trying to do as planned, but I'd still be pleased to know solutions.

答:
Yes, there will always be an empty row at the bottom of a DataGridView. It allows the user to add new data at run-time; all they have to do is start typing in the new row.

To disable it, you will also need to prevent the user from adding new rows. Do this by setting the AllowUserToAddRows property of your DataGridView control to False:

myDataGridView.AllowUserToAddRows = false;

Title: Removing last empty row of dataGridView