问:
How can I get data from different pages with javascripts buttons?
I have the following HTML:

            1

            2

            3

            4

            5

            6

            7

            8

            ...

            20

```
</div>
</div>
</p>

<p>When I click in this buttons I go to something like this www.example.com/something?page=X (x = number of the button)
I use this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Document doc = Jsoup.connect("www.example.com/something?page=5").get();</code>```

But I get always the first page HTML.
How I can "click" or extract information about this pages? I don't know so much about PHP but I think this page use it to change pages.

Edit:

I'm not using javascript. I'm using a java project that extract information from page using html.

答:
It seems you need to dynamically set the page URL argument. If you use jQuery you should be able to have a click event like this:

    Document doc = Jsoup.connect("www.example.com/something?page=" + $(this).data('page')).get();

Body:
I have the following HTML:

            1

            2

            3

            4

            5

            6

            7

            8

            ...

            20

When I click in this buttons I go to something like this www.example.com/something?page=X (x = number of the button)
I use this:

Document doc = Jsoup.connect("www.example.com/something?page=5").get();

But I get always the first page HTML.
How I can "click" or extract information about this pages? I don't know so much about PHP but I think this page use it to change pages.

Edit:

I'm not using javascript. I'm using a java project that extract information from page using html.


来源: stackexchange

问:
Trigger compiles without errors, But it does not add data
I'm trying to update the table called 'saturn.szrunsp' after a update or insert happens on the table 'saturn.szraspr'. After kind suggestions i've created a trigger without any errors. however, the main part still doesnt seem to work which is the trigger to add data onto the table saturn.szrunsp after update on table saturn.szraspr. please see all codes of table and trigger below. UPDATED!! </p>

```<code>-- INSERTING table --

        CREATE TABLE SATURN.SZRUNSP
    (
      SZRUNSP_STUDENT_NO       VARCHAR2(9 CHAR)     NOT NULL,
      SZRUNSP_PIDM             NUMBER(8)            NOT NULL,
      SZRUNSP_STUDENT_NAME     VARCHAR2(60 CHAR)    NOT NULL,
      SZRUNSP_SUSPEND_ACCOUNT  VARCHAR2(1 CHAR)     NOT NULL,
      SZRUNSP_UNSUSPEND_DATE   DATE                 NOT NULL,
      SZRUNSP_ACTIVITY_DATE    DATE                 NOT NULL,
      SZRUNSP_USER_ID          VARCHAR2(30 CHAR),
      SZRUNSP_ACTION           VARCHAR2(30 CHAR),
      SZRUNSP_SURROGATE_ID     NUMBER(19)           NOT NULL,
      SZRUNSP_VERSION          NUMBER(19)           NOT NULL,
      SZRUNSP_VPDI_CODE        VARCHAR2(6 CHAR)
    )

-- TRIGGER TABLE --

    CREATE TABLE SATURN.SZRASPR
(
  SZRASPR_STUDENT_NO             VARCHAR2(9 CHAR) NOT NULL,
  SZRASPR_STUDENT_NAME           VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_DATE_OF_BIRTH          VARCHAR2(8 CHAR) NOT NULL,
  SZRASPR_SUSPEND_ACCOUNT        VARCHAR2(1 CHAR) NOT NULL,
  SZRASPR_EMAIL_ADDRESS          VARCHAR2(100 CHAR) NOT NULL,
  SZRASPR_STUDENT_YEAR           VARCHAR2(2 CHAR) NOT NULL,
  SZRASPR_FACULTY                VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_SCHOOL_OF_STUDY        VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_DEGREE_NAME            VARCHAR2(100 CHAR) NOT NULL,
  SZRASPR_MODE_OF_STUDY          VARCHAR2(20 CHAR) NOT NULL,
  SZRASPR_FEE_STATUS             VARCHAR2(20 CHAR) NOT NULL,
  SZRASPR_YEAR_START             VARCHAR2(4 CHAR) NOT NULL,
  SZRASPR_SEMESTER_START         VARCHAR2(5 CHAR) NOT NULL,
  SZRASPR_ENROLMENT_STATUS       VARCHAR2(2 CHAR) NOT NULL,
  SZRASPR_LEAVING_DATE           VARCHAR2(8 CHAR),
  SZRASPR_PENDING_ACTIVITY_DATE  DATE,
  SZRASPR_ACTIVE_ACTIVITY_DATE   DATE,
  SZRASPR_PENDING_STATUS         VARCHAR2(2 CHAR),
  SZRASPR_ACTIVE_STATUS          VARCHAR2(2 CHAR),
  SZRASPR_PIDM                   NUMBER(8)      NOT NULL,
  SZRASPR_TERM_CODE              VARCHAR2(6 CHAR) NOT NULL,
  SZRASPR_ASPIRE_ERROR_REPORTED  VARCHAR2(10 CHAR),
  SZRASPR_ERROR_TEXT             VARCHAR2(100 CHAR),
  SZRASPR_SEQ_NO                 NUMBER,
  SZRASPR_SEND                   INTEGER,
  SZRASPR_SURROGATE_ID           NUMBER(19),
  SZRASPR_VERSION                NUMBER(19),
  SZRASPR_USER_ID                VARCHAR2(30 CHAR),
  SZRASPR_DATA_ORIGIN            VARCHAR2(30 CHAR),
  SZRASPR_ACTIVITY_DATE          DATE,
  SZRASPR_VPDI_CODE              VARCHAR2(6 CHAR)
);

--Trigger--

    CREATE OR REPLACE TRIGGER szrunsp_suspend_trigger
after update or insert on SATURN.SZRASPR
for each row
declare
    SZRUNSP_USER_ID varchar2(30 CHAR);
begin
    select user into SZRUNSP_USER_ID from dual;

    insert into SATURN.SZRUNSP values
        (:new.SZRASPR_STUDENT_NO,
         :new.SZRASPR_PIDM,
         :new.SZRASPR_STUDENT_NAME,
         :new.SZRASPR_SUSPEND_ACCOUNT,
         SYSDATE,
         SYSDATE,
         user,
         :new.SZRASPR_SURROGATE_ID,
         :new.SZRASPR_VERSION,
         :new.SZRASPR_VPDI_CODE);
 end;
/
</code>```

答:
You are inserting NULL values into

```<code>  SZRUNSP_SURROGATE_ID     NUMBER(19)           NOT NULL,
  SZRUNSP_VERSION          NUMBER(19)           NOT NULL,
</code>```

And you can only use the :new prefix for columns on the triggering table - not on the table you're inserting into

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to update the table called 'saturn.szrunsp' after a update or insert happens on the table 'saturn.szraspr'. After kind suggestions i've created a trigger without any errors. however, the main part still doesnt seem to work which is the trigger to add data onto the table saturn.szrunsp after update on table saturn.szraspr. please see all codes of table and trigger below. UPDATED!!

-- INSERTING table --

        CREATE TABLE SATURN.SZRUNSP
    (
      SZRUNSP_STUDENT_NO       VARCHAR2(9 CHAR)     NOT NULL,
      SZRUNSP_PIDM             NUMBER(8)            NOT NULL,
      SZRUNSP_STUDENT_NAME     VARCHAR2(60 CHAR)    NOT NULL,
      SZRUNSP_SUSPEND_ACCOUNT  VARCHAR2(1 CHAR)     NOT NULL,
      SZRUNSP_UNSUSPEND_DATE   DATE                 NOT NULL,
      SZRUNSP_ACTIVITY_DATE    DATE                 NOT NULL,
      SZRUNSP_USER_ID          VARCHAR2(30 CHAR),
      SZRUNSP_ACTION           VARCHAR2(30 CHAR),
      SZRUNSP_SURROGATE_ID     NUMBER(19)           NOT NULL,
      SZRUNSP_VERSION          NUMBER(19)           NOT NULL,
      SZRUNSP_VPDI_CODE        VARCHAR2(6 CHAR)
    )

-- TRIGGER TABLE --

    CREATE TABLE SATURN.SZRASPR
(
  SZRASPR_STUDENT_NO             VARCHAR2(9 CHAR) NOT NULL,
  SZRASPR_STUDENT_NAME           VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_DATE_OF_BIRTH          VARCHAR2(8 CHAR) NOT NULL,
  SZRASPR_SUSPEND_ACCOUNT        VARCHAR2(1 CHAR) NOT NULL,
  SZRASPR_EMAIL_ADDRESS          VARCHAR2(100 CHAR) NOT NULL,
  SZRASPR_STUDENT_YEAR           VARCHAR2(2 CHAR) NOT NULL,
  SZRASPR_FACULTY                VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_SCHOOL_OF_STUDY        VARCHAR2(60 CHAR) NOT NULL,
  SZRASPR_DEGREE_NAME            VARCHAR2(100 CHAR) NOT NULL,
  SZRASPR_MODE_OF_STUDY          VARCHAR2(20 CHAR) NOT NULL,
  SZRASPR_FEE_STATUS             VARCHAR2(20 CHAR) NOT NULL,
  SZRASPR_YEAR_START             VARCHAR2(4 CHAR) NOT NULL,
  SZRASPR_SEMESTER_START         VARCHAR2(5 CHAR) NOT NULL,
  SZRASPR_ENROLMENT_STATUS       VARCHAR2(2 CHAR) NOT NULL,
  SZRASPR_LEAVING_DATE           VARCHAR2(8 CHAR),
  SZRASPR_PENDING_ACTIVITY_DATE  DATE,
  SZRASPR_ACTIVE_ACTIVITY_DATE   DATE,
  SZRASPR_PENDING_STATUS         VARCHAR2(2 CHAR),
  SZRASPR_ACTIVE_STATUS          VARCHAR2(2 CHAR),
  SZRASPR_PIDM                   NUMBER(8)      NOT NULL,
  SZRASPR_TERM_CODE              VARCHAR2(6 CHAR) NOT NULL,
  SZRASPR_ASPIRE_ERROR_REPORTED  VARCHAR2(10 CHAR),
  SZRASPR_ERROR_TEXT             VARCHAR2(100 CHAR),
  SZRASPR_SEQ_NO                 NUMBER,
  SZRASPR_SEND                   INTEGER,
  SZRASPR_SURROGATE_ID           NUMBER(19),
  SZRASPR_VERSION                NUMBER(19),
  SZRASPR_USER_ID                VARCHAR2(30 CHAR),
  SZRASPR_DATA_ORIGIN            VARCHAR2(30 CHAR),
  SZRASPR_ACTIVITY_DATE          DATE,
  SZRASPR_VPDI_CODE              VARCHAR2(6 CHAR)
);

--Trigger--

    CREATE OR REPLACE TRIGGER szrunsp_suspend_trigger
after update or insert on SATURN.SZRASPR
for each row
declare
    SZRUNSP_USER_ID varchar2(30 CHAR);
begin
    select user into SZRUNSP_USER_ID from dual;

    insert into SATURN.SZRUNSP values
        (:new.SZRASPR_STUDENT_NO,
         :new.SZRASPR_PIDM,
         :new.SZRASPR_STUDENT_NAME,
         :new.SZRASPR_SUSPEND_ACCOUNT,
         SYSDATE,
         SYSDATE,
         user,
         :new.SZRASPR_SURROGATE_ID,
         :new.SZRASPR_VERSION,
         :new.SZRASPR_VPDI_CODE);
 end;
/

Body:
You are inserting NULL values into

  SZRUNSP_SURROGATE_ID     NUMBER(19)           NOT NULL,
  SZRUNSP_VERSION          NUMBER(19)           NOT NULL,

And you can only use the :new prefix for columns on the triggering table - not on the table you're inserting into


问:
how to use TypeConverters to convert a System.Datetime to custom type
For some reason I need to cast/convert a DateTime into one of many custom objects

This proves to be very difficult to do in a nice generic fashion.

I am thinking of implementing an extension method on object or perhaps extending DateTimeConverter.

But then what would be the generic way to handle this, I have an object and a destination type and at the moment I am using System.ConvertTo(..) but this is clearly limited because it only supports converting to .NET types and cant be extended.

Any ideas?

答:
You could add a constructor for your TimeStamp that takes DateTime as a parameter.

```<code>public class TimeStamp
{
   public TimeStamp(DateTime dateTime, ...)
   {
    // Your code here to convert from dateTime to TimeStamp
   }
}
</code>```

Then later ...

```<code> DestType Convert<DestType>( Object linqResult )
 {
  DestType result;
  if( linqResult is DateTime && DestType is TimeStamp )
  {
   DateTime dbTime = linqResult as DateTime;
   result = new TimeStamp( dbTime );
  }
  ...
  return result;
 }
</code>```

You could probably even extend this with all kinds of reflection and constructors etc.
But if you want to base one object off of another (like a time stamp from a date time) a constructor seems natural.

Hope this helps, TJB

OwnerDisplayName: Tom Deloford

ContentLicense: CC BY-SA 2.5

Body:
You could add a constructor for your TimeStamp that takes DateTime as a parameter.

public class TimeStamp
{
   public TimeStamp(DateTime dateTime, ...)
   {
    // Your code here to convert from dateTime to TimeStamp
   }
}

Then later ...

 DestType Convert<DestType>( Object linqResult )
 {
  DestType result;
  if( linqResult is DateTime && DestType is TimeStamp )
  {
   DateTime dbTime = linqResult as DateTime;
   result = new TimeStamp( dbTime );
  }
  ...
  return result;
 }

You could probably even extend this with all kinds of reflection and constructors etc.
But if you want to base one object off of another (like a time stamp from a date time) a constructor seems natural.

Hope this helps, TJB

OwnerDisplayName: TJB


问:
Abstraction, am I doing it too much?
I'm writing a game with a SDL, OpenGL, a physics engine and an embedded scripting language.

The thing I have been doing in the last weeks: Abstracting. I have written abstraction classes representing the program itself, textures, fonts, physics objects, and more.

Am I abstracting too much, or how can I know if I am?

Is this good practice at all to abstract all libraries first before getting into the actual development?

答:
Since your goal is to create a game, then I would recommend you to get rid of all layers of abstraction you have created so far. Use whatever libraries you have directly.

Spend all your time on getting stuff moving on the screen so that you can try out your game ideas and designs as quickly as possible. Having extra layers of abstraction will slow down this process.

When you have reached some part goal, then spend a fixed amount of time to clean up the code. This is where you add abstractions to solve your concrete problems. But don't overdo it.

Then continue creating your game. In the end abstractions will have very little to do with how fun or addicting the game is.

Title: Abstraction, am I doing it too much?


问:
angularjs How to escape “${variable}” in html?
I want to show a string like ${date} to the div element:

```<code><div>please use the ${date} as the substitute tag to the name</div>
</code>```

the content will be display like:

```<code>please use the ${date} as the substitute tag to the name.
</code>```

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

答:
A light-weight workaround without escape characters:
Split your expression and wrap inner part in span, as below.</p>

```<code><div>please use the ${<span>date</span>} as the substitute tag to the name</div>
</code>```

Body:
I want to show a string like ${date} to the div element:

please use the ${date} as the substitute tag to the name

the content will be display like:

please use the ${date} as the substitute tag to the name.

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

Body:
A light-weight workaround without escape characters:
Split your expression and wrap inner part in span, as below.

<div>please use the ${<span>date</span>} as the substitute tag to the name</div>


问:
Convert MySQL to SQlite
Is it possible to convert from MySQL to SQLite with a free tool on windows?</p>

答: If you have been given a database file and have not installed the correct server (either SQLite or MySQL), try this tool: https://dbconvert.com/sqlite/mysql/ The trial version allows converting the first 50 records of each table, the rest of the data is watermarked. This is a Windows program, and can either dump into a running database server, or can dump output to a .sql file</p>

Title: Convert MySQL to SQlite


问:
Intermittent bugs - sometimes this code works and sometimes it doesn't!
This code intermittently works. It's running on a small microcontroller. It will work fine even after restarting the processor, but if I change some part of the code, it breaks. This makes me think that it's some kind of pointer bug or memory corruption. What's happening is the coordinate, p_res.pos.x is sometimes read as 0 (the incorrect value) and 96 (the correct value) when it is passed to write_circle_outlined. y seems to be correct most of the time. If anyone can spot anything obviously wrong please point it out!

```<code>int demo_game()
{
    long int d;
    int x, y;
    struct WorldCamera p_viewer;
    struct Point3D_LLA p_subj;
    struct Point2D_CalcRes p_res;
    p_viewer.hfov = 27;
    p_viewer.vfov = 32;
    p_viewer.width = 192;
    p_viewer.height = 128;
    p_viewer.p.lat = 51.26f;
    p_viewer.p.lon = -1.0862f;
    p_viewer.p.alt = 100.0f;
    p_subj.lat = 51.20f;
    p_subj.lon = -1.0862f;
    p_subj.alt = 100.0f;
    while(1)
    {
        fill_buffer(draw_buffer_mask, 0x0000);
        fill_buffer(draw_buffer_level, 0xffff);
        compute_3d_transform(&p_viewer, &p_subj, &p_res, 10000.0f);
        x = p_res.pos.x;
        y = p_res.pos.y;
        write_circle_outlined(x, y, 1.0f / p_res.est_dist, 0, 0, 0, 1);
        p_viewer.p.lat -= 0.0001f;
        //p_viewer.p.alt -= 0.00001f;
        d = 20000;
        while(d--);
    }
    return 1;
}
</code>```

The code for compute_3d_transform is:

```<code>void compute_3d_transform(struct WorldCamera *p_viewer, struct Point3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph)
{
    // Estimate the distance to the waypoint. This isn't intended to replace
    // proper lat/lon distance algorithms, but provides a general indication
    // of how far away our subject is from the camera. It works accurately for
    // short distances of less than 1km, but doesn't give distances in any
    // meaningful unit (lat/lon distance?)
    res->est_dist = hypot2(p_viewer->p.lat - p_subj->lat, p_viewer->p.lon - p_subj->lon);
    // Save precious cycles if outside of visible world.
    if(res->est_dist > cliph)
        goto quick_exit;
    // Compute the horizontal angle to the point.
    // atan2(y,x) so atan2(lon,lat) and not atan2(lat,lon)!
    res->h_angle = RAD2DEG(angle_dist(atan2(p_viewer->p.lon - p_subj->lon, p_viewer->p.lat - p_subj->lat), p_viewer->yaw));
    res->small_dist = res->est_dist * 0.0025f; // by trial and error this works well.
    // Using the estimated distance and altitude delta we can calculate
    // the vertical angle.
    res->v_angle = RAD2DEG(atan2(p_viewer->p.alt - p_subj->alt, res->est_dist));
    // Normalize the results to fit in the field of view of the camera if
    // the point is visible. If they are outside of (0,hfov] or (0,vfov]
    // then the point is not visible.
    res->h_angle += p_viewer->hfov / 2;
    res->v_angle += p_viewer->vfov / 2;
    // Set flags.
    if(res->h_angle < 0 || res->h_angle > p_viewer->hfov)
        res->flags |= X_OVER;
    if(res->v_angle < 0 || res->v_angle > p_viewer->vfov)
        res->flags |= Y_OVER;
    res->pos.x = (res->h_angle / p_viewer->hfov) * p_viewer->width;
    res->pos.y = (res->v_angle / p_viewer->vfov) * p_viewer->height;
    return;
quick_exit:
    res->flags |= X_OVER | Y_OVER;
    return;
}
</code>```

Structure for the results:

```<code>typedef struct Point2D_Pixel { unsigned int x, y; };

// Structure for storing calculated results (from camera transforms.)
typedef struct Point2D_CalcRes
{
    struct Point2D_Pixel pos;
    float h_angle, v_angle, est_dist, small_dist;
    int flags;
};
</code>```

The code is part of an open source project of mine so it's okay to post a lot of code here.

答:
A couple of things that seem sketchy:

You can return from compute_3d_transform without setting many of the fields in p_res/res but the caller never checks for this situation.

You consistently read from res->flags without initializing it first.

Body:
This code intermittently works. It's running on a small microcontroller. It will work fine even after restarting the processor, but if I change some part of the code, it breaks. This makes me think that it's some kind of pointer bug or memory corruption. What's happening is the coordinate, p_res.pos.x is sometimes read as 0 (the incorrect value) and 96 (the correct value) when it is passed to write_circle_outlined. y seems to be correct most of the time. If anyone can spot anything obviously wrong please point it out!

int demo_game()
{
    long int d;
    int x, y;
    struct WorldCamera p_viewer;
    struct Point3D_LLA p_subj;
    struct Point2D_CalcRes p_res;
    p_viewer.hfov = 27;
    p_viewer.vfov = 32;
    p_viewer.width = 192;
    p_viewer.height = 128;
    p_viewer.p.lat = 51.26f;
    p_viewer.p.lon = -1.0862f;
    p_viewer.p.alt = 100.0f;
    p_subj.lat = 51.20f;
    p_subj.lon = -1.0862f;
    p_subj.alt = 100.0f;
    while(1)
    {
        fill_buffer(draw_buffer_mask, 0x0000);
        fill_buffer(draw_buffer_level, 0xffff);
        compute_3d_transform(&p_viewer, &p_subj, &p_res, 10000.0f);
        x = p_res.pos.x;
        y = p_res.pos.y;
        write_circle_outlined(x, y, 1.0f / p_res.est_dist, 0, 0, 0, 1);
        p_viewer.p.lat -= 0.0001f;
        //p_viewer.p.alt -= 0.00001f;
        d = 20000;
        while(d--);
    }
    return 1;
}

The code for compute_3d_transform is:

void compute_3d_transform(struct WorldCamera *p_viewer, struct Point3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph)
{
    // Estimate the distance to the waypoint. This isn't intended to replace
    // proper lat/lon distance algorithms, but provides a general indication
    // of how far away our subject is from the camera. It works accurately for
    // short distances of less than 1km, but doesn't give distances in any
    // meaningful unit (lat/lon distance?)
    res->est_dist = hypot2(p_viewer->p.lat - p_subj->lat, p_viewer->p.lon - p_subj->lon);
    // Save precious cycles if outside of visible world.
    if(res->est_dist > cliph)
        goto quick_exit;
    // Compute the horizontal angle to the point.
    // atan2(y,x) so atan2(lon,lat) and not atan2(lat,lon)!
    res->h_angle = RAD2DEG(angle_dist(atan2(p_viewer->p.lon - p_subj->lon, p_viewer->p.lat - p_subj->lat), p_viewer->yaw));
    res->small_dist = res->est_dist * 0.0025f; // by trial and error this works well.
    // Using the estimated distance and altitude delta we can calculate
    // the vertical angle.
    res->v_angle = RAD2DEG(atan2(p_viewer->p.alt - p_subj->alt, res->est_dist));
    // Normalize the results to fit in the field of view of the camera if
    // the point is visible. If they are outside of (0,hfov] or (0,vfov]
    // then the point is not visible.
    res->h_angle += p_viewer->hfov / 2;
    res->v_angle += p_viewer->vfov / 2;
    // Set flags.
    if(res->h_angle < 0 || res->h_angle > p_viewer->hfov)
        res->flags |= X_OVER;
    if(res->v_angle < 0 || res->v_angle > p_viewer->vfov)
        res->flags |= Y_OVER;
    res->pos.x = (res->h_angle / p_viewer->hfov) * p_viewer->width;
    res->pos.y = (res->v_angle / p_viewer->vfov) * p_viewer->height;
    return;
quick_exit:
    res->flags |= X_OVER | Y_OVER;
    return;
}

Structure for the results:

typedef struct Point2D_Pixel { unsigned int x, y; };

// Structure for storing calculated results (from camera transforms.)
typedef struct Point2D_CalcRes
{
    struct Point2D_Pixel pos;
    float h_angle, v_angle, est_dist, small_dist;
    int flags;
};

The code is part of an open source project of mine so it's okay to post a lot of code here.


问:
How to select earliest date according to current sg
I need to come with a SQL (SQL Server) that gets the earliest date according to the current sg. Below is the sample table where current sg is 4-3 (current because the end date is 1900-01-01). I want to get the date where the sg actually started (which is 2015-01-01) per employee. I really need some help on this.</p>

```<code>empno      position             sg           date_from         date_to
4508       ADMIN AIDE IV        4-3          2017-01-01        1900-01-01
4508       ADMIN AIDE IV        4-3          2016-01-01        2016-12-31
4508       ADMIN AIDE IV        4-3          2015-01-01        2015-12-31
4508       ADMIN AIDE IV        4-2          2014-01-01        2014-12-31
4508       ADMIN AIDE IV        4-2          2013-01-01        2013-12-31
1207       AIRCRAFT MECHANIC I  6-1          1988-01-01        1989-06-30
1207       AIRCRAFT MECHANIC II 8-7          2006-05-08        2015-12-31
1207       AIRCRAFT MECHANIC II 8-8          2016-01-01        1900-01-01
0889       DATA ENTRY OPERATOR  1-1          2000-12-12        2001-06-30
0889       ADMIN ASSISTANT VI   12-5         2017-03-10        1900-01-01
0889       ADMIN ASSISTANT VI   12-5         2016-01-01        2016-12-31
</code>```

答:
If a sg can't have multiple positions you could use the next query</p>

```<code>SELECT t.position, t.sg, MIN(date_from) AS date_from
FROM @t AS t
    INNER JOIN
      (select sg from @t where date_to = '19000101') as cur
    ON t.sg = cur.sg
GROUP BY t.position, t.sg
</code>```

Body:
I need to come with a SQL (SQL Server) that gets the earliest date according to the current sg. Below is the sample table where current sg is 4-3 (current because the end date is 1900-01-01). I want to get the date where the sg actually started (which is 2015-01-01) per employee. I really need some help on this.

empno      position             sg           date_from         date_to
4508       ADMIN AIDE IV        4-3          2017-01-01        1900-01-01
4508       ADMIN AIDE IV        4-3          2016-01-01        2016-12-31
4508       ADMIN AIDE IV        4-3          2015-01-01        2015-12-31
4508       ADMIN AIDE IV        4-2          2014-01-01        2014-12-31
4508       ADMIN AIDE IV        4-2          2013-01-01        2013-12-31
1207       AIRCRAFT MECHANIC I  6-1          1988-01-01        1989-06-30
1207       AIRCRAFT MECHANIC II 8-7          2006-05-08        2015-12-31
1207       AIRCRAFT MECHANIC II 8-8          2016-01-01        1900-01-01
0889       DATA ENTRY OPERATOR  1-1          2000-12-12        2001-06-30
0889       ADMIN ASSISTANT VI   12-5         2017-03-10        1900-01-01
0889       ADMIN ASSISTANT VI   12-5         2016-01-01        2016-12-31

Body:
If a sg can't have multiple positions you could use the next query

SELECT t.position, t.sg, MIN(date_from) AS date_from
FROM @t AS t
    INNER JOIN
      (select sg from @t where date_to = '19000101') as cur
    ON t.sg = cur.sg
GROUP BY t.position, t.sg


问:
Visual Studio. Same path for different computers/users
I started a project on my house computer and set the includes and libs paths: "C:\Users\admin\Documents\GitHub\project1\include;%(AdditionalIncludeDirectories)"
"C:\Users\admin\Documents\GitHub\project1\lib;%(AdditionalLibraryDirectories)".

My problem is when i'm in a different computer or user, when i open the project, the paths are the same but those path doesn't exist because the user is different and i'm changing the paths everytime i change computers/users.

How can i set that the paths starts at "Documents\GitHub\project1..." so it works for all computers/users?

I'm using visual studio 2015.

Thanks.

答:
use macros like $(SolutionDir) or $(ProjectDir) to make the path relative to the project.

You can find them in the edit panel for paths, there's a button named Macros..


问:
add additional-include-directory and reference => point to a static library in ONE setting
I have an application project (MyGame) that want to access everything inside a static library (MyLib) in the same solution:-

```<code>MyVisualSolution
- MyLib (static library)  : 200  .h & .cpp
- MyGame (win32 app)      : 100  .h & .cpp
</code>```

The steps to achieve the above requirement are :-

set project property of MyGame > add additional include directory = .h folder in MyLib

In Solution Explorer, click References of MyGame, then click the check-box MyLib.

I have to do both steps, and the settings are   in very different places.

I think it is tedious, dirty, not intuitive, and error prone.

Is there any way to do it in a single place inside Visual Studio?

I expect to do just one thing that is similar to the second step.

(I feel that property sheet may be the closest answer, but it still can't solve.)

As far as I searched, there is none.  (visual c++: #include files from other projects in the same solution)

答:
In general, that is normal. In C++ a "library" consists of a .lib/.dll and a .h./.hpp pair, and you need them both. Due to the fact that compiler and linker are in fact a different tools, you have different configuration settings for them.

Actually, to be able to use an external library, you need to configure not 2, but 4 things:

add an entry to include-search-paths and/or make sure that .h file is there (in project properties)

add an entry to library-search-paths and/or make sure that .lib file is there (in project properties)

include .lib file in linking by adding it to the linker options (in project properties)

include that .h with an #include with proper relative path (in code)

However, it is somewhat true that there is a way to provide something like one point of 'inclusion', so at least the last two can be merged.

There is a

```<code>#pragma comment(lib, "foobar.lib")
</code>```

(What does "#pragma comment" mean?)

instruction that may be a hint to the toolset saying which .lib file to include. If you put that into the header (in this case, probably foobar.h), then just the fact that you #include that header, will make the build process pickup that lib and add it to linking phase..

..or so is the theory. As you may notice, that's a #pragma, and also a comment, so the process can simply ignore that or may simply not have that part implemented and that's 100% OK since it is not required by C++ standard. Fortunately, VisualStudio has support for this - actually iy understands that directive since a long time.

But! as I said, adding that directive is not enough. This directive only contains the filename, and it links the .h file with a .lib filename. You still need to ensure that the .lib is located somewhere in the library search paths, and that the .h file is somewhere in include search paths. If your linker settings point to some directories, you need to ensure that the lib file has been put in one of them, or else you will have to add the directory path to the settings, and similarly for .h/.hpp file.

That's relatively simple to overcome, just create an extra folder in your project, add that path to the search paths, and from now on, drop all additional .h/.lib files there.

If I may, I'd suggest something like ./3rdparty and subfolders for specific libraries, like ./3rdpart/xml', './3rdparty/zlib and so on. Add the `3rdparty' to both search paths and then, #include 'xml/tinyxml.h' etc. Otherwise you can get a filename clash. Of course, most of the libraries will actually not come with #pragma-comment-lib, so that part you will probably need to manually add.

Body:
I have an application project (MyGame) that want to access everything inside a static library (MyLib) in the same solution:-

MyVisualSolution
- MyLib (static library)  : 200  .h & .cpp
- MyGame (win32 app)      : 100  .h & .cpp

The steps to achieve the above requirement are :-

set project property of MyGame > add additional include directory = .h folder in MyLib

In Solution Explorer, click References of MyGame, then click the check-box MyLib.

I have to do both steps, and the settings are   in very different places.

I think it is tedious, dirty, not intuitive, and error prone.

Is there any way to do it in a single place inside Visual Studio?

I expect to do just one thing that is similar to the second step.

(I feel that property sheet may be the closest answer, but it still can't solve.)

As far as I searched, there is none.  (visual c++: #include files from other projects in the same solution)

Body:
In general, that is normal. In C++ a "library" consists of a .lib/.dll and a .h./.hpp pair, and you need them both. Due to the fact that compiler and linker are in fact a different tools, you have different configuration settings for them.

Actually, to be able to use an external library, you need to configure not 2, but 4 things:

add an entry to include-search-paths and/or make sure that .h file is there (in project properties)

add an entry to library-search-paths and/or make sure that .lib file is there (in project properties)

include .lib file in linking by adding it to the linker options (in project properties)

include that .h with an #include with proper relative path (in code)

However, it is somewhat true that there is a way to provide something like one point of 'inclusion', so at least the last two can be merged.

There is a

#pragma comment(lib, "foobar.lib")

(What does "#pragma comment" mean?)

instruction that may be a hint to the toolset saying which .lib file to include. If you put that into the header (in this case, probably foobar.h), then just the fact that you #include that header, will make the build process pickup that lib and add it to linking phase..

..or so is the theory. As you may notice, that's a #pragma, and also a comment, so the process can simply ignore that or may simply not have that part implemented and that's 100% OK since it is not required by C++ standard. Fortunately, VisualStudio has support for this - actually iy understands that directive since a long time.

But! as I said, adding that directive is not enough. This directive only contains the filename, and it links the .h file with a .lib filename. You still need to ensure that the .lib is located somewhere in the library search paths, and that the .h file is somewhere in include search paths. If your linker settings point to some directories, you need to ensure that the lib file has been put in one of them, or else you will have to add the directory path to the settings, and similarly for .h/.hpp file.

That's relatively simple to overcome, just create an extra folder in your project, add that path to the search paths, and from now on, drop all additional .h/.lib files there.

If I may, I'd suggest something like ./3rdparty and subfolders for specific libraries, like ./3rdpart/xml', './3rdparty/zlib and so on. Add the `3rdparty' to both search paths and then, #include 'xml/tinyxml.h' etc. Otherwise you can get a filename clash. Of course, most of the libraries will actually not come with #pragma-comment-lib, so that part you will probably need to manually add.


问:
Avoiding complex if statements
I have the following function

```<code>const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}
</code>```

is there a better way to express this? How would such a code be written in functional programming style

答:
Another proposition of early return approach:

```<code>const getVal = (type, a, b, val) => {
    if(!type)
      return toPx(val);

    if(!a)
      return undefined;

    if(b)
      return val;             // (a && b)

    return toPercent(val);    // (a && !b)
}
</code>```

This becomes a one-level comparison, without nested ifs.

But maybe it's harder to deconvert...

Title: Avoiding complex if statements

Body:
I have the following function

const getVal = (type, a, b, val) => {
    if(type) {
        if(a && b) {
            return val;
        }else if(a) {
            return toPercent(val);
        }else{
            return undefined;
        }
    }
    return toPx(val);
}

is there a better way to express this? How would such a code be written in functional programming style

Body:
Another proposition of early return approach:

const getVal = (type, a, b, val) => {
    if(!type)
      return toPx(val);

    if(!a)
      return undefined;

    if(b)
      return val;             // (a && b)

    return toPercent(val);    // (a && !b)
}

This becomes a one-level comparison, without nested ifs.

But maybe it's harder to deconvert...


问:
randomforest R： why the print predict doesnt equal to the predict stored
I am running randomforest model to predict blacklist.I get a real problem that I cant solve by myself.
My code is below.

```<code>library(xlsx)
library(randomForest)
setwd('E:\\laolai')
rm(list=ls())
accepts <- read.xlsx('fuckdata.xlsx',sheetIndex = 1)
set.seed(10)
ind <- sample(2,nrow(accepts),replace=TRUE,prob=c(0.5,0.5))
train_data <- accepts[ind==1,]
test_data <- accepts[ind==2,]
rf <- randomForest(formula,data=train_data,ntree=1500,na.action=na.roughfix)
plot(rf,main='randomforest')
print(rf)
source_3pred <- predict(rf,test_data)
plot(source_3pred,main='predict',xlab='trees',type='l')
</code>```

Global Environment data:

```<code>accepts 3279obs. of 27 variables
test_data 1648 obs.of 27 variblss
train_data 1648 obs.of 27 variblss
</code>```

Values:

```<code>source_3pred Named num [1:1648] NA NA NA NA NA.......
</code>```

then

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

get data from 2 to 3279.such as 3218 NA,3224 0.7609778.

答:
The randomForest package comes with a function called importance(), which can compute two metrics of robustness for a random forest model built using the same package.  The first compares the prediction accuracy of each tree against the same tree but using a random permutation of the predictors.  The other method uses the Gini index/residual sum of squares to measure the decrease in node impurities for each split in the tree.

Here is a code sample of how you might access the importance of your random forest model:

```<code>rf <- randomForest(formula, data=train_data, ntree=1500, na.action=na.roughfix,
                   importance=TRUE)
# for permutation measure of accuracy
importance(rf, type=1)

# for split measure of accuracy
importance(rf, type=2)
</code>```

Body:
I am running randomforest model to predict blacklist.I get a real problem that I cant solve by myself.
My code is below.

library(xlsx)
library(randomForest)
setwd('E:\\laolai')
rm(list=ls())
accepts <- read.xlsx('fuckdata.xlsx',sheetIndex = 1)
set.seed(10)
ind <- sample(2,nrow(accepts),replace=TRUE,prob=c(0.5,0.5))
train_data <- accepts[ind==1,]
test_data <- accepts[ind==2,]
rf <- randomForest(formula,data=train_data,ntree=1500,na.action=na.roughfix)
plot(rf,main='randomforest')
print(rf)
source_3pred <- predict(rf,test_data)
plot(source_3pred,main='predict',xlab='trees',type='l')

Global Environment data:

accepts 3279obs. of 27 variables
test_data 1648 obs.of 27 variblss
train_data 1648 obs.of 27 variblss

Values:

source_3pred Named num [1:1648] NA NA NA NA NA.......

then

print(source_3pred)

get data from 2 to 3279.such as 3218 NA,3224 0.7609778.

Body:
The randomForest package comes with a function called importance(), which can compute two metrics of robustness for a random forest model built using the same package.  The first compares the prediction accuracy of each tree against the same tree but using a random permutation of the predictors.  The other method uses the Gini index/residual sum of squares to measure the decrease in node impurities for each split in the tree.

Here is a code sample of how you might access the importance of your random forest model:

rf <- randomForest(formula, data=train_data, ntree=1500, na.action=na.roughfix,
                   importance=TRUE)
# for permutation measure of accuracy
importance(rf, type=1)

# for split measure of accuracy
importance(rf, type=2)


问:
Can you deploy to a device via Gradle from the command line
What the question says really - can you issue any commands directly to gradlew via the command line to build, package and deploy to a device?</p>

答:
I wrote this task to be able to install and also open the application on the device. Since I had multiple buildTypes and flavors with different application ids, it was not feasible to hard code the package name. So I wrote it like this instead:

```<code>android.applicationVariants.all { variant ->
    task "open${variant.name.capitalize()}" {
        dependsOn "install${variant.name.capitalize()}"

        doLast {
            exec {
                commandLine "adb shell monkey -p ${variant.applicationId} -c android.intent.category.LAUNCHER 1".split(" ")
            }
        }
    }
}
</code>```

This would give you open{variant} for every install{variant} task you already have.

Body:
I wrote this task to be able to install and also open the application on the device. Since I had multiple buildTypes and flavors with different application ids, it was not feasible to hard code the package name. So I wrote it like this instead:

android.applicationVariants.all { variant ->
    task "open${variant.name.capitalize()}" {
        dependsOn "install${variant.name.capitalize()}"

        doLast {
            exec {
                commandLine "adb shell monkey -p ${variant.applicationId} -c android.intent.category.LAUNCHER 1".split(" ")
            }
        }
    }
}

This would give you open{variant} for every install{variant} task you already have.


问:
Appropriate Data structure of java to find unique word from file
I have a requirement to parse a file which contains 1000 of sentences in the file.
where I have to find a unique word in a file means that has not come more than one time in the file.
which data structure of should I use.(need to perform this operation using DS of java only)and why and how

2nd Question is

```<code>map.put("abc","hello");
map.put.("ABC","hi");
</code>```

when we are inserting in map object as given above code what will happen.

答:
Use Map, use the word as key and value as count, for every word you have put it in the map and increment the count by one.

```<code>if(map.containsKey("some")){
    // get the current value
    int currentValue = map.get("some");
    // put back the key with incremented value
    map.put("some",currentValue+1);
} else {
    // first time
    map.put("some",1);
}
</code>```

For your second question, both put will be added in the Map since map key is case sensitive.

Body:
I have a requirement to parse a file which contains 1000 of sentences in the file.
where I have to find a unique word in a file means that has not come more than one time in the file.
which data structure of should I use.(need to perform this operation using DS of java only)and why and how

2nd Question is

map.put("abc","hello");
map.put.("ABC","hi");

when we are inserting in map object as given above code what will happen.

Body:
Use Map, use the word as key and value as count, for every word you have put it in the map and increment the count by one.

if(map.containsKey("some")){
    // get the current value
    int currentValue = map.get("some");
    // put back the key with incremented value
    map.put("some",currentValue+1);
} else {
    // first time
    map.put("some",1);
}

For your second question, both put will be added in the Map since map key is case sensitive.


问:
How to put an image over the content of a div?
I want to display my locker image at the right of the div but kept the div size and format.

that's the default state:

that's what happens now when I lock:

And I want to do something like this:

To make this I made this css:

```<code>.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
}
</code>```

and the HTML is not special but I put it:

```<code><template name="machine">
    <li class="liMachine switch">
        <div id="nameMachine">
            <h3>{{nameMachine}}</h3>
        </div>
        <div id="stateMachine">
            State:<span class="state">{{stateMachine}}</span>
        </div>
        {{#if isLocked}}
        <div>
          <img class="imgCadenas">
        </div>
        {{else}}
          {{#if hideStopM}}
            {{else}}
              {{#if is_running_machine}}<i class="fa fa-spinner fa-spin"></i>
            {{else}}<button type="button" class="stop {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if hideKillM}}
          {{else}}
            {{#if is_alive_machine}}<i class="fa fa-spinner fa-spin"></i>
              {{else}}<button type="button" class="kill {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if is_stopped_machine}}<i class="fa fa-spinner fa-spin"></i>{{else}}<button type="button" class="start {{#if to_hide_startM}}hidden{{/if}}"></button>{{/if}}
        {{/if}}
    </li>
</template>
</code>```

the part I'm working on is the {{#if isLocked}}

When I use float:right I have :

When I use the solution of setting the position: absolute;top:0px..:

When I use the solution of @this.believer:

答:
using float and keeping the postion relative on the image would fix the issue.

img {
  postion: relative;
  float: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <ul>
    <li id="hello">
      <img src="http://zdnet3.cbsistatic.com/hub/i/2015/09/01/cb834e24-18e7-4f0a-a9bf-4c2917187d3f/83bb139aac01023dbf3e55a3d1789ad8/google-new-logo.png">
    </li>
  </ul>
</div></code>```

Body:
I want to display my locker image at the right of the div but kept the div size and format.

that's the default state:

that's what happens now when I lock:

And I want to do something like this:

To make this I made this css:

.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
}

and the HTML is not special but I put it:

<template name="machine">

{{nameMachine}}

            State:{{stateMachine}}

        {{#if isLocked}}

        {{else}}
          {{#if hideStopM}}
            {{else}}
              {{#if is_running_machine}}
            {{else}}<button type="button" class="stop {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if hideKillM}}
          {{else}}
            {{#if is_alive_machine}}
              {{else}}<button type="button" class="kill {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if is_stopped_machine}}{{else}}<button type="button" class="start {{#if to_hide_startM}}hidden{{/if}}"></button>{{/if}}
        {{/if}}

</template>

the part I'm working on is the {{#if isLocked}}

When I use float:right I have :

When I use the solution of setting the position: absolute;top:0px..:

When I use the solution of @this.believer:

Body:
using float and keeping the postion relative on the image would fix the issue.

img {
  postion: relative;
  float: right;
}

<div class="nav">
  <ul>
    <li id="hello">
      <a href="home.php"><img src="http://zdnet3.cbsistatic.com/hub/i/2015/09/01/cb834e24-18e7-4f0a-a9bf-4c2917187d3f/83bb139aac01023dbf3e55a3d1789ad8/google-new-logo.png"></a>
    </li>
  </ul>
</div>


问:
How to create a Custom Dialog box in android?
I want to create a custom dialog box like below

I have tried the following things.

I created a subclass of AlertDialog.Builder and used a custom Title and Custom Content View and used that but the result was not as expected.

Another attempt was to subclass DialogFragment and customize the dialog inside onCreateDialog that but result was not as expected.

Then I tried using a plain Dialog class. The result was not as expected.

In all three cases, the problem is when I overlook the title view the size of the dialog is not as expected and when I use Title view the result is there is a thick border around the content view (which really looks bad). Now I have two questions in my mind...

How can I achieve that? As I have already tried so many things, a direct answer will be more appreciated.

What is the best way to show an error or alert dialog in an android app?

EDIT
Android Developer Documentation recommends that we should use either DialogFragments or Dialogs for showing Error / Alert Messages to the user. However at one point they say ...

Tip: If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the  manifest element.

What is the meaning of that? Isn't it too much to use an Activity just for showing an error message???

答:
Dialog Fragment is the simplest way of creating a custom Alert Dialog.Follow the above code to create a custom view for your dialog and then implement it using Dialog Fragment. Add the following code to your layout file: </p>

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp"
    android:background="#3E80B4"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt_dia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Do you realy want to exit ?"
        android:textColor="@android:color/white"
        android:textSize="15dp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#3E80B4"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_yes"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="Yes"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_no"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_marginLeft="5dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="No"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>
</code>```

Body:
Dialog Fragment is the simplest way of creating a custom Alert Dialog.Follow the above code to create a custom view for your dialog and then implement it using Dialog Fragment. Add the following code to your layout file:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp"
    android:background="#3E80B4"
    android:orientation="vertical">

    <TextView
        android:id="@+id/txt_dia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Do you realy want to exit ?"
        android:textColor="@android:color/white"
        android:textSize="15dp"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#3E80B4"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_yes"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="Yes"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_no"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_marginLeft="5dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="No"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

ContentLicense: CC BY-SA 4.0


问:
What controls where an event can be called?
Say I have a class like this:

```<code>public class FauxIdentityForm
{
    public Guid FormID { get; set; }
    public event EventHandler Closed;
    public void TheObjectWasClosed(EventArgs e)
    {
        Closed(this, e);
    }
}
</code>```

It is fine for me to call the Closed Event inside the TheObjectWasClosed method.  But if, in a different class (even in the same file), I have a method like this:

```<code>public void CallTheEvent()
{
    FauxIdentityForm _formIdentity = new FauxIdentityForm {FormID = Guid.NewGuid()};

    _formIdentity.Closed(_formIdentity, null);  // <-- Does not compile!
}
</code>```

The call to Closed is shot down by the compiler (it wants me to only use += and -=).

So, is actually calling the event only allowed inside the class?  Is that the limitation?

If so, is there anyway around it?  And if not, why did the creators of C# do this?  (It makes working with events very hard sometimes.  I imagine there is a good reason and it is probably saving me from myself, but I would like to know it.)

答:
So, is actually calling the event only allowed inside the class? Is that the limitation?

Yes

If so, is there anyway around it?

Only with the consent (help) from the FauxIdentityForm class. It could have a public OnClosed() method.

An Event is a lot like a property, one of its main purposes is encapsulation and that is what you ran into.

Body:
Say I have a class like this:

public class FauxIdentityForm
{
    public Guid FormID { get; set; }
    public event EventHandler Closed;
    public void TheObjectWasClosed(EventArgs e)
    {
        Closed(this, e);
    }
}

It is fine for me to call the Closed Event inside the TheObjectWasClosed method.  But if, in a different class (even in the same file), I have a method like this:

public void CallTheEvent()
{
    FauxIdentityForm _formIdentity = new FauxIdentityForm {FormID = Guid.NewGuid()};

    _formIdentity.Closed(_formIdentity, null);  // <-- Does not compile!
}

The call to Closed is shot down by the compiler (it wants me to only use += and -=).

So, is actually calling the event only allowed inside the class?  Is that the limitation?

If so, is there anyway around it?  And if not, why did the creators of C# do this?  (It makes working with events very hard sometimes.  I imagine there is a good reason and it is probably saving me from myself, but I would like to know it.)


问:
i run my application on android 6.0.1 and give thats type of error
```<code>FATAL EXCEPTION: IntentService[]
Process: com.frenzin.alert, PID: 5892
java.lang.SecurityException: getDeviceId: Neither user 10240 nor current process has android.permission.READ_PHONE_STATE.
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at com.android.internal.telephony.ITelephony$Stub$Proxy.getDeviceId(ITelephony.java:4207)
at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:706)
at com.frenzin.alert.RegistrationIntentService.onHandleIntent(RegistrationIntentService.java:44)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
</code>```

答:
Add runtime permission for access</p>

```<code>Add library:
compile 'pub.devrel:easypermissions:0.2.1'

private String[] phonePermissions = {Manifest.permission.READ_PHONE_STATE};

if (EasyPermissions.hasPermissions(this, phonePermissions)) {
        //success
    } else {
        EasyPermissions.requestPermissions(this, "Access for Read Phone",
                101, phonePermissions);
    }
</code>```

Body:
Add runtime permission for access

Add library:
compile 'pub.devrel:easypermissions:0.2.1'

private String[] phonePermissions = {Manifest.permission.READ_PHONE_STATE};

if (EasyPermissions.hasPermissions(this, phonePermissions)) {
        //success
    } else {
        EasyPermissions.requestPermissions(this, "Access for Read Phone",
                101, phonePermissions);
    }


问:
Item "AdminBundle\Entity\Prize:000000046fa222" has been successfully created
hi i want with sonata to have an item using 'name' label.
but not always the same.

i put this in admin class

```<code>public function toString($object) {
    if (!is_object($object)) {
        return '';
    }
    if (method_exists($object, '__toString') && null !== $object->__toString()) {
        return (string) $object;
    }

    $cname = explode('\\', get_class($object));
    return end($cname);
}
</code>```

but it give always the same name. i want to have the label 'name' of each entity

答:
You need to override the __toString() magic method in your entity class

```<code>public function __toString(){
    return $this->name;
}
</code>```

Body:
hi i want with sonata to have an item using 'name' label.
but not always the same.

i put this in admin class

public function toString($object) {
    if (!is_object($object)) {
        return '';
    }
    if (method_exists($object, '__toString') && null !== $object->__toString()) {
        return (string) $object;
    }

    $cname = explode('\\', get_class($object));
    return end($cname);
}

but it give always the same name. i want to have the label 'name' of each entity

Body:
You need to override the __toString() magic method in your entity class

public function __toString(){
    return $this->name;
}


问:
How to grep word from file
I want to grep some word inside a file from another file. My code is able to grep the word on last line of the file but not the word before it. I have no idea why and hope can get help here. Below is the perl script i using:

```<code>open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

use strict;
use warnings;
use List::MoreUtils qw(uniq);

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
my $zone =0;
for ($j=0; $j<=$#file2; $j++){
    $zone = $file2[$j];
    unless ( $zone =~ m/#(.*?)/ ) {
        print "$zone";
        my @fid = grep /$zone/ , @file1;
        @fid = uniq(@fid);
        s{^\s+|\s+$}{}g foreach @fid;                #cancel leading space
        for ($i=0; $i<=$#fid; $i++){
            print FILE3 "$fid[$i]\n";
        }
        #@fid=();

    }
}

close(FILE3);
</code>```

My file1.txt is something like this:

```<code>i am a dog
i am a cat
we are the fish
he is a boy
she is a girl
</code>```

My file2.txt is like this:

```<code>is
am
</code>```

But my file3 can only show those sentence contain am but no is, if i put is in second line and am in first line then my file3 only contain the sentences with is. I not very sure why my code can only grep the last row in my file2. Thanks for the help.

答:
When reading from a file, the final newline is part of each line read. You can remove the newlines from the pattern array by chomping:</p>

```<code>chomp( my @file2 = <FILE2> );
</code>```

Title: How to grep word from file

Body:
I want to grep some word inside a file from another file. My code is able to grep the word on last line of the file but not the word before it. I have no idea why and hope can get help here. Below is the perl script i using:

open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";

use strict;
use warnings;
use List::MoreUtils qw(uniq);

my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
my $zone =0;
for ($j=0; $j<=$#file2; $j++){
    $zone = $file2[$j];
    unless ( $zone =~ m/#(.*?)/ ) {
        print "$zone";
        my @fid = grep /$zone/ , @file1;
        @fid = uniq(@fid);
        s{^\s+|\s+$}{}g foreach @fid;                #cancel leading space
        for ($i=0; $i<=$#fid; $i++){
            print FILE3 "$fid[$i]\n";
        }
        #@fid=();

    }
}

close(FILE3);

My file1.txt is something like this:

i am a dog
i am a cat
we are the fish
he is a boy
she is a girl

My file2.txt is like this:

is
am

But my file3 can only show those sentence contain am but no is, if i put is in second line and am in first line then my file3 only contain the sentences with is. I not very sure why my code can only grep the last row in my file2. Thanks for the help.

Body:
When reading from a file, the final newline is part of each line read. You can remove the newlines from the pattern array by chomping:

chomp( my @file2 = <FILE2> );


问:
*** Collection <__NSArrayM: 0x117d7320> was mutated while being enumerated.'
I made a bug when I implement the search function. I opened an asynchronous thread. But when deleting a character (a digit of a phone number), the app would crash.

Error:

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x117d7320> was mutated while being enumerated.'

Code:

```<code>- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    //
    self.isSearch = YES;

    //remove the last search all the contacts
    [self.resultArr removeAllObjects];
    //
    [self.rcs_SearchTableView reloadData];
    //
    dispatch_queue_t uploadQueue = dispatch_get_global_queue(0, 0);
    dispatch_queue_t getMainQueue = dispatch_get_main_queue();
    dispatch_async(uploadQueue, ^{

        NSMutableArray *phoneArr = (NSMutableArray *)[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText];
        //
        //NSLog(@"清空上次搜索的数据:%@", self.resultArr);
        //NSLog(@"输入的关键字是---%@---%lu",searchText,(unsigned long)searchText.length);
        if (0 == searchText.length || [searchText isEqualToString:@" "]) {
            self.isSearch = NO;
            //[self.rcs_SearchTableView reloadData];
            [self.resultArr removeAllObjects];
        }
        //[self.rcs_SearchTableView reloadData];

        if (0 != phoneArr.count) {
            //
            for (NSUInteger i = 0; i < phoneArr.count; i ++) {

                RCSPhoneModel *flagPhoneModel = phoneArr[i];

                for (NSUInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {

                    RCSContactModel *flagModel = self.rcsRecentSearchDataSource[i];

                    if ([flagPhoneModel.serverId isEqualToString:flagModel.serverId] || [flagPhoneModel.phone isEqualToString:flagModel.name]) {

                        //the same contact has multiple Numbers To prevent repeated add the same contacts
                        if (![self.resultArr containsObject:flagModel]) {

                            [self.resultArr addObject:flagModel];
                            continue;
                        }
                    }
                }
            }

        }else{
            //search contacts by name

            for (NSInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {
                RCSContactModel *model = self.rcsRecentSearchDataSource[i];
                NSString *nameStr = model.name;
                if (nameStr.length >= searchText.length) {
                    //search all the name
                    if ([nameStr containsString:searchText]) {
                        [self.resultArr addObject:model];
                    }
                }
            }
        }
        //
        if (self.resultArr.count > 0) {
            self.isSearch = YES;
            //[self.rcs_SearchTableView reloadData];
        }
        //The phone contacts or local contact synchronized to the server
        dispatch_async(getMainQueue, ^{

            [self.rcs_SearchTableView reloadData];
        });
    });
}
</code>```

答:
I got it answer and like unders codes:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    //
    self.isSearch = YES;
    //
    if (0 == searchText.length || [searchText isEqualToString:@" "]) {
        self.isSearch = NO;
        //[self.resultArr removeAllObjects];
    }
    //Remove the last search all the contacts
    [self.resultArr removeAllObjects];
    //
    [self.rcs_SearchTableView reloadData];
    //
    NSMutableArray *localSearchDataSource = [self.resultArr mutableCopy];
    //Create an array of objects as well as the original array
    //According to the input access to the phone number of the data
    NSArray *localPhoneArr = [[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText] copy];
    //
    //[self.rcs_SearchTableView reloadData];
    if (0 != localPhoneArr.count) {
        //Because when data matching number takes longer, using asynchronous thread
        dispatch_queue_t uploadQueue = dispatch_get_global_queue(0, 0);
        dispatch_queue_t getMainQueue = dispatch_get_main_queue();
        dispatch_async(uploadQueue, ^{
            //
            for (NSUInteger i = 0; i < localPhoneArr.count; i ++) {
                RCSPhoneModel *flagPhoneModel = localPhoneArr[i];
                for (NSUInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {
                    RCSContactModel *flagModel = self.rcsRecentSearchDataSource[i];

```<code>                if ([flagPhoneModel.serverId isEqualToString:flagModel.serverId] || [flagPhoneModel.phone isEqualToString:flagModel.name]) {
                    //The same contact has multiple Numbers To prevent repeated add the same contacts
                    if (![localSearchDataSource containsObject:flagModel]) {

                        [localSearchDataSource addObject:flagModel];
                    }
                }
            }
        }
        //Add the search results to the search data source
        dispatch_async(getMainQueue, ^{
            [self.resultArr addObjectsFromArray:localSearchDataSource];
            [self.rcs_SearchTableView reloadData];
        });
    });

}else{
    //Search contacts by name

    for (NSInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {
        RCSContactModel *model = self.rcsRecentSearchDataSource[i];
        NSString *nameStr = model.name;
        if (nameStr.length >= searchText.length) {
            //Search all name
            if ([nameStr containsString:searchText]) {
                [self.resultArr addObject:model];
            }
        }
    }
}
//
if (self.resultArr.count > 0) {
    self.isSearch = YES;
    [self.rcs_SearchTableView reloadData];
}
</code>```

}

I made two change that 'NSMutableArray *localSearchDataSource = [self.resultArr mutableCopy];' and 'NSArray *localPhoneArr = [[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText] copy];'. And finish it . Collection <__NSArrayM: 0x117d7320> was mutated while being enumerated.'

Body:
I made a bug when I implement the search function. I opened an asynchronous thread. But when deleting a character (a digit of a phone number), the app would crash.

Error:

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x117d7320> was mutated while being enumerated.'

Code:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    //
    self.isSearch = YES;

    //remove the last search all the contacts
    [self.resultArr removeAllObjects];
    //
    [self.rcs_SearchTableView reloadData];
    //
    dispatch_queue_t uploadQueue = dispatch_get_global_queue(0, 0);
    dispatch_queue_t getMainQueue = dispatch_get_main_queue();
    dispatch_async(uploadQueue, ^{

        NSMutableArray *phoneArr = (NSMutableArray *)[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText];
        //
        //NSLog(@"清空上次搜索的数据:%@", self.resultArr);
        //NSLog(@"输入的关键字是---%@---%lu",searchText,(unsigned long)searchText.length);
        if (0 == searchText.length || [searchText isEqualToString:@" "]) {
            self.isSearch = NO;
            //[self.rcs_SearchTableView reloadData];
            [self.resultArr removeAllObjects];
        }
        //[self.rcs_SearchTableView reloadData];

        if (0 != phoneArr.count) {
            //
            for (NSUInteger i = 0; i < phoneArr.count; i ++) {

                RCSPhoneModel *flagPhoneModel = phoneArr[i];

                for (NSUInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {

                    RCSContactModel *flagModel = self.rcsRecentSearchDataSource[i];

                    if ([flagPhoneModel.serverId isEqualToString:flagModel.serverId] || [flagPhoneModel.phone isEqualToString:flagModel.name]) {

                        //the same contact has multiple Numbers To prevent repeated add the same contacts
                        if (![self.resultArr containsObject:flagModel]) {

                            [self.resultArr addObject:flagModel];
                            continue;
                        }
                    }
                }
            }

        }else{
            //search contacts by name

            for (NSInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {
                RCSContactModel *model = self.rcsRecentSearchDataSource[i];
                NSString *nameStr = model.name;
                if (nameStr.length >= searchText.length) {
                    //search all the name
                    if ([nameStr containsString:searchText]) {
                        [self.resultArr addObject:model];
                    }
                }
            }
        }
        //
        if (self.resultArr.count > 0) {
            self.isSearch = YES;
            //[self.rcs_SearchTableView reloadData];
        }
        //The phone contacts or local contact synchronized to the server
        dispatch_async(getMainQueue, ^{

            [self.rcs_SearchTableView reloadData];
        });
    });
}

Body:
I got it answer and like unders codes:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    //
    self.isSearch = YES;
    //
    if (0 == searchText.length || [searchText isEqualToString:@" "]) {
        self.isSearch = NO;
        //[self.resultArr removeAllObjects];
    }
    //Remove the last search all the contacts
    [self.resultArr removeAllObjects];
    //
    [self.rcs_SearchTableView reloadData];
    //
    NSMutableArray *localSearchDataSource = [self.resultArr mutableCopy];
    //Create an array of objects as well as the original array
    //According to the input access to the phone number of the data
    NSArray *localPhoneArr = [[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText] copy];
    //
    //[self.rcs_SearchTableView reloadData];
    if (0 != localPhoneArr.count) {
        //Because when data matching number takes longer, using asynchronous thread
        dispatch_queue_t uploadQueue = dispatch_get_global_queue(0, 0);
        dispatch_queue_t getMainQueue = dispatch_get_main_queue();
        dispatch_async(uploadQueue, ^{
            //
            for (NSUInteger i = 0; i < localPhoneArr.count; i ++) {
                RCSPhoneModel *flagPhoneModel = localPhoneArr[i];
                for (NSUInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {
                    RCSContactModel *flagModel = self.rcsRecentSearchDataSource[i];

                if ([flagPhoneModel.serverId isEqualToString:flagModel.serverId] || [flagPhoneModel.phone isEqualToString:flagModel.name]) {
                    //The same contact has multiple Numbers To prevent repeated add the same contacts
                    if (![localSearchDataSource containsObject:flagModel]) {

                        [localSearchDataSource addObject:flagModel];
                    }
                }
            }
        }
        //Add the search results to the search data source
        dispatch_async(getMainQueue, ^{
            [self.resultArr addObjectsFromArray:localSearchDataSource];
            [self.rcs_SearchTableView reloadData];
        });
    });

}else{
    //Search contacts by name

    for (NSInteger i = 0; i < self.rcsRecentSearchDataSource.count; i ++) {
        RCSContactModel *model = self.rcsRecentSearchDataSource[i];
        NSString *nameStr = model.name;
        if (nameStr.length >= searchText.length) {
            //Search all name
            if ([nameStr containsString:searchText]) {
                [self.resultArr addObject:model];
            }
        }
    }
}
//
if (self.resultArr.count > 0) {
    self.isSearch = YES;
    [self.rcs_SearchTableView reloadData];
}

}

I made two change that 'NSMutableArray *localSearchDataSource = [self.resultArr mutableCopy];' and 'NSArray *localPhoneArr = [[self rcs_GetPhoneNumberFromeDatabaseWithPhone:searchText] copy];'. And finish it . Collection <__NSArrayM: 0x117d7320> was mutated while being enumerated.'


问:
Hibernate generates negative id after a certain amount of insert
I have a weird behavior of Hibernate (3.6.1.Final) in my application and I am pretty desperate at the moment. The behavior occurs on both MariaDB 10.1 and RDS on Amazon.

After a certain amount of successful persists (always around ~5k) Hibernate fires a:

```<code>SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
</code>```

From what I see in the stacktrace Hibernate tries to fill a foreign key in a entity with a negative value that violates the FK constraint (the target table of the FK does not have such primary key value).

The strange thing is:

It happens only after around ~5k successful persists

After submitting such number of persist operation, the error occurs even if I restart the application (as well as the DB). Only solution is to wipe out the DB and repeat.

The error occurs independently from the load (continuous, in batches, single or multithread).

The following is the FK of the entity that is violated during the insert:

```<code>    @Entity
    @Cacheable
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public class Charge extends Entry {

        @OneToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "totalId")
        private Amount total;
     //....
</code>```

And this is how the primary key is defined in the Amount entity:

```<code>     @GeneratedValue
     @Id
     @Column(nullable = false)
     private Integer pk;
     //....
</code>```

My questions are:

Why a non-valid negative value occurs in the FK ? (the primary key targeted by the FK is set as auto increment, starting from one and all the preceeding inserts worked perfectly accordingly to this)

Why does the error occurs only after ~5k persists  ?

Why not even a restart of the application fix the problem? DB is fine because a manual insert outside the application works (with valid FK values)

My suspicion is Hibernate and how it manages the auto_increment on the DB. The are many posts on the topic but none of them fit my specific case (error occurring only after a certain usage).

Last note: On the DB auto_increment is initially set to 1. All the initial persists (before the error appears) of the Amount entity have a incremental PK that start by 1: (1,2,3, ...). So again why after a while Hibernate comes up with a negative (incompatible to the FK)?

Thank you so much in advance for your help.

Best
G.

答:
we had exact the same issue and it was due to old mariadb jdbc driver. We were using version 1.4.2
After switching to the version 1.5.5 of mariadb jdbc driver the problem were gone</p>

Body:
I have a weird behavior of Hibernate (3.6.1.Final) in my application and I am pretty desperate at the moment. The behavior occurs on both MariaDB 10.1 and RDS on Amazon.

After a certain amount of successful persists (always around ~5k) Hibernate fires a:

SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

From what I see in the stacktrace Hibernate tries to fill a foreign key in a entity with a negative value that violates the FK constraint (the target table of the FK does not have such primary key value).

The strange thing is:

It happens only after around ~5k successful persists

After submitting such number of persist operation, the error occurs even if I restart the application (as well as the DB). Only solution is to wipe out the DB and repeat.

The error occurs independently from the load (continuous, in batches, single or multithread).

The following is the FK of the entity that is violated during the insert:

    @Entity
    @Cacheable
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public class Charge extends Entry {

        @OneToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "totalId")
        private Amount total;
     //....

And this is how the primary key is defined in the Amount entity:

     @GeneratedValue
     @Id
     @Column(nullable = false)
     private Integer pk;
     //....

My questions are:

Why a non-valid negative value occurs in the FK ? (the primary key targeted by the FK is set as auto increment, starting from one and all the preceeding inserts worked perfectly accordingly to this)

Why does the error occurs only after ~5k persists  ?

Why not even a restart of the application fix the problem? DB is fine because a manual insert outside the application works (with valid FK values)

My suspicion is Hibernate and how it manages the auto_increment on the DB. The are many posts on the topic but none of them fit my specific case (error occurring only after a certain usage).

Last note: On the DB auto_increment is initially set to 1. All the initial persists (before the error appears) of the Amount entity have a incremental PK that start by 1: (1,2,3, ...). So again why after a while Hibernate comes up with a negative (incompatible to the FK)?

Thank you so much in advance for your help.

Best
G.


问:
Optimization Tips
```<code>int *s;
allocate memory for s[100];
void func (int *a, int *b)
{
    int i;

    for (i = 0; i < 100; i++)
    {
        s[i] = a[i] ^ b[i];
    }
}
</code>```

Assume that this particular code snippet is being called 1000 times, and this is the most time consuming operation in my code. Also assume that addresses of a and b is changed every time. 's' is a global variable which is updated with different sets of values of a & b.

As far as I assume, the main performance bottleneck would be memory access, because the only other operation is XOR, which is very trivial.

Would you please suggest how can I optimize my code in the best possible way?

the question I really wanted to ask, but I think it didn't get properly conveyed is, let for example this for loop contains 10 such XOR operations, the loop count is 100 and the function is called 1000 times, the point is high memory access..If the code is to be executed on a single core machine, what are scopes for improvement?

答:
Just a guess here. If this is a cache issue you could try this:

```<code>int *s;
allocate memory for s[100];
void func (int *a, int *b)
{
    int i;

    memcpy( s, a, 100 );

    for (i = 0; i < 100; i++)
    {
        s[i] = s[i] ^ b[i];
    }
}
</code>```

The memcpy, although it's a function call will often be inlined by the compiler if the size argument is a constant. Loop unrolling will probably not help here as it can be done automatically by the compiler. But you shouldn't take my word for it, verify on your platform.

Title: Optimization Tips

Body:
int *s;
allocate memory for s[100];
void func (int *a, int *b)
{
    int i;

    for (i = 0; i < 100; i++)
    {
        s[i] = a[i] ^ b[i];
    }
}

Assume that this particular code snippet is being called 1000 times, and this is the most time consuming operation in my code. Also assume that addresses of a and b is changed every time. 's' is a global variable which is updated with different sets of values of a & b.

As far as I assume, the main performance bottleneck would be memory access, because the only other operation is XOR, which is very trivial.

Would you please suggest how can I optimize my code in the best possible way?

the question I really wanted to ask, but I think it didn't get properly conveyed is, let for example this for loop contains 10 such XOR operations, the loop count is 100 and the function is called 1000 times, the point is high memory access..If the code is to be executed on a single core machine, what are scopes for improvement?

Body:
Just a guess here. If this is a cache issue you could try this:

int *s;
allocate memory for s[100];
void func (int *a, int *b)
{
    int i;

    memcpy( s, a, 100 );

    for (i = 0; i < 100; i++)
    {
        s[i] = s[i] ^ b[i];
    }
}

The memcpy, although it's a function call will often be inlined by the compiler if the size argument is a constant. Loop unrolling will probably not help here as it can be done automatically by the compiler. But you shouldn't take my word for it, verify on your platform.


问:
Adding global title to Plots.jl subplots
I would like to add a global title to a group of subplots using Plots.jl.

Ideally, I'd do something like:

```<code>using Plots
pyplot()
plot(rand(10,2), plot_title="Main title", title=["A" "B"], layout=2)
</code>```

but, as per the Plots.jl documentation, the plot_title attribute is not yet implemented:

Title for the whole plot (not the subplots) (Note: Not currently implemented)

In the meanwhile, is there any way around it?

I'm currently using the pyplot backend, but I'm not especially tied to it.

答:
subplots are fields of the Plot type, and each subplot has a field called :attr that you can modify and re-display() the plot.  Try the following:

```<code>julia> l = @layout([a{0.1h} ;b [c; d e]])
Plots.GridLayout(2,1)

julia> p = plot(randn(100,5),layout=l,t=[:line :histogram :scatter :steppre :bar],leg=false,ticks=nothing,border=false)

julia> p.subplots
5-element Array{Plots.Subplot,1}:
 Subplot{1}
 Subplot{2}
 Subplot{3}
 Subplot{4}
 Subplot{5}

julia> fieldnames(p.subplots[1])
8-element Array{Symbol,1}:
 :parent
 :series_list
 :minpad
 :bbox
 :plotarea
 :attr
 :o
 :plt

julia> for i in 1:length(p.subplots)
           p.subplots[i].attr[:title] = "subtitle $i"
       end

 julia> display(p)
</code>```

You should now see a title in each subplot

Body:
I would like to add a global title to a group of subplots using Plots.jl.

Ideally, I'd do something like:

using Plots
pyplot()
plot(rand(10,2), plot_title="Main title", title=["A" "B"], layout=2)

but, as per the Plots.jl documentation, the plot_title attribute is not yet implemented:

Title for the whole plot (not the subplots) (Note: Not currently implemented)

In the meanwhile, is there any way around it?

I'm currently using the pyplot backend, but I'm not especially tied to it.

Body:
subplots are fields of the Plot type, and each subplot has a field called :attr that you can modify and re-display() the plot.  Try the following:

julia> l = @layout([a{0.1h} ;b [c; d e]])
Plots.GridLayout(2,1)

julia> p = plot(randn(100,5),layout=l,t=[:line :histogram :scatter :steppre :bar],leg=false,ticks=nothing,border=false)

julia> p.subplots
5-element Array{Plots.Subplot,1}:
 Subplot{1}
 Subplot{2}
 Subplot{3}
 Subplot{4}
 Subplot{5}

julia> fieldnames(p.subplots[1])
8-element Array{Symbol,1}:
 :parent
 :series_list
 :minpad
 :bbox
 :plotarea
 :attr
 :o
 :plt

julia> for i in 1:length(p.subplots)
           p.subplots[i].attr[:title] = "subtitle $i"
       end

 julia> display(p)

You should now see a title in each subplot


问:
how can i query where clause using between date in sphinx
I have this query:

```<code>select * from tabel where last_purchase_categories = 'flight'
 and last_purchase_date between '2016-10-23 11:06:47' and '2016-10-23 11:06:49';
</code>```

it is didnt work in sphinx. i use fulltext search using mysql query browser.
do anyone know how to using date format in sphinx ?

答: i think it is because data type of last_purchase_date is string. thats why i cant use between query</p>

Body:
I have this query:

select * from tabel where last_purchase_categories = 'flight'
 and last_purchase_date between '2016-10-23 11:06:47' and '2016-10-23 11:06:49';

it is didnt work in sphinx. i use fulltext search using mysql query browser.
do anyone know how to using date format in sphinx ?


问:
Determine if List<Type> contains ICollection<dynamic>
I need to determine if a List contains ICollection where T is dynamic and not known at compiletime. Heres my code to better understand what I mean:

```<code>private void RefreshDataSource<T>(ICollection<T> dataSource) where T : IEquatable<T>
{
   dynamic row = view.GetFocusedRow();
   //Get's the focused row from a DevExpress-Grid
   //I don't know the type because it's MasterDetail and the view can be a DetailView. In this case type T isn't the underlying type.

   //Getting all Properties
   var dummy = dataSource.FirstOrDefault();
   var props = dummy.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();

   //Now comes the real problem, I need to determine the Detail Datasource
   //and to do this I want to check if there is a Property from ICollection<typeof(row)>

   //How can I check on ICollection<typeof(row)> instead of row
   //IsAssignableFrom would better fit my needs but I don't get how to solve my problem with it.
   var detailSource = props.FirstOrDefault(p => p.PropertyType.IsInstanceOfType(row));
}
</code>```

The code is broken to the important points, so don't wonder if sth. doesn't makes sense in your eyes ;-). Is there any way to check on ICollection<T> where T is a dynamic type and just know at runtime?

Notice that the given T on top of the method isn't the type of row, because of MasterDetail relationship!!!

UDPATE

I think I need to clarify what I need. Think of me as a Grid. I'm getting a DataSource which is a ICollection<T> and every row is represented by an object of T. Now I'm using MasterDetail relationships so that T just represents one MasterRow in the Grid. The Rows of a DetailView are represented by any ICollection<AnyClass> which is defined as a Property on T.

Now I need to determine this ICollection<AnyClass> Property from T without knowing what AnyClass is at compile time. Because I know the DetailView I can do this:

```<code>dynamic row = view.GetFocusedRow();
</code>```

So row is of type AnyClass and known at Runtime. But how can I find this ICollection<AnyClass> Property in the PropertyCollection of T? This is my problem.

答:
In general, this should do

```<code>.GetType().GetInterfaces().Any(intf => intf == typeof(ICollection<dynamic>));
</code>```

in case you meant Tand not dynamic, simple replace them.

```<code> .GetType().GetInterfaces().Any(intf => intf == typeof(ICollection<T>));
</code>```

If you want T and subtypes of it, it gets more complicated

```<code>.GetType().GetInterfaces().Any(intf => intf.IsGenericType &&
                                        intf.GetGenericTypeDefinition() == typeof(ICollection<>) &&
                                        intf.GetGenericArguments()[0].IsAssigneableFrom(typeof(T)));
</code>```

EDIT Since you calrified what you actually need:

```<code>.GetType().GetInterfaces().Any(intf => intf.IsGenericType &&
                                       intf.GetGenericTypeDefinition() == typeof(ICollection<>));
</code>```

It could be much simpler, but ICollection<T> does not implement ICollection.

Body:
I need to determine if a List contains ICollection where T is dynamic and not known at compiletime. Heres my code to better understand what I mean:

private void RefreshDataSource<T>(ICollection<T> dataSource) where T : IEquatable<T>
{
   dynamic row = view.GetFocusedRow();
   //Get's the focused row from a DevExpress-Grid
   //I don't know the type because it's MasterDetail and the view can be a DetailView. In this case type T isn't the underlying type.

   //Getting all Properties
   var dummy = dataSource.FirstOrDefault();
   var props = dummy.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();

   //Now comes the real problem, I need to determine the Detail Datasource
   //and to do this I want to check if there is a Property from ICollection<typeof(row)>

   //How can I check on ICollection<typeof(row)> instead of row
   //IsAssignableFrom would better fit my needs but I don't get how to solve my problem with it.
   var detailSource = props.FirstOrDefault(p => p.PropertyType.IsInstanceOfType(row));
}

The code is broken to the important points, so don't wonder if sth. doesn't makes sense in your eyes ;-). Is there any way to check on ICollection<T> where T is a dynamic type and just know at runtime?

Notice that the given T on top of the method isn't the type of row, because of MasterDetail relationship!!!

UDPATE

I think I need to clarify what I need. Think of me as a Grid. I'm getting a DataSource which is a ICollection<T> and every row is represented by an object of T. Now I'm using MasterDetail relationships so that T just represents one MasterRow in the Grid. The Rows of a DetailView are represented by any ICollection<AnyClass> which is defined as a Property on T.

Now I need to determine this ICollection<AnyClass> Property from T without knowing what AnyClass is at compile time. Because I know the DetailView I can do this:

dynamic row = view.GetFocusedRow();

So row is of type AnyClass and known at Runtime. But how can I find this ICollection<AnyClass> Property in the PropertyCollection of T? This is my problem.

Body:
In general, this should do

.GetType().GetInterfaces().Any(intf => intf == typeof(ICollection<dynamic>));

in case you meant Tand not dynamic, simple replace them.

 .GetType().GetInterfaces().Any(intf => intf == typeof(ICollection<T>));

If you want T and subtypes of it, it gets more complicated

.GetType().GetInterfaces().Any(intf => intf.IsGenericType &&
                                        intf.GetGenericTypeDefinition() == typeof(ICollection<>) &&
                                        intf.GetGenericArguments()[0].IsAssigneableFrom(typeof(T)));

EDIT Since you calrified what you actually need:

.GetType().GetInterfaces().Any(intf => intf.IsGenericType &&
                                       intf.GetGenericTypeDefinition() == typeof(ICollection<>));

It could be much simpler, but ICollection<T> does not implement ICollection.


问:
NoMethodError in ReportsController#import undefined method `original_filename' for "students.xlsx":String
I want to import the student records but when i choose file it shows an error as
NoMethodError in ReportsController#import
undefined methodoriginal_filename' for "students.xlsx":String`

and i tried to debbug this and I got

[1] pry(#<ReportsController>)> Student.import(params[:file])
NoMethodError: undefined methodoriginal_filename' for "import.xlsx":String
from /home/dk/import_multiple/school/app/models/student.rb:283:in open_spreadsheet'

This is my code:

controller

```<code>def importer
  params[:role] == :guardian ? Guardian : Student
end

def import
  importer.import(params[:file])
  redirect_to import_reports_path, notice: "Students imported."
end
</code>```

student.rb

```<code>COLUMNS_TO_STRING = ["batch_id", "class_roll_no","phone1","phone2"]  # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  record = Student.find_by(:id => row["id"],:batch_id =>    row["batch_id"],:class_roll_no => row["class_roll_no"],:phone1 =>  row["phone1"],:phone2 => row["phone2"]) || new
  record.attributes = row.to_hash.slice(*row.to_hash.keys)
  record.save!
 end
end
def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end
</code>```

guardian.rb

```<code>COLUMNS_TO_STRING = ["student_id"] # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  guardian = Guardian.find_by(:id => row["id"],:student_id => row["student_id"]) || new
  guardian.attributes = row.to_hash.slice(*row.to_hash.keys)
  guardian.save!
 end
end
def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end
</code>```

view

```<code><h1>IMPORT</h1>
<div class = "well">
    <p>
        <%= form_tag import_reports_path do %>
        <%= file_field_tag :file%>
        <br>
        <%= submit_tag "Import",class: "btn btn-primary" %>
        <% end %>
    </p>
</div>
</code>```

答: It looks like open_spreadsheet is expecting a File Object, not a String</p>

Body:
I want to import the student records but when i choose file it shows an error as
NoMethodError in ReportsController#import
undefined methodoriginal_filename' for "students.xlsx":String`

and i tried to debbug this and I got

[1] pry(#<ReportsController>)> Student.import(params[:file])
NoMethodError: undefined methodoriginal_filename' for "import.xlsx":String
from /home/dk/import_multiple/school/app/models/student.rb:283:in open_spreadsheet'

This is my code:

controller

def importer
  params[:role] == :guardian ? Guardian : Student
end

def import
  importer.import(params[:file])
  redirect_to import_reports_path, notice: "Students imported."
end

student.rb

COLUMNS_TO_STRING = ["batch_id", "class_roll_no","phone1","phone2"]  # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  record = Student.find_by(:id => row["id"],:batch_id =>    row["batch_id"],:class_roll_no => row["class_roll_no"],:phone1 =>  row["phone1"],:phone2 => row["phone2"]) || new
  record.attributes = row.to_hash.slice(*row.to_hash.keys)
  record.save!
 end
end
def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end

guardian.rb

COLUMNS_TO_STRING = ["student_id"] # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  guardian = Guardian.find_by(:id => row["id"],:student_id => row["student_id"]) || new
  guardian.attributes = row.to_hash.slice(*row.to_hash.keys)
  guardian.save!
 end
end
def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end

view

IMPORT

        <%= form_tag import_reports_path do %>
        <%= file_field_tag :file%>

        <%= submit_tag "Import",class: "btn btn-primary" %>
        <% end %>


答:
It's complicated :)

What you're using is called a field-like event. When you declare one of those in your class, you're creating a field and an event. When you "call the event" you're actually invoking the delegate referred to by the field. As it's a private field, you have access to it within the class (and any nested types), but not outside.

Events themselves in C# only support add and remove operations. From the outside, callers can only subscribe to an event and unsubscribe from it. They can't raise it, or find out anything about who's subscribed. Of course, the class can provide a method which will raise the event, but the other class can't access the backing field for the event

I've written this up in more detail in an article about events and delegates.

Title: What controls where an event can be called?

Body:
Say I have a class like this:

public class FauxIdentityForm
{
    public Guid FormID { get; set; }
    public event EventHandler Closed;
    public void TheObjectWasClosed(EventArgs e)
    {
        Closed(this, e);
    }
}

It is fine for me to call the Closed Event inside the TheObjectWasClosed method.  But if, in a different class (even in the same file), I have a method like this:

public void CallTheEvent()
{
    FauxIdentityForm _formIdentity = new FauxIdentityForm {FormID = Guid.NewGuid()};

    _formIdentity.Closed(_formIdentity, null);  // <-- Does not compile!
}

The call to Closed is shot down by the compiler (it wants me to only use += and -=).

So, is actually calling the event only allowed inside the class?  Is that the limitation?

If so, is there anyway around it?  And if not, why did the creators of C# do this?  (It makes working with events very hard sometimes.  I imagine there is a good reason and it is probably saving me from myself, but I would like to know it.)


问:
Angular - how to concat var name
I just started to learn Angular, and I tried to make concat var name so I can control it dynamically.

This is what I tried -

```<code><div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="myFunc(1)">Click Me!</button>

<div ng-show="showMe1">
    <h1>Menu:</h1>
    <div>Pizza</div>
    <div>Pasta</div>
    <div>Pesce</div>
</div>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.showMe1 = false;
    $scope.myFunc = function(x) {
        var nametocng = 'showMe'+x;
        //var nametocng = $parse("showMe"+x);  // - I tried this also
        $scope.nametocng = !$scope.nametocng;
    }
});
</script>
</code>```

答:
use $scope[variable] for dynamic.

From your comment: In the end, I want to make multiple Toggles, but I want one function for all of them. and then, every button will handle one toggle

You can use ng-repeat for button to handle different menu's

<!DOCTYPE html>

<button ng-repeat="button in array"  ng-click="myFunc(button)">Click Me!</button>

Menu:

Pizza1

Pasta1

Pesce1

Menu:

Pizza2

Pasta2

Pesce2

{{nametocng}}

```

Please run the above snippet

Here is a DEMO

Title: Angular - how to concat var name

Body:
I just started to learn Angular, and I tried to make concat var name so I can control it dynamically.

This is what I tried -

<button ng-click="myFunc(1)">Click Me!</button>

Menu:

Pizza

Pasta

Pesce

Body:
use $scope[variable] for dynamic.

From your comment: In the end, I want to make multiple Toggles, but I want one function for all of them. and then, every button will handle one toggle

You can use ng-repeat for button to handle different menu's

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<button ng-repeat="button in array"  ng-click="myFunc(button)">Click Me!</button>

<div ng-show="showMe1">
    <h1>Menu:</h1>
    <div>Pizza1</div>
    <div>Pasta1</div>
    <div>Pesce1</div>
</div>

<div ng-show="showMe2">
    <h1>Menu:</h1>
    <div>Pizza2</div>
    <div>Pasta2</div>
    <div>Pesce2</div>
</div>
{{nametocng}}

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.array = [1,2];
    $scope.firstName = "John";
    $scope.lastName = "Doe";

    $scope.myFunc = function(x) {
     angular.forEach($scope.array, function(value, key){
       $scope['showMe'+value] = false
});
        var nametocng = 'showMe'+x;
        //var nametocng = $parse("showMe"+x);  // - I tried this also
        $scope[nametocng] = !$scope[nametocng];
    }
});
</script>

</body>
</html>

Please run the above snippet

Here is a DEMO


问:
Git operations from command line adding 'www.' and '.com' to remote url
I have a situation where git operations from the command line client are changing the remote url from

http://{servername}:{portnumber}/tfs/DefaultCollection/_git/{repositoryname}

to

http://www.{servername}.com/tfs/DefaultCollection/_git/{repositoryname}

For example:

Commands like git remote show origin or git push origin (actually, git clone http://{servername}:8080/tfs/DefaultCollection/_git/obs produces the same thing, it's just that I'm trying to push an existing repo), results in
fatal: unable to access 'HTTP://www.{servername}.com/tfs/DefaultCollection/_git/obs': The requested URL returned error: 503

Does anyone have any ideas how to address this?

答:
According to the error info:

The requested URL returned error: 503

This issue usually related to proxy setting up. If you have an environment variable for a proxy it will override git proxy settings. Please give a try after removing the proxy.