问:
Inject environment and system variables from gradle to Intellij run and debug mode
I have some environment variables defined in my build.gradle that I'd like IntelliJ to automatically load when I run/debug unit tests or other kinds of tests (including with coverage and individual test runs)

Example:

build.gradle

```<code>plugins {
    id 'org.unbroken-dome.test-sets' version '1.4.2'
}

apply plugin: 'java'
apply plugin: 'idea'

testSets {
    integrationTest {
        dirName = 'integration-test'
    }
}

test {
    environment 'MY_ENV_VAR_1', 'my_env_value_1'
}

integrationTest {
    environment 'MY_ENV_VAR_1', 'my_env_value_1000'
}
</code>```

test method (in both test and integration-test dirs)

```<code>@Test
public void test() {
    System.out.println(System.getenv("MY_ENV_VAR_1"));
}
</code>```

runs

gradle test prints out my_env_value_1

gradle integrationTest prints out my_env_value_1000

from IntelliJ: right click on the test and run -> prints nothing. Same for integration test.

I clicked the "Refresh all gradle projects" button in IntelliJ's gradle projects pane. No change.
The question isn't just scoped to environment variable. Ability to load system properties or others from gradle to any run/debug modes in IntelliJ would also be nice.

答: In IntelliJ, be sure that IDE build/run actions are delegated to Gradle instead of handled through IntelliJ natively.  Without this ticked, IntelliJ will attempt to resolve these variables using the properties it is aware of, which may not be what you're looking for.

Body:
I have some environment variables defined in my build.gradle that I'd like IntelliJ to automatically load when I run/debug unit tests or other kinds of tests (including with coverage and individual test runs)

Example:

build.gradle

plugins {
    id 'org.unbroken-dome.test-sets' version '1.4.2'
}

apply plugin: 'java'
apply plugin: 'idea'

testSets {
    integrationTest {
        dirName = 'integration-test'
    }
}

test {
    environment 'MY_ENV_VAR_1', 'my_env_value_1'
}

integrationTest {
    environment 'MY_ENV_VAR_1', 'my_env_value_1000'
}

test method (in both test and integration-test dirs)

@Test
public void test() {
    System.out.println(System.getenv("MY_ENV_VAR_1"));
}

runs

gradle test prints out my_env_value_1

gradle integrationTest prints out my_env_value_1000

from IntelliJ: right click on the test and run -> prints nothing. Same for integration test.

I clicked the "Refresh all gradle projects" button in IntelliJ's gradle projects pane. No change.
The question isn't just scoped to environment variable. Ability to load system properties or others from gradle to any run/debug modes in IntelliJ would also be nice.


来源: stackexchange

问:
Conditional statement is not recognizing variable values
I am making a simple reaction time game for a final project.
We are using javascript to power the functions in the game, most of my code is in working order, but I have an if conditional statement that's giving me trouble.
Here's the code

function fireTime() {
  setTimeout(ShotsFired, time);

  function ShotsFired() {
    fire.style.visibility = "visible";
    createdTime = Date.now();
    console.log(createdTime);
    EnemyTime = Math.floor((Math.random() * 1000) + 400);
    setTimeout(EnemyShoot, EnemyTime)

    function EnemyShoot() {
      console.log(EnemyTime);
      gameplay();
    }

    function gameplay() {
      reactionTime = -(createdTime - clickedTime);
      var EnemyTime;
      console.log(reactionTime);
      if (reactionTime < EnemyTime) {
        alert("Wow you beat him! Congrats!");
        fire.style.visibility = "hidden";
        clickedTime = 0;
        createdTime = 0;
        reactionTime = 0;
        scavnumber++;
        BGnumber++;
        DesertBG.src = "images/Desert" + BGnumber + ".png";
        scav.src = "images/scav" + scavnumber + ".png";
        fireTime();
      } else {
        EndScreen.style.visibility = "visible";
      }
    }
```

This is not the entire code, just the function that should progress the game to the next level.

For whatever reason, even though reactionTime is less than EnemyTime, the EndScreen becomes visible.

Anyone know what could cause this?

答:
Use floating point for your enemy time maths, i.e. 400.0 , else you are getting 0/1 seconds and not using milliseconds, and it is useing Math integer. Specifically cast your enemyTime as a float number, for the moment, if you print it it's probably an integer. its a MAJOR js coding detail that you will cost you hours of bughunting in the future if you think that 101/50 = 2.05, it isn't it equals 2, so divide by 50.0 and same with all second/ms tasks.

Use EnemyTime as a global variable for all scripts, at the moment, the code things you have a different function called EnemyTime in all scripts, the latter one has no value.

Use print to see when your else conditions work, specify a print in both an print the enemyTime value.

That's how you are supposed to resolve the issue, by printing the variables that are confusing.

ContentLicense: CC BY-SA 3.0

Body:
I am making a simple reaction time game for a final project.
We are using javascript to power the functions in the game, most of my code is in working order, but I have an if conditional statement that's giving me trouble.
Here's the code

function fireTime() {
  setTimeout(ShotsFired, time);

  function ShotsFired() {
    fire.style.visibility = "visible";
    createdTime = Date.now();
    console.log(createdTime);
    EnemyTime = Math.floor((Math.random() * 1000) + 400);
    setTimeout(EnemyShoot, EnemyTime)

    function EnemyShoot() {
      console.log(EnemyTime);
      gameplay();
    }

    function gameplay() {
      reactionTime = -(createdTime - clickedTime);
      var EnemyTime;
      console.log(reactionTime);
      if (reactionTime < EnemyTime) {
        alert("Wow you beat him! Congrats!");
        fire.style.visibility = "hidden";
        clickedTime = 0;
        createdTime = 0;
        reactionTime = 0;
        scavnumber++;
        BGnumber++;
        DesertBG.src = "images/Desert" + BGnumber + ".png";
        scav.src = "images/scav" + scavnumber + ".png";
        fireTime();
      } else {
        EndScreen.style.visibility = "visible";
      }
    }

This is not the entire code, just the function that should progress the game to the next level.

For whatever reason, even though reactionTime is less than EnemyTime, the EndScreen becomes visible.

Anyone know what could cause this?


问:
Best way to reload data in Redis (or other cache service) upon restart?
When the Redis server fails and restarts, what's the best way to reload data into Redis? (I'm a bit new to Redis and in-memory databases)

I have three parts, I'll describe them as follows:

Producer app - Updates a SQL database and also writes a subset of the SQL data into a Redis server

Redis server - Has an important subset of the SQL data

Consumer app - Needs to look up data in Redis at a fast rate (currently doesn't write to Redis or the SQL database)

Some options I'm considering:

Put reload script in Redis server so it'll query the SQL database and reload itself upon startup

Build an endpoint in the Producer app that the Consumer app can call to tell the Producer app to reload Redis when the Consumer app notices that the Redis server is empty and has restarted

Get rid of the Producer app completely and have the Consumer app directly query the SQL database and write the results in Redis (but then how will it know when the SQL data has been updated?)

Keep the Producer app, but also have the Consumer app directly query the SQL database and write the results in Redis when the Consumer app senses Redis to be empty

答:
Reloading data into Redis or any other cache is called cache-warming. The problem you seem to have is that you're not trying to use Redis as a cache but as a means to communicate between the apps.

Normally you would want your application to query Redis to see if there's data in there and if not query the endpoint or database so you should always have some kind of means to go without Redis.

Whether you have the producer purge the consumer's cache or have consumer mind it's own cache and deal with stale data or introduce another application just for serving the data would depends on your exact needs.


问:
Subscribe to Observable -> Filter -> Provide as Observable
I'm trying to work out an Angular service that consumes other services to provide meta data on those services. The data objects are different classes of people with a connecting class. (i.e. Client, Consultant, and sales relationship.)

A basic metric I would like to track is whether the client has been assigned a consultant. (i.e. un-matched). I have in my standard service, an Observable Array called Clients that I subscribe to in my MetaData Service like so:

```<code>this.clientService.clientArray().map( ..... ).subscribe(i => this.unmatchedClients.next(i);
</code>```

What I want to do is filter the array that comes in from the Observable Subscription to check multiple fields. It was suggested elsewhere that I should have the full filter call like this:

```<code>this.clientService.clientArray().map( r => {
    r.filter( i => {
        i.connected === true
    })
}).subscribe(r => this.unmatchedClients.next(r));
</code>```

The expected results should be an array  of clients, not individual clients which I can subscribe to and get the length for counting.

How can I accomplish this?

答:
I think you have one additional unnecessary step. If you want to filter the array you pipe to the subscription why not just do

```<code>this.clientService.clientArray()
 .filter( client => {
    return client.connected;
})
.subscribe(r => this.unmatchedClients.next(r));
</code>```

The bit of code inside the subscription I have no idea what’s the goal so I kept it as is.

Body:
I'm trying to work out an Angular service that consumes other services to provide meta data on those services. The data objects are different classes of people with a connecting class. (i.e. Client, Consultant, and sales relationship.)

A basic metric I would like to track is whether the client has been assigned a consultant. (i.e. un-matched). I have in my standard service, an Observable Array called Clients that I subscribe to in my MetaData Service like so:

this.clientService.clientArray().map( ..... ).subscribe(i => this.unmatchedClients.next(i);

What I want to do is filter the array that comes in from the Observable Subscription to check multiple fields. It was suggested elsewhere that I should have the full filter call like this:

this.clientService.clientArray().map( r => {
    r.filter( i => {
        i.connected === true
    })
}).subscribe(r => this.unmatchedClients.next(r));

The expected results should be an array  of clients, not individual clients which I can subscribe to and get the length for counting.

How can I accomplish this?

Body:
I think you have one additional unnecessary step. If you want to filter the array you pipe to the subscription why not just do

this.clientService.clientArray()
 .filter( client => {
    return client.connected;
})
.subscribe(r => this.unmatchedClients.next(r));

The bit of code inside the subscription I have no idea what’s the goal so I kept it as is.


问:
push rails app to heroku
I am trying to push a rails application to heroku.

When I get to the last step:

```<code>git push heroku master
</code>```

It doesn't work and gives me these errors:

```<code>Counting objects: 85, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (74/74), done.
Writing objects: 100% (85/85), 24.38 KiB, done.
Total 85 (delta 23), reused 0 (delta 0)

-----> Heroku receiving push
 !     Heroku push rejected, no Rails or Rack app detected.

error: hooks/pre-receive exited with error code 1
To git@heroku.com:smooth-dusk-26.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:smooth-dusk-26.git'
</code>```

I don't know what I'm doing wrong :(

答:
I encountered the same errors working through Chapter 1 of Michael Hartl's Rails Tutorial.  They were eventually resolved by issuing another git commit command after opening a Heroku account and configuring the SSH keys: git commit -a -m "Heroku recommit"

git push heroku master then succeeded.

ContentLicense: CC BY-SA 2.5

Title: push rails app to heroku

Body:
I am trying to push a rails application to heroku.

When I get to the last step:

git push heroku master

It doesn't work and gives me these errors:

Counting objects: 85, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (74/74), done.
Writing objects: 100% (85/85), 24.38 KiB, done.
Total 85 (delta 23), reused 0 (delta 0)

-----> Heroku receiving push
 !     Heroku push rejected, no Rails or Rack app detected.

error: hooks/pre-receive exited with error code 1
To git@heroku.com:smooth-dusk-26.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:smooth-dusk-26.git'

I don't know what I'm doing wrong :(


问:
How to programmatically drive ISR on M0+
I'm writing some Unity unit tests for an embedded project running on an Arm M0+. Some of my APIs depend on wether they're called from the ISR context or not. So I want to programmatically drive an interrupt. In pseudo code, I want my test to look something like:

```<code>// set (global) flag indicating what ISR should do
// trigger the ISR
// control transfers to ISR which branches off of (global) flag and computes result, store in some global
// control now returns to here, where I can assert the nature of the global result
</code>```

The part that I need some direction in is how to trigger the ISR. I saw some references in the M3 docs about a Software Interrupt Trigger, but I'm not finding anything like that for M0+.

A "workaround" solution might be to grab an unused timer, use it's ISR, then set it's compare to 0, and start it so it drives the interrupt. Or maybe a similar scheme with an unused pin which I configure? Is there a more direct way to accomplish this?

答:
Based on the hints from @user58697 and @andymango, I came up with the following scheme.

-1 Determined that for my board (SAMD21), there was no peripheral at IRQ 21.

-2 Copying the other alias dummy handlers in my resetVectors.c file, I added:

```<code>void PV21Handler             ( void ) __attribute__ ((weak, alias("Dummy_Handler")));
</code>```

-3 Modified the DeviceVectors structure to set .pvReserved21 to that:

```<code>__attribute__ ((section(".vectors")))
const DeviceVectors exception_table = {
    ...
    ...
    .pvReserved21           = (void*) PV21Handler,
    ...
    ...
};
</code>```

-4 Implemented a void PV21Handler(void) { } function that actually does something

-5 Used the following to enable the interrupt:

```<code>NVIC_EnableIRQ(21);
// this comes from the core_cm0plus.h file
</code>```

-6 Finally trigger the interrupt with:

```<code>while (NVIC_GetPendingIRQ(21)) {  }
NVIC_SetPendingIRQ(21);
while (NVIC_GetPendingIRQ(21)) {  }
</code>```

The poll for clear status was necessary since there seems to be a slight delay between setting the interrupt and it actually happening, so to get a true edge, I had to assert it low first.

Body:
I'm writing some Unity unit tests for an embedded project running on an Arm M0+. Some of my APIs depend on wether they're called from the ISR context or not. So I want to programmatically drive an interrupt. In pseudo code, I want my test to look something like:

// set (global) flag indicating what ISR should do
// trigger the ISR
// control transfers to ISR which branches off of (global) flag and computes result, store in some global
// control now returns to here, where I can assert the nature of the global result

The part that I need some direction in is how to trigger the ISR. I saw some references in the M3 docs about a Software Interrupt Trigger, but I'm not finding anything like that for M0+.

A "workaround" solution might be to grab an unused timer, use it's ISR, then set it's compare to 0, and start it so it drives the interrupt. Or maybe a similar scheme with an unused pin which I configure? Is there a more direct way to accomplish this?

Body:
Based on the hints from @user58697 and @andymango, I came up with the following scheme.

-1 Determined that for my board (SAMD21), there was no peripheral at IRQ 21.

-2 Copying the other alias dummy handlers in my resetVectors.c file, I added:

void PV21Handler             ( void ) __attribute__ ((weak, alias("Dummy_Handler")));

-3 Modified the DeviceVectors structure to set .pvReserved21 to that:

__attribute__ ((section(".vectors")))
const DeviceVectors exception_table = {
    ...
    ...
    .pvReserved21           = (void*) PV21Handler,
    ...
    ...
};

-4 Implemented a void PV21Handler(void) { } function that actually does something

-5 Used the following to enable the interrupt:

NVIC_EnableIRQ(21);
// this comes from the core_cm0plus.h file

-6 Finally trigger the interrupt with:

while (NVIC_GetPendingIRQ(21)) {  }
NVIC_SetPendingIRQ(21);
while (NVIC_GetPendingIRQ(21)) {  }

The poll for clear status was necessary since there seems to be a slight delay between setting the interrupt and it actually happening, so to get a true edge, I had to assert it low first.


问:
q-field-no-input being added to fields
Does anyone know why the q-field-no-input class would be added to my fields even though there is an input inside it? This is happening in all of my pages and is creating a weird margin that breaks the formatting.

I would rather not override the CSS and just find out why the class is being added.

答:
Updating to latest version did not work for me. Had to resort to disabling the .q-field-no-input styles.

```<code>.q-field-with-error .q-field-no-input
  border-top 0
.q-field-no-input
  margin-top 0
</code>```

This solves the issue (I am sure I have no fields without input so I do not worry about disabling it)

Title: q-field-no-input being added to fields

Body:
Updating to latest version did not work for me. Had to resort to disabling the .q-field-no-input styles.

.q-field-with-error .q-field-no-input
  border-top 0
.q-field-no-input
  margin-top 0

This solves the issue (I am sure I have no fields without input so I do not worry about disabling it)


问:
How to add text reference to other listings?

I want to add a comment into the columns when the listings has it. Could anyone please help me?

```<code><dl class="listings">
<dt>Apple</dt>
<dd>Delicious</dd>
<dt>Green Apple</dt>
<dd>Love it!</dd>
</dl>
<table>
<tr>
<td>Apple, Orange, Banana</td>
<td>Green Apple, Lemon</td>
</tr>
</table>

$(document).ready(function () {
        $(".listings").find('dt').each(function() {
            var title = $(this).html();
            var comment = $(this).next().html();
            $('table td').filter(":contains('"+title+"')").each(function(){
                $(this).html('<span>'+title+'</span><span>'+comment+'</span>');
            });
        });
    });
</code>```

Expected

```<code>Apple Delicious, Orange, Banana
Green Apple Love it!, Lemon
</code>```

Result

```<code>Apple Delicious
Apple Delicious
</code>```

答:
Following assumes  phrases/words in table that you want to change are all separated with a comma.

Otherwise "Apple" by itself is also found in "Green Apple" and can turn into something like  "Green Apple Delicious Love it!"

Thus have to split all the phrases and do direct equality matches of each one individually

$(".listings").find('dt').each(function() {
  var title = $(this).html();
  var comment = $(this).next().html();

  $('table td').filter(":contains('" + title + "')").html(function(_, currHtml) {
      // break all the phrases into array by splitting at comma
      // and map array to new html strings
      return currHtml.split(',').map(function(phrase){
         // check each phrase/word separately
         phrase = phrase.trim()
         if(phrase===title){
           return '' + title + ' ' + comment + ''
         }else{
           return phrase;
         }
      // join array back into string
      }).join(', ');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl class="listings">
  <dt>Apple</dt>
  <dd>Delicious</dd>
  <dt>Green Apple</dt>
  <dd>Love it!</dd>
</dl>
<table>
  <tr>
    <td>Apple, Orange, Banana</td>
  </tr>
  <tr>
    <td>Green Apple, Lemon</td>
  </tr>
</table></code>```

Body:
I want to add a comment into the columns when the listings has it. Could anyone please help me?

Apple

Delicious

Green Apple

Love it!

Apple, Orange, Banana
Green Apple, Lemon

$(document).ready(function () {
        $(".listings").find('dt').each(function() {
            var title = $(this).html();
            var comment = $(this).next().html();
            $('table td').filter(":contains('"+title+"')").each(function(){
                $(this).html(''+title+''+comment+'');
            });
        });
    });

Expected

Apple Delicious, Orange, Banana
Green Apple Love it!, Lemon

Result

Apple Delicious
Apple Delicious

Body:
Following assumes  phrases/words in table that you want to change are all separated with a comma.

Otherwise "Apple" by itself is also found in "Green Apple" and can turn into something like  "Green Apple Delicious Love it!"

Thus have to split all the phrases and do direct equality matches of each one individually

$(".listings").find('dt').each(function() {
  var title = $(this).html();
  var comment = $(this).next().html();

  $('table td').filter(":contains('" + title + "')").html(function(_, currHtml) {
      // break all the phrases into array by splitting at comma
      // and map array to new html strings
      return currHtml.split(',').map(function(phrase){
         // check each phrase/word separately
         phrase = phrase.trim()
         if(phrase===title){
           return '<span>' + title + '</span><span> ' + comment + '</span>'
         }else{
           return phrase;
         }
      // join array back into string
      }).join(', ');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl class="listings">
  <dt>Apple</dt>
  <dd>Delicious</dd>
  <dt>Green Apple</dt>
  <dd>Love it!</dd>
</dl>
<table>
  <tr>
    <td>Apple, Orange, Banana</td>
  </tr>
  <tr>
    <td>Green Apple, Lemon</td>
  </tr>
</table>


问:
Working with plain objects client side?
I receive a plain object from the server that i assert as an interface, lets say:

```<code>interface Person {
    firstName: string;
    lastName: string;
    // ...
}

const person = json as Person;
</code>```

I want to avoid the boilerplate and duplication of wrapping the response in my own class like this:

```<code>class MyPerson {
    public firstName: string;
    public lastName: string;
    // ...

    public get fullName(): string {
        return `${this.firstName} ${this.lastName}`;
    }

    constructor(data: Person) {
        this.firstName = data.firstName;
        this.lastName = data.lastName;
        // ...
    }

    public serialize(): Person {
        return {
            firstName: this.firstName,
            lastName: this.lastName
            // ...
        };
    }
}
</code>```

But i still want to have methods/getters like fullName.

I have considered to use "C-style" classes, passing the plain object around and use functions that take the instance as first argument:

```<code>function Person_getName(person: Person): string {
    return `${person.firstName} ${person.lastName}`;
}
</code>```

Is there a better way to do this?

答:
You could use the spread operator introduced in TypeScript 2.1 (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html).

So in your example:

```<code>const MY_PERSON = new MyPerson();
// ...
const person = { ...MY_PERSON, ...json };
</code>```

If you want to understand the syntax a little better there is a good explanation on Google developers

Title: Working with plain objects client side?

Body:
I receive a plain object from the server that i assert as an interface, lets say:

interface Person {
    firstName: string;
    lastName: string;
    // ...
}

const person = json as Person;

I want to avoid the boilerplate and duplication of wrapping the response in my own class like this:

class MyPerson {
    public firstName: string;
    public lastName: string;
    // ...

    public get fullName(): string {
        return `${this.firstName} ${this.lastName}`;
    }

    constructor(data: Person) {
        this.firstName = data.firstName;
        this.lastName = data.lastName;
        // ...
    }

    public serialize(): Person {
        return {
            firstName: this.firstName,
            lastName: this.lastName
            // ...
        };
    }
}

But i still want to have methods/getters like fullName.

I have considered to use "C-style" classes, passing the plain object around and use functions that take the instance as first argument:

function Person_getName(person: Person): string {
    return `${person.firstName} ${person.lastName}`;
}

Is there a better way to do this?

Body:
You could use the spread operator introduced in TypeScript 2.1 (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html).

So in your example:

const MY_PERSON = new MyPerson();
// ...
const person = { ...MY_PERSON, ...json };

If you want to understand the syntax a little better there is a good explanation on Google developers


问:
Can I access the "enclosing" object for an inlined function call in Kotlin?
Idea: Make an inlined convenience function to synchronize a function call on the "inlining" object's intrinsic lock:

```<code>public inline fun <T> intrinsicSync(block: () -> T): T {
    return synchronized(intrinsicLockOfTheObjectUsingTheFunction) {
        block()
    }
}

fun someFunction(parameter: SomeClass) {
    intrinsicSync(sharedResource.operation(parameter))
}
</code>```

Is this possible? If not, is there a different but equally convenient way? I concede that

```<code>fun someFunction(parameter: SomeClass) {
    synchronized(this) {
        sharedResource.operation(parameter)
    }
}
</code>```

isn't the biggest hassle in the world, but I'd still like to know if it's possible to do something similar to what I imagined.

答:
The most you can do is give the function a receiver (i.e. make it an extension function):

```<code>public inline fun <T> Any.intrinsicSync(crossinline block: () -> T): T {
                   // ^ within this function, `this` refers to the receiver
    return synchronized(this, block)
}
</code>```

and then in a member function, you can do

```<code>this.intrinsicSync { sharedResource.operation() }
</code>```

and since this is inferred you should be able to shorten this to

```<code>intrinsicSync { sharedResource.operation() }
</code>```

Keep in mind that extension functions cannot shadow member functions, so if this object has another function with the same signature, it won't choose the extension function.

In your case, though, this seems unlikely.

Body:
Idea: Make an inlined convenience function to synchronize a function call on the "inlining" object's intrinsic lock:

public inline fun <T> intrinsicSync(block: () -> T): T {
    return synchronized(intrinsicLockOfTheObjectUsingTheFunction) {
        block()
    }
}

fun someFunction(parameter: SomeClass) {
    intrinsicSync(sharedResource.operation(parameter))
}

Is this possible? If not, is there a different but equally convenient way? I concede that

fun someFunction(parameter: SomeClass) {
    synchronized(this) {
        sharedResource.operation(parameter)
    }
}

isn't the biggest hassle in the world, but I'd still like to know if it's possible to do something similar to what I imagined.

Body:
The most you can do is give the function a receiver (i.e. make it an extension function):

public inline fun <T> Any.intrinsicSync(crossinline block: () -> T): T {
                   // ^ within this function, `this` refers to the receiver
    return synchronized(this, block)
}

and then in a member function, you can do

this.intrinsicSync { sharedResource.operation() }

and since this is inferred you should be able to shorten this to

intrinsicSync { sharedResource.operation() }

Keep in mind that extension functions cannot shadow member functions, so if this object has another function with the same signature, it won't choose the extension function.

In your case, though, this seems unlikely.


问:
WCF OperationBehavior: ApplyDispatchBehavior not being called
My goal is to create an endpointbehavior for WCF, which adds an extra Ping() operation to an existing contract. The EndpointBehavior works fine, I can actually see the added Ping() operation when I run my service and use the WCF test client. I've implemented this endpointbehavior as follows:

Configuration:

```<code><configuration>
  <system.serviceModel>

    <services>
      <service name="X">
        <endpoint address="mex" kind="mexEndpoint" />
        <endpoint address="" binding="basicHttpBinding" contract="IX"
             behaviorConfiguration="ping" />
      </service>
    </services>

    <behaviors>
      <endpointBehaviors>
        <behavior name="ping">
          <PingEndpointBehavior />
        </behavior>
      </endpointBehaviors>
    </behaviors>

    <extensions>
      <behaviorExtensions>
        <add name="PingEndpointBehavior"
          type="Assembly.PingEndpointBehavior, Assembly, .. />
      <behaviorExtensions>
    </extensions>

  </system.serviceModel>
</configuration>
</code>```

Endpoint behavior:

```<code>public class PingEndpointBehavior : BehaviorExtensionElement, IEndpointBehavior
{
    ...

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint,
      EndpointDispatcher endpointDispatcher)
    {
        var cd = endpoint.Contract;

        var inputMessage = new MessageDescription(...);
        var outputMessage = new MessageDescription(...);
        // Set input/output messages correctly

        var od = new OperationDescription("Ping", cd);
        od.Messages.Add(inputMessage);
        od.Messages.Add(outputMessage);

        od.Behaviors.Add(new DataContractSerializerOperationBehavior(od));
        od.Behaviors.Add(new PingOperationBehavior());

        endpoint.Contract.Operations.Add(od);
    }

    ...
}
</code>```

The operation behavior however, is not working. The ApplyDispatchBehavior() method on the operationbehavior never gets called, and therefore, my own PingInvoker is not used. This results in not getting a response when calling the added Ping() operation to a contract.

The reason for this seems to be that the OperationBehavior only gets added after the service has already started, resulting in the ApplyDispactchBehavior not getting called. See code below:

Operation Behavior:

```<code>public class PingOperationBehavior : IOperationBehavior
{
    ...

    public void ApplyDispatchBehavior(OperationDescription od, DispatchOperation do)
    {
        do.Invoker = new PingInvoker();
    }

    ...
}
</code>```

Invoker:

```<code>public class PingInvoker : IOperationInvoker
{
    ...

    public object Invoke(object instance, object[] inputs, out object[] outputs)
    {
        outputs = new object[0];
        return Ping();
    }

    public static DateTime Ping()
    {
        return DateTime.Now;
    }

    ...
}
</code>```

Anyone have an idea how I can get the OperationBehavior to work properly?

Note:

Should work for services hosted in IIS (not self-hosted)

Except for adding the behavior in configuration (and referencing the assembly that contains the behavior), I don't want to have to change anything on the service

答:
I had this same problem with my custom Behavior.  I was deriving from WebHttpBehavior (which inherits from IEndpointBehavior), but the ApplyDispatchBehavior was not being called.

The solution to my problem was to add the missing override keyword like: public override void ApplyDispatchBehavior(...

Body:
My goal is to create an endpointbehavior for WCF, which adds an extra Ping() operation to an existing contract. The EndpointBehavior works fine, I can actually see the added Ping() operation when I run my service and use the WCF test client. I've implemented this endpointbehavior as follows:

Configuration:

<configuration>
  <system.serviceModel>

    <services>
      <service name="X">
        <endpoint address="mex" kind="mexEndpoint" />
        <endpoint address="" binding="basicHttpBinding" contract="IX"
             behaviorConfiguration="ping" />
      </service>
    </services>

    <behaviors>
      <endpointBehaviors>
        <behavior name="ping">
          <PingEndpointBehavior />
        </behavior>
      </endpointBehaviors>
    </behaviors>

    <extensions>
      <behaviorExtensions>
        <add name="PingEndpointBehavior"
          type="Assembly.PingEndpointBehavior, Assembly, .. />
      <behaviorExtensions>
    </extensions>

  </system.serviceModel>
</configuration>

Endpoint behavior:

public class PingEndpointBehavior : BehaviorExtensionElement, IEndpointBehavior
{
    ...

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint,
      EndpointDispatcher endpointDispatcher)
    {
        var cd = endpoint.Contract;

        var inputMessage = new MessageDescription(...);
        var outputMessage = new MessageDescription(...);
        // Set input/output messages correctly

        var od = new OperationDescription("Ping", cd);
        od.Messages.Add(inputMessage);
        od.Messages.Add(outputMessage);

        od.Behaviors.Add(new DataContractSerializerOperationBehavior(od));
        od.Behaviors.Add(new PingOperationBehavior());

        endpoint.Contract.Operations.Add(od);
    }

    ...
}

The operation behavior however, is not working. The ApplyDispatchBehavior() method on the operationbehavior never gets called, and therefore, my own PingInvoker is not used. This results in not getting a response when calling the added Ping() operation to a contract.

The reason for this seems to be that the OperationBehavior only gets added after the service has already started, resulting in the ApplyDispactchBehavior not getting called. See code below:

Operation Behavior:

public class PingOperationBehavior : IOperationBehavior
{
    ...

    public void ApplyDispatchBehavior(OperationDescription od, DispatchOperation do)
    {
        do.Invoker = new PingInvoker();
    }

    ...
}

Invoker:

public class PingInvoker : IOperationInvoker
{
    ...

    public object Invoke(object instance, object[] inputs, out object[] outputs)
    {
        outputs = new object[0];
        return Ping();
    }

    public static DateTime Ping()
    {
        return DateTime.Now;
    }

    ...
}

Anyone have an idea how I can get the OperationBehavior to work properly?

Note:

Should work for services hosted in IIS (not self-hosted)

Except for adding the behavior in configuration (and referencing the assembly that contains the behavior), I don't want to have to change anything on the service


问:
How to cleanly pass down keyword args?
When writing functions that call other sub-functions I often want to allow the caller to pass in arbitrary keyword arguments for those subfunctions. However, the current way that I implement this is messy and I am looking for a more clear, concise, and maintainable way.

Below is an example of how I currently implement this:

```<code>def foo(a, print_line="Hello World!"):
    print a, print_line

def bar(a, number=2, multiple=4):
    print a, number * multiple

def baz(a, **kwargs):
    if "print_line" in kwargs:
        foo(a, print_line=kwargs["print_line"])
    else:
        foo(a)

    bar_kwargs = dict()
    if "number" in kwargs:
        bar_kwargs["number"] = kwargs["number"]
    if "multiple" in kwargs:
        bar_kwargs["multiple"] = kwargs["multiple"]
    bar(a, **bar_kwargs)
</code>```

This method is error-prone and I need to implement every kwarg that I want to express. I can sometimes get away with foo(a, print_line=kwargs.get("print_line", False) but I would like to preserve the default argument of the kwarg.

答:
Simple. just pass the kwargs themselves into the sub function and add a kwargs variable to the sub functions

```<code>def foo(a, print_line="Hello World!", **kwargs):
    print a, print_line

def bar(a, number=2, multiple=4, **kwargs):
    print a, number * multiple

def baz(a, **kwargs):
    foo(a, **kwargs)
    bar(a, **kwargs)
</code>```

This works because now the sub functions can receive an arbitrary number of keyword arguments while concretely defining the arguments they are required to have. Thus, a kwarg dict that looks like {'print_line':'test_line', 'number':1,'multiple':2} will function perfectly for both functions.

As requested by comment:

```<code>class SomeoneElsesClass:
  def someone_elses_function(self, a, foo="bar"):
    print(foo)

class MyClass(SomeoneElsesClass):
  def someone_elses_function(self, a, foo="bar2", **kwargs):
    super(MyClass, self).someone_elses_function(a, foo)
</code>```

Title: How to cleanly pass down keyword args?

Body:
When writing functions that call other sub-functions I often want to allow the caller to pass in arbitrary keyword arguments for those subfunctions. However, the current way that I implement this is messy and I am looking for a more clear, concise, and maintainable way.

Below is an example of how I currently implement this:

def foo(a, print_line="Hello World!"):
    print a, print_line

def bar(a, number=2, multiple=4):
    print a, number * multiple

def baz(a, **kwargs):
    if "print_line" in kwargs:
        foo(a, print_line=kwargs["print_line"])
    else:
        foo(a)

    bar_kwargs = dict()
    if "number" in kwargs:
        bar_kwargs["number"] = kwargs["number"]
    if "multiple" in kwargs:
        bar_kwargs["multiple"] = kwargs["multiple"]
    bar(a, **bar_kwargs)

This method is error-prone and I need to implement every kwarg that I want to express. I can sometimes get away with foo(a, print_line=kwargs.get("print_line", False) but I would like to preserve the default argument of the kwarg.

Body:
Simple. just pass the kwargs themselves into the sub function and add a kwargs variable to the sub functions

def foo(a, print_line="Hello World!", **kwargs):
    print a, print_line

def bar(a, number=2, multiple=4, **kwargs):
    print a, number * multiple

def baz(a, **kwargs):
    foo(a, **kwargs)
    bar(a, **kwargs)

This works because now the sub functions can receive an arbitrary number of keyword arguments while concretely defining the arguments they are required to have. Thus, a kwarg dict that looks like {'print_line':'test_line', 'number':1,'multiple':2} will function perfectly for both functions.

As requested by comment:

class SomeoneElsesClass:
  def someone_elses_function(self, a, foo="bar"):
    print(foo)

class MyClass(SomeoneElsesClass):
  def someone_elses_function(self, a, foo="bar2", **kwargs):
    super(MyClass, self).someone_elses_function(a, foo)


问:
How to iterate through a global array and return user input
I am trying to build a news site using the guardian api and search this api using user input to return the webTitle attribute for each matching element. I know simply appending user input into the ajax call would be a simpler method of completing this task but I'm looking for a bit of a challenge so I decided I could assign the ajax response to a global array and iterate through that to find the user input but I am having trouble iterating through the array.

The code for the global array and ajax call is here;

```<code>var searchQuery=[];

                $.ajax({
                    url: 'https://content.guardianapis.com/search?&api-key=xxxx',
                    async: true,
                    dataType: "json",
                    success: function(data){
                        searchQuery.push(data);
                    }
                });
</code>```

And this works as when outputted to the console it shows the array populated with all of the elements within the ajax call.

I am just wondering how I can then take this array, and using JQuery, iterate through it and check if any elements contain the user input from an input text box located in my application preferably when the search button is clicked, the code for which is here;

```<code><div id="search">
                            <div class="input-group col-md-12">
                                <input type="text" class="search-query form-control" placeholder="Search" id= 'userSearch' <a href="#" data-toggle="popover" title="How To Search" data-content="Enter a Key Word and Receive News Stories Associated With It"></a>
                                <span class="input-group-btn">
                                    <button class="btn btn-primary mb1 bg-blue" type="button" id="submitSearch">
                                        <span class=" glyphicon glyphicon-search"></span>
                                    </button>
                                </span>
                            </div>
</div>
</code>```

Any help with this would be greatly appreciated and I'm sure it is just my inexperience with web development giving me the issues so please don't judge me too much haha.

答:
Going by what your require, here's something that may help you:</p>

```<code>var searchQuery;
var keyword = $("#userSearch").val().toLowerCase();

$.ajax({
   url: 'https://content.guardianapis.com/search?api-key=xxxx',
   async: true,
   dataType: "json",
   success: function(data){
      searchQuery =  data.response.results;
   }
});

$("#submitSearch").on("click", function(){
    for(i=0;i<searchQuery.length;i++){
       if(searchQuery[i].webTitle.toLowerCase().indexOf(keyword) > 0){
         console.log(searchQuery[i].webTitle);
         console.log(searchQuery[i].webUrl);
         console.log(searchQuery[i].apiUrl);
       }
    }
});
</code>```

Body:
I am trying to build a news site using the guardian api and search this api using user input to return the webTitle attribute for each matching element. I know simply appending user input into the ajax call would be a simpler method of completing this task but I'm looking for a bit of a challenge so I decided I could assign the ajax response to a global array and iterate through that to find the user input but I am having trouble iterating through the array.

The code for the global array and ajax call is here;

var searchQuery=[];

                $.ajax({
                    url: 'https://content.guardianapis.com/search?&api-key=xxxx',
                    async: true,
                    dataType: "json",
                    success: function(data){
                        searchQuery.push(data);
                    }
                });

And this works as when outputted to the console it shows the array populated with all of the elements within the ajax call.

I am just wondering how I can then take this array, and using JQuery, iterate through it and check if any elements contain the user input from an input text box located in my application preferably when the search button is clicked, the code for which is here;

                                <input type="text" class="search-query form-control" placeholder="Search" id= 'userSearch'

                                    <button class="btn btn-primary mb1 bg-blue" type="button" id="submitSearch">

                                    </button>

Any help with this would be greatly appreciated and I'm sure it is just my inexperience with web development giving me the issues so please don't judge me too much haha.

Body:
Going by what your require, here's something that may help you:

var searchQuery;
var keyword = $("#userSearch").val().toLowerCase();

$.ajax({
   url: 'https://content.guardianapis.com/search?api-key=xxxx',
   async: true,
   dataType: "json",
   success: function(data){
      searchQuery =  data.response.results;
   }
});

$("#submitSearch").on("click", function(){
    for(i=0;i<searchQuery.length;i++){
       if(searchQuery[i].webTitle.toLowerCase().indexOf(keyword) > 0){
         console.log(searchQuery[i].webTitle);
         console.log(searchQuery[i].webUrl);
         console.log(searchQuery[i].apiUrl);
       }
    }
});


问:
Scala: How to extend an Akka actor?
I wrote an Akka base-actor that can handle some common messages. I want to reuse this basic behavior in a sub-actor, by extending the base-actor (not by composition of the base-actor).

I have seen several approaches in previous questions. They are all valid but also may be improved:

How extend behaviour of super actor in akka

and

How do I best share behavior among Akka actors?

To make the implementation cleaner, I am trying to achieve the following:

When defining the sub-actor, I try to extend only the base-actor (not both Actor and sub-actor). However, I was not able to force the compiler to do this.

I also try to not rename the receive partial function, because it is a kind of convention.

Here is a sample of my implementation:

```<code>//This is the base-actor that implements the common behavior

trait BetterActor extends Actor {

  abstract override def receive = {
    super.receive orElse { case _ => println("Missing pattern!") }
  }
}

//This is the actor that implements the additional behavior.
//I actually wanted to extend BetterActor. It was not possible.

class MyActor extends Actor {

  def receive = {
    case i: Int =>
      println(s"Yay!!! Got $i")
  }
}
</code>```

Here are two alternative ways how I can create an instance of the sub-actor, which combines both the common and the additional behaviors:

```<code>//1.

val myBetterActor = system.actorOf(Props(new MyActor with BetterActor), "myBetterActor")

//2.

class MyBetterActor extends MyActor with BetterActor
val myBetterActor = system.actorOf(Props[MyBetterActor], "myBetterActor")
</code>```

Finally, I may invoke the sub-actor by:

```<code>myBetterActor ! 2
myBetterActor ! "a"
</code>```

Problems with my implementation:

When I create an instance of the sub-actor, only then I can mix in the base-actor, either directly (1) or by defining a new class that mixes in the base-actor.

Like I said before, I would prefer to mix in the base-actor when I define the sub-actor. Not when I try to create an instance of the sub-actor.

P.S. It's fascinating that the designers of this framework did not see it necessary to make this common requirement easy to accomplish.

答:
i suppose as long as you're not trying to override behavior with BetterActor, you could try something like this:

```<code>trait BetterActor extends Actor {
  override def unhandled(message: Any): Unit = message match {
    case e: CommonMessage => println("COMMON!")
    case e => super.unhandled(e)
  }
}

class MyActor extends BetterActor {
  override def receive = {
    case i: Int => println(s"Yay!!! Got $i")
  }
}
</code>```

Title: Scala: How to extend an Akka actor?

Body:
I wrote an Akka base-actor that can handle some common messages. I want to reuse this basic behavior in a sub-actor, by extending the base-actor (not by composition of the base-actor).

I have seen several approaches in previous questions. They are all valid but also may be improved:

How extend behaviour of super actor in akka

and

How do I best share behavior among Akka actors?

To make the implementation cleaner, I am trying to achieve the following:

When defining the sub-actor, I try to extend only the base-actor (not both Actor and sub-actor). However, I was not able to force the compiler to do this.

I also try to not rename the receive partial function, because it is a kind of convention.

Here is a sample of my implementation:

//This is the base-actor that implements the common behavior

trait BetterActor extends Actor {

  abstract override def receive = {
    super.receive orElse { case _ => println("Missing pattern!") }
  }
}

//This is the actor that implements the additional behavior.
//I actually wanted to extend BetterActor. It was not possible.

class MyActor extends Actor {

  def receive = {
    case i: Int =>
      println(s"Yay!!! Got $i")
  }
}

Here are two alternative ways how I can create an instance of the sub-actor, which combines both the common and the additional behaviors:

//1.

val myBetterActor = system.actorOf(Props(new MyActor with BetterActor), "myBetterActor")

//2.

class MyBetterActor extends MyActor with BetterActor
val myBetterActor = system.actorOf(Props[MyBetterActor], "myBetterActor")

Finally, I may invoke the sub-actor by:

myBetterActor ! 2
myBetterActor ! "a"

Problems with my implementation:

When I create an instance of the sub-actor, only then I can mix in the base-actor, either directly (1) or by defining a new class that mixes in the base-actor.

Like I said before, I would prefer to mix in the base-actor when I define the sub-actor. Not when I try to create an instance of the sub-actor.

P.S. It's fascinating that the designers of this framework did not see it necessary to make this common requirement easy to accomplish.

Body:
i suppose as long as you're not trying to override behavior with BetterActor, you could try something like this:

trait BetterActor extends Actor {
  override def unhandled(message: Any): Unit = message match {
    case e: CommonMessage => println("COMMON!")
    case e => super.unhandled(e)
  }
}

class MyActor extends BetterActor {
  override def receive = {
    case i: Int => println(s"Yay!!! Got $i")
  }
}


问:
Keeping state in airflow pipeline
I am new to airflow, I feel like I may be missing some convention or concept.

Context: I have files being periodically dropped into an S3 bucket. My pipeline will need to grab new files and process them.

Basically: How do I avoid re-processing?

It is not unlikely that some part of the pipeline will change in the future and I will want to re-process files. But on a day-to-day basis I don't want to re-process files. Additionally there will likely be other pipelines in the future which would need to start from the beginning and process all the files for a different output.

I have plenty of scrappy ways of preserving state (a local json file, or checking the existence of output files) - but I'm wondering if there's a convention in airflow. What makes the most sense to me at the moment is to re-use the postgres that exists for airflow (maybe bad form?), add another DB and start creating tables in there where I list input files if they have been processed for workflow X, workflow Y, etc.

How would you do this?

答:
Here is how I have solved a similar problem with a 4 task DAG.

Write a custom S3Sensor that extends BaseSensorOperator.
This sensor uses the boto3 library, watches a specific folder in the bucket.
If any files are put into this bucket, it posts all the file paths to Xcom.

This Sensor is the first operator in the dag.

The next operator in the dag is a python operator that reads the list from the previous tasks Xcom.
It moves all the files to another folder in the same bucket, again listing the new paths to Xcom.

The next operator processes each of these files.

The next operator triggers this same dag again (so we start back at the custom s3 file sensor because this dag retriggers itself).

The dag needs to not have any schedule_interval, and needs to be triggered once manually. It will then watch the bucket until forever, or until something breaks.

Title: Keeping state in airflow pipeline


问:
ffmpeg FPS information mismatch with the video
I have a bunch of videos with some statistics of what is happening inside a video. One such piece of information is given in terms of time of the video in seconds up to one decimal point.

To get the FPS of a video, I am using ffmpeg -i

But when I manually compute one particular frame's time using given FPS, it does not match.

For example, ffmpeg outputs FPS = 30.

I look at the video statistics, the frame at the 156.8 = 2.368 has to be
4704'th frame. I open the video using 'skvideo', read all the frames, and view the 4704'th frame. It is some frame around time 2.12?. I checked multiple such instances in multiple videos and this is a common behavior.

I do not understand why this is so and how can I get around the problem?

As such I am not bounded by ffmpeg. Skvideo is being used to read the videos. I tried opencv, as of now it does not work with VideoCapture, and reinstalling it is costly for me time wise. But I guess 'opencv/skvideo' should not matter, one can count the frames manually as well.

So, in the solution, I am looking out for -

Given timestamps of inside of a video, how can I find a frame of that particular time location?

In case someone might have already worked on this, this is related to THUMOS dataset. I am on Ubuntu 16.04

EDIT_1

Actually I can be more specific as it is a publicly available data. The time bounds are of an important activity. For example, in a video, when does basketball dunk occurs? It is given in pairs - [start end]. Some videos have multiple activities, some have only one.

Here is a sample video, and following are the activity times.

```<code>[[  16.5, 20.8],
[  26.6, 32.2],
[  34.8, 42.1],
[  47.8, 50.0],
[  58.1, 62.9],
[  65.6, 67.2],
[  68.5, 74.0],
[  76.4, 78.3],
[  78.7, 79.8],
[  80.8, 82.1],
[  85.0, 87.3],
[  90.1, 91.4],
[  98.5, 100.3]]
</code>```

I also tried checking manually, 32.87 FPS "almost" works for few videos but not for all. and almost means it is off by ~ 10 frames. This is a huge difference for my task, and I need exact frame.

Also, there has to be some way, because it can be visually observed with multiple video players that times in the dataset are correct.

答:
A simple frame accurate way to get a frame at a given timestamp using ffmpeg is use the ffmpeg seek -ss option.
If that's what you are looking for, you can find the description here - https://trac.ffmpeg.org/wiki/Seeking

Body:
I have a bunch of videos with some statistics of what is happening inside a video. One such piece of information is given in terms of time of the video in seconds up to one decimal point.

To get the FPS of a video, I am using ffmpeg -i

But when I manually compute one particular frame's time using given FPS, it does not match.

For example, ffmpeg outputs FPS = 30.

I look at the video statistics, the frame at the 156.8 = 2.368 has to be
4704'th frame. I open the video using 'skvideo', read all the frames, and view the 4704'th frame. It is some frame around time 2.12?. I checked multiple such instances in multiple videos and this is a common behavior.

I do not understand why this is so and how can I get around the problem?

As such I am not bounded by ffmpeg. Skvideo is being used to read the videos. I tried opencv, as of now it does not work with VideoCapture, and reinstalling it is costly for me time wise. But I guess 'opencv/skvideo' should not matter, one can count the frames manually as well.

So, in the solution, I am looking out for -

Given timestamps of inside of a video, how can I find a frame of that particular time location?

In case someone might have already worked on this, this is related to THUMOS dataset. I am on Ubuntu 16.04

EDIT_1

Actually I can be more specific as it is a publicly available data. The time bounds are of an important activity. For example, in a video, when does basketball dunk occurs? It is given in pairs - [start end]. Some videos have multiple activities, some have only one.

Here is a sample video, and following are the activity times.

[[  16.5, 20.8],
[  26.6, 32.2],
[  34.8, 42.1],
[  47.8, 50.0],
[  58.1, 62.9],
[  65.6, 67.2],
[  68.5, 74.0],
[  76.4, 78.3],
[  78.7, 79.8],
[  80.8, 82.1],
[  85.0, 87.3],
[  90.1, 91.4],
[  98.5, 100.3]]

I also tried checking manually, 32.87 FPS "almost" works for few videos but not for all. and almost means it is off by ~ 10 frames. This is a huge difference for my task, and I need exact frame.

Also, there has to be some way, because it can be visually observed with multiple video players that times in the dataset are correct.


问:
OpenOffice HTML & CSS : JODConverter
I'm using JODConverter in my application to convert a HTML file with basic CSS 2 to a PDF file.

When I convert the file, the pdf is just a mess, And when I tried to view in openOffice directly it was a mess also.

This is the file generated :

and this is what I have in my chrome browser :

As you see there's a big difference.

This is my code :

```<code><div style="padding : 5% 25% 0% 10%; diplay : inline-block; ">
  <div>
    <span style="color : green; float : left; "><b>MyCompany - MyConsultant</b></span>
    <hr style="width : 100%; border-top: dotted 1px; " />
  </div>
  <div>
    <div>
      <div style="float : left;">Number of days</div>
      <div style="float : right ">20,5</div>
      <hr style="width : 100%; border-top: dotted 1px; " />
    </div>
    <div>
      <div style="float : left ">Your number</div>
      <div style="float : right ">520,00€</div>
      <hr style="width : 100%; border-top: dotted 1px; " />
    </div>
    <div>
      <div style="float : left ">Total HT</div>
      <div style="float : right ">10 660,00€</div>
      <hr style="width : 100%; border-top: dotted 1px; " />
    </div>
    <div>
      <div style="float : left ">TVA [20%]</div>
      <div style="float : right ">2 132,00€</div>
    </div>
    <div>
      <hr style="width : 100%; border-top: dotted 3px;font-weight : bold;" />
      <div style="float : left;font-weight : bold;">TOTAL TTC</div>
      <div style="float : right;font-weight : bold;">12 792,00€</div>
    </div>
  </div>
</code>```

And if anyone got another solution, then I wanted :), thx

答:
LibreOffice/Apache OpenOffice is a great application, but in this case it is not the right tool for the job.  There are many applications that render HTML more effectively.

This worked for me, adapted from https://superuser.com/questions/592974/how-to-print-to-save-as-pdf-from-a-command-line-with-chrome-or-chromium.

```<code>./chrome.exe --headless --disable-gpu --print-to-pdf=file1.pdf http://www.example.com/
</code>```

EDIT:

To make this call in Java, see How to execute system commands (linux/bsd) using Java.

Title: OpenOffice HTML & CSS : JODConverter

Body:
I'm using JODConverter in my application to convert a HTML file with basic CSS 2 to a PDF file.

When I convert the file, the pdf is just a mess, And when I tried to view in openOffice directly it was a mess also.

This is the file generated :

and this is what I have in my chrome browser :

As you see there's a big difference.

This is my code :

    MyCompany - MyConsultant

Number of days

20,5

Your number

520,00€

Total HT

10 660,00€

TVA [20%]

2 132,00€

TOTAL TTC

12 792,00€

And if anyone got another solution, then I wanted :), thx

Body:
LibreOffice/Apache OpenOffice is a great application, but in this case it is not the right tool for the job.  There are many applications that render HTML more effectively.

This worked for me, adapted from https://superuser.com/questions/592974/how-to-print-to-save-as-pdf-from-a-command-line-with-chrome-or-chromium.

./chrome.exe --headless --disable-gpu --print-to-pdf=file1.pdf http://www.example.com/

EDIT:

To make this call in Java, see How to execute system commands (linux/bsd) using Java.


问:
Inner join two tables and join count from a third table
I have 2 main tables - posts and users, and a third table that stores a user's favourited post as a row. I need to do a query on a post that is joined with the user data, and also whether or not the current user has favourited post (lookup in the user_favs table).

Ultimately I want to return something like the following to the client:

```<code>{
    post_id: '...',
    title: '...',
    user_id: '...',
    username: '...',
    isFavourited: isFaved > 0 ? true : false
}
</code>```

Is this possible to do with 1 select query?

```<code>CREATE TABLE posts (
    post_id    uuid,
    title      text
    author_id  uuid
);

CREATE TABLE users (
    user_id   uuid,
    username  text
);

CREATE TABLE user_favs (
    user_id     uuid REFERENCES users ON DELETE CASCADE,
    post_id  uuid REFERENCES posts ON DELETE CASCADE
);
</code>```

My query looks like:

```<code>SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,

    count(f.*) as isfaved
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN user_favs f
ON f.user_id = p.author_id AND f.post_id = '1234'
</code>```

and I've also tried:

```<code>SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN
    (SELECT count(*) FROM user_favs
) f ON f.user_id = p.author_id AND f.post_id = '1234'
</code>```

EDIT: Just to clarify what I'm hoping to accomplish: I'm fetching a post, returning respective author of that post, and then also checking if the post is favorited by the requesting user.

答:
You're probably better off bringing the select count(*) up into your SELECT clause similar to </p>

```<code>SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,
(SELECT count(*) FROM user_favs f where f.user_id = p.author_id AND f.post_id = p.post_id)
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
</code>```

Body:
I have 2 main tables - posts and users, and a third table that stores a user's favourited post as a row. I need to do a query on a post that is joined with the user data, and also whether or not the current user has favourited post (lookup in the user_favs table).

Ultimately I want to return something like the following to the client:

{
    post_id: '...',
    title: '...',
    user_id: '...',
    username: '...',
    isFavourited: isFaved > 0 ? true : false
}

Is this possible to do with 1 select query?

CREATE TABLE posts (
    post_id    uuid,
    title      text
    author_id  uuid
);

CREATE TABLE users (
    user_id   uuid,
    username  text
);

CREATE TABLE user_favs (
    user_id     uuid REFERENCES users ON DELETE CASCADE,
    post_id  uuid REFERENCES posts ON DELETE CASCADE
);

My query looks like:

SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,

    count(f.*) as isfaved
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN user_favs f
ON f.user_id = p.author_id AND f.post_id = '1234'

and I've also tried:

SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'
LEFT JOIN
    (SELECT count(*) FROM user_favs
) f ON f.user_id = p.author_id AND f.post_id = '1234'

EDIT: Just to clarify what I'm hoping to accomplish: I'm fetching a post, returning respective author of that post, and then also checking if the post is favorited by the requesting user.

Body:
You're probably better off bringing the select count(*) up into your SELECT clause similar to

SELECT
    p.post_id,
    p.title,
    u.user_id,
    u.username,
(SELECT count(*) FROM user_favs f where f.user_id = p.author_id AND f.post_id = p.post_id)
FROM posts p
JOIN users u
ON p.author_id = u.user_id AND p.post_id = '1234'


问:
CSS Grab All Class Name Except For Last
I want to grab all the class name ('my-class') and change it's color to red EXCEPT for the last one

Apparently I've been googling and there's no such thing as :last-of-class or whatever. I'm having trouble trying to find a work around without using JS.

div1 and div2 are both dynamic! If div2 doesn't exist, then div1 should have the first p element red and the second not.

Please note I left a 'p' tag at the top because I don't want that being part of my selector. I just need the 'my-class' specifically.

or is there a selector I can write to grab all "p"s inside of my-container which include nested P's

```<code><p>Some text</p>
<div class="my-container">
  <div class="div1">
    <p class="my-class"></p>
    <p class="my-class"></p>
  </div>
  <div class="div2">
    <p class="my-class"></p>
    <p class="my-class"></p>
    <p class="my-class"></p>
    <p class="my-class"></p>   <!-- This tag should not be red-->
  </div>
</div>
</code>```

I can also use sass so feel free to include that in if need be.

答:
You can use the workaround below.

use div:last-child . that will select the last div in the container and if there is only one, it will select it and so...the last p from the last div will be of other color ( in this example )

.my-container div p.my-class {
color:red;
}
.my-container div:last-child p.my-class:last-child {
color:blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Some text</p>
<div class="my-container">
  <div class="div1">
    <p class="my-class">a</p>
    <p class="my-class">a</p>
  </div>
  <div class="div2">
    <p class="my-class">a</p>
    <p class="my-class">a</p>
    <p class="my-class">a</p>
    <p class="my-class">b</p>   <!-- This tag should not be red-->
  </div>
</div></code>```

Title: CSS Grab All Class Name Except For Last

Body:
I want to grab all the class name ('my-class') and change it's color to red EXCEPT for the last one

Apparently I've been googling and there's no such thing as :last-of-class or whatever. I'm having trouble trying to find a work around without using JS.

div1 and div2 are both dynamic! If div2 doesn't exist, then div1 should have the first p element red and the second not.

Please note I left a 'p' tag at the top because I don't want that being part of my selector. I just need the 'my-class' specifically.

or is there a selector I can write to grab all "p"s inside of my-container which include nested P's

Some text

I can also use sass so feel free to include that in if need be.

Body:
You can use the workaround below.

use div:last-child . that will select the last div in the container and if there is only one, it will select it and so...the last p from the last div will be of other color ( in this example )

.my-container div p.my-class {
color:red;
}
.my-container div:last-child p.my-class:last-child {
color:blue;
}

<p>Some text</p>
<div class="my-container">
  <div class="div1">
    <p class="my-class">a</p>
    <p class="my-class">a</p>
  </div>
  <div class="div2">
    <p class="my-class">a</p>
    <p class="my-class">a</p>
    <p class="my-class">a</p>
    <p class="my-class">b</p>   <!-- This tag should not be red-->
  </div>
</div>


问:
AJAX DELETE request in asp.net MVC
I've always thought that a delete request should be done using type: "DELETE". However, it seems not work in .NET

```<code>$.ajax({
    type: "GET",
    url: '/TestController/DeleteTest?id=10',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        if (data) {
            // Works
        }
    },
    error: function (erro) {
        console.debug(erro);
    }
});
</code>```

Controller:

```<code>[HttpGet]
    public JsonResult DeleteTest()
    {
        int id= Int32.Parse(Request["id"]);

        var myTableTest= db.myTable.Where(x => x.id== id).FirstOrDefault();
        db.mytable.Remove(myTableTest);

        db.SaveChanges();
        return Json(true, JsonRequestBehavior.AllowGet);
    }
</code>```

This code works fine! But if I change to type: "DELETE", it won't work anymore. So, does asp.net have HttpDelete?

Thanks

答:
In asp.net-mvc we have HttpGet and HttpPost and in this particular case you should be using HttpPost not HttpGet, otherwise anybody can hit the url with query string to request deletion of any record, and another thing is to not use magic strings for generating urls instead of that use Url.Action method which would take care to generate the correct urls for you.

Change your jquery ajax call to use post:

```<code>$.ajax({
    type: "POST",
    url: '@Url.Action("DeleteTest","Test")',
    data: {id:10},
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
</code>```

and then in your action use HttpPost and add parameter to your action method signatures like:

```<code>[HttpPost]
public JsonResult DeleteTest(int id)
{

    var myTableTest= db.myTable.Where(x => x.id== id).FirstOrDefault();
    db.mytable.Remove(myTableTest);

    db.SaveChanges();
    return Json(true, JsonRequestBehavior.AllowGet);
}
</code>```

Hope it helps.

Title: AJAX DELETE request in asp.net MVC

Body:
I've always thought that a delete request should be done using type: "DELETE". However, it seems not work in .NET

$.ajax({
    type: "GET",
    url: '/TestController/DeleteTest?id=10',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        if (data) {
            // Works
        }
    },
    error: function (erro) {
        console.debug(erro);
    }
});

Controller:

[HttpGet]
    public JsonResult DeleteTest()
    {
        int id= Int32.Parse(Request["id"]);

        var myTableTest= db.myTable.Where(x => x.id== id).FirstOrDefault();
        db.mytable.Remove(myTableTest);

        db.SaveChanges();
        return Json(true, JsonRequestBehavior.AllowGet);
    }

This code works fine! But if I change to type: "DELETE", it won't work anymore. So, does asp.net have HttpDelete?

Thanks

Body:
In asp.net-mvc we have HttpGet and HttpPost and in this particular case you should be using HttpPost not HttpGet, otherwise anybody can hit the url with query string to request deletion of any record, and another thing is to not use magic strings for generating urls instead of that use Url.Action method which would take care to generate the correct urls for you.

Change your jquery ajax call to use post:

$.ajax({
    type: "POST",
    url: '@Url.Action("DeleteTest","Test")',
    data: {id:10},
    contentType: 'application/json; charset=utf-8',
    success: function (data) {

and then in your action use HttpPost and add parameter to your action method signatures like:

[HttpPost]
public JsonResult DeleteTest(int id)
{

    var myTableTest= db.myTable.Where(x => x.id== id).FirstOrDefault();
    db.mytable.Remove(myTableTest);

    db.SaveChanges();
    return Json(true, JsonRequestBehavior.AllowGet);
}

Hope it helps.


问:
Import only Last column of Excel through SSIS
I have an excel file which I receive daily. The number of columns in that file is not specific. My requirement is just to load the last column in my table through SSIS. How will I be able to identify last used column dynamically?</p>

答:
Solution Overview

Use a Script Task to:

Get the last column index

Use the following function to convert the index to Column Letter (ex: 1 -> A)

```<code>Private Function GetExcelColumnName(columnNumber As Integer) As String
    Dim dividend As Integer = columnNumber
    Dim columnName As String = String.Empty
    Dim modulo As Integer

    While dividend > 0
       modulo = (dividend - 1) Mod 26
       columnName = Convert.ToChar(65 + modulo).ToString() & columnName
       dividend = CInt((dividend - modulo) / 26)
   End While

   Return columnName
End Function
</code>```

Build the SQL Command that read only the last column

Choose this query as Excel Source

Detailed Solution

This answer is assuming that the Sheet Name is Sheet1, and the programming language used is VB.Net

First create an SSIS variable of type string (i.e. @[User::strQuery])

Add another variable that contains the Excel File Path (i.e. @[User::ExcelFilePath])

Add A Script Task, and select @[User::strQuery] as ReadWrite Variable, and @[User::ExcelFilePath] as ReadOnly Variable (in the script task window)

Set the Script Language to VB.Net and in the script editor window write the following script:

Note: you have to imports System.Data.OleDb

    m_strExcelPath = Dts.Variables.Item("ExcelFilePath").Value.ToString

    Dim strSheetname As String = String.Empty
    Dim intLastColumn As Integer = 0

    m_strExcelConnectionString = Me.BuildConnectionString()
    Try

        Using OleDBCon As New OleDbConnection(m_strExcelConnectionString)

            If OleDBCon.State <> ConnectionState.Open Then
                OleDBCon.Open()
            End If

            'Get all WorkSheets
            m_dtschemaTable = OleDBCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
                                                               New Object() {Nothing, Nothing, Nothing, "TABLE"})

            'Loop over work sheet to get the first one (the excel may contains temporary sheets or deleted ones

            For Each schRow As DataRow In m_dtschemaTable.Rows
                strSheetname = schRow("TABLE_NAME").ToString

                If Not strSheetname.EndsWith("_") AndAlso strSheetname.EndsWith("$") Then

                    Using cmd As New OleDbCommand("SELECT * FROM [" & strSheetname & "]", OleDBCon)

                        Dim dtTable As New DataTable("Table1")

                        cmd.CommandType = CommandType.Text

                        Using daGetDataFromSheet As New OleDbDataAdapter(cmd)

                            daGetDataFromSheet.Fill(dtTable)

                        End Using
                    'Get the last Column Index
                    intLastColumn =  dtTable.Columns.Count

                    End Using

                    'when the first correct sheet is found there is no need to check others
                    Exit For

                End If
            Next

            OleDBCon.Close()

        End Using

    Catch ex As Exception
        Throw New Exception(ex.Message, ex)
    End Try

    Dim strColumnname as String = GetExcelColumnName(intLastColumn)
    Dts.Variables.Item("strQuery").Value = "SELECT * FROM [" & strSheetname & strColumnname & ":" & strColumnname & "]"

    Dts.TaskResult = ScriptResults.Success
End Sub

Private Function GetExcelColumnName(columnNumber As Integer) As String
    Dim dividend As Integer = columnNumber
    Dim columnName As String = String.Empty
    Dim modulo As Integer

    While dividend > 0
       modulo = (dividend - 1) Mod 26
       columnName = Convert.ToChar(65 + modulo).ToString() & columnName
       dividend = CInt((dividend - modulo) / 26)
   End While

   Return columnName
End Function
```

Then you have to add an Excel connection manager, and choose the excel file that you want to import (just select a sample to define the metadata for the first time only)

Assign a default value of Select * from [Sheet1$] to the variable @[User::strQuery]

In the Data Flow Task add an Excel Source, choose SQL Command from variable, and select  @[User::strQuery]

Set the DataFlow Task Delay Validation property to True

Add other components to DataFlow Task

References

Importing excel files having variable headers

Converting Numbers to Excel Letter Column vb.net

Body:
Solution Overview

Use a Script Task to:

Get the last column index

Use the following function to convert the index to Column Letter (ex: 1 -> A)

Private Function GetExcelColumnName(columnNumber As Integer) As String
    Dim dividend As Integer = columnNumber
    Dim columnName As String = String.Empty
    Dim modulo As Integer

    While dividend > 0
       modulo = (dividend - 1) Mod 26
       columnName = Convert.ToChar(65 + modulo).ToString() & columnName
       dividend = CInt((dividend - modulo) / 26)
   End While

   Return columnName
End Function

Build the SQL Command that read only the last column

Choose this query as Excel Source

Detailed Solution

This answer is assuming that the Sheet Name is Sheet1, and the programming language used is VB.Net

First create an SSIS variable of type string (i.e. @[User::strQuery])

Add another variable that contains the Excel File Path (i.e. @[User::ExcelFilePath])

Add A Script Task, and select @[User::strQuery] as ReadWrite Variable, and @[User::ExcelFilePath] as ReadOnly Variable (in the script task window)

Set the Script Language to VB.Net and in the script editor window write the following script:

Note: you have to imports System.Data.OleDb

    m_strExcelPath = Dts.Variables.Item("ExcelFilePath").Value.ToString

    Dim strSheetname As String = String.Empty
    Dim intLastColumn As Integer = 0

    m_strExcelConnectionString = Me.BuildConnectionString()
    Try

        Using OleDBCon As New OleDbConnection(m_strExcelConnectionString)

            If OleDBCon.State <> ConnectionState.Open Then
                OleDBCon.Open()
            End If

            'Get all WorkSheets
            m_dtschemaTable = OleDBCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
                                                               New Object() {Nothing, Nothing, Nothing, "TABLE"})

            'Loop over work sheet to get the first one (the excel may contains temporary sheets or deleted ones

            For Each schRow As DataRow In m_dtschemaTable.Rows
                strSheetname = schRow("TABLE_NAME").ToString

                If Not strSheetname.EndsWith("_") AndAlso strSheetname.EndsWith("$") Then

                    Using cmd As New OleDbCommand("SELECT * FROM [" & strSheetname & "]", OleDBCon)

                        Dim dtTable As New DataTable("Table1")

                        cmd.CommandType = CommandType.Text

                        Using daGetDataFromSheet As New OleDbDataAdapter(cmd)

                            daGetDataFromSheet.Fill(dtTable)

                        End Using
                    'Get the last Column Index
                    intLastColumn =  dtTable.Columns.Count

                    End Using

                    'when the first correct sheet is found there is no need to check others
                    Exit For

                End If
            Next

            OleDBCon.Close()

        End Using

    Catch ex As Exception
        Throw New Exception(ex.Message, ex)
    End Try

    Dim strColumnname as String = GetExcelColumnName(intLastColumn)
    Dts.Variables.Item("strQuery").Value = "SELECT * FROM [" & strSheetname & strColumnname & ":" & strColumnname & "]"

    Dts.TaskResult = ScriptResults.Success
End Sub

Private Function GetExcelColumnName(columnNumber As Integer) As String
    Dim dividend As Integer = columnNumber
    Dim columnName As String = String.Empty
    Dim modulo As Integer

    While dividend > 0
       modulo = (dividend - 1) Mod 26
       columnName = Convert.ToChar(65 + modulo).ToString() & columnName
       dividend = CInt((dividend - modulo) / 26)
   End While

   Return columnName
End Function

Then you have to add an Excel connection manager, and choose the excel file that you want to import (just select a sample to define the metadata for the first time only)

Assign a default value of Select * from [Sheet1$] to the variable @[User::strQuery]

In the Data Flow Task add an Excel Source, choose SQL Command from variable, and select  @[User::strQuery]

Set the DataFlow Task Delay Validation property to True

Add other components to DataFlow Task

References

Importing excel files having variable headers

Converting Numbers to Excel Letter Column vb.net


问:
java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view
my app crashes when trying to display server message and I think the problem could be with my getView(). below is the registerActivity were the crash occurs and my activity_register.xml

```<code>import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.fastchat.helper.SQLiteHandler;
import com.fastchat.helper.SessionManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RegisterActivity extends Activity {

private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
private ProgressBar progress;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    inputFullName = (EditText) findViewById(R.id.name);
    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(true);

    /*
    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
   if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(RegisterActivity.this,
                SearchableActivity.class);
        startActivity(intent);
        finish();

    }
*/
    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerProcess(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Link to Login Screen
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(i);
            finish();
        }
    });

}

 private void registerProcess(String name,String email,String password){

    String tag_string_req = "req_register";
    //pDialog = new AlertDialog.Builder(getActivity());
    pDialog.setMessage("please wait");
    pDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setName(name);
    user.setEmail(email);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.REGISTER_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        private View view;

        public View getView() {
            return view;

        }

        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();

           if(resp !=null)//tried to check if resp is null but its not

//crash occurs here
            Snackbar.make(getView(),resp.getMessage(), Snackbar.LENGTH_LONG).show();
            pDialog.dismiss();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

           // progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG, "failed");
            Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            pDialog.dismiss();

        }
    });
}
</code>```

activity_register.xml

```<code>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/bg_register"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:id="@+id/chat">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="20dp" >

    <ImageView
        android:layout_width="389dp"
        android:layout_height="72dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="24dp"
        android:src="@drawable/logo"
        tools:ignore="ContentDescription" />

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_name"
        android:padding="10dp"
        android:singleLine="true"
        android:inputType="textCapWords"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_password"
        android:inputType="textPassword"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <!-- Login Button -->

    <Button
        android:id="@+id/btnRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:background="#ea4c88"
        android:text="register"
        android:textColor="@color/white" />

    <!-- Link to Login Screen -->

    <Button
        android:id="@+id/btnLinkToLoginScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:background="@null"
        android:text="already a member? login"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15dp" />
</LinearLayout>
</code>```

below is logcat message

```<code> java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
                                                              at android.support.design.widget.Snackbar.make(Snackbar.java:137)
                                                              at com.chat.RegisterActivity$3.onResponse(RegisterActivity.java:143)
                                                              at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
</code>```

答:
To solve this Exception, you can do this.

```<code> private void CrearSnackBar(String mensaje)
{
    Snackbar snackbar = Snackbar
            .make(constraintLayout, mensaje, Snackbar.LENGTH_LONG)
            .setActionTextColor(getResources().getColor(R.color.colorWhite))
            .setAction(getResources().getString(R.string.label_settings), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent myIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    startActivity(myIntent);
                }
            });

    View sbView = snackbar.getView();
    snackbar.show();
}
</code>```

Where constraintLayout is the layout parent where I want to show the message, declare the layout:

ConstraintLayout constraintLayout;

And find it by Id.

constraintLayout = findViewById(R.id.cl_layout);

The function works for me. I hope it could help you.

Body:
my app crashes when trying to display server message and I think the problem could be with my getView(). below is the registerActivity were the crash occurs and my activity_register.xml

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.fastchat.helper.SQLiteHandler;
import com.fastchat.helper.SessionManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RegisterActivity extends Activity {

private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
private ProgressBar progress;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    inputFullName = (EditText) findViewById(R.id.name);
    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(true);

    /*
    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
   if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(RegisterActivity.this,
                SearchableActivity.class);
        startActivity(intent);
        finish();

    }
*/
    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerProcess(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Link to Login Screen
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(i);
            finish();
        }
    });

}

 private void registerProcess(String name,String email,String password){

    String tag_string_req = "req_register";
    //pDialog = new AlertDialog.Builder(getActivity());
    pDialog.setMessage("please wait");
    pDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setName(name);
    user.setEmail(email);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.REGISTER_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        private View view;

        public View getView() {
            return view;

        }

        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();

           if(resp !=null)//tried to check if resp is null but its not

//crash occurs here
            Snackbar.make(getView(),resp.getMessage(), Snackbar.LENGTH_LONG).show();
            pDialog.dismiss();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

           // progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG, "failed");
            Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            pDialog.dismiss();

        }
    });
}

activity_register.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/bg_register"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:id="@+id/chat">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="20dp" >

    <ImageView
        android:layout_width="389dp"
        android:layout_height="72dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="24dp"
        android:src="@drawable/logo"
        tools:ignore="ContentDescription" />

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_name"
        android:padding="10dp"
        android:singleLine="true"
        android:inputType="textCapWords"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_password"
        android:inputType="textPassword"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <Button
        android:id="@+id/btnRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:background="#ea4c88"
        android:text="register"
        android:textColor="@color/white" />

    <Button
        android:id="@+id/btnLinkToLoginScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:background="@null"
        android:text="already a member? login"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15dp" />
</LinearLayout>

below is logcat message

 java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
                                                              at android.support.design.widget.Snackbar.make(Snackbar.java:137)
                                                              at com.chat.RegisterActivity$3.onResponse(RegisterActivity.java:143)
                                                              at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                              at android.os.Handler.dispatchMessage(Handler.java:95)

Body:
To solve this Exception, you can do this.

 private void CrearSnackBar(String mensaje)
{
    Snackbar snackbar = Snackbar
            .make(constraintLayout, mensaje, Snackbar.LENGTH_LONG)
            .setActionTextColor(getResources().getColor(R.color.colorWhite))
            .setAction(getResources().getString(R.string.label_settings), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent myIntent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    startActivity(myIntent);
                }
            });

    View sbView = snackbar.getView();
    snackbar.show();
}

Where constraintLayout is the layout parent where I want to show the message, declare the layout:

ConstraintLayout constraintLayout;

And find it by Id.

constraintLayout = findViewById(R.id.cl_layout);

The function works for me. I hope it could help you.


问:
Angular custom validator @input
Is there a way in Angular2 to pass an object to custom validator using @input or any other technique?
I have to pass an existing object to the custom validator from the parent class where the validator is included? How to achieve it</p>

答:
You can create an async validator in a child, but you'd need a validator that can take an arbitrary value and not an AbstractControl. You can pass this value from a parent and then give it to such a validator as an argument.

Take a look at this code sample: https://github.com/Farata/angulartypescript/tree/master/chapter7/form-samples/src/app/async-validator

In the app component in ngOnInit(), I just pass a text to a validator function checkWorkAuthorizationV2(ssnValue). I could have passed any object if needed.

Title: Angular custom validator @input