问:
Link to RSS/Atom feed, relative, doesn't work in Firefox
I have a weird problem. I generate a HTML page, hosted let's say at http://www.x.com/stuff which contains

```<code><head>
  <link type="application/atom+xml" rel="alternate" href="/stuff/feed"/>
  ..
</head>
</code>```

The result is:

In IE7 all works well - you can click on the feed icon in the browser and the feed is displayed

In Firefox, view source, click on the linked /stuff/feed and you see the source of the feed, so that works as expected

In Firefox, view the page (not source), then click on the feed icon in the address bar, I get an error that it can't retrieve the URL feed://http//www.x.com/stuff/feed

So the problem is, that it's appending feed:// to the front of the URL and then taking out the colon : after the http. I understand that feed: is HTTP anyway so perhaps the adding of that isn't a big problem.

But anyway, the fact is, that URL Firefox generates out of my <link> tag doesn't work.

I have considered making the URL absolute, but I haven't found any evidence that those URLs have to be absolute, nor can I understand why that would be the case. And for various reasons it would be inconvenient in my code to generate an absolute URL. I can do it if necessary but I would prefer to see proof (e.g. specification, or Mozilla bug report) that it's necessary before making my code messy

What do you think? Does anyone know of any evidence that the URL should be absolute? Or am I doing something else wrong? It seems such a simple/obvious tag, where nothing could go wrong, but I can't get it to work.

答: Put an absolute URL, it's a good practice for  elements and won't break browsers...</p>

Body:
I have a weird problem. I generate a HTML page, hosted let's say at http://www.x.com/stuff which contains

  <link type="application/atom+xml" rel="alternate" href="/stuff/feed"/>
  ..

The result is:

In IE7 all works well - you can click on the feed icon in the browser and the feed is displayed

In Firefox, view source, click on the linked /stuff/feed and you see the source of the feed, so that works as expected

In Firefox, view the page (not source), then click on the feed icon in the address bar, I get an error that it can't retrieve the URL feed://http//www.x.com/stuff/feed

So the problem is, that it's appending feed:// to the front of the URL and then taking out the colon : after the http. I understand that feed: is HTTP anyway so perhaps the adding of that isn't a big problem.

But anyway, the fact is, that URL Firefox generates out of my <link> tag doesn't work.

I have considered making the URL absolute, but I haven't found any evidence that those URLs have to be absolute, nor can I understand why that would be the case. And for various reasons it would be inconvenient in my code to generate an absolute URL. I can do it if necessary but I would prefer to see proof (e.g. specification, or Mozilla bug report) that it's necessary before making my code messy

What do you think? Does anyone know of any evidence that the URL should be absolute? Or am I doing something else wrong? It seems such a simple/obvious tag, where nothing could go wrong, but I can't get it to work.


来源: stackexchange

问:
Android How to change layout option from Material Design to standard android
Im beginner to Android (and programming too) and Im following one of the tutorial how to make an Android app using Material Desing. Unfortunately as the tutorial was made two years ago it looks like the newer version of Android have dropped the dependency Im looking for (roundIcon). How to change the layout from MD into the standard android?

Below there is  my manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gosia.animalsystem"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="23" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.gosia.animalsystem.AnimalSystemActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
In the styles.xml check for the appTheme.
Currently it must be an AppCompatTheme

Change that to Any HOLO theme.

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
Im beginner to Android (and programming too) and Im following one of the tutorial how to make an Android app using Material Desing. Unfortunately as the tutorial was made two years ago it looks like the newer version of Android have dropped the dependency Im looking for (roundIcon). How to change the layout from MD into the standard android?

Below there is  my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gosia.animalsystem"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="23" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.gosia.animalsystem.AnimalSystemActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


问:
Jenkins- Rendering html page in email
Sending email using Editable Email Notification plugin in Jenkins

Following is the complete folder structure of the index.html file contains folders related to CCS, styling and images for the html page.

After receiving a mail- email is not loading image and css contents in email body.

Not sure how it will get reference to CSS, image and other stylings

答:
For emails to work the CSS has to in-lined first, there are some email clients that don't read CSS in the head of the document.

Here are three resources you can use to inline your CSS:

PutsMail (litmus powered)

CSS Inliner Tool

CSS inliner

Note in order to use these your CSS has to be in the head of the document or it will not work.

That covers the CSS part, now the images. The images have to be loaded to a server and an absolute path has to be referenced in the HTML. If there is a relative path those images will not load.

Let me know if you have any questions.

Title: Jenkins- Rendering html page in email


问:
What's the difference between DMA Controller and I/O processor
Given the starting memory address & word count DMA controller transfers data while the CPU works on some other process.
The Input Output processor too handles I/O processes given the starting address & word count..
(correct me if I'm in error)

So what's the difference in functionality between IOP & DMA controller?

答:
In  case of memory specific I/O operations (Simple example instructions  like lw $r1,$r2,16 in case of MIPS processor), CPU needs to  get the data from memory,to facilitate I/O operations. And so CPU has to pause any other operation and monitor the memory READ/WRITE  operation till it is not completed. In other words CPU is totally  occupied as long as read/write operation is in progress without DMA .If the  processor was free during this time,then processor could have executed  some other instructions .

Direct Memory Access(DMA):

DMA  provides this capability to carry out memory specific operations with  minimal CPU intervention. When any I/O device needs a memory  access. It sends a DMA request(in form of interrupt) to CPU. CPU initiates the the transfer by providing appropriate grant signals to the data bus. And passes the control to the DMA controller  which controls the rest of the data transfer and transfers the data  directly to I/O device. During this time, CPU continues with  other instructions. Once the Read/Write operation in completed (or any  exception is occurred )the DMA controller initiates an interrupt and  notifies the processor about the status of read/write operation.

In  this way the read/write operation is also carried out and CPU also executes some other instruction during that time. However, initialization of DMA still requires CPU intervention. And so the  overall performance is maximized.

I/O processor

You can think I/O processor along the lines of DMA approach.
The I/O processor, generally used in large computer systems, is a coprocessor which is capable of executing the instructions in addition to transfer of data. By the way, the coprocessor instruction system is different from the central processing unit.

CPU can execute the I/O specific program by initializing the basic operations like enabling the data path and setting up the I/O devices participating in operation. And then it transfers the task to I/O  processor,which then carry out rest of the tasks and upon completion  notifies the processor. The processor meanwhile executes other important  instructions.

The I/O processor is essentially a small DMA dedicated processor that can execute limited input and output instructions and can be shared by multiple peripherals.

The I/O processor solves two problems:

The job of input and output is assumed by the CPU.
Although DMA does not require CPU for data exchange between peripherals and memory, it only reduces the burden of CPU. Because in DMA, the initialization of input and output is still done by CPU.

The problem of sharing DMA interface of high speed equipment in large computer system. A large computer system peripherals so much that it had to share the DMA interface Limited (small computer systems such as PC in each device is assigned a DMA high speed interface).


问:
JAXB serialize JsonElement field in POJO
I have a POJO class like:

```<code>class Cat {
  public Cat() {}
  private String name;
  private JsonElement arbitraryProperties;
}
</code>```

I am using Jackson (JAXB) and cat is a resource I want to import and export.

```<code>GET /cats/{id}
POST /cats
</code>```

Export is working fine. Import did not work because JsonElement is abstract. So I added @JsonDeserialize(using = MyJsonElementDeserialize.class) annotation to the arbitraryProperties field.

The MyJsonElementDeserialize class looks like:

```<code>public class JsonElementDeserialize extends JsonDeserializer<JsonElement> {

public JsonElementDeserialize() {
}

@Override
public JsonElement deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    return new JsonObject(); // here I need to create my object later
}
</code>```

}

When I now call POST /cats with payload:

```<code>{
  "name": "Mia",
  "arbitraryProperties": {
        "a": 3,
        "b": [],
        "c": {
            "d": "race"
        }
   }
 }
</code>```

Jacksons returns error code 400:

Unrecognized field "a" (class Cat), not marked as ignorable (1 known properties: "name"]).

Where is my mistake? How can I have a JsonElement in my POJO that gets automatically serialized and deserialized?

答: If could, I would change JsonElement to  JsonNode, and use “Tree Model” of Jackson. </p>

Body:
I have a POJO class like:

class Cat {
  public Cat() {}
  private String name;
  private JsonElement arbitraryProperties;
}

I am using Jackson (JAXB) and cat is a resource I want to import and export.

GET /cats/{id}
POST /cats

Export is working fine. Import did not work because JsonElement is abstract. So I added @JsonDeserialize(using = MyJsonElementDeserialize.class) annotation to the arbitraryProperties field.

The MyJsonElementDeserialize class looks like:

public class JsonElementDeserialize extends JsonDeserializer<JsonElement> {

public JsonElementDeserialize() {
}

@Override
public JsonElement deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    return new JsonObject(); // here I need to create my object later
}

}

When I now call POST /cats with payload:

{
  "name": "Mia",
  "arbitraryProperties": {
        "a": 3,
        "b": [],
        "c": {
            "d": "race"
        }
   }
 }

Jacksons returns error code 400:

Unrecognized field "a" (class Cat), not marked as ignorable (1 known properties: "name"]).

Where is my mistake? How can I have a JsonElement in my POJO that gets automatically serialized and deserialized?


问:
android: html in textview with link clickable
I use an a-htmltag in my TextView, but when i tap on it nothing happens.

How can I make it open the web browser with the url?

答:
You can do it this way;</p>
```<code>mTextView = (TextView) findViewById(R.id.textView);
String text = "Visit my developer.android.com";
mTextView.setText(text);
// pattern we want to match and turn into a clickable link
Pattern pattern = Pattern.compile("developer.android.com");
// prefix our pattern with http://
Linkify.addLinks(mTextView, pattern, "http://")
</code>```

Body:
You can do it this way;

mTextView = (TextView) findViewById(R.id.textView);
String text = "Visit my developer.android.com";
mTextView.setText(text);
// pattern we want to match and turn into a clickable link
Pattern pattern = Pattern.compile("developer.android.com");
// prefix our pattern with http://
Linkify.addLinks(mTextView, pattern, "http://")

ContentLicense: CC BY-SA 4.0


问:
I don't know what happened in terminal
I have some problem and I don't know at all... Here is my shell.

```<code>Last login: Tue Jun  6 20:20:15 on ttys000
-bash: home/username/programs/apache-maven-3.5.0/bin:/usr/local/bin:/usr/bin:/bi
n:/usr/sbin:/sbin:/usr/local/share/dotnet:/Library/Frameworks/Mono.framework/Ver
sions/Current/Commands: No such file or directory
-bash: uname: command not found
-bash: ps: command not found
-bash: touch: command not found
</code>```

I already googling but I can't find answer... what is this problem and how can I fix it?

答:
It look like your PATH environment variable setting wrong value.

change home/username/programs/apache-maven-3.5.0/bin to /home/username/programs/apache-maven-3.5.0/bin

or just to deleted it

Title: I don't know what happened in terminal

Body:
I have some problem and I don't know at all... Here is my shell.

Last login: Tue Jun  6 20:20:15 on ttys000
-bash: home/username/programs/apache-maven-3.5.0/bin:/usr/local/bin:/usr/bin:/bi
n:/usr/sbin:/sbin:/usr/local/share/dotnet:/Library/Frameworks/Mono.framework/Ver
sions/Current/Commands: No such file or directory
-bash: uname: command not found
-bash: ps: command not found
-bash: touch: command not found

I already googling but I can't find answer... what is this problem and how can I fix it?


问:
Conditional Joins in SQL
I'm trying to write a query which checks to see if a value in TblFamily is null and if it is, performs a different set of joins.  I'm getting the error 'Incorrect syntax near the keyword 'OUTER''.

I've had a look at other conditional join posts and most of them seem to be related to which field to join to, not whether or not to substitute one join for another so I haven't found any examples of correct syntax.

Any clues?

```<code>SELECT
  TblServiceUser.ServiceUserId

FROM
TblServiceUser

(CASE WHEN TblFamily.FamilyServiceUserId IS NULL THEN
(LEFT OUTER JOIN TblActivity ON TblActivity.ActivityServiceUserId = TblServiceUser.ServiceUserId)
ELSE
(LEFT OUTER JOIN TblFamily ON TblFamily.FamilyServiceUserId = TblServiceUser.ServiceUserId
 LEFT OUTER JOIN TblActivity ON TblServiceUser.ServiceUserId = TblActivity.ActivityServiceUserId)
END)
</code>```

答:
Here what u need</p>

```<code>declare @SQL varchar(max)
select @SQL = 'SELECT
  TblServiceUser.ServiceUserId
FROM
TblServiceUser'+
CASE WHEN TblFamily.FamilyServiceUserId IS NULL THEN
+'LEFT OUTER JOIN TblActivity ON TblActivity.ActivityServiceUserId = TblServiceUser.ServiceUserId+' ELSE
+'LEFT OUTER JOIN TblFamily ON TblFamily.FamilyServiceUserId = TblServiceUser.ServiceUserId
 LEFT OUTER JOIN TblActivity ON TblServiceUser.ServiceUserId = TblActivity.ActivityServiceUserId'+ END

 exec @SQL
</code>```

Title: Conditional Joins in SQL

Body:
I'm trying to write a query which checks to see if a value in TblFamily is null and if it is, performs a different set of joins.  I'm getting the error 'Incorrect syntax near the keyword 'OUTER''.

I've had a look at other conditional join posts and most of them seem to be related to which field to join to, not whether or not to substitute one join for another so I haven't found any examples of correct syntax.

Any clues?

SELECT
  TblServiceUser.ServiceUserId

FROM
TblServiceUser

(CASE WHEN TblFamily.FamilyServiceUserId IS NULL THEN
(LEFT OUTER JOIN TblActivity ON TblActivity.ActivityServiceUserId = TblServiceUser.ServiceUserId)
ELSE
(LEFT OUTER JOIN TblFamily ON TblFamily.FamilyServiceUserId = TblServiceUser.ServiceUserId
 LEFT OUTER JOIN TblActivity ON TblServiceUser.ServiceUserId = TblActivity.ActivityServiceUserId)
END)

Body:
Here what u need

declare @SQL varchar(max)
select @SQL = 'SELECT
  TblServiceUser.ServiceUserId
FROM
TblServiceUser'+
CASE WHEN TblFamily.FamilyServiceUserId IS NULL THEN
+'LEFT OUTER JOIN TblActivity ON TblActivity.ActivityServiceUserId = TblServiceUser.ServiceUserId+' ELSE
+'LEFT OUTER JOIN TblFamily ON TblFamily.FamilyServiceUserId = TblServiceUser.ServiceUserId
 LEFT OUTER JOIN TblActivity ON TblServiceUser.ServiceUserId = TblActivity.ActivityServiceUserId'+ END

 exec @SQL


问:
Listener to detect whether a view is at the front?
I have RecyclerView and, in some cases, I show another view on top of it - ProgressDialog, AlertDialog or DialogFragment.

Is there some way to notify me about cases when my RecyclerView is at front or another view is above it now?

I tried to add onFocusChangeListener() to my RecyclerView, but no luck.

PS. Definitely, I can in my RecyclerView create some method isOnFront(boolean onFront) and in all my other views call it, but maybe there is some more elegance way?

答:
I think you should rethink your software design. If YOU trigger dialogs to be shown on top of another views, then you SHOULD know if the are shown or not. Another question is: Why should your RecyclerView know something about other views in your application?

If you really want to know, if your dialog is shown or not, set a boolean variable in your Fragment (or Activity), when you show it. Or use the field itself as indicator (myDialog != null equals "myDialog is shown"). Set it to null if you dismiss your dialog. If you really need to let other Fragments or Views know, that you show a dialog on top of them you can use any kind of event bus to broadcast this event.

I do not recommend tampering with any kind of ViewTreeObserver listeners or FragmentBackstack listeners for getting this result.


问:
Wordpress/PHP: Shorten title if title characters are more than 8 characters
I am trying to learn how to shorten a title only if it is over 8 characters long. If it is longer than 8 characters, then echo the first 8 characters and put an ellipse after it.

Here is how I am getting the title:

<?php echo $post->post_title ?>

Any help would be greatly appreciated. This will be a great learning lesson for me so I can replicate this in the future, so again any help would be amazing.

答:
you can try this.

```<code>$maxlength = 8;
if (strlen($post->post_title) > $maxlength)
       echo substr($post->post_title, 0, $maxlength) . ' ...';
    else
       echo $post->post_title;
</code>```

So by now you no need to change max char in all the line of code.

Thanks.

ContentLicense: CC BY-SA 2.5

Body:
you can try this.

$maxlength = 8;
if (strlen($post->post_title) > $maxlength)
       echo substr($post->post_title, 0, $maxlength) . ' ...';
    else
       echo $post->post_title;

So by now you no need to change max char in all the line of code.

Thanks.


问:
Is it possible to take the last folder in the path?
Need to get the last folder or element after slash in the path. In other words I have:

```<code>path = '/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/'
</code>```

and I need to get:

```<code>'thumbnails_features_deduped_sample'
</code>```

from it.

```<code>for d, _, files in os.walk(path):
    print(d[4])  # would be great to have something like this..
</code>```

How to do it nicely, maybe someone knows?

Thanks a lot in advance.

答:
Yes, it's possible:

Use os.path.basename:

```<code>>>> os.path.basename('/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/')
'thumbnails_features_deduped_sample'
</code>```

You can also use normpath to accommodate the trailing /:

```<code>>>> os.path.basename(os.path.normpath('/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/'))
</code>```

Body:
Need to get the last folder or element after slash in the path. In other words I have:

path = '/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/'

and I need to get:

'thumbnails_features_deduped_sample'

from it.

for d, _, files in os.walk(path):
    print(d[4])  # would be great to have something like this..

How to do it nicely, maybe someone knows?

Thanks a lot in advance.

Body:
Yes, it's possible:

Use os.path.basename:

>>> os.path.basename('/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/')
'thumbnails_features_deduped_sample'

You can also use normpath to accommodate the trailing /:

>>> os.path.basename(os.path.normpath('/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/'))


问:
Disable Javascript after page is loaded should be detected on action page
I think i have searched already about  tags and yes i am using them already.

But here my question or Idea is:

I have a form including input to search/insert data into database (mysql) (index.php)
form action is being performed on search.php
search box searches input data in the selected tables, if it is found, then it gives the records in result.php, otherwise it inserts the data in table(sql) and then shows it in result.php

I am validating the form/input using javascript on the same page even using  tags
Now after loading the index.php page, if someone disable javascript, it shows an alert to reload the page. if someone reload the page, searchbox will hide.

but the problem is, if after loading the page, if someone disable javascript and does not reload the page, and search some restricted text using javascript regex, that text goes into mysql database and it is saved. search.php perform its action and redirect it to result.php

I want some trick in search.php that checks some condition for javascript enabled/disabled, then perform the remaining actions.

IS THERE ANY WAY, IF ACTION SHOULD BE ANOTHER PAGE, on that page is javascript is disabled then it shows nothing, and if it is enabled then redirects to search.php

答:
Form validation on JS level is unimportant, what you need to think about is your php validation. Please read top answers of: form validation with javascript vs php

and this:
How can I prevent SQL injection in PHP?

If you need to check if JS is enabled you can simply make button for your form (but not type="submit" but just a button element). Add event to that button:

```<code>onclick="document.getElementById('FormId').submit();"
</code>```

and your form will be submitted only if JS is enabled as button will use JS for submission

Body:
Form validation on JS level is unimportant, what you need to think about is your php validation. Please read top answers of: form validation with javascript vs php

and this:
How can I prevent SQL injection in PHP?

If you need to check if JS is enabled you can simply make button for your form (but not type="submit" but just a button element). Add event to that button:

onclick="document.getElementById('FormId').submit();"

and your form will be submitted only if JS is enabled as button will use JS for submission


问:
Set Variable Varchar2 to date fields
I have a Script that I update a Date field

this is a part of my script

```<code>    var VARCHAR2(8 char);

var = '01/01/22';
    update table1 t set t.date = to_date(var,'dd/mm/yy');
</code>```

and then I got a null value in field date

why I dont have a 01/01/22 value ??

could you help me please !!

ANSWER       :::::::::::     PETIT PAPA merci :D

I created I new Varible with Date type

and I affecte the to_date to this variable

```<code>date_var Date;

date_var :=to_date(var,'dd/mm/yy');

update table1 t set t.date = date_var where ...;
</code>```

and it work THANK YOU everyONE

答: Miistake here is that it's not todate it is to_date

Title: Set Variable Varchar2 to date fields

Body:
I have a Script that I update a Date field

this is a part of my script

    var VARCHAR2(8 char);

var = '01/01/22';
    update table1 t set t.date = to_date(var,'dd/mm/yy');

and then I got a null value in field date

why I dont have a 01/01/22 value ??

could you help me please !!

ANSWER       :::::::::::     PETIT PAPA merci :D

I created I new Varible with Date type

and I affecte the to_date to this variable

date_var Date;

date_var :=to_date(var,'dd/mm/yy');

update table1 t set t.date = date_var where ...;

and it work THANK YOU everyONE


问:
First
 element in
 in same line
```<code><ul>
  <li>1</li>
  <ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
  </ul>
</ul>
</code>```

How would I display this list like so:

答:
Display the ul as inline-block inside the li, and align it vertically to top:

.nested {
  display: inline-block;
  vertical-align: top;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>1
    <ul class="nested">
      <li>a</li>
      <li>b</li>
      <li>c</li>
    </ul>
  </li>
</ul></code>```

Title: First <li> element in <ul> in same line

Body:
1

a

b

c

How would I display this list like so:

Body:
Display the ul as inline-block inside the li, and align it vertically to top:

.nested {
  display: inline-block;
  vertical-align: top;
}

<ul>
  <li>1
    <ul class="nested">
      <li>a</li>
      <li>b</li>
      <li>c</li>
    </ul>
  </li>
</ul>


问:
ZF3 dbadapters not getting in form validation
I have configure dbadapters as per below.

Added below code in config/autoload/global.php

```<code>  use Zend\Session\Storage\SessionArrayStorage;
  use Zend\Session\Validator\RemoteAddr;
  use Zend\Session\Validator\HttpUserAgent;

  use Zend\Db\Adapter;
  use Zend\ServiceManager\Factory\InvokableFactory;

   return [
// Session configuration.
'session_config' => [
    'cookie_lifetime' => 60 * 60 * 1, // Session cookie will expire in 1 hour.
    'gc_maxlifetime' => 60 * 60 * 24 * 30, // How long to store session data on server (for 1 month).
],
// Session manager configuration.
'session_manager' => [
    // Session validators (used for security).
    'validators' => [
        RemoteAddr::class,
        HttpUserAgent::class,
    ]
],
// Session storage configuration.
'session_storage' => [
    'type' => SessionArrayStorage::class
],

'service_manager' => [
    'abstract_factories' => [
        Adapter\AdapterAbstractServiceFactory::class,
    ],
    'factories' => [
        Adapter\AdapterInterface::class => Adapter\AdapterServiceFactory::class,
    ],
    'aliases' => [
        Adapter\Adapter::class => Adapter\AdapterInterface::class,
    ],
],

];
</code>```

After that i have added below code to config/autoload/development.local.php

```<code>return [
'view_manager' => [
    'display_exceptions' => true,
],

'doctrine' => [
    'connection' => [
        'orm_default' => [
            'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
            'params' => [
                'host' => 'host',
                'user' => 'root',
                'password' => 'root',
                'dbname' => 'dbname',
            ]
        ],
    ],
],

'db' => [
    'adapters' => [
        'db' => [
            'driver' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
            'dsn' => 'mysql:dbname=dbname;host=host',
            'driver_options' => [
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
            ],
            'username' => 'root',
            'password' => 'root',
        ],
    ],
],
];
</code>```

How to get dbAdapters in controller and form?

I want to use NoRecordExists validation in form filter.
like

```<code>  array(
                    'name' => 'Zend\Validator\Db\NoRecordExists',
                    'options' => array(
                        'table' => 'test_user',
                        'field' => 'email',
                        'adapter' => $this->dbAdapter,
                        'exclude' => $this->excludeFields,
                        'messages' => array(
                            \Zend\Validator\Db\NoRecordExists::ERROR_RECORD_FOUND => 'Email already exists'
                        ),
                    ),
                    'break_chain_on_failure' => true
                )
</code>```

Share your ideas or give me suggestion to configure dbAdapters globally in ZF3.

答:
You need to inject the adapter into the form using a factory. I'm not sure if form validation with Doctrine is supported out of the box so my example will be using regular old zend-db.

In short:

Set up a simple factory and supply the adapter to the form using dependency injection.

The form

The form needs to accept the dependency, so add a parameter to the constructor:

```<code>/**
 * @var \Zend\Db\Adapter\Adapter
 */
private $dbAdapter;

/**
 * @param \Zend\Db\Adapter\Adapter $adapter
 */
public function __construct(\Zend\Db\Adapter\Adapter $adapter)
{
    $this->dbAdapter = $adapter;
}
</code>```

The factory

```<code>namespace MyModule\Factory\Form;

use Zend\ServiceManager\Factory\FactoryInterface;

/**
 * Class MyFormFactory
 * @package MyModule\Factory\Form
 */
class MyFormFactory implements FactoryInterface
{
    /**
     * Create an object
     *
     * @param  ContainerInterface $container
     * @param  string             $requestedName
     * @param  null|array         $options
     *
     * @return object
     * @throws ServiceNotFoundException if unable to resolve the service.
     * @throws ServiceNotCreatedException if an exception is raised when
     *     creating a service.
     * @throws ContainerException if any other error occurs
     */
    public function __invoke(
        ContainerInterface $container,
        $requestedName,
        array $options = null
    ) {
        /** @var \Zend\Db\Adapter\AdapterInterface $adapter */
        $adapter  = $container->get(AdapterInterface::class);

        return new MyForm($adapter);
    }
}
</code>```

Finally:

In your module.config.php you need to tell your application to invoke the factory to set up the form:

```<code>'service_manager_' => [
    'factories' => [
        Form\MyForm::class => Factory\Form\MyFormFactory::class
    ]
],
</code>```

As Dymen1 mentioned you could probably benefit from trying out the tutorial in the documentation where this subject is explained.

Body:
I have configure dbadapters as per below.

Added below code in config/autoload/global.php

  use Zend\Session\Storage\SessionArrayStorage;
  use Zend\Session\Validator\RemoteAddr;
  use Zend\Session\Validator\HttpUserAgent;

  use Zend\Db\Adapter;
  use Zend\ServiceManager\Factory\InvokableFactory;

   return [
// Session configuration.
'session_config' => [
    'cookie_lifetime' => 60 * 60 * 1, // Session cookie will expire in 1 hour.
    'gc_maxlifetime' => 60 * 60 * 24 * 30, // How long to store session data on server (for 1 month).
],
// Session manager configuration.
'session_manager' => [
    // Session validators (used for security).
    'validators' => [
        RemoteAddr::class,
        HttpUserAgent::class,
    ]
],
// Session storage configuration.
'session_storage' => [
    'type' => SessionArrayStorage::class
],

'service_manager' => [
    'abstract_factories' => [
        Adapter\AdapterAbstractServiceFactory::class,
    ],
    'factories' => [
        Adapter\AdapterInterface::class => Adapter\AdapterServiceFactory::class,
    ],
    'aliases' => [
        Adapter\Adapter::class => Adapter\AdapterInterface::class,
    ],
],

];

After that i have added below code to config/autoload/development.local.php

return [
'view_manager' => [
    'display_exceptions' => true,
],

'doctrine' => [
    'connection' => [
        'orm_default' => [
            'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
            'params' => [
                'host' => 'host',
                'user' => 'root',
                'password' => 'root',
                'dbname' => 'dbname',
            ]
        ],
    ],
],

'db' => [
    'adapters' => [
        'db' => [
            'driver' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
            'dsn' => 'mysql:dbname=dbname;host=host',
            'driver_options' => [
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
            ],
            'username' => 'root',
            'password' => 'root',
        ],
    ],
],
];

How to get dbAdapters in controller and form?

I want to use NoRecordExists validation in form filter.
like

  array(
                    'name' => 'Zend\Validator\Db\NoRecordExists',
                    'options' => array(
                        'table' => 'test_user',
                        'field' => 'email',
                        'adapter' => $this->dbAdapter,
                        'exclude' => $this->excludeFields,
                        'messages' => array(
                            \Zend\Validator\Db\NoRecordExists::ERROR_RECORD_FOUND => 'Email already exists'
                        ),
                    ),
                    'break_chain_on_failure' => true
                )

Share your ideas or give me suggestion to configure dbAdapters globally in ZF3.

Body:
You need to inject the adapter into the form using a factory. I'm not sure if form validation with Doctrine is supported out of the box so my example will be using regular old zend-db.

In short:

Set up a simple factory and supply the adapter to the form using dependency injection.

The form

The form needs to accept the dependency, so add a parameter to the constructor:

/**
 * @var \Zend\Db\Adapter\Adapter
 */
private $dbAdapter;

/**
 * @param \Zend\Db\Adapter\Adapter $adapter
 */
public function __construct(\Zend\Db\Adapter\Adapter $adapter)
{
    $this->dbAdapter = $adapter;
}

The factory

namespace MyModule\Factory\Form;

use Zend\ServiceManager\Factory\FactoryInterface;

/**
 * Class MyFormFactory
 * @package MyModule\Factory\Form
 */
class MyFormFactory implements FactoryInterface
{
    /**
     * Create an object
     *
     * @param  ContainerInterface $container
     * @param  string             $requestedName
     * @param  null|array         $options
     *
     * @return object
     * @throws ServiceNotFoundException if unable to resolve the service.
     * @throws ServiceNotCreatedException if an exception is raised when
     *     creating a service.
     * @throws ContainerException if any other error occurs
     */
    public function __invoke(
        ContainerInterface $container,
        $requestedName,
        array $options = null
    ) {
        /** @var \Zend\Db\Adapter\AdapterInterface $adapter */
        $adapter  = $container->get(AdapterInterface::class);

        return new MyForm($adapter);
    }
}

Finally:

In your module.config.php you need to tell your application to invoke the factory to set up the form:

'service_manager_' => [
    'factories' => [
        Form\MyForm::class => Factory\Form\MyFormFactory::class
    ]
],

As Dymen1 mentioned you could probably benefit from trying out the tutorial in the documentation where this subject is explained.


问:
Define bean depending on Spring's bean
When using Spring Boot, a lot of beans are created implicitly by Spring Boot itself. For example, when I link the spring-boot-starter-data-redis dependency, the jedisConnectionFactory bean is created automatically under the hood.

What I'm looking for is the way to define my custom bean with a dependency on such an implicit bean, e.g. new MyService( jedisConnectionFactory ). The problem is that I don't have a variable or a method which would be resolved to that implicit bean.

For now I've come up with the following solution: create a separate BeanConfig class, autowire/inject ApplicationContext into it and then retrieve the required bean with ApplicationContext.getBean( Class<T> ) method call:

```<code>@Bean
public Transport eventTransport() {
    final JedisConnectionFactory jedisConnectionFactory = context.getBean( JedisConnectionFactory.class );
    return new RedisTransport( jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort() );
}
</code>```

Is there any integrated way to get a reference to the beans defined internally? So that I could move this bean definition to MyApplication class without injecting the ApplicationContext instance.

答:
If JedisConnectionFactory class is getting instantiated by spring then you can simply autowire this instance at the class level and use the same to create RedisTransport object.

```<code>@Autowired
private JedisConnectionFactory jedisConnectionFactory;

@Bean
public Transport eventTransport() {
    return new RedisTransport( jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort() );
}
</code>```

Title: Define bean depending on Spring's bean

Body:
When using Spring Boot, a lot of beans are created implicitly by Spring Boot itself. For example, when I link the spring-boot-starter-data-redis dependency, the jedisConnectionFactory bean is created automatically under the hood.

What I'm looking for is the way to define my custom bean with a dependency on such an implicit bean, e.g. new MyService( jedisConnectionFactory ). The problem is that I don't have a variable or a method which would be resolved to that implicit bean.

For now I've come up with the following solution: create a separate BeanConfig class, autowire/inject ApplicationContext into it and then retrieve the required bean with ApplicationContext.getBean( Class<T> ) method call:

@Bean
public Transport eventTransport() {
    final JedisConnectionFactory jedisConnectionFactory = context.getBean( JedisConnectionFactory.class );
    return new RedisTransport( jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort() );
}

Is there any integrated way to get a reference to the beans defined internally? So that I could move this bean definition to MyApplication class without injecting the ApplicationContext instance.

Body:
If JedisConnectionFactory class is getting instantiated by spring then you can simply autowire this instance at the class level and use the same to create RedisTransport object.

@Autowired
private JedisConnectionFactory jedisConnectionFactory;

@Bean
public Transport eventTransport() {
    return new RedisTransport( jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort() );
}


问:
Is it possible to disable Toasts or wait until toast disappears while testing
I am testing an app with Espresso. I have one question is it possible to wait until there are no toast are currently being showed. I have a lot of different toast in my app, but while testing I have problems with them because as far as I can guess focus is gone to the toast and I am getting quite another view hierarchy as I can see in error logs.

So my question is it possible to hide all (system wide with root access) or just wait until there are any toasts on the screen or maybe if it is possible to set focus to the activity view hierarchy manually.

I would be grateful for any help with this problem.

Thank you.

P.S. Disabling toast directly somewhere in my app is not an option because it brings some extra logic into the app which is only required while testing.

答:
I have not found any perfect solution to this, but the best is to make a mToast member variable visible for testing, and use that to cancel any active toast in @After, like this:

When showing toast (the production code for the Activity under test):

```<code>@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
Toast mToast;

private void showToast(final String text) {
    mToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    mToast.show();
}
</code>```

The test code (in the same package as the code under test):

```<code>    @After
    public void tearDown() {
        // Remove any toast message that is still shown:
        Toast toast = mActivityRule.getActivity().mToast;
        if (toast != null) {
            toast.cancel();
        }
    }
</code>```

This will require you to change the production code a tiny bit, but using @VisibleForTesting in the latest version of Android Studio will give error if you use the member variable elsewhere.

Body:
I have not found any perfect solution to this, but the best is to make a mToast member variable visible for testing, and use that to cancel any active toast in @After, like this:

When showing toast (the production code for the Activity under test):

@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
Toast mToast;

private void showToast(final String text) {
    mToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    mToast.show();
}

The test code (in the same package as the code under test):

    @After
    public void tearDown() {
        // Remove any toast message that is still shown:
        Toast toast = mActivityRule.getActivity().mToast;
        if (toast != null) {
            toast.cancel();
        }
    }

This will require you to change the production code a tiny bit, but using @VisibleForTesting in the latest version of Android Studio will give error if you use the member variable elsewhere.


问:
Searching by has_parent and another query elasticsearch
I have a parent/child relationship and I need to filter children based on parent ID and child properties. However, I can filter children by parent ID but I can not filter by any child properties.

Here is my search:

```<code>{
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "name": "beer"
                    }
                }
            ],
            "must": [
                {
                    "has_parent": {
                        "type": "pubs",
                        "score_mode": "score",
                        "query": {
                            "ids": {
                                "values": ["AVx3Ruk03JWWfjjJokHs"]
                            }
                        }
                    }
                }
            ]
        }
    }
}
</code>```

But I was given results like this:

```<code>{
    "took": 98,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 0.5,
        "hits": [
            {
                "_index": "wildwest",
                "_type": "drinks",
                "_id": "AVx3Xc8g3JWWfjjJokHx",
                "_score": 0.5,
                "_routing": "AVx3Ruk03JWWfjjJokHs",
                "_parent": "AVx3Ruk03JWWfjjJokHs",
                "_source": {
                    "name": "Milk",
                    "description": "Milk description",
                    "unit_price": 2.9,
                    "amount": 20
                }
            }
        ]
    }
}
</code>```

What am I doing wrong?
I'm using Elasticsearch 2.4.

NOTE: I tried to put all filters inside should query, but I was given drinks from another pub. Changing to must query nothing is returned.

答:
I needed a query that filters my drinks with this condition: parent_id AND (name OR description OR...). Based on @user3775217 answer and elasticsearch documentation I did this query:

```<code>{
    "query": {
        "bool": {
            "must": [
                {
                    "query": {
                        "bool": {
                            "should": [
                                {
                                    "term": {
                                        "name": "milk"
                                    }
                                },
                                {
                                    "term": {
                                        "description": "milk"
                                    }
                                }
                            ]
                        }
                    }
                },
                {
                    "has_parent": {
                        "parent_type": "pubs",
                        "score_mode": "score",
                        "query": {
                            "ids": {
                                "values": ["AVx3Ruk03JWWfjjJokHs"]
                            }
                        }
                    }
                }
            ]
        }
    }
}
</code>```

Using only must query I filter my drinks only with AND condition, so I added should query within must query to add OR condition.

Body:
I have a parent/child relationship and I need to filter children based on parent ID and child properties. However, I can filter children by parent ID but I can not filter by any child properties.

Here is my search:

{
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "name": "beer"
                    }
                }
            ],
            "must": [
                {
                    "has_parent": {
                        "type": "pubs",
                        "score_mode": "score",
                        "query": {
                            "ids": {
                                "values": ["AVx3Ruk03JWWfjjJokHs"]
                            }
                        }
                    }
                }
            ]
        }
    }
}

But I was given results like this:

{
    "took": 98,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 0.5,
        "hits": [
            {
                "_index": "wildwest",
                "_type": "drinks",
                "_id": "AVx3Xc8g3JWWfjjJokHx",
                "_score": 0.5,
                "_routing": "AVx3Ruk03JWWfjjJokHs",
                "_parent": "AVx3Ruk03JWWfjjJokHs",
                "_source": {
                    "name": "Milk",
                    "description": "Milk description",
                    "unit_price": 2.9,
                    "amount": 20
                }
            }
        ]
    }
}

What am I doing wrong?
I'm using Elasticsearch 2.4.

NOTE: I tried to put all filters inside should query, but I was given drinks from another pub. Changing to must query nothing is returned.

Body:
I needed a query that filters my drinks with this condition: parent_id AND (name OR description OR...). Based on @user3775217 answer and elasticsearch documentation I did this query:

{
    "query": {
        "bool": {
            "must": [
                {
                    "query": {
                        "bool": {
                            "should": [
                                {
                                    "term": {
                                        "name": "milk"
                                    }
                                },
                                {
                                    "term": {
                                        "description": "milk"
                                    }
                                }
                            ]
                        }
                    }
                },
                {
                    "has_parent": {
                        "parent_type": "pubs",
                        "score_mode": "score",
                        "query": {
                            "ids": {
                                "values": ["AVx3Ruk03JWWfjjJokHs"]
                            }
                        }
                    }
                }
            ]
        }
    }
}

Using only must query I filter my drinks only with AND condition, so I added should query within must query to add OR condition.


问:
changed PGA , SGA sizes but the changes are not reflecting
I have changed the PGA and SGA in my system like below. after which we restarted the dB but the changes are not reflected.

This is a RAC DB and has 4 instances

scope=spfile

is there any problem?

```<code>SQL> alter system set sga_max_size=90g scope=spfile sid = 'OFSAA';

System altered.

SQL> alter system set sga_target=90g scope=spfile sid = 'OFSAA';

System altered.

SQL> alter system set pga_aggregate_target=90G scope =spfile sid='OFSAA';

System altered.

SQL> alter system set pga_aggregate_limit=50G scope =spfile sid='OFSAA';
</code>```

答:
This can happen if sid parameter is incorrectly specified.

Check it with this command:

select instance_name from v$instance;

Note that the sid parameter is case sensitive.

For example:

OFSAA != ofsaa

Body:
I have changed the PGA and SGA in my system like below. after which we restarted the dB but the changes are not reflected.

This is a RAC DB and has 4 instances

scope=spfile

is there any problem?

SQL> alter system set sga_max_size=90g scope=spfile sid = 'OFSAA';

System altered.

SQL> alter system set sga_target=90g scope=spfile sid = 'OFSAA';

System altered.

SQL> alter system set pga_aggregate_target=90G scope =spfile sid='OFSAA';

System altered.

SQL> alter system set pga_aggregate_limit=50G scope =spfile sid='OFSAA';


问:
Apply onClick to Iframe
Is there any way to "encapsulate" an Iframe with some other element to simulate onClick? I know the Iframe doesn't support events but I need to track clicks from my website that are leaving thru the Iframe.

Thanks!

答:
Try using: https://github.com/vincepare/iframeTracker-jquery

Since it's impossible to read iframe content (DOM) from the parent page due to the same origin policy, tracking is based on the blur event associated to a page/iframe boundary monitoring system telling over which iframe is the mouse cursor at any time.

Match the iframe elements you want to track with a jQuery selector and call iframeTracker with a callback function that will be called when a click on the iframe is detected :

```<code>jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when the iframe is clicked (like firing an XHR request)
        }
    });
});
</code>```

And many more options.

Title: Apply onClick to Iframe

Body:
Try using: https://github.com/vincepare/iframeTracker-jquery

Since it's impossible to read iframe content (DOM) from the parent page due to the same origin policy, tracking is based on the blur event associated to a page/iframe boundary monitoring system telling over which iframe is the mouse cursor at any time.

Match the iframe elements you want to track with a jQuery selector and call iframeTracker with a callback function that will be called when a click on the iframe is detected :

jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when the iframe is clicked (like firing an XHR request)
        }
    });
});

And many more options.


问:
Return a single relationship from multiple relationships between 2 nodes in neo4j
I am new to Neo4j and I have some trouble filtering out relationships in a return statement. I created two nodes and 3 instances of the same relationship between these two nodes that differ only in the value of the properties:

```<code>create (p:person {name:'batman'})
create (p:person {name:'superman'})

match (p1:person {name:'batman'}),(p2:person{name:'superman'}) create (p1)-  [h:HATES {intensity: 1}]->(p2)
match (p1:person {name:'batman'}),(p2:person{name:'superman'}) create (p1)-  [h:HATES {intensity: 2}]->(p2)
match (p1:person {name:'batman'}),(p2:person{name:'superman'}) create (p1)-  [h:HATES {intensity: 3}]->(p2)
</code>```

When I try to visualise only one of those relationships (eg: intensity=2) with this code:

```<code>match (a: person)-[h:HATES]->(b: person) where h.intensity=2  return  a,h,b
</code>```

all 3 relationships are plotted:

Whereas by looking at the data only the filtered relationship is returned
"a" "h" "b"

```<code>{"name":"batman"}   {"intensity":2} {"name":"superman"}
</code>```

Does anyone know how to plot only the corresponding relationship?

答:
This is the default behavior of the Neo4j browser. If you are using Neo4j 3.2 go to "Browser settings" and uncheck the option "Connect result nodes".

After it the result showld be:

If you are using a older version of Neo4j you should toggle the option highlighted in the image below:

Body:
I am new to Neo4j and I have some trouble filtering out relationships in a return statement. I created two nodes and 3 instances of the same relationship between these two nodes that differ only in the value of the properties:

create (p:person {name:'batman'})
create (p:person {name:'superman'})

match (p1:person {name:'batman'}),(p2:person{name:'superman'}) create (p1)-  [h:HATES {intensity: 1}]->(p2)
match (p1:person {name:'batman'}),(p2:person{name:'superman'}) create (p1)-  [h:HATES {intensity: 2}]->(p2)
match (p1:person {name:'batman'}),(p2:person{name:'superman'}) create (p1)-  [h:HATES {intensity: 3}]->(p2)

When I try to visualise only one of those relationships (eg: intensity=2) with this code:

match (a: person)-[h:HATES]->(b: person) where h.intensity=2  return  a,h,b

all 3 relationships are plotted:

Whereas by looking at the data only the filtered relationship is returned
"a" "h" "b"

{"name":"batman"}   {"intensity":2} {"name":"superman"}

Does anyone know how to plot only the corresponding relationship?


问:
How to show years on X axis when using matplotlib?
I never used python and I have to do this as my first assignment. It took me 3 hours just to get to this point and I really need some help.

I have a one dimensional array with some numbers. I have to make a timeseries plot.

```<code>import datetime
import matplotlib.pyplot as plt
import numpy as np

data = np.load("abnormal.npy")

x = np.array(range(1,len(data)+1))
y = np.load("abnormal.npy")

plt.plot(x,y)
plt.show()
</code>```

As you can see the X axis now is the array range of my array.
How can I change this to date time 2002-2012 ?

答:
You will need to have an array of dates that is exactly as long as your data array. If e.g. you know that there is one datapoint per day, you can create this array as

```<code>start = datetime.date(2002, 01, 01)
dates = [start + datetime.timedelta(n) for n in range(len(y))]
</code>```

Complete example:

```<code>import datetime
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

y = np.cumsum(np.random.normal(size=4000))

start = datetime.date(2002, 01, 01)
dates = [start + datetime.timedelta(n) for n in range(len(y))]

plt.plot(dates,y)
plt.show()
</code>```

Body:
I never used python and I have to do this as my first assignment. It took me 3 hours just to get to this point and I really need some help.

I have a one dimensional array with some numbers. I have to make a timeseries plot.

import datetime
import matplotlib.pyplot as plt
import numpy as np

data = np.load("abnormal.npy")

x = np.array(range(1,len(data)+1))
y = np.load("abnormal.npy")

plt.plot(x,y)
plt.show()

As you can see the X axis now is the array range of my array.
How can I change this to date time 2002-2012 ?

Body:
You will need to have an array of dates that is exactly as long as your data array. If e.g. you know that there is one datapoint per day, you can create this array as

start = datetime.date(2002, 01, 01)
dates = [start + datetime.timedelta(n) for n in range(len(y))]

Complete example:

import datetime
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

y = np.cumsum(np.random.normal(size=4000))

start = datetime.date(2002, 01, 01)
dates = [start + datetime.timedelta(n) for n in range(len(y))]

plt.plot(dates,y)
plt.show()


问:
Cons for defining logger non-static
Comments for this answer How do you reduce Java logging boilerplate code? strongly suggest not to use loggers as instance member variables. I can think of two negative side-effects:

1) superclass logs with the subclass's logger

2) object cannot be serialized (unless marked transient)

But if serializing is not necessary and logging with subclass name is not a problem, is there anything else why it should be avoided? I think it reduces boilerplate code and avoids copy-paste errors while copying logger variable definition from one class to another. Even Spring framework (which I believe has very good coding standards) uses this method.

答:
Try debugging an error where you see a message generated by the SuperClass class when the error is really being logged in the SubClass class. I've seen several situations where developers create a LoggingUtils class which generates messages which generally duplicate the things which are already baked-in by the logging framework.

The only real situation I see for using a shared logging instance is something like the Apache commons HttpClient logger httpclient.wire which is shared between several classes for logging the contents of the requests and responses sent through the client. This particular logging situation does not log information for the actual implementation of the package, it logs information about the whole http "transaction".

OwnerDisplayName: martsraits

Title: Cons for defining logger non-static

OwnerDisplayName: Ryan Ransford


问:
Why is System.out.println so slow?
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

```<code>package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}
</code>```

答: By default, System.out.print() is only line-buffered and does a lot work related to Unicode handling. Because of its small buffer size, System.out.println() is not well suited to handle many repetitive outputs in a batch mode. Each line is flushed right away. If your output is mainly ASCII-based then by removing the Unicode-related activities, the overall execution time will be better.</p>

Title: Why is System.out.println so slow?

Body:
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}


问:
How do I run multiple spark applications in parallel in standalone master
Using Spark(1.6.1) standalone master, I need to run multiple applications on same spark master.
All application submitted after first one, keep on holding 'WAIT' state always. I also observed, the one running holds all cores sum of workers.
I already tried limiting it by using SPARK_EXECUTOR_CORES but its for yarn config, while I am running is "standalone master". I tried running many workers on same master but every time first submitted application consumes all workers.

答:
I was having same problem on spark standalone cluster.

What I got is, Somehow it is utilising all the resources for one single job. We need to define the resources so that their will be space to run other job as well.

Below is the command I am using to submit spark job.

```<code>bin/spark-submit --class classname --master spark://hjvm1:6066 --deploy-mode cluster  --driver-memory 500M --conf spark.executor.memory=1g --conf spark.cores.max=1 /data/test.jar
</code>```

Body:
I was having same problem on spark standalone cluster.

What I got is, Somehow it is utilising all the resources for one single job. We need to define the resources so that their will be space to run other job as well.

Below is the command I am using to submit spark job.

bin/spark-submit --class classname --master spark://hjvm1:6066 --deploy-mode cluster  --driver-memory 500M --conf spark.executor.memory=1g --conf spark.cores.max=1 /data/test.jar


问:
Dynamically add element to map after pattern matching match case
I have a method as follows:

```<code>  protected def extract(implicit params:Params) =
    Map(
  "address" -> params.address,
  "city" -> reconcileCity,
  "region" -> params.region,
)collect {
    case (k, v) if v.isDefined => k -> v.get
  }
</code>```

I want to substitute value of city from another method as follows :

```<code>  protected def reconcileCity(implicit params:Params)
  params.city match {
  case Some("madras") => "Chennai"
  case Some("bangalore") => "Bengaluru"
  case Some("gurgaon") => "Gurugram"
  case _ => params.city.mkString
}
</code>```

But I am getting error like :

```<code>  Error:(177, 24) value isDefined is not a member of java.io.Serializable
  case (k, v) if v.isDefined => k -> v.get
  Error:(177, 44) value get is not a member of java.io.Serializable
  case (k, v) if v.isDefined => k -> v.get
</code>```

Please help.

答:
isDefined is a method that exists in Option class.
But you're trying to replace Option[String] with String, and call isDefined on it.

I'm assuming everything in params is an Option, so your code should look something like this:

```<code>protected def reconcileCity(implicit params:Params)
params.city match {
case Some("madras") => Some("Chennai")
  case Some("bangalore") => Some("Bengaluru")
  case Some("gurgaon") => Some("Gurugram")
  case other => other
}
</code>```

Body:
I have a method as follows:

  protected def extract(implicit params:Params) =
    Map(
  "address" -> params.address,
  "city" -> reconcileCity,
  "region" -> params.region,
)collect {
    case (k, v) if v.isDefined => k -> v.get
  }

I want to substitute value of city from another method as follows :

  protected def reconcileCity(implicit params:Params)
  params.city match {
  case Some("madras") => "Chennai"
  case Some("bangalore") => "Bengaluru"
  case Some("gurgaon") => "Gurugram"
  case _ => params.city.mkString
}

But I am getting error like :

  Error:(177, 24) value isDefined is not a member of java.io.Serializable
  case (k, v) if v.isDefined => k -> v.get
  Error:(177, 44) value get is not a member of java.io.Serializable
  case (k, v) if v.isDefined => k -> v.get

Please help.

Body:
isDefined is a method that exists in Option class.
But you're trying to replace Option[String] with String, and call isDefined on it.

I'm assuming everything in params is an Option, so your code should look something like this:

protected def reconcileCity(implicit params:Params)
params.city match {
case Some("madras") => Some("Chennai")
  case Some("bangalore") => Some("Bengaluru")
  case Some("gurgaon") => Some("Gurugram")
  case other => other
}


问:
How to view DLL functions?
I have a DLL file. How can I view the functions in that DLL?</p>

答:
Without telling us what language this DLL/assembly is from, we can only guess.

So how about .NET Reflector.

Title: How to view DLL functions?


问:
Text from csv is cached on reload
I have created a html page of a list of info that's read from a csv file. The webpage is for internal use in my workplace and I can live with a few possible unhandled compatibility issues.
I'm using Chrome to get the page to work and I might address the IE/Edge compatibility issues late.

My problem is that when I edit the data in the the dynamically created table and the new data is saved and the page is reloaded (using php), the browser shows the date from before the edit.

How can I force the browser to reload with the updated file?

I've tried all the <meta ***> solutions I've been able to find and, as you can see in the php file, I've tried the php header solution. The only thing I've found to work is checking the "Disable cache" in Chrome's developer tool and this solution is not optimal with non tech savvy users.

The html file:

```<code><!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta HTTP-EQUIV="Expires" CONTENT="-1">
    <title>Some title</title>

    <style>
        table {
            font-family: arial, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }

        td, th {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }

        tr:nth-child(even) {
            background-color: #dddddd;
        }
    </style>

    <link rel="stylesheet" type="text/css" href="cssData.css">
</head>

<body onload='getData("")'>
    <div class='wrap'>
        <h1 id='createdDate' align='center'>Header</h1>
        <br>
        <div>
            <form action="phpFunc.php" id="some" name="someName" method="post" align='center'>
                <input type='button' id='edit' onclick='editData()' value='btn1' style='display:inline;' />
                <input type='button' id='add' onclick='addData()' value='btn2' style='display:none;' />
                <input type='button' id='save' onclick='saveData()' value='btn3' style='display:none;'/>

                <input type="text" id="tempText" class="someClass" value="Test" name="fileWrite" style='display:none;'/>
                <input type="submit" id='saveBtn' value="" class="submitClass" style='display:none;'/>

                <input type='button' id='cancel' onclick='cancelEdit()' value='btn4' style='display:none;'/>
            </form>
        </div>
        <table id='dataTable'></table>
        <br><br><br><br>
    </div>
    <div class='footer'>
        <i>Made by some guy</i>
    </div>
    <script src="functions.js"></script>
</body>
</code>```

The js function file:

```<code>var list = "", colNames = ["Kursus", "Image", "RAM", "SSD"];
var noCol = 4;

function getData(addon) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            visualFormating(this.responseText, addon);
        }else if (this.status == 404){
            visualFormating("","");
        }
    };
    xhttp.open("GET", "Data.csv", true);

    xhttp.send();
} else {
    alert("Functionen er ikke understøttet i denne browser.");
}
};

function visualFormating(input, addon){
if(input.length > 0 || addon.length > 0){
if(list.length < 1){
    input = input.replace(/(\")+/g,'')
    var array = input.split('\n');
    var text = "";
    var temp = array[0].split(';');

    for (var i = 0; i < array.length; i++){
        var temp = array[i].split(';');
        if(temp.length == 4){
        text += "<tr>";

        if(i != 0){
            for (var j = 0; j < temp.length; j++){
                text += "<td contenteditable='false'>" + temp[j];
                text += "</td>";
            }
            text += "<td class='checkboxes' style='display:none'><input type='checkbox' id='check"+i+"'>"
        }else{
            for (var j = 0; j < temp.length; j++){
                text += "<th onclick='sortTable("+j+")' style='cursor: pointer;'>" + temp[j];
                text += "</th>";
            }
            text += "<th id='delete' class='checkboxes' style='display:none'>Slet</th>";
        }

        text += "</tr>";}
    }
}else{
    text = list
}
}else{
    text = "<tr>";
    for (var i = 0; i < colNames.length; i++)
    {
        text += "<th onclick='sortTable("+i+")' style='cursor: pointer;'>" + colNames[i] + "</th>";
    }
    text += "<th id='delete' class='checkboxes' style='display:none'>Slet</th></tr>";
}

list = text + addon;
text = "<table>" + list + "</table>";
document.getElementById('dataTable').innerHTML = text;
};

function changeEditable(editable){
if(editable==true){
    var editable_elements = document.querySelectorAll("[contenteditable=false]");
    document.getElementById('edit').style.display = "none";
    document.getElementById('add').style.display = "inline";
    document.getElementById('save').style.display = "inline";
    document.getElementById('cancel').style.display = "inline";
    var checkboxes = document.getElementsByClassName('checkboxes');
    for (var i = 0; i < checkboxes.length; i++){
        checkboxes[i].style.display = "block";
    }
}else{
    var editable_elements = document.querySelectorAll("[contenteditable=true]");
    document.getElementById('edit').style.display = "inline";
    document.getElementById('add').style.display = "none";
    document.getElementById('save').style.display = "none";
    document.getElementById('cancel').style.display = "none";
    var checkboxes = document.getElementsByClassName('checkboxes');
    for (var i = 0; i < checkboxes.length; i++){
        checkboxes[i].style.display = "none";
    }
}

for(var i=0; i<editable_elements.length; i++){
    editable_elements[i].setAttribute("contenteditable", editable);
}
}

function saveData(){
changeEditable(false);
checkDelete();
writeData();
clearEdit();
getData("");
}

function checkDelete(){
var table = document.getElementById("dataTable");
var newList = "";

for (var i = table.rows.length - 1; i > 0; i--){
    if (document.getElementById("check"+i).checked) {
        table.deleteRow(i);
    }
}
}

function writeData(){
var rows = document.getElementById("dataTable").rows;
var text = "";

for (var r = 0; r < rows.length; r++){
    var tempText = "";
    for(var c = 0; c < noCol; c++){
        tempText += '"' + rows[r].cells[c].innerHTML + '"';
        if(c+2 != rows[r].cells.length) tempText += ";";
        else tempText += "\n";
    }
    //var tempText = '"' + rows[r].cells[0].innerHTML + '";"' + rows[r].cells[1].innerHTML + '";"' + rows[r].cells[2].innerHTML + '";"' + rows[r].cells[3].innerHTML + '"' + "\n";
    if (!checkEmpty(tempText))text += tempText;
}

document.getElementById('tempText').value = encodeURIComponent(text);
document.getElementById('saveBtn').click();
}

function addData() {
var text = "<tr>";

for (var i = 0; i < noCol; i++){
    text += "<td contenteditable='true'></td>"
}

text += "<td class='checkboxes' style='display:block'><input type='checkbox' id='check" + document.getElementById("dataTable").rows.length + "'></tr>";

updateList(text);
}

function updateList(input){
var rows = document.getElementById("dataTable").rows;
var text = "";
for (var i = 0; i < rows.length; i++){
    text += '<tr>' + rows[i].innerHTML + '</tr>';
}

list = text;

visualFormating("", input);
}

function editData(){
changeEditable(true);

}

function cancelEdit(){
clearEdit();
changeEditable(false);
getData("");
}

function clearEdit(){
list = "";
}

function checkEmpty(input){
input = input.replace(/"/g, '');
input = input.replace(/;/g, '');
input = input.replace(/\n/g, '');

if(input.length < 1) return true;
else return false;
}

function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("dataTable");
switching = true;
//Set the sorting direction to ascending:
dir = "asc";
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.getElementsByTagName("TR");
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++) {
  //start by saying there should be no switching:
  shouldSwitch = false;
  /*Get the two elements you want to compare,
  one from current row and one from the next:*/
  x = rows[i].getElementsByTagName("TD")[n];
  y = rows[i + 1].getElementsByTagName("TD")[n];
  /*check if the two rows should switch place,
  based on the direction, asc or desc:*/
  if (dir == "asc") {
    if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
      //if so, mark as a switch and break the loop:
      shouldSwitch= true;
      break;
    }
  } else if (dir == "desc") {
    if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
      //if so, mark as a switch and break the loop:
      shouldSwitch= true;
      break;
    }
  }
}
if (shouldSwitch) {
  /*If a switch has been marked, make the switch
  and mark that a switch has been done:*/
  rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
  switching = true;
  //Each time a switch is done, increase this count by 1:
  switchcount ++;
} else {
  /*If no switching has been done AND the direction is "asc",
  set the direction to "desc" and run the while loop again.*/
  if (switchcount == 0 && dir == "asc") {
    dir = "desc";
    switching = true;
  }
}
}
}
</code>```

The php file:

```<code><?php
$file = 'Data.csv';
$fileWrite = '';
if(isset($_POST['fileWrite']) && !empty($_POST['fileWrite'])) {
    $fileWrite = urldecode($_POST['fileWrite']);
}
file_put_contents($file, $fileWrite);
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
header( 'Location: index.html' ) ;
?>
</code>```

The csv is formated as follows:

```<code>"column 1";"column 2";"column 3";"column 4"
"Data 1";"Data 2";"Data 3";"Data 4"
</code>```

If some info is missing please let me know. The whole 4 space to make code block is making a mess for me.

答:
You can set, when the data is expired. Simplest trick is to use the past of timestamp(0). Add these two lines to your header code.

```<code>header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s') . ' GMT');
</code>```

Title: Text from csv is cached on reload

Body:
I have created a html page of a list of info that's read from a csv file. The webpage is for internal use in my workplace and I can live with a few possible unhandled compatibility issues.
I'm using Chrome to get the page to work and I might address the IE/Edge compatibility issues late.

My problem is that when I edit the data in the the dynamically created table and the new data is saved and the page is reloaded (using php), the browser shows the date from before the edit.

How can I force the browser to reload with the updated file?

I've tried all the <meta ***> solutions I've been able to find and, as you can see in the php file, I've tried the php header solution. The only thing I've found to work is checking the "Disable cache" in Chrome's developer tool and this solution is not optimal with non tech savvy users.

The html file:

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta HTTP-EQUIV="Expires" CONTENT="-1">
    <title>Some title</title>

    <link rel="stylesheet" type="text/css" href="cssData.css">

Header

            <form action="phpFunc.php" id="some" name="someName" method="post" align='center'>
                <input type='button' id='edit' onclick='editData()' value='btn1' style='display:inline;' />
                <input type='button' id='add' onclick='addData()' value='btn2' style='display:none;' />
                <input type='button' id='save' onclick='saveData()' value='btn3' style='display:none;'/>

                <input type="text" id="tempText" class="someClass" value="Test" name="fileWrite" style='display:none;'/>
                <input type="submit" id='saveBtn' value="" class="submitClass" style='display:none;'/>

                <input type='button' id='cancel' onclick='cancelEdit()' value='btn4' style='display:none;'/>
            </form>

        Made by some guy

The js function file:

var list = "", colNames = ["Kursus", "Image", "RAM", "SSD"];
var noCol = 4;

function getData(addon) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            visualFormating(this.responseText, addon);
        }else if (this.status == 404){
            visualFormating("","");
        }
    };
    xhttp.open("GET", "Data.csv", true);

    xhttp.send();
} else {
    alert("Functionen er ikke understøttet i denne browser.");
}
};

function visualFormating(input, addon){
if(input.length > 0 || addon.length > 0){
if(list.length < 1){
    input = input.replace(/(\")+/g,'')
    var array = input.split('\n');
    var text = "";
    var temp = array[0].split(';');

    for (var i = 0; i < array.length; i++){
        var temp = array[i].split(';');
        if(temp.length == 4){
        text += "
";

        if(i != 0){
            for (var j = 0; j < temp.length; j++){
                text += "" + temp[j];
                text += "	";
            }
            text += "<input type='checkbox' id='check"+i+"'>"
        }else{
            for (var j = 0; j < temp.length; j++){
                text += "" + temp[j];
                text += "	";
            }
            text += "Slet	";
        }

        text += "
";}
    }
}else{
    text = list
}
}else{
    text = "
";
    for (var i = 0; i < colNames.length; i++)
    {
        text += "" + colNames[i] + "	";
    }
    text += "Slet
";
}

list = text + addon;
text = "
" + list + "
";
document.getElementById('dataTable').innerHTML = text;
};

function changeEditable(editable){
if(editable==true){
    var editable_elements = document.querySelectorAll("[contenteditable=false]");
    document.getElementById('edit').style.display = "none";
    document.getElementById('add').style.display = "inline";
    document.getElementById('save').style.display = "inline";
    document.getElementById('cancel').style.display = "inline";
    var checkboxes = document.getElementsByClassName('checkboxes');
    for (var i = 0; i < checkboxes.length; i++){
        checkboxes[i].style.display = "block";
    }
}else{
    var editable_elements = document.querySelectorAll("[contenteditable=true]");
    document.getElementById('edit').style.display = "inline";
    document.getElementById('add').style.display = "none";
    document.getElementById('save').style.display = "none";
    document.getElementById('cancel').style.display = "none";
    var checkboxes = document.getElementsByClassName('checkboxes');
    for (var i = 0; i < checkboxes.length; i++){
        checkboxes[i].style.display = "none";
    }
}

for(var i=0; i<editable_elements.length; i++){
    editable_elements[i].setAttribute("contenteditable", editable);
}
}

function saveData(){
changeEditable(false);
checkDelete();
writeData();
clearEdit();
getData("");
}

function checkDelete(){
var table = document.getElementById("dataTable");
var newList = "";

for (var i = table.rows.length - 1; i > 0; i--){
    if (document.getElementById("check"+i).checked) {
        table.deleteRow(i);
    }
}
}

function writeData(){
var rows = document.getElementById("dataTable").rows;
var text = "";

for (var r = 0; r < rows.length; r++){
    var tempText = "";
    for(var c = 0; c < noCol; c++){
        tempText += '"' + rows[r].cells[c].innerHTML + '"';
        if(c+2 != rows[r].cells.length) tempText += ";";
        else tempText += "\n";
    }
    //var tempText = '"' + rows[r].cells[0].innerHTML + '";"' + rows[r].cells[1].innerHTML + '";"' + rows[r].cells[2].innerHTML + '";"' + rows[r].cells[3].innerHTML + '"' + "\n";
    if (!checkEmpty(tempText))text += tempText;
}

document.getElementById('tempText').value = encodeURIComponent(text);
document.getElementById('saveBtn').click();
}

function addData() {
var text = "
";

for (var i = 0; i < noCol; i++){
    text += "	"
}

text += "<input type='checkbox' id='check" + document.getElementById("dataTable").rows.length + "'>
";

updateList(text);
}

function updateList(input){
var rows = document.getElementById("dataTable").rows;
var text = "";
for (var i = 0; i < rows.length; i++){
    text += '
' + rows[i].innerHTML + '
';
}

list = text;

visualFormating("", input);
}

function editData(){
changeEditable(true);

}

function cancelEdit(){
clearEdit();
changeEditable(false);
getData("");
}

function clearEdit(){
list = "";
}

function checkEmpty(input){
input = input.replace(/"/g, '');
input = input.replace(/;/g, '');
input = input.replace(/\n/g, '');

if(input.length < 1) return true;
else return false;
}

function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("dataTable");
switching = true;
//Set the sorting direction to ascending:
dir = "asc";
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.getElementsByTagName("TR");
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++) {
  //start by saying there should be no switching:
  shouldSwitch = false;
  /*Get the two elements you want to compare,
  one from current row and one from the next:*/
  x = rows[i].getElementsByTagName("TD")[n];
  y = rows[i + 1].getElementsByTagName("TD")[n];
  /*check if the two rows should switch place,
  based on the direction, asc or desc:*/
  if (dir == "asc") {
    if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
      //if so, mark as a switch and break the loop:
      shouldSwitch= true;
      break;
    }
  } else if (dir == "desc") {
    if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
      //if so, mark as a switch and break the loop:
      shouldSwitch= true;
      break;
    }
  }
}
if (shouldSwitch) {
  /*If a switch has been marked, make the switch
  and mark that a switch has been done:*/
  rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
  switching = true;
  //Each time a switch is done, increase this count by 1:
  switchcount ++;
} else {
  /*If no switching has been done AND the direction is "asc",
  set the direction to "desc" and run the while loop again.*/
  if (switchcount == 0 && dir == "asc") {
    dir = "desc";
    switching = true;
  }
}
}
}

The php file:

<?php
$file = 'Data.csv';
$fileWrite = '';
if(isset($_POST['fileWrite']) && !empty($_POST['fileWrite'])) {
    $fileWrite = urldecode($_POST['fileWrite']);
}
file_put_contents($file, $fileWrite);
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
header( 'Location: index.html' ) ;
?>

The csv is formated as follows:

"column 1";"column 2";"column 3";"column 4"
"Data 1";"Data 2";"Data 3";"Data 4"

If some info is missing please let me know. The whole 4 space to make code block is making a mess for me.

Body:
You can set, when the data is expired. Simplest trick is to use the past of timestamp(0). Add these two lines to your header code.

header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s') . ' GMT');


问:
Jenkins - Excluded Regions
Hope you can help :)

I have problem with Excluded Regions in Jenkins.

I'm using Multiple SCM and SVN. In one module I want to retrieve almost everything from directory A without one dir.

Structure below:

```<code>-> A
    -> dir_B
    -> dir_C
    -> dir_D
    -> file_a.txt
    -> file_b.txt
</code>```

For example, how to avoid downloading dir_C ?
Now I'm using sth like

```<code>./dir_C/
</code>```

Thanks :)

答:
I think you need to apply regex for that folder:</p>

```<code>dir_C/.*
</code>```

Title: Jenkins - Excluded Regions

Body:
Hope you can help :)

I have problem with Excluded Regions in Jenkins.

I'm using Multiple SCM and SVN. In one module I want to retrieve almost everything from directory A without one dir.

Structure below:

-> A
    -> dir_B
    -> dir_C
    -> dir_D
    -> file_a.txt
    -> file_b.txt

For example, how to avoid downloading dir_C ?
Now I'm using sth like

./dir_C/

Thanks :)

Body:
I think you need to apply regex for that folder:

dir_C/.*


问:
App Crashing in Simulator After Deleting and Re-builiding Entities in Xcode CoreData file (.xcdatamodeld)
I'm sure this is a rookie mistake but I'm stumped.

I've noticed that when I rename things in Xcode (viewController.swift) after their initial linkage from the main storyboard, I have to dig down into the files and rename them in the under-the-hood code as well.

I've recently been using Core Data and accidentally defined one of the attributes to be an Int instead of a string.  At first, I simply updated the attribute type but that didn't seem to help.  Still crashing.

Then, I deleted all the Entities from the Core Data file (.xcdatamodeld) and now it is crashing every time I'm trying to set the context.  Here's the relevant code:

The relevant code:

```<code>    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
</code>```

This worked fine until my meddling.  Now it dies on line 2 above.

Quit and opened Xcode.
I've tried doing a Clean and Clean Build Folder.

I'm pretty stuck.  Any help would be appreciated.

答:
I tried various combinations and finally got it working again.

The last combo I did was:

1) Clean

2) Clean Build Folder

3) Quit Xcode

4) Deleted the app within the simulator

5) Shut down the simulator

6) Restarted the machine

After restart, I opened Xcode and was able to compile as I had before.  If anyone else runs into this, I hope this helps.

Body:
I'm sure this is a rookie mistake but I'm stumped.

I've noticed that when I rename things in Xcode (viewController.swift) after their initial linkage from the main storyboard, I have to dig down into the files and rename them in the under-the-hood code as well.

I've recently been using Core Data and accidentally defined one of the attributes to be an Int instead of a string.  At first, I simply updated the attribute type but that didn't seem to help.  Still crashing.

Then, I deleted all the Entities from the Core Data file (.xcdatamodeld) and now it is crashing every time I'm trying to set the context.  Here's the relevant code:

The relevant code:

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

This worked fine until my meddling.  Now it dies on line 2 above.

Quit and opened Xcode.
I've tried doing a Clean and Clean Build Folder.

I'm pretty stuck.  Any help would be appreciated.


问:
ARKit - Issue with ARSession
I'm trying to create ARSession, using ARKit with Xcode 9 beta (for iOS 11). But it seems not working properly.

Code I've tried is:

```<code>override func viewDidLoad() {

    super.viewDidLoad()

    // configure session
    let configuration = ARWorldTrackingSessionConfiguration()
    configuration.planeDetection = .horizontal

    // run session
    sceneView.session.run(configuration)
}
</code>```

Can anyone help? Code is almost correct according to Apple Documentation.

答:
ARWorldTrackingSessionConfiguration supports only iOS devices with an A9 processor or later.

As per Apple doc:

On iOS devices with an A9 processor or later, the
ARWorldTrackingSessionConfiguration
   subclass provides high-precision motion tracking and enables features to help you place virtual content in relation to real-world
surfaces.

On other devices supported by ARKit, the ARSessionConfiguration base
class provides basic motion tracking that permits slightly less
immersive AR experiences.

iPhone and Processors:

```<code> iPhone 6 and iPhone 6 plus has A8 processor.
 iPhone SE, iPhone 6s, iPhone 6s plus has A9 processor.
 iPhone 7, iPhone 7plus has A10 processor
</code>```

Title: ARKit - Issue with ARSession

Body:
I'm trying to create ARSession, using ARKit with Xcode 9 beta (for iOS 11). But it seems not working properly.

Code I've tried is:

override func viewDidLoad() {

    super.viewDidLoad()

    // configure session
    let configuration = ARWorldTrackingSessionConfiguration()
    configuration.planeDetection = .horizontal

    // run session
    sceneView.session.run(configuration)
}

Can anyone help? Code is almost correct according to Apple Documentation.

Body:
ARWorldTrackingSessionConfiguration supports only iOS devices with an A9 processor or later.

As per Apple doc:

On iOS devices with an A9 processor or later, the
ARWorldTrackingSessionConfiguration
   subclass provides high-precision motion tracking and enables features to help you place virtual content in relation to real-world
surfaces.

On other devices supported by ARKit, the ARSessionConfiguration base
class provides basic motion tracking that permits slightly less
immersive AR experiences.

iPhone and Processors:

 iPhone 6 and iPhone 6 plus has A8 processor.
 iPhone SE, iPhone 6s, iPhone 6s plus has A9 processor.
 iPhone 7, iPhone 7plus has A10 processor


问:
make width of  equal to its text contents
I have below snippet where td takes up space unnecessarily. For e.g. if the text contents inside td take 20 pixels width, td should also be 20 pixels wide. Can you help me fix it?

tr {
  width: 100%;
}
.td2{
   width:auto;
   max-width: 180px;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;
}

span {
   background-color: #7e7;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3 style="width:600px;">The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily
</h3>

<table>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive exhaust materialssss</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
  <tr>
    <td class="td1"><input type="checkbox" name="checkbox" value="value"></td>
    <td class="td2"><span>Excessive</span></td>
    <td class="td3"><img src="https://www.w3schools.com/html/smiley.gif"></td>
  </tr>
</table></code>```

答:
try adding the following css code

```<code>tr {
  width: 100%;
  display:table-row;
}
tr td
{
  display:inline-block;
}
</code>```

here is a link for reference

hope this helps..

Title: make width of <td> equal to its text contents

Body:
I have below snippet where td takes up space unnecessarily. For e.g. if the text contents inside td take 20 pixels width, td should also be 20 pixels wide. Can you help me fix it?

tr {
  width: 100%;
}
.td2{
   width:auto;
   max-width: 180px;
   word-wrap: break-word;
   background-color:red;
   padding-left: 0;
   padding-right: 0;
}

span {
   background-color: #7e7;
}

The image in below strucure should be displayed immediately after text ends
but the td is eating up space unnecessarily

    <input type="checkbox" name="checkbox" value="value">
    Excessive exhaust materialssss

    <input type="checkbox" name="checkbox" value="value">
    Excessive

Body:
try adding the following css code

tr {
  width: 100%;
  display:table-row;
}
tr td
{
  display:inline-block;
}

here is a link for reference

hope this helps..


问:
Use Github API to disable the merge button on a pull request and reenable it using REST
I have developed my own web server that does automation on my android app. If there are issues when the automation runs, I want to programmatically disable the "merge" button on a github pull request using a cURL REST command. I cannot find out the proper way to do this but it seems that many people would benefit from this functionality.

The api for github pull requests can be found here: https://developer.github.com/v3/pulls/

I know that this is possible because if you have merge conflicts on your branch, the button gets grayed out and you cannot click/merge it. That is the exact functionality I am looking for. Any help would be much appreciated.

答:
Protecting the branch and then blocking merging if the status checks doesn't pass or reviews are not done works. This is a very straight solution and it works perfectly.
But if you are more curious then try doing it without protecting the branch. I could not find a way to do this.</p>


问:
conversion of java string to json object
I have json object named 'jo' in the below code.I convert this json object to java string to return this json object as response.Then how i convert this string back to json object in the required format.Please help me.</p>

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*,java.util.ArrayList"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="net.sf.json.JSONArray"%>
<%
    JSONArray cellarray = new JSONArray();
    JSONObject cellobj = null; //new JSONObject();
    JSONObject jo=new JSONObject();
    String country=request.getParameter("count");
    try{
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
        3306/test","root","root");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("Select * from state
        where countryid='"+country+"'");
            while(rs.next()){
                cellobj = new JSONObject();
                cellobj.put("id", rs.getString(1));
                cellobj.put("name", rs.getString(3));
                cellarray.add(cellobj);
            }
            jo.put("arrayName",cellarray);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(jo.toString());
        }
    catch(Exception e){
        System.out.println(e);
    }
%>
</code>```

答:
It is just a suggestion, I also faces like this issue.

Finally, I tried with GSON library. GSON is directly convert your JSONString to java class object.

Example:

```<code>String jsonString = {"phoneNumber": "8888888888"}
</code>```

create a new class:

```<code>class Phone {

@SerializedName("phoneNumber")
private String phoneNumebr;

public void setPhoneNumber(String phoneNumebr) {
this.phoneNumebr = phoneNumebr;
}

public String getPhoneNumebr(){
return phoneNumber;
}

}
</code>```

// in java

```<code>Gson gson = new Gson();
Phone phone = gson.fromJson(jsonString, Phone.class);

System.out.println(" Phone number is "+phone.getPhoneNumebr());
</code>```

Body:
I have json object named 'jo' in the below code.I convert this json object to java string to return this json object as response.Then how i convert this string back to json object in the required format.Please help me.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*,java.util.ArrayList"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="net.sf.json.JSONArray"%>
<%
    JSONArray cellarray = new JSONArray();
    JSONObject cellobj = null; //new JSONObject();
    JSONObject jo=new JSONObject();
    String country=request.getParameter("count");
    try{
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
        3306/test","root","root");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("Select * from state
        where countryid='"+country+"'");
            while(rs.next()){
                cellobj = new JSONObject();
                cellobj.put("id", rs.getString(1));
                cellobj.put("name", rs.getString(3));
                cellarray.add(cellobj);
            }
            jo.put("arrayName",cellarray);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(jo.toString());
        }
    catch(Exception e){
        System.out.println(e);
    }
%>

Body:
It is just a suggestion, I also faces like this issue.

Finally, I tried with GSON library. GSON is directly convert your JSONString to java class object.

Example:

String jsonString = {"phoneNumber": "8888888888"}

create a new class:

class Phone {

@SerializedName("phoneNumber")
private String phoneNumebr;

public void setPhoneNumber(String phoneNumebr) {
this.phoneNumebr = phoneNumebr;
}

public String getPhoneNumebr(){
return phoneNumber;
}

}

// in java

Gson gson = new Gson();
Phone phone = gson.fromJson(jsonString, Phone.class);

System.out.println(" Phone number is "+phone.getPhoneNumebr());