问:
Gradle build fail for Affectiva Affdex SDK dependency can not be resolved when opening project on another computer
I am developing an application which uses the Affectiva Affdex SDK and which I am including in the gradle file.  Everything worked fine on my computer at work until I tried to open the project at home on my MacBook (I don't think it has sth to do with Windows vs. Apple so I don't wanna start an endless discussion about pros/cons Apple vs. Windows ;) )
So the thing is that the build fails because the dependency compile 'com.affectiva.android:affdexsdk:3.2.0' cannot be resolved.
I dunno if it's relevant but at work I use a proxy, at home I do not use one.

Here's the error:

```<code>    Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
   > Could not resolve com.affectiva.android:affdexsdk:3.2.0.
     Required by:
         Emojat:app:unspecified
      > Could not resolve com.affectiva.android:affdexsdk:3.2.0.
         > Could not get resource 'http://maven.affectiva.com/com/affectiva/android/affdexsdk/3.2.0/affdexsdk-3.2.0.pom'.
            > Could not GET 'http://maven.affectiva.com/com/affectiva/android/affdexsdk/3.2.0/affdexsdk-3.2.0.pom'.
               > Connect to 192.168.205.11:8080 [/192.168.205.11] failed: Operation timed out
</code>```

This is my app gradle:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        applicationId "com.example.plucinst.emojat"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.affectiva.android:affdexsdk:3.2.0'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.android.support:support-v13:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
}
</code>```

This is the project gradle:

```<code>    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'http://repo1.maven.org/maven2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        mavenLocal()
        maven {
            url "http://maven.affectiva.com"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

I dunno if necessary but here's the manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.plucinst.emojat">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

<application
    tools:replace="android:allowBackup,android:label"
    android:allowBackup="true"
    android:icon="@drawable/launcher_icon_alternativ3"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:largeHeap="true"
    android:hardwareAccelerated="true"
    >

    <activity android:name="com.example.plucinst.emojat.MainActivity"><!--com.example.plucinst.emojat.MainActivity-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.example.plucinst.emojat.ScreenSlidePagerActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.ChatActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.InboxActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.EmojiDetectionActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.EmojiSelectionActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.AndroidDatabaseManager"></activity>
    <activity android:name="com.example.plucinst.emojat.SettingsActivity"></activity>

</application>
</code>```

Many thanks in advance! :)

答: The correct artifact version is "3.2" (not "3.2.0").  This was a mistake on the Affectiva Developer Portal, which is now corrected.</p>

Body:
I am developing an application which uses the Affectiva Affdex SDK and which I am including in the gradle file.  Everything worked fine on my computer at work until I tried to open the project at home on my MacBook (I don't think it has sth to do with Windows vs. Apple so I don't wanna start an endless discussion about pros/cons Apple vs. Windows ;) )
So the thing is that the build fails because the dependency compile 'com.affectiva.android:affdexsdk:3.2.0' cannot be resolved.
I dunno if it's relevant but at work I use a proxy, at home I do not use one.

Here's the error:

    Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
   > Could not resolve com.affectiva.android:affdexsdk:3.2.0.
     Required by:
         Emojat:app:unspecified
      > Could not resolve com.affectiva.android:affdexsdk:3.2.0.
         > Could not get resource 'http://maven.affectiva.com/com/affectiva/android/affdexsdk/3.2.0/affdexsdk-3.2.0.pom'.
            > Could not GET 'http://maven.affectiva.com/com/affectiva/android/affdexsdk/3.2.0/affdexsdk-3.2.0.pom'.
               > Connect to 192.168.205.11:8080 [/192.168.205.11] failed: Operation timed out

This is my app gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        applicationId "com.example.plucinst.emojat"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.affectiva.android:affdexsdk:3.2.0'
    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.android.support:support-v13:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
}

This is the project gradle:

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        maven { url 'http://repo1.maven.org/maven2' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        mavenLocal()
        maven {
            url "http://maven.affectiva.com"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I dunno if necessary but here's the manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.plucinst.emojat">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

<application
    tools:replace="android:allowBackup,android:label"
    android:allowBackup="true"
    android:icon="@drawable/launcher_icon_alternativ3"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    android:largeHeap="true"
    android:hardwareAccelerated="true"
    >

    <activity android:name="com.example.plucinst.emojat.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.example.plucinst.emojat.ScreenSlidePagerActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.ChatActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.InboxActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.EmojiDetectionActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.EmojiSelectionActivity"></activity>
    <activity android:name="com.example.plucinst.emojat.AndroidDatabaseManager"></activity>
    <activity android:name="com.example.plucinst.emojat.SettingsActivity"></activity>

</application>

Many thanks in advance! :)


来源: stackexchange

问:
How to place div in second row directly under div in first row with same column size but blocked by the height of another column in first row
Sorry if the title is confusing. I have included a screenshot of my issue to make it more clear.

Essentially, I want the green-bordered div to be directly underneath the red-bordered div without the blue-bordered div interfering.

Here is my HTML code (I am using Bootstrap v3.3.7)

```<code><div class="container appParent">
    <div class="row">
        <div class="col-md-6" id="song-view">
            <app-selected-song-view></app-selected-song-view>
        </div>
        <div class="col-md-6" id="songs-added">
            <app-songs-added></app-songs-added>
        </div>

    </div>
    <div class="row">
        <div class="col-md-6" id="playlist-form">
            <app-playlist-form></app-playlist-form>
        </div>
    </div>
</div>
</code>```

My CSS is only putting the borders around the div. Everything else is bootstrap.

```<code>#song-view{
    border: 2px solid red;
}
#songs-added{
    border: 2px solid blue;
}
#playlist-form{
    border: 2px solid green;
}
</code>```

答:
You can re-arrange your HTML.

#song-view {
  border: 2px solid red;
  height: 100px;
  margin-bottom: 30px;
}

#songs-added {
  border: 2px solid blue;
  height: 150px;
}

#playlist-form {
  border: 2px solid green;
  height: 100px;
  margin-bottom: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container appParent">
  <div class="row">
    <div class="col-md-6">
      <div id="song-view">
        <app-selected-song-view></app-selected-song-view>
      </div>
      <div id="playlist-form">
        <app-playlist-form></app-playlist-form>
      </div>
    </div>
    <div class="col-md-6">
      <div id="songs-added">
        <app-songs-added></app-songs-added>
      </div>
    </div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Sorry if the title is confusing. I have included a screenshot of my issue to make it more clear.

Essentially, I want the green-bordered div to be directly underneath the red-bordered div without the blue-bordered div interfering.

Here is my HTML code (I am using Bootstrap v3.3.7)

            <app-selected-song-view></app-selected-song-view>

            <app-songs-added></app-songs-added>

            <app-playlist-form></app-playlist-form>

My CSS is only putting the borders around the div. Everything else is bootstrap.

#song-view{
    border: 2px solid red;
}
#songs-added{
    border: 2px solid blue;
}
#playlist-form{
    border: 2px solid green;
}

Body:
You can re-arrange your HTML.

#song-view {
  border: 2px solid red;
  height: 100px;
  margin-bottom: 30px;
}

#songs-added {
  border: 2px solid blue;
  height: 150px;
}

#playlist-form {
  border: 2px solid green;
  height: 100px;
  margin-bottom: 30px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container appParent">
  <div class="row">
    <div class="col-md-6">
      <div id="song-view">
        <app-selected-song-view></app-selected-song-view>
      </div>
      <div id="playlist-form">
        <app-playlist-form></app-playlist-form>
      </div>
    </div>
    <div class="col-md-6">
      <div id="songs-added">
        <app-songs-added></app-songs-added>
      </div>
    </div>
  </div>
</div>


问:
Lazy Loading not working in EntityFramework Core
Below are two classes that control database tables using Code First Entity Framework (DbContext).

public class Employee
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string EmployeeName { get; set; }

    public int DepartmentId { get; set; }

    public Department Department { get; set; }

}
```

<p>--</p>

<pre class="lang-cs prettyprint-override"><code>public class Department
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string DepartmentName { get; set; }
}
</code>```

If I retrieve the employees with the line below the navigation property for Department is null:

        var employees = _context.Employees.ToList();
```

<p>However, if I first populate a separate variable with <code>Departments</code>, like this ...</p>

<pre class="lang-cs prettyprint-override"><code>        var departments = _context.Departments.ToList();

        var employees = _context.Employees.ToList();
</code>```

... Each employee in the employees list contains the Department object.

My question:
What is best practice to populate the navigation property? I had imagined that Entity Framework would have done this by default and that the ToList() method would handle the lazy loading.

答:
Reading the docs/roadmap you'd have realized that lazy loading is not yet supported in EF Core 1.0/1.1.

Currently only .Include or eager loading is supported, both well documented in the documentation.

You must not assume that all features from EF 6 are available in EF Core. EF Core is a complete rewrite and do not include many of the features of EF6. If you need any of that stuff, you should keep using EF6 instead.

EF Core is good enough for most simple/basic ORM stuff, but even Microsoft recommends to use EF6 for production where you depend on these features.

ContentLicense: CC BY-SA 4.0

Body:
Below are two classes that control database tables using Code First Entity Framework (DbContext).

public class Employee
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string EmployeeName { get; set; }

    public int DepartmentId { get; set; }

    public Department Department { get; set; }

}

--

public class Department
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string DepartmentName { get; set; }
}

If I retrieve the employees with the line below the navigation property for Department is null:

        var employees = _context.Employees.ToList();

However, if I first populate a separate variable with Departments, like this ...

        var departments = _context.Departments.ToList();

        var employees = _context.Employees.ToList();

... Each employee in the employees list contains the Department object.

My question:
What is best practice to populate the navigation property? I had imagined that Entity Framework would have done this by default and that the ToList() method would handle the lazy loading.


问:
getpwuid and getgrgid causes segfault when user does not exist for given UID
I am running a C program in linux, which prints filename plus its user and group ownership. I am using getpwuid and getgrgid.

When file is owned by non-existent user (ie, there is no entry in /etc/passwd for given UID on my machine), my program segfaults with "terminated by signal 11".

How can I make my program behave same as ls, so that it prints numerical UID when user does not exist, instead of segfaulting?

Relevant code snippet is below:

```<code>lstat(filename,&fileStat)

struct group *grp;
struct passwd *pwd;

pwd = getpwuid(fileStat.st_uid);
printf(" %s", pwd->pw_name);

grp = getgrgid(fileStat.st_gid);
printf(" %s", grp->gr_name);
</code>```

答:
getpwuid and getgrgid return a NULL pointer if the user is not found in /etc/passwd database or there was an error.
You have to check that is not NULL before accessing it value to avoid segfaults.

You have to also check the return value of lstat to be sure that it was successful before using fileStat otherwise it cause another segfault. lstat returns -1 on fail and sets errno otherwise 0.
lstat(3)

```<code>int ret =  lstat(filename,&fileStat)

if(ret == -1){
  fprintf(stderr, "lstat: (%s): %s\n", filename, strerror(errno));
  return 1;
}

struct group *grp;
struct passwd *pwd;

pwd = getpwuid(fileStat.st_uid);

if(pwd != NULL){
   printf(" %s", pwd->pw_name);
}else{
  printf(" %ld", (long)fileStat.st_uid);
}

grp = getgrgid(fileStat.st_gid);
if(grp != NULL){
 printf(" %s", grp->gr_name);}
else{
  printf(" %ld", (long)fileStat.st_gid);
}
</code>```

getpwuid(3)
Sometimes it might return a NULL pointer on an error and will set errno. Which you have to set errno to zero before you check for the specific error

Body:
I am running a C program in linux, which prints filename plus its user and group ownership. I am using getpwuid and getgrgid.

When file is owned by non-existent user (ie, there is no entry in /etc/passwd for given UID on my machine), my program segfaults with "terminated by signal 11".

How can I make my program behave same as ls, so that it prints numerical UID when user does not exist, instead of segfaulting?

Relevant code snippet is below:

lstat(filename,&fileStat)

struct group *grp;
struct passwd *pwd;

pwd = getpwuid(fileStat.st_uid);
printf(" %s", pwd->pw_name);

grp = getgrgid(fileStat.st_gid);
printf(" %s", grp->gr_name);

Body:
getpwuid and getgrgid return a NULL pointer if the user is not found in /etc/passwd database or there was an error.
You have to check that is not NULL before accessing it value to avoid segfaults.

You have to also check the return value of lstat to be sure that it was successful before using fileStat otherwise it cause another segfault. lstat returns -1 on fail and sets errno otherwise 0.
lstat(3)

int ret =  lstat(filename,&fileStat)

if(ret == -1){
  fprintf(stderr, "lstat: (%s): %s\n", filename, strerror(errno));
  return 1;
}

struct group *grp;
struct passwd *pwd;

pwd = getpwuid(fileStat.st_uid);

if(pwd != NULL){
   printf(" %s", pwd->pw_name);
}else{
  printf(" %ld", (long)fileStat.st_uid);
}

grp = getgrgid(fileStat.st_gid);
if(grp != NULL){
 printf(" %s", grp->gr_name);}
else{
  printf(" %ld", (long)fileStat.st_gid);
}

getpwuid(3)
Sometimes it might return a NULL pointer on an error and will set errno. Which you have to set errno to zero before you check for the specific error


问:
Finding which of two points is to the right
Suppose I have two vector3s, one for camera position, the other for the target position. I also have two vectors V1, V2 from each side of the camera. I don't know which one of them is on the right, but one of them is on the right for certain.

It looks like this from above:

How can I know if V1 is on the right or on the left?

I have a built in function to move the camera to the right, so I thought to do that and check distances and return it to its original position, but that's an ugly solution.

I also thought to use the dot product between the {target - camera} and {V1 - camera} vectors, and if it's positive, then it's on the right, and if negative on the left, but it appears that it doesn't work like that because for example:

{0,1,0}.{1,1,0} = {0,1,0}.{-1,1,0} = 1

Any other ideas on how to do that?

答:
Thanks to the comments, the answer is to take the normal of the plane spanned by {cam, target, cam + up} and do dot product with v1.

i.e: {{cam + up} - {cam} x {target - cam}} . {v1 - cam}

Which is the same as det({cam + up} - {cam} | {target - cam} | {v1 - cam}) since all three subtractions are linearly independent.


问:
SQL query from time_in column but not from time_out column
I'm using mysql. I have a table time_record. There are four columns namely id, time_in, time_out and students_id. I only want to query the record of the latest time_in of the student but if the latest record of the student is in time_out, it will not query. How do I query the student's latest time_in record if given that the student still does not times out?

Thanks

Here is my sample code (though it returns both records from timein and timeout)

```<code>select concat (
        st.student_fname,
        ' ',
        st.student_lname
        ) as 'Name',
    t.students_id,
    t.time_in,
    t.time_out,
    case
        when t.time_in > t.time_out
            then t.time_in
        else t.time_out
        end as MostRecentDate
from classes c
join student_classes s on c.id = s.classes_id
join timerecords t on t.students_id = s.students_id
join students st on s.students_id = st.student_id
where c.employees_id = 'sessionvalue2'
    and
where date (t.time_in) between date (now()) and date (now())
</code>```

答:
I think your time_out columns may have nulls due to which the comparison results in false in that case and it return time_out.

Also,

```<code>date (t.time_in) between date (now()) and date (now())
</code>```

doesn't make any sense. If you want to check the time_in for today's date, do:

```<code>date(t.time_in) = curdate();
</code>```

Use curdate() instead of date(now()).

or Sargable so that index can be used if any:

```<code>date >= curdate()
and date < date_add(curdate(), interval 1 day)
</code>```

Try flipping the condition like this:

```<code>select concat (
        st.student_fname,
        ' ',
        st.student_lname
        ) as 'Name',
    t.students_id,
    t.time_in,
    t.time_out,
    case
        when t.time_in < t.time_out
            then t.time_out
        else t.time_in
        end as MostRecentDate
from classes c
join student_classes s on c.id = s.classes_id
join timerecords t on t.students_id = s.students_id
join students st on s.students_id = st.student_id
where c.employees_id = 'sessionvalue2'
and date >= curdate()
and date < date_add(curdate(), interval 1 day)
</code>```

Body:
I'm using mysql. I have a table time_record. There are four columns namely id, time_in, time_out and students_id. I only want to query the record of the latest time_in of the student but if the latest record of the student is in time_out, it will not query. How do I query the student's latest time_in record if given that the student still does not times out?

Thanks

Here is my sample code (though it returns both records from timein and timeout)

select concat (
        st.student_fname,
        ' ',
        st.student_lname
        ) as 'Name',
    t.students_id,
    t.time_in,
    t.time_out,
    case
        when t.time_in > t.time_out
            then t.time_in
        else t.time_out
        end as MostRecentDate
from classes c
join student_classes s on c.id = s.classes_id
join timerecords t on t.students_id = s.students_id
join students st on s.students_id = st.student_id
where c.employees_id = 'sessionvalue2'
    and
where date (t.time_in) between date (now()) and date (now())

Body:
I think your time_out columns may have nulls due to which the comparison results in false in that case and it return time_out.

Also,

date (t.time_in) between date (now()) and date (now())

doesn't make any sense. If you want to check the time_in for today's date, do:

date(t.time_in) = curdate();

Use curdate() instead of date(now()).

or Sargable so that index can be used if any:

date >= curdate()
and date < date_add(curdate(), interval 1 day)

Try flipping the condition like this:

select concat (
        st.student_fname,
        ' ',
        st.student_lname
        ) as 'Name',
    t.students_id,
    t.time_in,
    t.time_out,
    case
        when t.time_in < t.time_out
            then t.time_out
        else t.time_in
        end as MostRecentDate
from classes c
join student_classes s on c.id = s.classes_id
join timerecords t on t.students_id = s.students_id
join students st on s.students_id = st.student_id
where c.employees_id = 'sessionvalue2'
and date >= curdate()
and date < date_add(curdate(), interval 1 day)


问:
s#arp castle injection
I have a soap web service in my web layer (s#arp architecture) which uses a service like this:

```<code>public ReportWebService(IReportService ReportService)
{
 Check.Require(ReportService != null, "ReportService may not be null");
 this.ReportService = ReportService;
}
</code>```

Can someone please remind me how/where I configure the injection of the implementation for IReportService again?

Thanks.

Christian

答:
Here is from ComponentRegistrar.cs:

```<code>    /// <summary>
    /// The add application services to.
    /// </summary>
    /// <param name="container">
    /// The container.
    /// </param>
    private static void AddApplicationServicesTo(IWindsorContainer container)
    {
        container.Register(AllTypes.Pick().FromAssemblyNamed("MyAssembly.ApplicationServices").WithService.FirstInterface());
    }
</code>```

and here is from the a service

```<code>    private readonly IDocumentManagementService _client;

    public DocumentService(IDocumentManagementService client)
    {
        _client = client;
    }
</code>```

This should help you out.

ContentLicense: CC BY-SA 2.5

Title: s#arp castle injection

Body:
I have a soap web service in my web layer (s#arp architecture) which uses a service like this:

public ReportWebService(IReportService ReportService)
{
 Check.Require(ReportService != null, "ReportService may not be null");
 this.ReportService = ReportService;
}

Can someone please remind me how/where I configure the injection of the implementation for IReportService again?

Thanks.

Christian

Body:
Here is from ComponentRegistrar.cs:

    /// <summary>
    /// The add application services to.
    /// </summary>
    /// <param name="container">
    /// The container.
    /// </param>
    private static void AddApplicationServicesTo(IWindsorContainer container)
    {
        container.Register(AllTypes.Pick().FromAssemblyNamed("MyAssembly.ApplicationServices").WithService.FirstInterface());
    }

and here is from the a service

    private readonly IDocumentManagementService _client;

    public DocumentService(IDocumentManagementService client)
    {
        _client = client;
    }

This should help you out.


问:
Graph Theory: Queries with bounded edge weight in undirected graph
Given a weighted undirected graph of n <= 200000 nodes and m <= 200000 edges. Edge weights (integers) can be upto 1e9. There are q <= 200000 queries. Each query gives two nodes u v and a integer bound p (<= 1e9). If there's a path between u and v such that each edge weight in the path is <= p then answer is yes else no.

Notice that the path doesn't have to shortest. Just the maximum weight on the path is <= p. Naive approaches of course don't work. How to answer the queries fast (in O(n lg n) or something like that)?

答:
First build the minimum spanning tree from the given graph.

Then you can use heavy light decomposition technique to answer each query in logn.

So overall complexity of O(mlogm + qlogn).
You can find about heavy light decomposition in the following link
https://blog.anudeep2011.com/heavy-light-decomposition/


问:
textured sprite is all black in three.js
I'm starting on three.js and I'm already stuck on a trivial case : display an image on a sprite. I can only get a black plane following the lines written in the documentation:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8>
        <title>TEST Sprite</title>
        <style>
            body { margin: 0; background-color:#000; }
            canvas { width: 100%; height: 100%; }
            #glRender {
                position:absolute;
                top: 50px;
                left: 200px;
                min-width: 200px;
                width: 50%;
                min-height: 200px;
                z-index: 1;
                height: 50%;
                border: 10px solid #38272C;
            }

        </style>
    </head>
    <body>
        <div id="glRender"></div>
        <script src="http://threejs.org/build/three.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth / 2, window.innerHeight / 2 );

            container = document.getElementById( 'glRender' );
            document.body.appendChild( container );
            container.appendChild( renderer.domElement );

            // A simple cube
            var geometry = new THREE.BoxGeometry( 1, 1, 1 );
            var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
            var cube = new THREE.Mesh( geometry, material );
            scene.add( cube );

            // completely black...
            var photoTexLoad = new THREE.TextureLoader().load( 'http://s2.favim.com/610/150817/plage-summer-Favim.com-3137863.jpg' );
            var matPhoto = new THREE.SpriteMaterial( { map: photoTexLoad, color: 0xffffff } );
            var sprite = new THREE.Sprite( matPhoto );
            sprite.scale.set( 2, 2, 2 );
            sprite.position.set( 1, 0, 0.5 );
            scene.add( sprite );

            camera.position.z = 5;

            function render() {
                requestAnimationFrame( render );
                cube.rotation.x += 0.01;
                cube.rotation.y += 0.1;
                renderer.render( scene, camera );
            }

            render();

        </script>
    </body>
</html>
</code>```

I get the spinning green cube intersecting with a black plane.
What did I miss to have the image displayed on the plane?

答:
I just found out I got the "CORS" issue highlighted in question three.js: texture goes all black

The code is working fine but I cannot try to load an image from external website or directly on my computer, only files on my localhost.

For testing, I now use a specific instance of google chrome using a desktop shortcut launching the browser as : "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --args  --user-data-dir="C:/Chrome dev session" --disable-web-security

Body:
I'm starting on three.js and I'm already stuck on a trivial case : display an image on a sprite. I can only get a black plane following the lines written in the documentation:

<!DOCTYPE html>

        <meta charset=utf-8>
        <title>TEST Sprite</title>

I get the spinning green cube intersecting with a black plane.
What did I miss to have the image displayed on the plane?


问:
Post form data to php without page refresh
I am trying to post form data, an array to php file without page refresh. I am using ajax which doesn't seem to be working. Below is form syntax and ajax. Can somebody please help me? Thanks.

```<code><form name="postcontent" id="postcontent">
function[]; //just for an example of data
<button type="button" id="submitform" onclick="posttophp" >Send</button>

<script>
function posttophp() {
  var xhttp = new XMLHttpRequest();
  xhttp1.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("submitform").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "options.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("
function_Options1[]=function[]")
}
</script>
</code>```

In php, I store function_Options1[] in another variable and use further.

答:
Two ideas to try:

Maybe the script should be placed before calling the function, but not sure about this.

Try onclick="posttophp();"

Body:
I am trying to post form data, an array to php file without page refresh. I am using ajax which doesn't seem to be working. Below is form syntax and ajax. Can somebody please help me? Thanks.

<form name="postcontent" id="postcontent">
function[]; //just for an example of data
<button type="button" id="submitform" onclick="posttophp" >Send</button>

In php, I store function_Options1[] in another variable and use further.


问:
Python pandas groupby aggregate on multiple columns, then pivot
In Python, I have a pandas DataFrame similar to the following:

```<code>Item | shop1 | shop2 | shop3 | Category
------------------------------------
Shoes| 45    | 50    | 53    | Clothes
TV   | 200   | 300   | 250   | Technology
Book | 20    | 17    | 21    | Books
phone| 300   | 350   | 400   | Technology
</code>```

Where shop1, shop2 and shop3 are the costs of every item in different shops.
Now, I need to  return a DataFrame, after some data cleaning, like this one:

```<code>Category (index)| size| sum| mean | std
----------------------------------------
</code>```

where size is the number of items in each Category and sum, mean and std are related to the same functions applied to the 3 shops. How can I do these operations with the split-apply-combine pattern (groupby, aggregate, apply,...) ?

Can someone help me out? I'm going crazy with this one...thank you!

答:
If I understand correctly, you want to calculate aggregate metrics for all shops, not for each individually. To do that, you can first stack your dataframe and then group by Category:

```<code>stacked = df.set_index(['Item', 'Category']).stack().reset_index()
stacked.columns = ['Item', 'Category', 'Shop', 'Price']
stacked.groupby('Category').agg({'Price':['count','sum','mean','std']})
</code>```

Which results in

```<code>           Price
           count   sum        mean        std
Category
Books          3    58   19.333333   2.081666
Clothes        3   148   49.333333   4.041452
Technology     6  1800  300.000000  70.710678
</code>```

Body:
In Python, I have a pandas DataFrame similar to the following:

Item | shop1 | shop2 | shop3 | Category
------------------------------------
Shoes| 45    | 50    | 53    | Clothes
TV   | 200   | 300   | 250   | Technology
Book | 20    | 17    | 21    | Books
phone| 300   | 350   | 400   | Technology

Where shop1, shop2 and shop3 are the costs of every item in different shops.
Now, I need to  return a DataFrame, after some data cleaning, like this one:

Category (index)| size| sum| mean | std
----------------------------------------

where size is the number of items in each Category and sum, mean and std are related to the same functions applied to the 3 shops. How can I do these operations with the split-apply-combine pattern (groupby, aggregate, apply,...) ?

Can someone help me out? I'm going crazy with this one...thank you!

Body:
If I understand correctly, you want to calculate aggregate metrics for all shops, not for each individually. To do that, you can first stack your dataframe and then group by Category:

stacked = df.set_index(['Item', 'Category']).stack().reset_index()
stacked.columns = ['Item', 'Category', 'Shop', 'Price']
stacked.groupby('Category').agg({'Price':['count','sum','mean','std']})

Which results in

           Price
           count   sum        mean        std
Category
Books          3    58   19.333333   2.081666
Clothes        3   148   49.333333   4.041452
Technology     6  1800  300.000000  70.710678


问:
Scrapy: How to extract content in nested div's (xpath selector)?
Please see the below html markup. How can I use the xpath selector in Scrapy to pull content from the col-sm-7 class name in div?

I want to extract this text:

Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE

HTML:

```<code><div class="pricing panel panel-primary">
   <div class="panel-heading">Infortrend Products</div>
   <div class="body">
    <div class="panel-subheading"><strong>EonNAS Pro Models</strong></div>
    <div class="row">
     <div class="col-sm-7"><strong>Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE</strong><br />
      <small>Intel Core i3 Dual-Core 3.3GHz Processor, 8GB DDR3 RAM (Drives Not Included)</small></div>
     <div class="col-sm-3">#ENP8502MD-0030<br />
      <strong> Our Price: $2,873.00</strong></div>
     <div class="col-sm-2">
      <form action="/addcart.asp" method="get">
       <input type="hidden" name="item" value="ENP8502MD-0030 - Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE (Drives Not Included)">
       <input type="hidden" name="price" value="$2873.00">
       <input type="hidden" name="custID" value="">
       <input type="hidden" name="quantity" value="1">
       <button type="submit" class="btn btn-primary center-block"><i class="fa fa-shopping-cart"></i> Add to Cart</button>
      </form>
     </div>
    </div>
   </div>
  </div>
</code>```

I tried to use this command but it didn't work:

```<code>response.xpath('//div[@class="pricing panel panel-primary"]/div[@class="panel-heading"]/text()/div[@class="body"]//div[@class="panel-subheading" and contains(@style,'font-weight:bold')]/text()').extract_first()
</code>```

答:
Try this:

```<code>response.xpath('//*[@class="col-sm-7"]//strong//text()').extract()
</code>```

Hope it help :)

Body:
Please see the below html markup. How can I use the xpath selector in Scrapy to pull content from the col-sm-7 class name in div?

I want to extract this text:

Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE

HTML:

Infortrend Products

EonNAS Pro Models

Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE

      Intel Core i3 Dual-Core 3.3GHz Processor, 8GB DDR3 RAM (Drives Not Included)

#ENP8502MD-0030

       Our Price: $2,873.00

      <form action="/addcart.asp" method="get">
       <input type="hidden" name="item" value="ENP8502MD-0030 - Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE (Drives Not Included)">
       <input type="hidden" name="price" value="$2873.00">
       <input type="hidden" name="custID" value="">
       <input type="hidden" name="quantity" value="1">
       <button type="submit" class="btn btn-primary center-block"> Add to Cart</button>
      </form>

I tried to use this command but it didn't work:

response.xpath('//div[@class="pricing panel panel-primary"]/div[@class="panel-heading"]/text()/div[@class="body"]//div[@class="panel-subheading" and contains(@style,'font-weight:bold')]/text()').extract_first()

Body:
Try this:

response.xpath('//*[@class="col-sm-7"]//strong//text()').extract()

Hope it help :)


问:
How to have parallel convolutional layers in keras?
I am a little new to neural networks and keras. I have some images with size 6*7 and the size of the filter is 15. I want to have several filters and train a convolutional layer separately on each and then combine them. I have looked at one example here:

```<code>model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                    border_mode='valid',
                    input_shape=input_shape))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.25))
model.add(Flatten(input_shape=input_shape))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('tanh'))
</code>```

This model works with one filter. Can anybody give me some hints on how to modify the model to work with parallel convolutional layers.

Thanks

答:
My approach is to create other model that defines all parallel convolution and pulling operations and concat all parallel result tensors to single output tensor. Now you can add this parallel model graph in your sequential model just like layer. Here is my solution, hope it solves your problem.

```<code># variable initialization
from keras import Input, Model, Sequential
from keras.layers import Conv2D, MaxPooling2D, Concatenate, Activation, Dropout, Flatten, Dense

nb_filters =100
kernel_size= {}
kernel_size[0]= [3,3]
kernel_size[1]= [4,4]
kernel_size[2]= [5,5]
input_shape=(32, 32, 3)
pool_size = (2,2)
nb_classes =2
no_parallel_filters = 3

# create seperate model graph for parallel processing with different filter sizes
# apply 'same' padding so that ll produce o/p tensor of same size for concatination
# cancat all paralle output

inp = Input(shape=input_shape)
convs = []
for k_no in range(len(kernel_size)):
    conv = Conv2D(nb_filters, kernel_size[k_no][0], kernel_size[k_no][1],
                    border_mode='same',
                         activation='relu',
                    input_shape=input_shape)(inp)
    pool = MaxPooling2D(pool_size=pool_size)(conv)
    convs.append(pool)

if len(kernel_size) > 1:
    out = Concatenate()(convs)
else:
    out = convs[0]

conv_model = Model(input=inp, output=out)

# add created model grapg in sequential model

model = Sequential()
model.add(conv_model)        # add model just like layer
model.add(Conv2D(nb_filters, kernel_size[1][0], kernel_size[1][0]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.25))
model.add(Flatten(input_shape=input_shape))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('tanh'))
</code>```

For more information refer similar question:  Combining the outputs of multiple models into one model

Body:
I am a little new to neural networks and keras. I have some images with size 6*7 and the size of the filter is 15. I want to have several filters and train a convolutional layer separately on each and then combine them. I have looked at one example here:

model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                    border_mode='valid',
                    input_shape=input_shape))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.25))
model.add(Flatten(input_shape=input_shape))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('tanh'))

This model works with one filter. Can anybody give me some hints on how to modify the model to work with parallel convolutional layers.

Thanks

Body:
My approach is to create other model that defines all parallel convolution and pulling operations and concat all parallel result tensors to single output tensor. Now you can add this parallel model graph in your sequential model just like layer. Here is my solution, hope it solves your problem.

# variable initialization
from keras import Input, Model, Sequential
from keras.layers import Conv2D, MaxPooling2D, Concatenate, Activation, Dropout, Flatten, Dense

nb_filters =100
kernel_size= {}
kernel_size[0]= [3,3]
kernel_size[1]= [4,4]
kernel_size[2]= [5,5]
input_shape=(32, 32, 3)
pool_size = (2,2)
nb_classes =2
no_parallel_filters = 3

# create seperate model graph for parallel processing with different filter sizes
# apply 'same' padding so that ll produce o/p tensor of same size for concatination
# cancat all paralle output

inp = Input(shape=input_shape)
convs = []
for k_no in range(len(kernel_size)):
    conv = Conv2D(nb_filters, kernel_size[k_no][0], kernel_size[k_no][1],
                    border_mode='same',
                         activation='relu',
                    input_shape=input_shape)(inp)
    pool = MaxPooling2D(pool_size=pool_size)(conv)
    convs.append(pool)

if len(kernel_size) > 1:
    out = Concatenate()(convs)
else:
    out = convs[0]

conv_model = Model(input=inp, output=out)

# add created model grapg in sequential model

model = Sequential()
model.add(conv_model)        # add model just like layer
model.add(Conv2D(nb_filters, kernel_size[1][0], kernel_size[1][0]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Dropout(0.25))
model.add(Flatten(input_shape=input_shape))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('tanh'))

For more information refer similar question:  Combining the outputs of multiple models into one model


答:
You can simple use min-heights and surround the containers and rows with a div for extra styling. You can check this example I quickly made: JsFiddle

```<code><div class="song-list">
    <div class="row">
        <div class="container">
            <div class="col-md-6" id="song-view">
               Song View
            </div>

            <div class="col-md-6" id="songs-added">
               Songs Added
            </div>
        </div>
     </div>
</div>

<div class="playlist">
    <div class="row">
        <div class="container">
            <div class="col-md-6" id="playlist-form">
                Playlist Form
            </div>
        </div>
    </div>
</div>
</code>```

CSS:

```<code>.song-list #song-view {
  border:1px solid blue;
  min-height:300px;
}
.song-list #songs-added {
  border:1px solid red;
  min-height:500px;
}

.playlist #playlist-form {
  border:1px solid green;
}
</code>```

Title: How to place div in second row directly under div in first row with same column size but blocked by the height of another column in first row

Body:
Sorry if the title is confusing. I have included a screenshot of my issue to make it more clear.

Essentially, I want the green-bordered div to be directly underneath the red-bordered div without the blue-bordered div interfering.

Here is my HTML code (I am using Bootstrap v3.3.7)

            <app-selected-song-view></app-selected-song-view>

            <app-songs-added></app-songs-added>

            <app-playlist-form></app-playlist-form>

My CSS is only putting the borders around the div. Everything else is bootstrap.

#song-view{
    border: 2px solid red;
}
#songs-added{
    border: 2px solid blue;
}
#playlist-form{
    border: 2px solid green;
}

Body:
You can simple use min-heights and surround the containers and rows with a div for extra styling. You can check this example I quickly made: JsFiddle

<div class="song-list">
    <div class="row">
        <div class="container">
            <div class="col-md-6" id="song-view">
               Song View
            </div>

            <div class="col-md-6" id="songs-added">
               Songs Added
            </div>
        </div>
     </div>
</div>

<div class="playlist">
    <div class="row">
        <div class="container">
            <div class="col-md-6" id="playlist-form">
                Playlist Form
            </div>
        </div>
    </div>
</div>

CSS:

.song-list #song-view {
  border:1px solid blue;
  min-height:300px;
}
.song-list #songs-added {
  border:1px solid red;
  min-height:500px;
}

.playlist #playlist-form {
  border:1px solid green;
}


问:
Apply function to single column of structured numpy array in Python
I have a structured numpy array with two columns. One column contains a series of date times as strings, and the other contains measured values corresponding to that date.

```<code>data = array([('date1', 2.3), ('date3', 2.4), ...]
             dtype=[('date', '<U16'), ('val', '<f8')])
</code>```

I also have a number of functions similar to the following:

```<code>def example_func(x):
    return 5*x + 1
</code>```

I am trying to apply example_func to the second column of my array and generate the result

```<code>array([('date1', 12.5), ('date3', 11.6), ...]
      dtype=[('date', '<U16'), ('val', '<f8')])
</code>```

Everything I try, however, either raises a future warning from numpy or requires a for loop. Any ideas on how I can do this efficiently?

答:
This works for me:

```<code>In [7]: example_func(data['val'])
Out[7]: array([ 12.5,  13. ])
In [8]: data['val'] = example_func(data['val'])
In [9]: data
Out[9]:
array([('date1',  12.5), ('date3',  13. )],
      dtype=[('date', '<U16'), ('val', '<f8')])
In [10]: np.__version__
Out[10]: '1.12.0'
</code>```

I have gotten future warnings when accessing several fields (with a list of names), and then attempting some sort of modification.  It suggests making a copy etc.  But I can't generate such a warning with a single field access like this.

```<code>In [15]: data[['val', 'date']]
Out[15]:
array([( 12.5, 'date1'), ( 13. , 'date3')],
      dtype=[('val', '<f8'), ('date', '<U16')])
In [16]: data[['val', 'date']][0] = (12, 'date2')
/usr/local/bin/ipython3:1: FutureWarning: Numpy has detected that you (may be) writing to an array returned
by numpy.diagonal or by selecting multiple fields in a structured
array. This code will likely break in a future numpy release --
see numpy.diagonal or arrays.indexing reference docs for details.
The quick fix is to make an explicit copy (e.g., do
arr.diagonal().copy() or arr[['f0','f1']].copy()).
</code>```

Developers aren't happy with how they access several fields at once.  It's ok to read them, but changing is under evaluation.  And in '1.13' there's some change about copying fields by position rather than name.

Body:
I have a structured numpy array with two columns. One column contains a series of date times as strings, and the other contains measured values corresponding to that date.

data = array([('date1', 2.3), ('date3', 2.4), ...]
             dtype=[('date', '<U16'), ('val', '<f8')])

I also have a number of functions similar to the following:

def example_func(x):
    return 5*x + 1

I am trying to apply example_func to the second column of my array and generate the result

array([('date1', 12.5), ('date3', 11.6), ...]
      dtype=[('date', '<U16'), ('val', '<f8')])

Everything I try, however, either raises a future warning from numpy or requires a for loop. Any ideas on how I can do this efficiently?

Body:
This works for me:

In [7]: example_func(data['val'])
Out[7]: array([ 12.5,  13. ])
In [8]: data['val'] = example_func(data['val'])
In [9]: data
Out[9]:
array([('date1',  12.5), ('date3',  13. )],
      dtype=[('date', '<U16'), ('val', '<f8')])
In [10]: np.__version__
Out[10]: '1.12.0'

I have gotten future warnings when accessing several fields (with a list of names), and then attempting some sort of modification.  It suggests making a copy etc.  But I can't generate such a warning with a single field access like this.

In [15]: data[['val', 'date']]
Out[15]:
array([( 12.5, 'date1'), ( 13. , 'date3')],
      dtype=[('val', '<f8'), ('date', '<U16')])
In [16]: data[['val', 'date']][0] = (12, 'date2')
/usr/local/bin/ipython3:1: FutureWarning: Numpy has detected that you (may be) writing to an array returned
by numpy.diagonal or by selecting multiple fields in a structured
array. This code will likely break in a future numpy release --
see numpy.diagonal or arrays.indexing reference docs for details.
The quick fix is to make an explicit copy (e.g., do
arr.diagonal().copy() or arr[['f0','f1']].copy()).

Developers aren't happy with how they access several fields at once.  It's ok to read them, but changing is under evaluation.  And in '1.13' there's some change about copying fields by position rather than name.


问:
Regex implementation with event driven matches?
This may sound a little odd, but it would be extremely useful to me. Are there any regex implementations (any language but preferably java, javascript, c, c++) that use an event based model for matches?

I would like to be able to register a bunch of different regular expressions I am looking for in a string via an event based model, feed the string though the regex engine, and just have the events fired off correctly. Does anything like this exist?

I realize this is bordering on the territory of a heavy duty lexer/parser, but I would prefer to stay away from that if at all possible, as my search expressions would need to be dynamic (completely).

Thanks

答: You might want to check out PIRE - a very fast automata-based regexp engine, tuned to match zillions of lines of text against many regular expressions quickly. It's available in C and has some bindings.</p>


问:
How to edit credentials in jenkins?
How do I edit the credentials that are showing up in jenkins?

答: If you have permission you should have an option to update credetials when you point the name column:

Title: How to edit credentials in jenkins?


问:
Issue With JavaScript / HTML Form Validation
The method validateRegistrationForm is not being called, I have tested this by placing an alert inside and can't figure out why this is the case.

There is other JavaScript to validate other things though I have removed that until this issue is resolved.

The JavaScript itself is being linked to the HTML via script tags inside of the body. I put an alert at the top of the JS to make sure the link is working and it is.

HTML:

```<code><form name="registrationForm" id="registrationForm" action="AddUserDetails">
    <div class="form-group">
        <label for="firstName">First Name</label>
        <span id="firstNameError">*</span>
        <input type="text" class="form-control" id="firstName">
    </div>
    <div class="form-group">
        <label for="lastName">Second Name</label>
        <span id="lastNameError">*</span>
        <input type="text" class="form-control" id="lastName">
    </div>
    <div class="form-group">
        <label for="phoneNumber">Phone Number</label>
        <span id="phoneNumberError">*</span>
        <input type="text" class="form-control" id="phoneNumber">
    </div>
    <div class="form-group">
        <label for="eMail">E-Mail</label>
        <span id="eMailError">*</span>
        <input type="text" class="form-control" id="eMail">
    </div>
    <div class="form-group">
        <label for="eMailConfirmation">Confirm E-Mail</label>
        <span id="eMailConfirmationError">*</span>
        <input type="text" class="form-control" id="eMailConfirmation">
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <span id="passwordError">*</span>
        <input type="password" class="form-control" id="password">
    </div>
</form>

<div class="text-center">
    <input type="button" id="submitRegistationForm" value="Submit">
</div>
</code>```

JavaScript:

```<code>var $ = function (id) {
    return document.getElementById(id);
}

var validateRegistrationForm = function () {
    alert("");
    var isValid = true;

    //First Name Validation
    if ($("firstName").value == "") {
        $("firstNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
        isValid = false;
    } else {
        $("firstNameError").firstChild.nodeValue = "";
    }

    //Second Name Validation
    if ($("lastName").value == "") {
        $("lastNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
        isValid = false;
    } else {
        $("lastNameError").firstChild.nodeValue = "";
    }

    if (isValid) {
        $("registrationForm").submit();
    }
}

window.onload = function () {
    $("submitRegistationForm").onclick = validateRegistrationForm;
}
</code>```

答:
Redefining $ seems like an awful idea, especially if this is code shared amongst other developers. In either case, why even wait for window.onload? You could just declare your click handler outside of it. Working jsfiddle:

```<code>$("submitRegistationForm").onclick = validateRegistrationForm;
</code>```

https://jsfiddle.net/ou3gLLqe/

Body:
The method validateRegistrationForm is not being called, I have tested this by placing an alert inside and can't figure out why this is the case.

There is other JavaScript to validate other things though I have removed that until this issue is resolved.

The JavaScript itself is being linked to the HTML via script tags inside of the body. I put an alert at the top of the JS to make sure the link is working and it is.

HTML:

<form name="registrationForm" id="registrationForm" action="AddUserDetails">

        First Name
        *
        <input type="text" class="form-control" id="firstName">

        Second Name
        *
        <input type="text" class="form-control" id="lastName">

        Phone Number
        *
        <input type="text" class="form-control" id="phoneNumber">

        E-Mail
        *
        <input type="text" class="form-control" id="eMail">

        Confirm E-Mail
        *
        <input type="text" class="form-control" id="eMailConfirmation">

        Password
        *
        <input type="password" class="form-control" id="password">

</form>

    <input type="button" id="submitRegistationForm" value="Submit">

JavaScript:

var $ = function (id) {
    return document.getElementById(id);
}

var validateRegistrationForm = function () {
    alert("");
    var isValid = true;

    //First Name Validation
    if ($("firstName").value == "") {
        $("firstNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
        isValid = false;
    } else {
        $("firstNameError").firstChild.nodeValue = "";
    }

    //Second Name Validation
    if ($("lastName").value == "") {
        $("lastNameError").firstChild.nodeValue = "This Text Box Cannot Be Blank";
        isValid = false;
    } else {
        $("lastNameError").firstChild.nodeValue = "";
    }

    if (isValid) {
        $("registrationForm").submit();
    }
}

window.onload = function () {
    $("submitRegistationForm").onclick = validateRegistrationForm;
}

Body:
Redefining $ seems like an awful idea, especially if this is code shared amongst other developers. In either case, why even wait for window.onload? You could just declare your click handler outside of it. Working jsfiddle:

$("submitRegistationForm").onclick = validateRegistrationForm;

https://jsfiddle.net/ou3gLLqe/


问:
XSLT and base URIs with copy-of - Why does the uri change from the XML-file to the XSLT-file?
Given the following stylesheet

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template name="start">
        <base-uris>
            <node-base-uri>
                <xsl:value-of select="base-uri(.)" />
            </node-base-uri>
            <node-base-uri-from-copy>
                <xsl:variable name="doc">
                    <xsl:copy-of select="." />
                </xsl:variable>
                <xsl:value-of select="base-uri($doc)" />
            </node-base-uri-from-copy>
        </base-uris>
    </xsl:template>

</xsl:stylesheet>
</code>```

After transforming an arbitrary XML file with Saxon from the command line with the following command:

```<code>java net.sf.saxon.Transform -s:xml/index.xml -xsl:xsl/base-uri.xsl -it:start
</code>```

I expected the same values for the base URIs pointing to the XML source file. But the base URI in the second case (with copy-of) points to the XSLT file.

```<code><base-uris>
    <node-base-uri>file:/xml/index.xml</node-base-uri>
    <node-base-uri-from-copy>file:/xsl/base-uri.xsl</node-base-uri-from-copy>
</base-uris>
</code>```

Motivation: In the "real world stylesheet" I use a template to include other XML sources. They are specified in the source XML itself (relative paths in a href attribute).

```<code><xsl:template match="include" mode="includes">
    <xsl:copy-of select="document(@href, .)/*"/>
</xsl:template>
</code>```

From the Spec:

The base URI of a node is copied, except in the case of an element node having an xml:base attribute

My question(s):

First of all, I would like to know, how to preserve/set/copy the base URI from the XML file and not from the XSLT file.

Second, I do not understand the Spec and/or do not understand the xml:base attribute thing. I simply thought: I do not see any xml:base attribute in my code, so the base URI of the node should be copied.

Last remark:

Playing around, I came up with something like this, which feels clumsy or simply the wrong way to go:

```<code><node-base-uri-work-around>
    <xsl:variable name="doc">
        <wrapper>
            <xsl:attribute name="xml:base" select="base-uri(.)" />
            <xsl:copy-of select="." />
        </wrapper>
    </xsl:variable>
    <xsl:value-of select="base-uri($doc/wrapper)" />
</node-base-uri-work-around>
</code>```

答:
I'm never sure how to interpret "why?" questions. One interpretation is "where in the spec does it say this should happen?" Another interpretation is "why did the authors of the spec decide to make it behave this way?"

Martin Honnen has pointed you to the section of the spec that dictates the base URI of a document created as a temporary tree using xsl:variable. As to why it's designed that way: well, a historically accurate answer to that would require a lot of trawling through the archives, and even then would be difficult because very often the answer is simply that no-one proposed any alternative. XSLT 1.0 says that every node has a base URI, but as far as I can see, it doesn't say what the base URI of a constructed node should be; this is added in XSLT 2.0. I don't think that the base URI of a document node constructed using xsl:variable could really be anything other than the stylesheet base URI (nothing else is really available at that point), but the rule in 5.7.1 (Constructing complex content) rule 10 "When copying an element or processing instruction node, its base URI property is changed to be the same as that of its new parent, unless it has an xml:base attribute (see [XML Base]) that overrides this." certainly could have been written differently, and I think it's quite likely that the choice was debated, but exactly what the arguments were I don't recall at this point. It's frankly a little academic, since the most likely form for the final result tree is either serialized XML or a DOM, and neither will preserve the base URI of a node anyway.

Body:
Given the following stylesheet

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template name="start">
        <base-uris>
            <node-base-uri>
                <xsl:value-of select="base-uri(.)" />
            </node-base-uri>
            <node-base-uri-from-copy>
                <xsl:variable name="doc">
                    <xsl:copy-of select="." />
                </xsl:variable>
                <xsl:value-of select="base-uri($doc)" />
            </node-base-uri-from-copy>
        </base-uris>
    </xsl:template>

</xsl:stylesheet>

After transforming an arbitrary XML file with Saxon from the command line with the following command:

java net.sf.saxon.Transform -s:xml/index.xml -xsl:xsl/base-uri.xsl -it:start

I expected the same values for the base URIs pointing to the XML source file. But the base URI in the second case (with copy-of) points to the XSLT file.

<base-uris>
    <node-base-uri>file:/xml/index.xml</node-base-uri>
    <node-base-uri-from-copy>file:/xsl/base-uri.xsl</node-base-uri-from-copy>
</base-uris>

Motivation: In the "real world stylesheet" I use a template to include other XML sources. They are specified in the source XML itself (relative paths in a href attribute).

<xsl:template match="include" mode="includes">
    <xsl:copy-of select="document(@href, .)/*"/>
</xsl:template>

From the Spec:

The base URI of a node is copied, except in the case of an element node having an xml:base attribute

My question(s):

First of all, I would like to know, how to preserve/set/copy the base URI from the XML file and not from the XSLT file.

Second, I do not understand the Spec and/or do not understand the xml:base attribute thing. I simply thought: I do not see any xml:base attribute in my code, so the base URI of the node should be copied.

Last remark:

Playing around, I came up with something like this, which feels clumsy or simply the wrong way to go:

<node-base-uri-work-around>
    <xsl:variable name="doc">
        <wrapper>
            <xsl:attribute name="xml:base" select="base-uri(.)" />
            <xsl:copy-of select="." />
        </wrapper>
    </xsl:variable>
    <xsl:value-of select="base-uri($doc/wrapper)" />
</node-base-uri-work-around>


问:
CRUD filtering/sorting doesnt work in asp.net
I have this database that I need to sort/filter. My current code shows no errors, but it does nothing as well.

ApplicationUsersController.cs

```<code>// GET: ApplicationUsers
        public ActionResult Index(string sortOrder, string searchString)
        {
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.EmailSortParm = sortOrder == "Email" ? "email_desc" : "Email";
            var users = from c in db.Users
                           select c;
            if (!String.IsNullOrEmpty(searchString))
            {
                users = users.Where(c => c.Name.ToUpper().Contains(searchString.ToUpper())
                                       || c.Email.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    users = users.OrderByDescending(c => c.Name);
                    break;
                case "Email":
                    users = users.OrderBy(c => c.Email);
                    break;
                case "email_desc":
                    users = users.OrderByDescending(c => c.Email);
                    break;
                default:
                    users = users.OrderBy(c => c.Name);
                    break;
            }

            return View(db.Users.ToList());
        }
</code>```

Index.cshtml

```<code>@using (Html.BeginForm())
{
    <p>
        Find by name: @Html.TextBox("SearchString")
        <input type="submit" value="Search" />
    </p>
}

<table class="table">
    <tr>
        <th>
            @Html.ActionLink("Email", "Index", new { sortOrder = ViewBag.EmailSortParm })
        </th>
        <th>
            @Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>
</code>```

Neither sorting, nor filtering seems to work. When sorting, address bar changes to

/ApplicationUsers?sortOrder=name_desc

but the order doesn't change at all. Maybe someone can see where is the problem?

EDIT:

Can it be 'var users = from c in db.Users select c; ' that the letter 'c' is wrong? How can I know for sure?

答:
Change:

```<code>return View(db.Users.ToList());
</code>```

To:

```<code>return View(users);
</code>```

:-)

Body:
I have this database that I need to sort/filter. My current code shows no errors, but it does nothing as well.

ApplicationUsersController.cs

// GET: ApplicationUsers
        public ActionResult Index(string sortOrder, string searchString)
        {
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.EmailSortParm = sortOrder == "Email" ? "email_desc" : "Email";
            var users = from c in db.Users
                           select c;
            if (!String.IsNullOrEmpty(searchString))
            {
                users = users.Where(c => c.Name.ToUpper().Contains(searchString.ToUpper())
                                       || c.Email.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    users = users.OrderByDescending(c => c.Name);
                    break;
                case "Email":
                    users = users.OrderBy(c => c.Email);
                    break;
                case "email_desc":
                    users = users.OrderByDescending(c => c.Email);
                    break;
                default:
                    users = users.OrderBy(c => c.Name);
                    break;
            }

            return View(db.Users.ToList());
        }

Index.cshtml

@using (Html.BeginForm())
{

        Find by name: @Html.TextBox("SearchString")
        <input type="submit" value="Search" />

}

            @Html.ActionLink("Email", "Index", new { sortOrder = ViewBag.EmailSortParm })

            @Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })

Neither sorting, nor filtering seems to work. When sorting, address bar changes to

/ApplicationUsers?sortOrder=name_desc

but the order doesn't change at all. Maybe someone can see where is the problem?

EDIT:

Can it be 'var users = from c in db.Users select c; ' that the letter 'c' is wrong? How can I know for sure?

Body:
Change:

return View(db.Users.ToList());

To:

return View(users);

:-)


问:
Currency conversion algorithm
Let's say I have only following pairs:

```<code>[
  {
    "from": "AUD",
    "rate": "0.5",
    "to": "USD"
  },
  {
    "from": "USD",
    "rate": "0.5",
    "to": "EUR"
  },
  {
    "from": "EUR",
    "rate": "0.5",
    "to": "GBP"
  },
  {
    "from": "GBP",
    "rate": "2",
    "to": "EUR"
  },
  {
    "from": "EUR",
    "rate": "2",
    "to": "USD"
  },
  {
    "from": "USD",
    "rate": "2",
    "to": "AUD"
  }
]
</code>```

And I need to convert from AUD to GBP.
Algorithm should find path how to do it using existing pairs: AUD -> USD -> EUR -> GBP.

After looking on this problem I think that it can be solved with recursion, but still didn't find the right way to do it.
Should I start looking backwards starting with the GBP in this case?
Or recursion is not needed and I can just iterate backwards and add values to the stack while I will not spot the right one?

答:
This is a job for either a depth-first search or a breadth-first search.  You don't need recursion, but you can use it if you want – a depth-first search uses a stack, and recursion would be a way of doing it with the call stack.  Note that a breadth-first search will give you the shortest conversion path.  A depth-first search might not.

Regardless of which search strategy you choose, you'll be building possible paths from currency to currency based on the available conversions.  When adding another conversion step to a path, make sure to filter out conversions to currencies that were already used earlier in the path, so you don't get loops in your path.  (For example, converting USD->EUR->USD->EUR->etc. would get a depth-first search stuck forever.)

You can start from either currency and work in either direction; you'll find a valid path ether way.

Title: Currency conversion algorithm

Body:
Let's say I have only following pairs:

[
  {
    "from": "AUD",
    "rate": "0.5",
    "to": "USD"
  },
  {
    "from": "USD",
    "rate": "0.5",
    "to": "EUR"
  },
  {
    "from": "EUR",
    "rate": "0.5",
    "to": "GBP"
  },
  {
    "from": "GBP",
    "rate": "2",
    "to": "EUR"
  },
  {
    "from": "EUR",
    "rate": "2",
    "to": "USD"
  },
  {
    "from": "USD",
    "rate": "2",
    "to": "AUD"
  }
]

And I need to convert from AUD to GBP.
Algorithm should find path how to do it using existing pairs: AUD -> USD -> EUR -> GBP.

After looking on this problem I think that it can be solved with recursion, but still didn't find the right way to do it.
Should I start looking backwards starting with the GBP in this case?
Or recursion is not needed and I can just iterate backwards and add values to the stack while I will not spot the right one?


问:
I want to check if parameter exist as an id in the body. how can I do that without hardcoding and using jquery? Javascript

```<code><a id="Param">This is an html element</a>

<script>

function Append(param1,text)
{
    if(document.getElementById(param1))
    {

        return document.getElementById(param1)+text;
    }
    else
    {
        console.error("the element was not found");
    }
}

var app1=Append("Anything",". yes"); //i called the append twice first is to see the output when false
var app2=Append("Param",". hi")//second is to see the output when true. I want the output to be "This is an html element. hi"
</code>```

this is the code that I have. I wanted to have a function that uses two parameters. The first one is to for an html element id and the second one is for the text that will be appended to the first parameter. How can the function check if "Param" is an id without hard coding or using jquery?

答:
```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab Test 1</title>
</head>
<body>

<a id="Param">This is an html element</a>

<script>

    function appendToElement(p1,p2)
    {
        var el=document.getElementById(p1);
        if(el)
        {
            el.innerHTML+=p2;
            return true;
        }
        else
        {
        console.error("Element with ID: "+p1+" not found");
        return false;
        }
    }

    var app1=appendToElement("Anything",". yes");
    var app2=appendToElement("Param",". hi")
</script>

</body>
</html>
</code>```

This is the code that I got from my professor.

Body: This is an html element

Body:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab Test 1</title>
</head>
<body>

<a id="Param">This is an html element</a>

<script>

    function appendToElement(p1,p2)
    {
        var el=document.getElementById(p1);
        if(el)
        {
            el.innerHTML+=p2;
            return true;
        }
        else
        {
        console.error("Element with ID: "+p1+" not found");
        return false;
        }
    }

    var app1=appendToElement("Anything",". yes");
    var app2=appendToElement("Param",". hi")
</script>

</body>
</html>

This is the code that I got from my professor.


问:
Neo4j filter on relationship
I have two types of nodes (node1) and (node2) with about 100,000 records in each. I have one type of relationship [:TYPE1] between those two nodes on only 100 rows of (a)

If I profile:
    MATCH (a:node1)-[:TYPE1]->(b:node2) RETURN a.field1, b.field2

it says it does a NodeByLabelScan with 80,000+ db hits, then uses the relationship to filter down to the 100 rows I want with many more db hits. The query does return the rows I want, but how can I get the neo4j analyzer to look at [:TYPE1] as the lowest cardinality to start the execution path?

Using Neo4j V 3.1.2 on Windows 10

Thanks

答:
As InverseFalcon said Neo4j's schema indexes don't apply to relationships. And the method he proposed works. There is another option: use node labels.

For example, add nodes and relationship:

```<code>CREATE (n1:node1)
CREATE (n2:node2)
CREATE (n1)-[r:TYPE1]->(n2)
SET n1:REL_OUT_TYPE1,
    n2:REL_IN_TYPE1
RETURN n1, n2, r
</code>```

And match:

```<code>MATCH (n1:node1:REL_OUT_TYPE1)-[:TYPE1]->(n2:node2:REL_IN_TYPE1)
RETURN n1, n2
</code>```

Title: Neo4j filter on relationship

Body:
As InverseFalcon said Neo4j's schema indexes don't apply to relationships. And the method he proposed works. There is another option: use node labels.

For example, add nodes and relationship:

CREATE (n1:node1)
CREATE (n2:node2)
CREATE (n1)-[r:TYPE1]->(n2)
SET n1:REL_OUT_TYPE1,
    n2:REL_IN_TYPE1
RETURN n1, n2, r

And match:

MATCH (n1:node1:REL_OUT_TYPE1)-[:TYPE1]->(n2:node2:REL_IN_TYPE1)
RETURN n1, n2


答:
You can fetch text between  element, something like this :

```<code>print(response.xpath('//div[@class="col-sm-7"]//text()').extract()[0].strip())
</code>```

or

```<code>print(response.xpath('//div[@class="col-sm-7"]/strong/text()').extract()[0].strip())
</code>```

Both the above statements will result in :

```<code>Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE
</code>```

You can fetch the text between all the elements inside this div with //text() including within  and  tags inside the element, something like this :

```<code>elem_text = ' '.join([txt.strip() for txt in response.xpath('//div[@class="col-sm-7"]//text()').extract()])
print(elem_text)
</code>```

This will result in :

```<code>Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE  Intel Core i3 Dual-Core 3.3GHz Processor, 8GB DDR3 RAM (Drives Not Included)
</code>```

Title: Scrapy: How to extract content in nested div's (xpath selector)?

Body:
You can fetch text between <strong> element, something like this :

print(response.xpath('//div[@class="col-sm-7"]//text()').extract()[0].strip())

or

print(response.xpath('//div[@class="col-sm-7"]/strong/text()').extract()[0].strip())

Both the above statements will result in :

Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE

You can fetch the text between all the elements inside this div with //text() including within <strong> and <small> tags inside the element, something like this :

elem_text = ' '.join([txt.strip() for txt in response.xpath('//div[@class="col-sm-7"]//text()').extract()])
print(elem_text)

This will result in :

Infortrend EonNAS Pro 850X 8-bay Tower NAS with 10GbE  Intel Core i3 Dual-Core 3.3GHz Processor, 8GB DDR3 RAM (Drives Not Included)


问:
DDoS attack mitigation on Azure infrastructure
I have a Django based web application hosted on Azure provisioned virtual machines (Ubuntu OS). My application recently experienced a DDoS attack and we were helpless against it.

The problem is that once traffic hits the server - even if it's blocked at a firewall or throttled in my webserver - the traffic is already consuming my network bandwidth. I can do nothing about it. This needs to be blocked "upstream", in the routing gear servicing my server.

Is there any DDoS protection Azure can offer me? Or at the very least, make recommendations as to how I might deploy my application so that it's more resistant to these attacks? Please advise.

答:
Current, Azure provides DDOS protection at the network level, but not at the application level.  So, if you are receiving a bunch of ACK requests, for example, this should be blocked by the platform itself.

For app level DDOS protection, you need to consider an upstream provider such as Incapsula or Silverline.  Integrating them is quite easy.  See https://www.incapsula.com/blog/how-to-add-incapsula-to-your-microsoft-azure-instance.html for an example.

Essentially, you will setup Incapsula and configure it with the DNS label of the web app (something.azurewebsites.net).  Your DNS (www.domain.com) will then point to the incapsula service and they will handle the rest.

Please note that separating the DDOS from the service still allows for an attack against the service itself (ie: if someone hits something.azurewebsites.net then Incapsula will not protect this traffic).

Hope that helps!


问:
Use of Casting on a parameter
IFrame it is an interface (That I should not modify) and Frame it is the extended class.

I need to use casting or instance of to reffer to use f as Frame instead os IFrame.

How can I achieve this?

```<code>public class Frame implements IFrame{
    private int numRows;
    private char code[][];
@Override
   public void replace(IFrame f) {
        for (int i=0; i<numRows; i++){
            for (int o=0; o<numRows; o++){

               (Frame f).code[i][o] = this.code[i][o];

                }
            }
        }
    }
</code>```

答:
((Frame) f).code[i][o] = this.code[i][o] should work but I suggest you test if the passed parameter actually is an instance of Frame before copying to avoid casting errors. Also, you should make sure that numRows of the passed Frame is greater or equal than the one of the called instance:

```<code>public void replace(IFrame iFrame) {
    if (iFrame instanceof Frame) {
        Frame f = (Frame) iFrame;
        if (f.numRows < this.numRows) {
            // Do what you want to do if the provided frame has fewer rows than this frame
            return; // Return in the if condition, this way you do not proceed to the for loop causing an IndexOutOfBounds exception
        }
        for (int i=0; i<numRows; i++){
            for (int o=0; o<numRows; o++){
                   (Frame f).code[i][o] = this.code[i][o];
                }
            }
        }
    }
}
</code>```

Title: Use of Casting on a parameter

Body:
IFrame it is an interface (That I should not modify) and Frame it is the extended class.

I need to use casting or instance of to reffer to use f as Frame instead os IFrame.

How can I achieve this?

public class Frame implements IFrame{
    private int numRows;
    private char code[][];
@Override
   public void replace(IFrame f) {
        for (int i=0; i<numRows; i++){
            for (int o=0; o<numRows; o++){

               (Frame f).code[i][o] = this.code[i][o];

                }
            }
        }
    }

Body:
((Frame) f).code[i][o] = this.code[i][o] should work but I suggest you test if the passed parameter actually is an instance of Frame before copying to avoid casting errors. Also, you should make sure that numRows of the passed Frame is greater or equal than the one of the called instance:

public void replace(IFrame iFrame) {
    if (iFrame instanceof Frame) {
        Frame f = (Frame) iFrame;
        if (f.numRows < this.numRows) {
            // Do what you want to do if the provided frame has fewer rows than this frame
            return; // Return in the if condition, this way you do not proceed to the for loop causing an IndexOutOfBounds exception
        }
        for (int i=0; i<numRows; i++){
            for (int o=0; o<numRows; o++){
                   (Frame f).code[i][o] = this.code[i][o];
                }
            }
        }
    }
}


问:
How can I show data from a db table that I'm already using else where in Rails
I've been going through the tutorials on rubyonrails.org so I have a model pulling data from the Articles table from my postgres db. I have my view displaying this table of records perfectly fine.  However I'd like to know how I then add just the last Article record on the home page for instance.  Do I 'query' the same Articles application record, or do I simply create an entirely new model, which doesn't seem that efficient as a site grows.

Do I generate complete new model such as rails generate model LastArticle?  I see that it looks like I can use article = Article.last or should this be lastarticle = Lastrticle.last and would I put this in the Model or a Controller?

Only been looking at RoR (coming from more of a php mysql background) for a few days so sorry if this is a jumbled question.

答:
Models can be used anywhere in the rails application.  In your home view controller you could do

```<code>@last_article = Article.last
</code>```

And then reference @last_article in your home view.

You can even retrieve the record as part of the view...

```<code><% last_article = Article.last %>
</code>```

And then reference last_article in the same view.

Body:
Models can be used anywhere in the rails application.  In your home view controller you could do

@last_article = Article.last

And then reference @last_article in your home view.

You can even retrieve the record as part of the view...

<% last_article = Article.last %>

And then reference last_article in the same view.


问:
Swift - UIView draw 1 pixel-width line
I'm trying to draw a line on UIView using Swift like that:

```<code>CGContextSetLineWidth(context, 1.0)
CGContextBeginPath(context)
    CGContextMoveToPoint(context, x1, y1)
    CGContextAddLineToPoint(context, x2, y2)
CGContextStrokePath(context)
</code>```

But drawn line is 2 pixels-width. I tried another way:

```<code>CGContextSetLineWidth(context, 0.5)
CGContextBeginPath(context)
    CGContextMoveToPoint(context, x1, y1)
    CGContextAddLineToPoint(context, x2, y2)
CGContextStrokePath(context)
</code>```

But result was the same.
What am I doing wrong and how to draw a 1 pixel-width line on UIView using Swift?

答:
As additional of rickster answer.

You can use this class in storeboard:

```<code>/** View that have line with 1px on the top */
class lineView :UIView {

    // pass in the scale of your UIScreen
    func drawHairline(in context: CGContext, scale: CGFloat, color: CGColor) {

        // pick which row/column of pixels to treat as the "center" of a point
        // through which to draw lines -- favor true center for odd scales, or
        // offset to the side for even scales so we fall on pixel boundaries
        let center: CGFloat
        if Int(scale) % 2 == 0 {
            center = 1 / (scale * 2)
        } else {
            center = 0
        }

        let offset = 0.5 - center // use the "center" choice to create an offset
        let p1 = CGPoint(x: 0, y: 0 + offset)
        let p2 = CGPoint(x: 800 + offset, y: 0 + offset)

        // draw line of minimal stroke width
        let width = 1 / scale
        context.setLineWidth(width)
        context.setStrokeColor(color)
        context.beginPath()
        context.move(to: p1)
        context.addLine(to: p2)
        context.strokePath()
    }

    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        drawHairline(in: context!, scale: 2, color: UIColor.gray.cgColor)
    }
}
</code>```

Title: Swift - UIView draw 1 pixel-width line

Body:
I'm trying to draw a line on UIView using Swift like that:

CGContextSetLineWidth(context, 1.0)
CGContextBeginPath(context)
    CGContextMoveToPoint(context, x1, y1)
    CGContextAddLineToPoint(context, x2, y2)
CGContextStrokePath(context)

But drawn line is 2 pixels-width. I tried another way:

CGContextSetLineWidth(context, 0.5)
CGContextBeginPath(context)
    CGContextMoveToPoint(context, x1, y1)
    CGContextAddLineToPoint(context, x2, y2)
CGContextStrokePath(context)

But result was the same.
What am I doing wrong and how to draw a 1 pixel-width line on UIView using Swift?

Body:
As additional of rickster answer.

You can use this class in storeboard:

/** View that have line with 1px on the top */
class lineView :UIView {

    // pass in the scale of your UIScreen
    func drawHairline(in context: CGContext, scale: CGFloat, color: CGColor) {

        // pick which row/column of pixels to treat as the "center" of a point
        // through which to draw lines -- favor true center for odd scales, or
        // offset to the side for even scales so we fall on pixel boundaries
        let center: CGFloat
        if Int(scale) % 2 == 0 {
            center = 1 / (scale * 2)
        } else {
            center = 0
        }

        let offset = 0.5 - center // use the "center" choice to create an offset
        let p1 = CGPoint(x: 0, y: 0 + offset)
        let p2 = CGPoint(x: 800 + offset, y: 0 + offset)

        // draw line of minimal stroke width
        let width = 1 / scale
        context.setLineWidth(width)
        context.setStrokeColor(color)
        context.beginPath()
        context.move(to: p1)
        context.addLine(to: p2)
        context.strokePath()
    }

    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        drawHairline(in: context!, scale: 2, color: UIColor.gray.cgColor)
    }
}


问:
making all input fields borders red when no one at least was filled in
I am not good enough with javascript. Simply I have a form with some input fields. The user has to fill in at least one of them. I had already found the right code to do this. This code tells the user there is an error using an alert message. But I want to make all input fields borders red instead of this alert message using the same code.

HTML

```<code><form  id="myform" action="" method="post">
    <input name="destination" class="form-control" type="text" >
    <input name="thingstodo" class="form-control" type="text">
    <input name="gsearch" class="form-control" type="text">
    <button type="submit" name="search">Search</button>
</form>
</code>```

JavaScript

```<code>$(function(){
  $("#myform").submit(function(){

    var valid=0;
    $(this).find('input[type=text]').each(function(){
        if($(this).val() != "") valid+=1;
    });

    if(valid){
        return true;
    }
    else {
        alert("error: you must fill in at least one field");
        return false;
    }
  });
});
</code>```

Thanks

答:
Modify the code like so</p>

```<code>$(function(){
$("#myform").submit(function(){

var valid=0;
$(this).find('input[type=text]').each(function(){

    if($(this).val() != "") valid+=1;
 else
 $(this).style.border = "solid 1px red"
});

if(valid){
    return true;
}
else {
    return false;
}
 });
 });
</code>```

Body:
I am not good enough with javascript. Simply I have a form with some input fields. The user has to fill in at least one of them. I had already found the right code to do this. This code tells the user there is an error using an alert message. But I want to make all input fields borders red instead of this alert message using the same code.

HTML

<form  id="myform" action="" method="post">
    <input name="destination" class="form-control" type="text" >
    <input name="thingstodo" class="form-control" type="text">
    <input name="gsearch" class="form-control" type="text">
    <button type="submit" name="search">Search</button>
</form>

JavaScript

$(function(){
  $("#myform").submit(function(){

    var valid=0;
    $(this).find('input[type=text]').each(function(){
        if($(this).val() != "") valid+=1;
    });

    if(valid){
        return true;
    }
    else {
        alert("error: you must fill in at least one field");
        return false;
    }
  });
});

Thanks

Body:
Modify the code like so

$(function(){
$("#myform").submit(function(){

var valid=0;
$(this).find('input[type=text]').each(function(){

    if($(this).val() != "") valid+=1;
 else
 $(this).style.border = "solid 1px red"
});

if(valid){
    return true;
}
else {
    return false;
}
 });
 });


问:
Spring annotations conflicts with my design guidelines
Overview

Using

Spring 3.0.1 (annotation configuration)

Current configuration is using CGLib as proxy creator but this is not my preference

Transactions are annotation configured without any special settings

All configuration is done with annotations (@Service, @Transactional, @ManagedResource, @Inject, etc.)

Hibernate 3.5 (entities are annotated with javax.persistence)

Guidelines highlights

Every bean annotated with @Repository or @Service must have an interface

Constructor DI (when re-configuration isn't required)

Constructor has default visibility (Foo(Bar bar) {...})

Bean fields are final (when re-configuration isn't required)

Leads to no default constructor

Implementations are default visible with final modifier (final class Foo)

The Problem

CGLib can't proxy final classes

CGLib requires default (empty) constructor

Some services are required to be exposed via JMX

MBean exporter can't work unless proxied by CGLib

Some @Transactional @Services are accessed via facade service which requires more than one service to include in the facade transaction (e.g. Observer service over 2 application components)

Some interfaces have more than one implementation (which currently distinguished by @Qualifier)

Future guideline (or nice to have feature) - each application module will have beanRefContext.xml file to configure its internal application context

When I used to work with XML configuration I was able to enforce all the guidelines I presented above, but when switching to annotations it seems like Spring is misbehaving.

Developers in my group prefer annotation configuration (I seems easier to wire and write new code), but I've noticed all kind of "hacks" they introduce to the code to prevent from dealing with Spring application context failures.

The Question(s)

Are there best practices I should follow when using annotation configuration?

When using more than one implementation per interface (trying to reduce the use of @Primary or @Qualifier)

When using @Transactional

When using @ManagedResource

When using a combination of the above

Is there a way of stop working with CGLib, keep the annotation configuration and still be able to export my MBeans with annotations?

What is the suitable implementation for keeping most (preferably, all) of my guidelines?

答:
Answer to point 2)
You could use AspectJ instead of CGLib.</p>