问:
Covariance/contravariance and the relationship with consumers/producers
I have read this article on covariance/contravariance: http://julien.richard-foy.fr/blog/2013/02/21/be-friend-with-covariance-and-contravariance/

The examples are very clear. However, I am struggling to understand the conclusions drawn at the end:

If you look at the definitions of Run[+A] and Vet[-A] you may notice
  that the type Aappears only in the return type of methods of Run[+A]
  and only in the parameters of methods of Vet[-A]. More generally a
  type that produces values of type A can be made covariant on A (as you
  did with Run[+A]), and a type that consumes values of type A can be
  made contravariant on A (as you did with Vet[-A]).

From the above paragraph you can deduce that types that only have
  getters can be covariant (in other words, immutable data types can be
  covariant, and that’s the case for most of the data types of Scala’s
  standard library), but mutable data types are necessarily invariant
  (they have getters and setters, so they both produce and consume
  values).

Producers: If something produces type A, I can imagine some reference variable of type A being set to an object of type A or any subtypes of A, but not supertypes, so it's appropriate that it can be covariant.

Consumers: If something consumes type A, I guess that means type A may be used as parameters in methods. I'm not clear what relationship this has to covariance or contravariance.

It seems from the examples that specifying a type as covariant/contravariant affects how it can be consumed by other functions but not sure how it affects the classes themselves.

答:
It seems from the examples that specifying a type as covariant/contravariant affects how it can be consumed by other functions but not sure how it affects the classes themselves.

It is right that the article focused on the consequences of variance for users of a class, not for implementers of a class.

The article shows that covariant and contravariant types give more freedom to users (because a function that accepts a Run[Mammal] effectively accepts a Run[Giraffe] or a Run[Zebra]). For implementors, the perspective is dual: covariant and contravariant types give them more constraints.

These constraints are that covariant types can not occur in contravariant positions and vice versa.

Consider for instance this Producer type definition:

trait Producer[+A] {
  def produce(): A
}
```

<p>The type parameter <code>A</code> is covariant. Therefore we can only use it in covariant positions (such as a method return type), but we can not use it in contravariant position (such as a method parameter):</p>

<pre class="lang-scala prettyprint-override"><code>trait Producer[+A] {
  def produce(): A
  def consume(a: A): Unit // (does not compile because A is in contravariant position)
}
</code>```

Why is it illegal to do so? What could go wrong if this code compiled? Well, consider the following scenario. First, get some Producer[Zebra]:

val zebraProducer: Producer[Zebra] = …
```

<p>Then upcast it to a <code>Producer[Mammal]</code> (which is legal, because we claimed the type parameter to be covariant):</p>

<pre class="lang-scala prettyprint-override"><code>val mammalProducer: Producer[Mammal] = zebraProducer
</code>```

Finally, feed it with a Giraffe (which is legal too because the consume method a Producer[Mammal] accepts a Mammal, and a Giraffe is a Mammal):

mammalProducer.consume(new Giraffe)
```

<p>However, if you remember well, the <code>mammalProducer</code> was actually a <code>zebraProducer</code>, so its <code>consume</code> implementation actually only accepts a <code>Zebra</code>, not a <code>Giraffe</code>! So, in practice, if it was allowed to use covariant types in contravariant positions (like I did with the <code>consume</code> method), the type system would be unsound. We can construct a similar scenario (leading to an absurdity) if we pretend that a class with a contravariant type parameter can also have a method where it is in covariant position (see at the end for the code).</p>

<p>(Note that several programming languages, e.g. Java or TypeScript, have such unsound type systems.)</p>

<p>In practice, in Scala if we want to use a covariant type parameter in contravariant position, we have to use the following trick:</p>

<pre class="lang-scala prettyprint-override"><code>trait Producer[+A] {
  def produce(): A
  def consume[B >: A](b: B): Unit
}
</code>```

In that case, a Producer[Zebra] would not expect to get an actual Zebra passed in the consume method (but any value of a type B, lower-bounded by Zebra), so it would be legal to pass a Giraffe, which is a Mammal, which is a super-type of Zebra.

Appendix: similar scenario for contravariance

Consider the following class Consumer[-A], which has a contravariant type parameter A:

trait Consumer[-A] {
  def consume(a: A): Unit
}
```

<p>Suppose that the type system allowed us to define a method where <code>A</code> is in covariant position:</p>

<pre class="lang-scala prettyprint-override"><code>trait Consumer[-A] {
  def consume(a: A): Unit
  def produce(): A // (does not actually compile because A is in covariant position)
}
</code>```

Now we can get an instance of Consumer[Mammal], upcast it to Consumer[Zebra] (because of contravariance) and call the produce method to get a Zebra:

val mammalConsumer: Consumer[Mammal] = …
val zebraConsumer: Consumer[Zebra] = mammalConsumer // legal, because we claimed `A` to be contravariant
val zebra: Zebra = zebraConsumer.produce()
```

However, our zebraConsumer is actually mammalConsumer, whose method produce can return any Mammal, not just Zebras. So, at the end, zebra might be initialized to some Mammal that is not a Zebra! In order to avoid such absurdities, the type system forbids us to define the produce method in the Consumer class.

Body:
It seems from the examples that specifying a type as covariant/contravariant affects how it can be consumed by other functions but not sure how it affects the classes themselves.

It is right that the article focused on the consequences of variance for users of a class, not for implementers of a class.

The article shows that covariant and contravariant types give more freedom to users (because a function that accepts a Run[Mammal] effectively accepts a Run[Giraffe] or a Run[Zebra]). For implementors, the perspective is dual: covariant and contravariant types give them more constraints.

These constraints are that covariant types can not occur in contravariant positions and vice versa.

Consider for instance this Producer type definition:

trait Producer[+A] {
  def produce(): A
}

The type parameter A is covariant. Therefore we can only use it in covariant positions (such as a method return type), but we can not use it in contravariant position (such as a method parameter):

trait Producer[+A] {
  def produce(): A
  def consume(a: A): Unit // (does not compile because A is in contravariant position)
}

Why is it illegal to do so? What could go wrong if this code compiled? Well, consider the following scenario. First, get some Producer[Zebra]:

val zebraProducer: Producer[Zebra] = …

Then upcast it to a Producer[Mammal] (which is legal, because we claimed the type parameter to be covariant):

val mammalProducer: Producer[Mammal] = zebraProducer

Finally, feed it with a Giraffe (which is legal too because the consume method a Producer[Mammal] accepts a Mammal, and a Giraffe is a Mammal):

mammalProducer.consume(new Giraffe)

However, if you remember well, the mammalProducer was actually a zebraProducer, so its consume implementation actually only accepts a Zebra, not a Giraffe! So, in practice, if it was allowed to use covariant types in contravariant positions (like I did with the consume method), the type system would be unsound. We can construct a similar scenario (leading to an absurdity) if we pretend that a class with a contravariant type parameter can also have a method where it is in covariant position (see at the end for the code).

(Note that several programming languages, e.g. Java or TypeScript, have such unsound type systems.)

In practice, in Scala if we want to use a covariant type parameter in contravariant position, we have to use the following trick:

trait Producer[+A] {
  def produce(): A
  def consume[B >: A](b: B): Unit
}

In that case, a Producer[Zebra] would not expect to get an actual Zebra passed in the consume method (but any value of a type B, lower-bounded by Zebra), so it would be legal to pass a Giraffe, which is a Mammal, which is a super-type of Zebra.

Appendix: similar scenario for contravariance

Consider the following class Consumer[-A], which has a contravariant type parameter A:

trait Consumer[-A] {
  def consume(a: A): Unit
}

Suppose that the type system allowed us to define a method where A is in covariant position:

trait Consumer[-A] {
  def consume(a: A): Unit
  def produce(): A // (does not actually compile because A is in covariant position)
}

Now we can get an instance of Consumer[Mammal], upcast it to Consumer[Zebra] (because of contravariance) and call the produce method to get a Zebra:

val mammalConsumer: Consumer[Mammal] = …
val zebraConsumer: Consumer[Zebra] = mammalConsumer // legal, because we claimed `A` to be contravariant
val zebra: Zebra = zebraConsumer.produce()

However, our zebraConsumer is actually mammalConsumer, whose method produce can return any Mammal, not just Zebras. So, at the end, zebra might be initialized to some Mammal that is not a Zebra! In order to avoid such absurdities, the type system forbids us to define the produce method in the Consumer class.


来源: stackexchange

问:
Laravel redirecting when accessing post route directly
I do a post request to a route calculate-cars and display an other view with some data I query based on the data I entered in the form I do the post request from, but I want to redirect to the homepage when someone access this route directly.

Unfortunately I keep getting this error:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException No message

my route:

Route::post('calculate-cars', 'CarsController@calculateCars');

I know I get this error because I access a post route directly but I try this in my controller method but I still get the same error:

```<code>if (!$request->isMethod('post')) {
    return redirect()->to('/');
}
</code>```

答:
I understand you are trying to redirect the user upon MethodNotAllowedHttpException

You can use Laravel's Exception Handler for this:

Open app/Exception/Handler.php and change render method to this:

```<code>public function render($request, Exception $exception)
{
    if ($exception instanceof ModelNotFoundException)
    {
        return \Redirect::to('/');
    }
    return parent::render($request, $exception);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I do a post request to a route calculate-cars and display an other view with some data I query based on the data I entered in the form I do the post request from, but I want to redirect to the homepage when someone access this route directly.

Unfortunately I keep getting this error:

Symfony \ Component \ HttpKernel \ Exception \
  MethodNotAllowedHttpException No message

my route:

Route::post('calculate-cars', 'CarsController@calculateCars');

I know I get this error because I access a post route directly but I try this in my controller method but I still get the same error:

if (!$request->isMethod('post')) {
    return redirect()->to('/');
}

Body:
I understand you are trying to redirect the user upon MethodNotAllowedHttpException

You can use Laravel's Exception Handler for this:

Open app/Exception/Handler.php and change render method to this:

public function render($request, Exception $exception)
{
    if ($exception instanceof ModelNotFoundException)
    {
        return \Redirect::to('/');
    }
    return parent::render($request, $exception);
}


问:
Convert large Excel files to CSV
In my app which takes data from heavy csv files and uploads it to dataabse, I needed to import data from excel files too. For this, I first used xlrd to convert excel files into csv, which worked great for small files but took a lot of time when converting large files. When I gave a file of 6 sheets with 1m rows each, I waited for 40 minutes before terminating the process because that was too long of a time to wait.

Currently I'm using openmyxl library to convert excel files to csv and this library is significantly faster than xlrd, especially in read-only mode, but, sadly, even the delay of 8-10 minutes for conversion of heavy files is too much.

Is there any time efficient solution in Python where I can convert large Excel files with multiple sheets without having to wait for minutes?

This is the code I'm currently using:

```<code>def convertExcelToCSV(excelFilePath, uploadFilePath):

lstCSVFilePaths = []

workbook = load_workbook(excelFilePath, read_only=True)

for worksheet_name in workbook.get_sheet_names():
    worksheet = workbook.get_sheet_by_name(name = worksheet_name)

    #skip sheet if empty
    if worksheet.rows == 0: continue

    objCSV = {}

    objCSV["fileName"] = worksheet_name + '.csv'
    objCSV["isGZip"] = False

    csvFilePath = uploadFilePath + "CSV Files/"

    #make directory for CSV files that will be made from Excel file
    if not os.path.exists(csvFilePath):
        os.makedirs(csvFilePath)

    fd, csvFilePath = tempfile.mkstemp(suffix=worksheet_name + ".csv", dir=csvFilePath)

    objCSV["filePath"] = csvFilePath

    with open(csvFilePath, 'w', newline="") as your_csv_file:
        wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
        for rownum in worksheet.rows:
            wr.writerow([cell.value for cell in rownum])

    your_csv_file.close()

    lstCSVFilePaths.append(objCSV)

return lstCSVFilePaths
</code>```

答: With read-only mode you should be able to read worksheets and write CSV in parallel. Other than this I don't think there is a lot that can be done: converting XML to Python is probably the bottleneck.</p>

Title: Convert large Excel files to CSV

Body:
In my app which takes data from heavy csv files and uploads it to dataabse, I needed to import data from excel files too. For this, I first used xlrd to convert excel files into csv, which worked great for small files but took a lot of time when converting large files. When I gave a file of 6 sheets with 1m rows each, I waited for 40 minutes before terminating the process because that was too long of a time to wait.

Currently I'm using openmyxl library to convert excel files to csv and this library is significantly faster than xlrd, especially in read-only mode, but, sadly, even the delay of 8-10 minutes for conversion of heavy files is too much.

Is there any time efficient solution in Python where I can convert large Excel files with multiple sheets without having to wait for minutes?

This is the code I'm currently using:

def convertExcelToCSV(excelFilePath, uploadFilePath):

lstCSVFilePaths = []

workbook = load_workbook(excelFilePath, read_only=True)

for worksheet_name in workbook.get_sheet_names():
    worksheet = workbook.get_sheet_by_name(name = worksheet_name)

    #skip sheet if empty
    if worksheet.rows == 0: continue

    objCSV = {}

    objCSV["fileName"] = worksheet_name + '.csv'
    objCSV["isGZip"] = False

    csvFilePath = uploadFilePath + "CSV Files/"

    #make directory for CSV files that will be made from Excel file
    if not os.path.exists(csvFilePath):
        os.makedirs(csvFilePath)

    fd, csvFilePath = tempfile.mkstemp(suffix=worksheet_name + ".csv", dir=csvFilePath)

    objCSV["filePath"] = csvFilePath

    with open(csvFilePath, 'w', newline="") as your_csv_file:
        wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)
        for rownum in worksheet.rows:
            wr.writerow([cell.value for cell in rownum])

    your_csv_file.close()

    lstCSVFilePaths.append(objCSV)

return lstCSVFilePaths


问:
Downloading Twitter corpus
I am working on a data mining system and one of the requirements is it being able to perform the analysis without the use of API. Is there a way to download the Twitter database (or a big part of it, at least) and work with it locally?</p>

答: APIs are the official way of getting Twitter data and they work really well so it is not comprehensible why you do not want to use APIs. The web scraping is a work around but not recommended, in addition you would like to get a big part of it, so I do not think you will be satisfied with it. You can also buy the data from Gnip. </p>

Title: Downloading Twitter corpus


问:
If there is a Instruction after onDestroy , will the Instruction be executed?
Here after on Destroy I print a Log statement , will the Log get shown as the app already gets destroyed and no Instruction can be executed after app gets destroyed .

```<code>    @Override
protected void onDestroy() {
    super.onDestroy();
    Log.v(TestActivity,"App is currntly getting destroyed")
}
</code>```

So will "App is currently getting destroyed" be printed?
If it won't be printed then how can I execute code in onDestroy Method?

答:
The answer to your question is, "It Depends".

The reference documentation says that onDestroy is not guaranteed to be called.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

So, yes, you message will be called unless Android destroys the process first.

Documentation also say that you must call through to the super classes implementation...

If you override this method you must call through to the superclass implementation.

...but it doesn't say what order the call should be made.  Because of that, I would look at Activiy source to see what it is doing.  Here is the (version de jour) source code for onDestroy from Google Source.

```<code>protected void onDestroy() {
    mCalled = true;
    // dismiss any dialogs we are managing.
    if (mManagedDialogs != null) {
        final int numDialogs = mManagedDialogs.size();
        for (int i = 0; i < numDialogs; i++) {
            final ManagedDialog md = mManagedDialogs.valueAt(i);
            if (md.mDialog.isShowing()) {
                md.mDialog.dismiss();
            }
        }
        mManagedDialogs = null;
    }
    // close any cursors we are managing.
    synchronized (mManagedCursors) {
        int numCursors = mManagedCursors.size();
        for (int i = 0; i < numCursors; i++) {
            ManagedCursor c = mManagedCursors.get(i);
            if (c != null) {
                c.mCursor.close();
            }
        }
        mManagedCursors.clear();
    }
    // Close any open search dialog
    if (mSearchManager != null) {
        mSearchManager.stopSearch();
    }
}
</code>```

Though this could change at any time, we can see that onDestroy in the super class will clean up resources (as documentation says).  So, does your implementation of onDestroy rely upon any of those resources?  That would dictate that your code should be called before super.onDestroy().  If not, then the order doesn't matter (except that your teacher has told you what order to use).

Body:
Here after on Destroy I print a Log statement , will the Log get shown as the app already gets destroyed and no Instruction can be executed after app gets destroyed .

    @Override
protected void onDestroy() {
    super.onDestroy();
    Log.v(TestActivity,"App is currntly getting destroyed")
}

So will "App is currently getting destroyed" be printed?
If it won't be printed then how can I execute code in onDestroy Method?

Body:
The answer to your question is, "It Depends".

The reference documentation says that onDestroy is not guaranteed to be called.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

So, yes, you message will be called unless Android destroys the process first.

Documentation also say that you must call through to the super classes implementation...

If you override this method you must call through to the superclass implementation.

...but it doesn't say what order the call should be made.  Because of that, I would look at Activiy source to see what it is doing.  Here is the (version de jour) source code for onDestroy from Google Source.

protected void onDestroy() {
    mCalled = true;
    // dismiss any dialogs we are managing.
    if (mManagedDialogs != null) {
        final int numDialogs = mManagedDialogs.size();
        for (int i = 0; i < numDialogs; i++) {
            final ManagedDialog md = mManagedDialogs.valueAt(i);
            if (md.mDialog.isShowing()) {
                md.mDialog.dismiss();
            }
        }
        mManagedDialogs = null;
    }
    // close any cursors we are managing.
    synchronized (mManagedCursors) {
        int numCursors = mManagedCursors.size();
        for (int i = 0; i < numCursors; i++) {
            ManagedCursor c = mManagedCursors.get(i);
            if (c != null) {
                c.mCursor.close();
            }
        }
        mManagedCursors.clear();
    }
    // Close any open search dialog
    if (mSearchManager != null) {
        mSearchManager.stopSearch();
    }
}

Though this could change at any time, we can see that onDestroy in the super class will clean up resources (as documentation says).  So, does your implementation of onDestroy rely upon any of those resources?  That would dictate that your code should be called before super.onDestroy().  If not, then the order doesn't matter (except that your teacher has told you what order to use).


问:
Overflow for astype(int) with big number
I have the following number in python:

```<code>import pandas
x = pandas.Series(1508770848527.423339843750000)
</code>```

When I'm using x.apply(np.floor) I'm getting 1508770848527.0 but when I'm applying x.astype(int) I'm getting -2147483648.

How can I prevent this overflow? I would like to have the number as an integer.

答:
Convert to int64:

```<code>print (x.astype('int64'))
0    1508770848527
dtype: int64
</code>```

Or like commented Willem Van Onsem:

```<code>print (x.astype(np.int64))
0    1508770848527
dtype: int64
</code>```

Body:
I have the following number in python:

import pandas
x = pandas.Series(1508770848527.423339843750000)

When I'm using x.apply(np.floor) I'm getting 1508770848527.0 but when I'm applying x.astype(int) I'm getting -2147483648.

How can I prevent this overflow? I would like to have the number as an integer.

Body:
Convert to int64:

print (x.astype('int64'))
0    1508770848527
dtype: int64

Or like commented Willem Van Onsem:

print (x.astype(np.int64))
0    1508770848527
dtype: int64


问:
The prop `loadingElement` is marked as required in `withScriptjs(withGoogleMap(Component))
I'm getting this error: "Failed prop type: The prop loadingElement is marked as required in withScriptjs(withGoogleMap(Component)), but its value is undefined.
    in withScriptjs(withGoogleMap(Component))"

My Map.js file:

```<code>import React, {Component} from "react";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from "react-google-maps";

const MapWithAMarker = withScriptjs(withGoogleMap(props =>
  <GoogleMap
    defaultZoom={8}
    defaultCenter={{ lat: -34.397, lng: 150.644 }}
  >
    <Marker
      position={{ lat: -34.397, lng: 150.644 }}
    />
  </GoogleMap>
));

<MapWithAMarker
  googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIdFegRbfOurYRvDN8oQNJRmpKgIj48ZY&libraries=geometry,drawing,places"
  loadingElement={<div style={{ height: `100%` }} />}
  containerElement={<div style={{ height: `100%` }} />}
  mapElement={<div style={{ height: `100%` }} />}
/>
export default MapWithAMarker;
</code>```

I'm importing this file in my other js file and putting

```<code><div style={{width:400, hight:300, background:"red"}}>
          <MapWithAMarker />
        </div>
</code>```

like this inside that js. And I'm getting the mentioned error.

答:
This is how I'm calling it in my current project and it works just fine. Maybe this points you into the right direction.</p>

```<code>const EmptyMap = compose(
    withProps({
      googleMapURL: "https://maps.googleapis.com/maps/api/js?key=APIKEY&v=3.exp&libraries=geometry,drawing,places",
      loadingElement: <div style={{ height: `100%` }} />,
      containerElement: <div style={{ height: `1000px`, display: 'none' }} />,
      mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap
  )((props) =>
        <GoogleMap
        defaultZoom={9}
        defaultCenter={{ lat: parseFloat(props.userLat), lng: parseFloat(props.userLng) }}
        >

        </GoogleMap>
);
</code>```

Body:
I'm getting this error: "Failed prop type: The prop loadingElement is marked as required in withScriptjs(withGoogleMap(Component)), but its value is undefined.
    in withScriptjs(withGoogleMap(Component))"

My Map.js file:

import React, {Component} from "react";
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from "react-google-maps";

const MapWithAMarker = withScriptjs(withGoogleMap(props =>
  <GoogleMap
    defaultZoom={8}
    defaultCenter={{ lat: -34.397, lng: 150.644 }}
  >
    <Marker
      position={{ lat: -34.397, lng: 150.644 }}
    />
  </GoogleMap>
));

<MapWithAMarker
  googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIdFegRbfOurYRvDN8oQNJRmpKgIj48ZY&libraries=geometry,drawing,places"
  loadingElement={<div style={{ height: `100%` }} />}
  containerElement={<div style={{ height: `100%` }} />}
  mapElement={<div style={{ height: `100%` }} />}
/>
export default MapWithAMarker;

I'm importing this file in my other js file and putting

          <MapWithAMarker />

like this inside that js. And I'm getting the mentioned error.

Body:
This is how I'm calling it in my current project and it works just fine. Maybe this points you into the right direction.

const EmptyMap = compose(
    withProps({
      googleMapURL: "https://maps.googleapis.com/maps/api/js?key=APIKEY&v=3.exp&libraries=geometry,drawing,places",
      loadingElement: <div style={{ height: `100%` }} />,
      containerElement: <div style={{ height: `1000px`, display: 'none' }} />,
      mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap
  )((props) =>
        <GoogleMap
        defaultZoom={9}
        defaultCenter={{ lat: parseFloat(props.userLat), lng: parseFloat(props.userLng) }}
        >

        </GoogleMap>
);


问:
RSpec error: 'but it does not respond to `include?`'
I am running the following rspec test

```<code>expect(City.first.city_openings('2014-05-01', '2014-05-05')).to include(@listing2,@listing3)
</code>```

I am getting this result

This is confusing to me because it seems that my result does in fact include the right values. But rspec says that my result "does not respond to include?" Any ideas on how to fix this? I don't see much about it anywhere.

答:
Your method city_openings return true and not a array.
TrueClass is not iterable with include? method.

See the documentation here

https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/include-matcher

https://relishapp.com/rspec/rspec-expectations/v/3-7/docs/built-in-matchers/match-matcher

Body:
I am running the following rspec test

expect(City.first.city_openings('2014-05-01', '2014-05-05')).to include(@listing2,@listing3)

I am getting this result

This is confusing to me because it seems that my result does in fact include the right values. But rspec says that my result "does not respond to include?" Any ideas on how to fix this? I don't see much about it anywhere.


问:
Excel VBA macro:
I want to split quarterly the dates from a year (with some colors).

Right now I have a macro for 2 years only, but I want to make it automatically for every year. (ex: with Red color: between date 01/01/YYYY-01/05/YYYY..... and so on)

This is what did:

```<code>Private Sub CheckBox1_Click()

    If CheckBox1.Value = True Then
    Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="01/01/2015", Formula2:="01/05/2015"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="30/04/2015", Formula2:="01/08/2015"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 7461287
        .TintAndShade = 0
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="31/07/2015", Formula2:="01/01/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 6750207
        .TintAndShade = 0
    End With

      Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="01/01/2016", Formula2:="01/05/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="30/04/2016", Formula2:="01/08/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 7461287
        .TintAndShade = 0
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="31/07/2016", Formula2:="01/01/2017"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 6750207
        .TintAndShade = 0
    End With
End Sub
</code>```

The result:
enter image description here

答:
Ahh - it that case you need this:</p>

```<code> Sub demo()
 Dim r As Range
 For Each r In ActiveSheet.UsedRange.Columns(1).Cells
      If IsDate(r) Then
          Select Case Month(r)
               Case 1 To 3
                   With r.Interior
                       .ThemeColor = xlThemeColorLight2
                       .TintAndShade = 0.799981688894314
                   End With
               Case 4 To 6
                    r.Interior.Color = 7461287
               Case 7 To 8
                   r.Interior.Color = 7461287
               Case 9 To 12
                   r.Interior.Color = 6750207
          End Select
        End If
 Next r
 End Sub
</code>```

Title: Excel VBA macro:

Body:
I want to split quarterly the dates from a year (with some colors).

Right now I have a macro for 2 years only, but I want to make it automatically for every year. (ex: with Red color: between date 01/01/YYYY-01/05/YYYY..... and so on)

This is what did:

Private Sub CheckBox1_Click()

    If CheckBox1.Value = True Then
    Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="01/01/2015", Formula2:="01/05/2015"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="30/04/2015", Formula2:="01/08/2015"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 7461287
        .TintAndShade = 0
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="31/07/2015", Formula2:="01/01/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 6750207
        .TintAndShade = 0
    End With

      Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="01/01/2016", Formula2:="01/05/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.799981688894314
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="30/04/2016", Formula2:="01/08/2016"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 7461287
        .TintAndShade = 0
    End With

     Rows("1:1").Select
    Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlBetween, _
        Formula1:="31/07/2016", Formula2:="01/01/2017"
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = 6750207
        .TintAndShade = 0
    End With
End Sub

The result:
enter image description here

Body:
Ahh - it that case you need this:

 Sub demo()
 Dim r As Range
 For Each r In ActiveSheet.UsedRange.Columns(1).Cells
      If IsDate(r) Then
          Select Case Month(r)
               Case 1 To 3
                   With r.Interior
                       .ThemeColor = xlThemeColorLight2
                       .TintAndShade = 0.799981688894314
                   End With
               Case 4 To 6
                    r.Interior.Color = 7461287
               Case 7 To 8
                   r.Interior.Color = 7461287
               Case 9 To 12
                   r.Interior.Color = 6750207
          End Select
        End If
 Next r
 End Sub


问:
Keycloak language support
I'm using keycloak 2.5.1 to securise my web application, and it works really fine.

It currently supports 4 languages : english, french, german and italian.

I have received a new requirement to support dutch and latvian.

I follow the procedure described on Keycloak documentation in the Internationalization section of the themes paragraph (here), but it doesn't work at all, I cannot add those languages in the admin console.

As soon as I understand, there was a ticket on that problem but it was solved.

But I also see on the web that there are lots of problems with that specific aspect in Keycloak.

Has anybody an idea on how to make it work or about a possible error in Keycloak documentation ?

Thank you,

Seb

答: I couldn't enable Dutch (nl) either in Keycloak version 3.2.1 (where it is supported out of the box), but that was solved by upgrading to the latest version (3.4.0).</p>

Title: Keycloak language support


问:
Angular2 Component variable being modified by multiple promises
I have a searchbox which is querying the server on keydown event, as long as the query string is longer then 2 characters. Code below is typescript and from my search component. entries.items is directly used in the template html for this component. The code is stripped down from other stuff focusing on the problem area.

```<code>public Search(query: string)
{
        if (query && query.length > 2)
        {
            var ref = this;
            ref.entries.items = [];

            this.SearchService.Search(query).then(response => {
                let list = JSON.parse(response._body).items;
                list.forEach(element => {
                    ref.entries.items.push(element.details);
                });
            });
        }
 }
</code>```

When the user keeps on typing to get the final work (ex: s - st - sta- stac - stack) we keep on querying and end up in a state where the items are modified multiple times and I'm seeing the same result appended multiple times (ex: if there's one result for stack - it's displayed for sta, stac and stack search queries) - so we're in a state of promises returning and simultaneously modifying the items. It kind of feels like I need a lock, but I'm guessing there's a better way of doing this. Any recommendations?

答:
How did you handle input changes?

You're using angular2, let's use rxjs approach.
In your sample you lack of importantest thing - switching to another stream. It means that if new value from input is received then other requests are ignored.

Here is tutorial: https://alligator.io/angular/real-time-search-angular-rxjs/
Or demo: https://embed.plnkr.co/giSBvwKpq04qfRBLDY8x/?show=preview

You need to create something like that:

```<code>Observable.fromEvent(input, 'keydown')
  .debounceTime(500)
  .switchMap(query => Observable.fromPromise(SearchService.Search(query)))
  .subscribe(console.log);
</code>```

Body:
I have a searchbox which is querying the server on keydown event, as long as the query string is longer then 2 characters. Code below is typescript and from my search component. entries.items is directly used in the template html for this component. The code is stripped down from other stuff focusing on the problem area.

public Search(query: string)
{
        if (query && query.length > 2)
        {
            var ref = this;
            ref.entries.items = [];

            this.SearchService.Search(query).then(response => {
                let list = JSON.parse(response._body).items;
                list.forEach(element => {
                    ref.entries.items.push(element.details);
                });
            });
        }
 }

When the user keeps on typing to get the final work (ex: s - st - sta- stac - stack) we keep on querying and end up in a state where the items are modified multiple times and I'm seeing the same result appended multiple times (ex: if there's one result for stack - it's displayed for sta, stac and stack search queries) - so we're in a state of promises returning and simultaneously modifying the items. It kind of feels like I need a lock, but I'm guessing there's a better way of doing this. Any recommendations?

Body:
How did you handle input changes?

You're using angular2, let's use rxjs approach.
In your sample you lack of importantest thing - switching to another stream. It means that if new value from input is received then other requests are ignored.

Here is tutorial: https://alligator.io/angular/real-time-search-angular-rxjs/
Or demo: https://embed.plnkr.co/giSBvwKpq04qfRBLDY8x/?show=preview

You need to create something like that:

Observable.fromEvent(input, 'keydown')
  .debounceTime(500)
  .switchMap(query => Observable.fromPromise(SearchService.Search(query)))
  .subscribe(console.log);


问:
Best continuous integration setup for multi-platform development
What is the best continuous integration setup for a Devleopment department that codes in multiple environments?

At my company we write some code in C# and some in Java, I've previously used CC.Net but I've never done CInt with Java.

I'm aware of Continuum and was recently told about Hudson, but I've never used either.

Would it be better to use two CInt services one for each platform or to use a single one for both?

答: You could simply use the Java version of CruiseControl and have two setups. </p>

OwnerDisplayName: Omar Kooheji

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Tigraine


问:
Custom Fonts with Support Library is not working on a real device
I have used custom font with Support Library API 26. I have created font-family using style and add style to my text view. I found that font is going to set in Preview during design, but not working in android real devices. Below is my code and I have also attached screenshot. Thanks in advance.

TextView:

```<code><TextView
    android:id="@+id/card_number_text"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="111 5235 5563 8845"
    android:gravity="left"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="8dp"
    style="@style/creditCardText"
    app:layout_constraintTop_toBottomOf="@+id/payableLayout"
    app:layout_constraintLeft_toLeftOf="@+id/payableLayout"
    app:layout_constraintHorizontal_bias="0.0" />
</code>```

Style.xml:

```<code><style name="creditCardText">
    <item name="android:textSize">@dimen/textSizeLarge</item>
    <item name="android:fontFamily">@font/font_roboto_medium</item>
    <item name="android:textColor">@color/color_card_number</item>
</style>
</code>```

Font Family:

```<code><font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
    android:fontStyle="normal"
    android:fontWeight="400"
    android:font="@font/roboto_medium" />
</code>```

build.gradle:

```<code>apply plugin: 'com.android.application'
buildscript {
    repositories {
    }
    dependencies {
   }
}

android {
    signingConfigs {
    }
   compileSdkVersion 26
   defaultConfig {
        applicationId "org.saifintex.skypaytrans"
        minSdkVersion 18
        targetSdkVersion 26
        vectorDrawables.useSupportLibrary = true
        versionCode 7
        multiDexEnabled true
        versionName "1.6"
        testInstrumentationRunner
        "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
   }

lintOptions {
    abortOnError false        // true by default
    checkAllWarnings false
    checkReleaseBuilds false
    ignoreWarnings true       // false by default
    quiet true                // false by default
}

repositories {
    maven { url "https://jitpack.io" }
}
dexOptions {
    javaMaxHeapSize "4g"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

    }
}
externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
}
productFlavors {
}
sourceSets {
    main {
        assets.srcDirs = ['src/main/assets', 'src/main/assets/']
        java.srcDirs = ['src/main/java', 'src/main/java/fonts']
    }
  }
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile "com.android.support:appcompat-v7:26.1.0"
compile "com.android.support:design:26.1.0"
compile "com.android.support:recyclerview-v7:26.1.0"
compile project(':tooltip')
compile project(':mylibrary')
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.j256.ormlite:ormlite-
android:${rootProject.ormliteAndroidVersion}"
compile "com.j256.ormlite:ormlite-core:${rootProject.ormliteCoreVersion}"
testCompile 'junit:junit:4.12'
compile 'com.afollestad.material-dialogs:core:0.9.4.2'
compile 'com.fasterxml.jackson.core:jackson-core:2.7.2'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.2'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.2'
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.android.volley:volley:1.0.0'
compile 'commons-codec:commons-codec:1.10'
compile 'com.android.support:design:26.1.0'
compile 'com.squareup.picasso:picasso:2.4.0'
compile 'com.google.firebase:firebase-messaging:11.0.1'
compile 'com.google.firebase:firebase-core:11.0.1'
compile 'com.android.support:cardview-v7:26.1.0'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.wang.avi:library:2.1.3'
compile 'com.github.ayalma:ExpandableRecyclerView:0.2.0'
compile 'com.github.deano2390:MaterialShowcaseView:1.1.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-crash:11.0.1'
compile 'com.google.firebase:firebase-auth:11.0.1'
compile 'com.google.android.gms:play-services-analytics:11.0.1'
compile 'com.alimuzaffar.lib:pinentryedittext:1.3.1'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
testCompile 'junit:junit:4.12'
}

configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex") &&
        !requested.name.startsWith("crash")) {
            details.useVersion '25.3.1'
        }
    }
}
}

apply plugin: 'com.google.gms.google-services'
</code>```

Font resource dir:

Design preview: Here font is working

Android Device Screenshot: Here font is not working

答:
Requirement

1) assets folder which has sub folder "/fonts"

2) require custom fonts ".ttf" files in /fonts folder.

3) enum

4) attrs.xml file

5) java class

6) Usage

1)
create assets folder in

```<code>src/main/assets
</code>```

2)
add custom fonts in

```<code>src/main/assets/fonts/
</code>```

3) enum

```<code>import android.annotation.SuppressLint;
import android.content.Context;

@SuppressLint("StaticFieldLeak")
public enum Fonts {

OpenSans_Bold("OpenSans-Bold.ttf", 0),
OpenSans_BoldItalic("OpenSans-BoldItalic.ttf", 1),
OpenSans_CondBold("OpenSans-CondBold.ttf", 2),
OpenSans_CondLight("OpenSans-CondLight.ttf", 3),
OpenSans_CondLightItalic("OpenSans-CondLightItalic.ttf", 4),
OpenSans_ExtraBold("OpenSans-ExtraBold.ttf", 5),
OpenSans_ExtraBoldItalic("OpenSans-ExtraBoldItalic.ttf", 6),
OpenSans_Italic("OpenSans-Italic.ttf", 7),
OpenSans_Light("OpenSans-Light.ttf", 8),
OpenSans_LightItalic("OpenSans-LightItalic.ttf", 9),
OpenSans_Regular("OpenSans-Regular.ttf", 10),
OpenSans_Semibold("OpenSans-Semibold.ttf", 11),
OpenSans_SemiboldItalic("OpenSans-SemiboldItalic.ttf", 12),

AudioWide_Regular("Audiowide_Regular.ttf", 13);

String stringValue;
int value;
Context context;

Fonts(Context context) {
    this.context = context;
}

Fonts(String toString, int value) {
    stringValue = toString;
    this.value = value;
}

@Override
public String toString() {
    return "fonts/" + stringValue;
}

}
</code>```

4)
attrs.xml file

create attrs.xml in res/values folder

```<code><resources>
<declare-styleable name="FontTextView">

    <attr name="customFont" format="enum">
        <enum name="OpenSans_Bold" value="0" />
        <enum name="OpenSans_BoldItalic" value="1" />
        <enum name="OpenSans_CondBold" value="2" />
        <enum name="OpenSans_CondLight" value="3" />
        <enum name="OpenSans_CondLightItalic" value="4" />
        <enum name="OpenSans_ExtraBold" value="5" />
        <enum name="OpenSans_ExtraBoldItalic" value="6" />
        <enum name="OpenSans_Italic" value="7" />
        <enum name="OpenSans_Light" value="8" />
        <enum name="OpenSans_LightItalic" value="9" />
        <enum name="OpenSans_Regular" value="10" />
        <enum name="OpenSans_Semibold" value="11" />
        <enum name="OpenSans_SemiboldItalic" value="12" />
        <enum name="Audiowide_Regular" value="13" />

    </attr>

</declare-styleable>
</code>```

5)
FontTextView.java

```<code>import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import com.example.Fonts;
import com.example.R;

@SuppressLint("AppCompatCustomView")
public class FontTextView extends TextView {

public FontTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context, attrs);
}

public FontTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context, attrs);
}

public FontTextView(Context context) {
    super(context);
}

private void init(Context context, AttributeSet attrs) {

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.FontTextView, 0, 0);

    String fontText = a.getString(R.styleable.FontTextView_customFont);

    if (fontText != null) {
        switch (fontText) {
            case "0":
                fontText = Fonts.OpenSans_Bold.toString();
                break;
            case "1":
                fontText = Fonts.OpenSans_BoldItalic.toString();
                break;
            case "2":
                fontText = Fonts.OpenSans_CondBold.toString();
                break;
            case "3":
                fontText = Fonts.OpenSans_CondLight.toString();
                break;
            case "4":
                fontText = Fonts.OpenSans_CondLightItalic.toString();
                break;
            case "5":
                fontText = Fonts.OpenSans_ExtraBold.toString();
                break;
            case "6":
                fontText = Fonts.OpenSans_ExtraBoldItalic.toString();
                break;
            case "7":
                fontText = Fonts.OpenSans_Italic.toString();
                break;
            case "8":
                fontText = Fonts.OpenSans_Light.toString();
                break;
            case "9":
                fontText = Fonts.OpenSans_LightItalic.toString();
                break;
            case "10":
                fontText = Fonts.OpenSans_Regular.toString();
                break;
            case "11":
                fontText = Fonts.OpenSans_Semibold.toString();
                break;
            case "13":
                fontText = Fonts.AudioWide_Regular.toString();
                break;
            case "12":
                fontText = Fonts.OpenSans_SemiboldItalic.toString();
                break;
            default:
                fontText = Fonts.OpenSans_Regular.toString();
                break;
        }

        Log.e("String", fontText);
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), fontText);

        setTypeface(tf);
    }
    a.recycle();
}

}
</code>```

6)
Usage

```<code>    <com.example.FontTextView
         android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10sp"
        android:text="this is custom font"
        android:textSize="20sp"
        app:customFont="OpenSans_Semibold" />
</code>```

add below namespace to the top parents Layout of xml file
    xmlns:app="http://schemas.android.com/apk/res-auto"

reference by :

```<code>"Android Custom TypeFace fontFamily "
</code>```

click here

with this, you can easily add any font in android.

Body:
I have used custom font with Support Library API 26. I have created font-family using style and add style to my text view. I found that font is going to set in Preview during design, but not working in android real devices. Below is my code and I have also attached screenshot. Thanks in advance.

TextView:

<TextView
    android:id="@+id/card_number_text"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="111 5235 5563 8845"
    android:gravity="left"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="8dp"
    style="@style/creditCardText"
    app:layout_constraintTop_toBottomOf="@+id/payableLayout"
    app:layout_constraintLeft_toLeftOf="@+id/payableLayout"
    app:layout_constraintHorizontal_bias="0.0" />

Style.xml:

Font Family:

build.gradle:

apply plugin: 'com.android.application'
buildscript {
    repositories {
    }
    dependencies {
   }
}

android {
    signingConfigs {
    }
   compileSdkVersion 26
   defaultConfig {
        applicationId "org.saifintex.skypaytrans"
        minSdkVersion 18
        targetSdkVersion 26
        vectorDrawables.useSupportLibrary = true
        versionCode 7
        multiDexEnabled true
        versionName "1.6"
        testInstrumentationRunner
        "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
   }

lintOptions {
    abortOnError false        // true by default
    checkAllWarnings false
    checkReleaseBuilds false
    ignoreWarnings true       // false by default
    quiet true                // false by default
}

repositories {
    maven { url "https://jitpack.io" }
}
dexOptions {
    javaMaxHeapSize "4g"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

    }
}
externalNativeBuild {
    cmake {
        path "CMakeLists.txt"
    }
}
packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
}
productFlavors {
}
sourceSets {
    main {
        assets.srcDirs = ['src/main/assets', 'src/main/assets/']
        java.srcDirs = ['src/main/java', 'src/main/java/fonts']
    }
  }
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile "com.android.support:appcompat-v7:26.1.0"
compile "com.android.support:design:26.1.0"
compile "com.android.support:recyclerview-v7:26.1.0"
compile project(':tooltip')
compile project(':mylibrary')
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.j256.ormlite:ormlite-
android:${rootProject.ormliteAndroidVersion}"
compile "com.j256.ormlite:ormlite-core:${rootProject.ormliteCoreVersion}"
testCompile 'junit:junit:4.12'
compile 'com.afollestad.material-dialogs:core:0.9.4.2'
compile 'com.fasterxml.jackson.core:jackson-core:2.7.2'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.2'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.2'
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.android.volley:volley:1.0.0'
compile 'commons-codec:commons-codec:1.10'
compile 'com.android.support:design:26.1.0'
compile 'com.squareup.picasso:picasso:2.4.0'
compile 'com.google.firebase:firebase-messaging:11.0.1'
compile 'com.google.firebase:firebase-core:11.0.1'
compile 'com.android.support:cardview-v7:26.1.0'
compile 'com.android.support:support-v4:26.1.0'
compile 'com.wang.avi:library:2.1.3'
compile 'com.github.ayalma:ExpandableRecyclerView:0.2.0'
compile 'com.github.deano2390:MaterialShowcaseView:1.1.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-crash:11.0.1'
compile 'com.google.firebase:firebase-auth:11.0.1'
compile 'com.google.android.gms:play-services-analytics:11.0.1'
compile 'com.alimuzaffar.lib:pinentryedittext:1.3.1'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
testCompile 'junit:junit:4.12'
}

configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex") &&
        !requested.name.startsWith("crash")) {
            details.useVersion '25.3.1'
        }
    }
}
}

apply plugin: 'com.google.gms.google-services'

Font resource dir:

Design preview: Here font is working

Android Device Screenshot: Here font is not working

Body:
Requirement

1) assets folder which has sub folder "/fonts"

2) require custom fonts ".ttf" files in /fonts folder.

3) enum

4) attrs.xml file

5) java class

6) Usage

1)
create assets folder in

src/main/assets

2)
add custom fonts in

src/main/assets/fonts/

3) enum

import android.annotation.SuppressLint;
import android.content.Context;

@SuppressLint("StaticFieldLeak")
public enum Fonts {

OpenSans_Bold("OpenSans-Bold.ttf", 0),
OpenSans_BoldItalic("OpenSans-BoldItalic.ttf", 1),
OpenSans_CondBold("OpenSans-CondBold.ttf", 2),
OpenSans_CondLight("OpenSans-CondLight.ttf", 3),
OpenSans_CondLightItalic("OpenSans-CondLightItalic.ttf", 4),
OpenSans_ExtraBold("OpenSans-ExtraBold.ttf", 5),
OpenSans_ExtraBoldItalic("OpenSans-ExtraBoldItalic.ttf", 6),
OpenSans_Italic("OpenSans-Italic.ttf", 7),
OpenSans_Light("OpenSans-Light.ttf", 8),
OpenSans_LightItalic("OpenSans-LightItalic.ttf", 9),
OpenSans_Regular("OpenSans-Regular.ttf", 10),
OpenSans_Semibold("OpenSans-Semibold.ttf", 11),
OpenSans_SemiboldItalic("OpenSans-SemiboldItalic.ttf", 12),

AudioWide_Regular("Audiowide_Regular.ttf", 13);

String stringValue;
int value;
Context context;

Fonts(Context context) {
    this.context = context;
}

Fonts(String toString, int value) {
    stringValue = toString;
    this.value = value;
}

@Override
public String toString() {
    return "fonts/" + stringValue;
}

}

4)
attrs.xml file

create attrs.xml in res/values folder

<resources>
<declare-styleable name="FontTextView">

    <attr name="customFont" format="enum">
        <enum name="OpenSans_Bold" value="0" />
        <enum name="OpenSans_BoldItalic" value="1" />
        <enum name="OpenSans_CondBold" value="2" />
        <enum name="OpenSans_CondLight" value="3" />
        <enum name="OpenSans_CondLightItalic" value="4" />
        <enum name="OpenSans_ExtraBold" value="5" />
        <enum name="OpenSans_ExtraBoldItalic" value="6" />
        <enum name="OpenSans_Italic" value="7" />
        <enum name="OpenSans_Light" value="8" />
        <enum name="OpenSans_LightItalic" value="9" />
        <enum name="OpenSans_Regular" value="10" />
        <enum name="OpenSans_Semibold" value="11" />
        <enum name="OpenSans_SemiboldItalic" value="12" />
        <enum name="Audiowide_Regular" value="13" />

    </attr>

</declare-styleable>

5)
FontTextView.java

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import com.example.Fonts;
import com.example.R;

@SuppressLint("AppCompatCustomView")
public class FontTextView extends TextView {

public FontTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init(context, attrs);
}

public FontTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context, attrs);
}

public FontTextView(Context context) {
    super(context);
}

private void init(Context context, AttributeSet attrs) {

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.FontTextView, 0, 0);

    String fontText = a.getString(R.styleable.FontTextView_customFont);

    if (fontText != null) {
        switch (fontText) {
            case "0":
                fontText = Fonts.OpenSans_Bold.toString();
                break;
            case "1":
                fontText = Fonts.OpenSans_BoldItalic.toString();
                break;
            case "2":
                fontText = Fonts.OpenSans_CondBold.toString();
                break;
            case "3":
                fontText = Fonts.OpenSans_CondLight.toString();
                break;
            case "4":
                fontText = Fonts.OpenSans_CondLightItalic.toString();
                break;
            case "5":
                fontText = Fonts.OpenSans_ExtraBold.toString();
                break;
            case "6":
                fontText = Fonts.OpenSans_ExtraBoldItalic.toString();
                break;
            case "7":
                fontText = Fonts.OpenSans_Italic.toString();
                break;
            case "8":
                fontText = Fonts.OpenSans_Light.toString();
                break;
            case "9":
                fontText = Fonts.OpenSans_LightItalic.toString();
                break;
            case "10":
                fontText = Fonts.OpenSans_Regular.toString();
                break;
            case "11":
                fontText = Fonts.OpenSans_Semibold.toString();
                break;
            case "13":
                fontText = Fonts.AudioWide_Regular.toString();
                break;
            case "12":
                fontText = Fonts.OpenSans_SemiboldItalic.toString();
                break;
            default:
                fontText = Fonts.OpenSans_Regular.toString();
                break;
        }

        Log.e("String", fontText);
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), fontText);

        setTypeface(tf);
    }
    a.recycle();
}

}

6)
Usage

    <com.example.FontTextView
         android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10sp"
        android:text="this is custom font"
        android:textSize="20sp"
        app:customFont="OpenSans_Semibold" />

add below namespace to the top parents Layout of xml file
    xmlns:app="http://schemas.android.com/apk/res-auto"

reference by :

"Android Custom TypeFace fontFamily "

click here

with this, you can easily add any font in android.


问:
How to apply foreach loop in dynamic json in javascript?
Before few days i get one static json to implement in my code from jsfiddle and did some changes to create dynamic json from it. jsfiddle from which i got code

Now My code is working.but i want some changes in it.Below is my current code and image that data i got from mysql with json.

```<code>$(document).ready(function() {
    var data = [];
    $.ajax({
        url: "<?php echo base_url('responsible/get_pay_slips'); ?>",
        datatype: 'json',
        success: function(response) {
            response = $.parseJSON(response);
            x = 0;
            $.each(response, function(i, value) {

                console.log(value.PAY_YEAR, value.PAY_MONTH);

                var data1 = [];
                data[x++] = {
                    text: value.PAY_YEAR,
                    data: {},
                    children: [{
                        text: value.PAY_MONTH,
                        data: {
                            price: 0.1,
                            quantity: 20
                        }
                    }, ],
                    'state': {
                        'opened': false
                    }
                };
            });

            console.log(data);

            // load jstree
            $("div#jstree").jstree({
                plugins: ["table", "dnd", "contextmenu", "sort"],
                core: {
                    data: data
                },
                // configure tree table
                table: {
                    columns: [{
                            width: 500,
                            header: "YEAR"
                        },
                        {
                            width: 300,
                            value: "ACTION",
                            header: "ACTION",
                            format: function(v) {
                                if (v) {
                                    return 'Print | Save'
                                }
                            }
                        },

                    ],
                    resizable: true,
                    draggable: true,
                    contextmenu: true,

                }
            });
        }
    });

});
</code>```

Current flow of data:

flow that i actully want:

So, How can we create PAY_MONTH of same PAY_YEAR in single tree.
i want only one parent PAY_YEAR and within it his all childerns PAY_MONTH.

I am using codeigniter.

My model:

```<code>public function json_get_slips()

    {
      $empid ='34';
      $where = "where EMPLOYEE_ID='".$empid."' ";
      $query = $this->db->query("select PAY_MONTH,PAY_YEAR from india_salary_slip_details ".$where." group by pay_month order by pay_year");
      return $query->result_array();
    }
</code>```

My controller:

```<code>public function get_pay_slips()
  {
    $data = array();
    $data=$this->pay_slips->json_get_slips();
    echo json_encode($data);
  }
</code>```

I dont know much about jquery and here i want to create dynamic data with it.I am hopeless.please help me with the same.

答:
Use this query to fetch month your query will show only single month</p>

```<code>                  SELECT CASE
                  WHEN salary_amt IS NULL THEN 0 ELSE salary_amt
                  END as salary_amt
                  FROM
                  (
                      SELECT 1 AS MONTH
                       UNION SELECT 2 AS MONTH
                       UNION SELECT 3 AS MONTH
                       UNION SELECT 4 AS MONTH
                       UNION SELECT 5 AS MONTH
                       UNION SELECT 6 AS MONTH
                       UNION SELECT 7 AS MONTH
                       UNION SELECT 8 AS MONTH
                       UNION SELECT 9 AS MONTH
                       UNION SELECT 10 AS MONTH
                       UNION SELECT 11 AS MONTH
                       UNION SELECT 12 AS MONTH
                  ) as meses
                LEFT JOIN salaryData e ON meses.MONTH = MONTH(STR_TO_DATE(SALARY_DATE,'%d-%b-%y')) GROUP BY meses.MONTH
</code>```

Body:
Before few days i get one static json to implement in my code from jsfiddle and did some changes to create dynamic json from it. jsfiddle from which i got code

Now My code is working.but i want some changes in it.Below is my current code and image that data i got from mysql with json.

$(document).ready(function() {
    var data = [];
    $.ajax({
        url: "<?php echo base_url('responsible/get_pay_slips'); ?>",
        datatype: 'json',
        success: function(response) {
            response = $.parseJSON(response);
            x = 0;
            $.each(response, function(i, value) {

                console.log(value.PAY_YEAR, value.PAY_MONTH);

                var data1 = [];
                data[x++] = {
                    text: value.PAY_YEAR,
                    data: {},
                    children: [{
                        text: value.PAY_MONTH,
                        data: {
                            price: 0.1,
                            quantity: 20
                        }
                    }, ],
                    'state': {
                        'opened': false
                    }
                };
            });

            console.log(data);

            // load jstree
            $("div#jstree").jstree({
                plugins: ["table", "dnd", "contextmenu", "sort"],
                core: {
                    data: data
                },
                // configure tree table
                table: {
                    columns: [{
                            width: 500,
                            header: "YEAR"
                        },
                        {
                            width: 300,
                            value: "ACTION",
                            header: "ACTION",
                            format: function(v) {
                                if (v) {
                                    return 'Print | Save'
                                }
                            }
                        },

                    ],
                    resizable: true,
                    draggable: true,
                    contextmenu: true,

                }
            });
        }
    });

});

Current flow of data:

flow that i actully want:

So, How can we create PAY_MONTH of same PAY_YEAR in single tree.
i want only one parent PAY_YEAR and within it his all childerns PAY_MONTH.

I am using codeigniter.

My model:

public function json_get_slips()

    {
      $empid ='34';
      $where = "where EMPLOYEE_ID='".$empid."' ";
      $query = $this->db->query("select PAY_MONTH,PAY_YEAR from india_salary_slip_details ".$where." group by pay_month order by pay_year");
      return $query->result_array();
    }

My controller:

public function get_pay_slips()
  {
    $data = array();
    $data=$this->pay_slips->json_get_slips();
    echo json_encode($data);
  }

I dont know much about jquery and here i want to create dynamic data with it.I am hopeless.please help me with the same.

Body:
Use this query to fetch month your query will show only single month

                  SELECT CASE
                  WHEN salary_amt IS NULL THEN 0 ELSE salary_amt
                  END as salary_amt
                  FROM
                  (
                      SELECT 1 AS MONTH
                       UNION SELECT 2 AS MONTH
                       UNION SELECT 3 AS MONTH
                       UNION SELECT 4 AS MONTH
                       UNION SELECT 5 AS MONTH
                       UNION SELECT 6 AS MONTH
                       UNION SELECT 7 AS MONTH
                       UNION SELECT 8 AS MONTH
                       UNION SELECT 9 AS MONTH
                       UNION SELECT 10 AS MONTH
                       UNION SELECT 11 AS MONTH
                       UNION SELECT 12 AS MONTH
                  ) as meses
                LEFT JOIN salaryData e ON meses.MONTH = MONTH(STR_TO_DATE(SALARY_DATE,'%d-%b-%y')) GROUP BY meses.MONTH


问:
What is stored in variable cols in : var $cols = $('.sortdivs').on('click',function(){...});
```<code>var $cols = $('.sortdivs').on('click',function(){…});
</code>```

I know that the function will run when any element with sortdivs class is clicked.
I dont know what is being stored in variable cols and how it can be used.
I tried printing variable cols and i got 'object Object' as the output.Thanks in advance.

答:
The return value from .on is simply the collection that it was called on, for chaining purposes.

$cols, therefore, is the jQuery object containing a list of elements matched by $('.sortdivs') at the time of exection (NB: not at the time of click).

[object Object] is the string representation of any object. Try to inspect the object in another manner, for instance by using console.log($cols) to be able to get more information of just the output of a simple toString().

Body:
var $cols = $('.sortdivs').on('click',function(){…});

I know that the function will run when any element with sortdivs class is clicked.
I dont know what is being stored in variable cols and how it can be used.
I tried printing variable cols and i got 'object Object' as the output.Thanks in advance.


问:
Are URLs (not domains) suitable for OpenID 2.0 identities?
I have previously used OpenID 2.0 identities and delegation [1] in the context of indieweb use-cases, where there is an assumption that each user controls a domain. So an identity would look like https://example.com

Can an OpenID 2.0 identity take the form of a URL, rather than just a domain? For example, both https://example.com/alice and https://example.com/bob would be:

valid, independent identities

could each delegate to a separate identity provider

[1] Not OpenID Connect, which does not support delegation

答:
User-supplied identifiers must be normalized. If the input gets treated as HTTP(S) URL:

Use http if no scheme is specified

Strip off the fragment (including the #)

Follow redirects

Normalize the destination URL according to RFC 3986

Appendix A.1. gives some normalization examples: the inputs example.com and http://example.com would become http://example.com/.

So an identifier can’t be just a domain, it has to be a URL. And there is no relevant difference between the URLs https://example.com/ and https://example.com/foo. This means it’s perfectly fine to provide multiple identities under the same host/domain.


问:
What does exactly mean by 'Line feeds' in HTML and PHP? How do they are added in HTML and PHP code?
I was reading PHP Manual and I come across following text paragraph :

Line feeds have little meaning in HTML, however it is still a good
  idea to make your HTML look nice and clean by putting line feeds in. A
  linefeed that follows immediately after a closing ?> will be removed
  by PHP. This can be extremely useful when you are putting in many
  blocks of PHP or include files containing PHP that aren't supposed to
  output anything. At the same time it can be a bit confusing. You can
  put a space after the closing ?> to force a space and a line feed to
  be output, or you can put an explicit line feed in the last echo/print
  from within your PHP block.

I've following questions related to the text from above paragraph :

What does exactly mean by 'Line feeds' in HTML?

How to add them to the HTML code as well as PHP code and make visible in a web browser? What HTML entities/tags/characters are used to achieve this?

Is the meaning of 'Line feed' same in case of HTML and PHP? If no, what's the difference in meaning in both the contexts?

Why the PHP manual is saying in first line of paragraph itself that? What does PHP Manual want to say by the below sentence?

"Line feeds have little meaning in HTML"

How can it be useful to remove a linefeed that follows immediately after a closing tag ?> when someone is putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything?

Please someone clear my above mentioned doubts by giving answer in simple, lucid and easy to understand language. If someone could accompany the answer by suitable working code examples it would be of great help to me in understanding the concept more clearly.

Thank You.

答:
'Lines feed' exactly means a 'New line' both in Html and Php, only the syntax is different.

In case of Html tag, you can use
 or
 tag for a Lines feed. Basically, this tag shows a new line in the output of the Html attribute block, while running through the browser.

You can take the following example for
 tag:

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

<p> To break lines<br>in a text,<br/>use the br element. </p>

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

Output:

To break lines
in a text,
use the br element.

In case of Php, you can use '\n' for a lines feed.

If you are using a string in Php, then instead of writing,

echo "New \nLine";

you can use nl2br() function to get line break, like:

```<code>echo nl2br("New \nLine");
</code>```

Output:

New

Line

Body:
'Lines feed' exactly means a 'New line' both in Html and Php, only the syntax is different.

In case of Html tag, you can use <br> or <br/> tag for a Lines feed. Basically, this tag shows a new line in the output of the Html attribute block, while running through the browser.

You can take the following example for <br> tag:

<html> <body>

<p> To break lines<br>in a text,<br/>use the br element. </p>

</body> </html>

Output:

To break lines
in a text,
use the br element.

In case of Php, you can use '\n' for a lines feed.

If you are using a string in Php, then instead of writing,

echo "New \nLine";

you can use nl2br() function to get line break, like:

echo nl2br("New \nLine");

Output:

New

Line


问:
Is there an efficient way to find out whether a queue item is "before" another one?
For my Java application, I need some method that finds out if item1 is "before" item2 in my Queue Q. Of course, I can just use an iterator and start traversing the list. However, maybe there is another way of finding this out?

For my specific application, I can't use a LinkedList (which provides indexes and makes it easy to determine if one object is before another).

答:
If you only need to find out if item2 is already in the queue,
you could use a java.util.LinkedHashMap which maintains insertion order and can be used as a LIFO queue.</p>


问:
Bootstrap 4 Alpha Grid unable 2 tables on side by side
As using Bootstrap 4, I'm aware the .col-xs are dropped, instead of .col, I have tested on bootstrap 3.5 which I'm using

```<code>    <div class="col-xs-4">
         Table left side goes here
     </div>
    <div class="col-xs-8">
         Table right side goes here
    </div>
</code>```

And it works fine, as you can see it from here.

however, it's a bit different on Bootstrap 4 Alpha.

```<code><div class="col-2">
    <h2 class="sub-header">Test Arear</h2>
    <div class="table-responsive">
        <table class="table table-striped">
            <tbody>
                <tr>
                    <td class="col-md-1">Test</td>
                </tr>
                <tr>
                    <td class="col-md-1">Test 2</td>
                </tr>
                <tr>
                    <td class="col-md-1">Test 3</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
<div class="col-10">
    <h2 class="sub-header">Ticket Number</h2>
    <div class="table-responsive">
        <table class="table table-striped">
            <tbody>
                <tr>
                    <td class="col-md-1">1,001</td>
                    <td class="col-md-2">1,002</td>
                    <td class="col-md-3">1,003</td>
                </tr>
                <tr>
                    <td class="col-md-1">1,004</td>
                    <td class="col-md-2">1,005</td>
                    <td class="col-md-3">1,006</td>
                </tr>
                <tr>
                    <td class="col-md-1">1,002</td>
                    <td class="col-md-2">1,021</td>
                    <td class="col-md-3">1,023</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</code>```

As you can see results from here.

I want it on the side by side table but it's not side by side. Am I missing something?

答:
You need a row wrapper as bootstrap four is done on flex rather than floats so the columns now need to be wrapped to make them into columns

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap-grid.css" rel="stylesheet"/>

Test Arear

            Test

            Test 2

            Test 3

Ticket Number

            1,001
            1,002
            1,003

            1,004
            1,005
            1,006

            1,002
            1,021
            1,023

```

Example Bootply

Body:
As using Bootstrap 4, I'm aware the .col-xs are dropped, instead of .col, I have tested on bootstrap 3.5 which I'm using

         Table left side goes here

         Table right side goes here

And it works fine, as you can see it from here.

however, it's a bit different on Bootstrap 4 Alpha.

Test Arear

                    Test

                    Test 2

                    Test 3

Ticket Number

                    1,001
                    1,002
                    1,003

                    1,004
                    1,005
                    1,006

                    1,002
                    1,021
                    1,023

As you can see results from here.

I want it on the side by side table but it's not side by side. Am I missing something?

Body:
You need a row wrapper as bootstrap four is done on flex rather than floats so the columns now need to be wrapped to make them into columns

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap-grid.css" rel="stylesheet"/>
<div class="row">
  <div class="col-2">
    <h2 class="sub-header">Test Arear</h2>
    <div class="table-responsive">
      <table class="table table-striped">
        <tbody>
          <tr>
            <td class="col-md-1">Test</td>
          </tr>
          <tr>
            <td class="col-md-1">Test 2</td>
          </tr>
          <tr>
            <td class="col-md-1">Test 3</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
  <div class="col-10">
    <h2 class="sub-header">Ticket Number</h2>
    <div class="table-responsive">
      <table class="table table-striped">
        <tbody>
          <tr>
            <td class="col-md-1">1,001</td>
            <td class="col-md-2">1,002</td>
            <td class="col-md-3">1,003</td>
          </tr>
          <tr>
            <td class="col-md-1">1,004</td>
            <td class="col-md-2">1,005</td>
            <td class="col-md-3">1,006</td>
          </tr>
          <tr>
            <td class="col-md-1">1,002</td>
            <td class="col-md-2">1,021</td>
            <td class="col-md-3">1,023</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

Example Bootply


问:
Getting the Hostname or IP in Ruby on Rails
I'm in the process of maintaining a Ruby on Rails app and am looking for an easy way to find the hostname or IP address of the box I'm on (since it's a VM and new instances may have different hostnames or IP addresses). Is there a quick and easy way to do this in Ruby on Rails?

Edit: The answer below is correct but the clarification Craig provided is useful (see also provided link in answer):

The [below] code does NOT make a
  connection or send any packets (to
  64.233.187.99 which is google). Since UDP is a stateless protocol connect()
  merely makes a system call which
  figures out how to route the packets
  based on the address and what
  interface (and therefore IP address)
  it should bind to. addr() returns an
  array containing the family (AF_INET),
  local port, and local address (which
  is what we want) of the socket.

答:
The accepted answer works but you have to create a socket for every request and it does not work if the server is on a local network and/or not connected to the internet.  The below, I believe will always work since it is parsing the request header.</p>

```<code>request.env["SERVER_ADDR"]
</code>```

OwnerDisplayName: Chris Bunch

LastEditorDisplayName: Chris Bunch

Body:
The accepted answer works but you have to create a socket for every request and it does not work if the server is on a local network and/or not connected to the internet.  The below, I believe will always work since it is parsing the request header.

request.env["SERVER_ADDR"]


问:
Switching from manual to automation testing
Hello Test Automation Experts, Managers,

Seeking advice on how to transit from Manual Testing to automation testing

I have been a manual tester for over 8 years. I wish to switch to automation testing hence I attended training in Selenium web driver and Java ( we used TestNG and Maven ). Though being able to write medium complex automation scripts I am finding it hard to get interviews or seek attention from a hiring manager or recruiter just by saying them I have knowledge in automation.

What should I do to get one step closer so that a hiring manager will show interest in me?

I am very much keen on moving to test automation and willing to spend the required time to make this happen.

Should I write a blog portraying my skills in automation or post my samples in Git hub?

Looking forward to receiving your advice as I am totally lost and frustrated last few months making this attempt switching to automation testing

Thanks in advance

答:
As most of the Technocrats from Selenium, Mozilla, Google Chrome and IE community are active and visits Stack Overflow on regular basis you can try the following ideas to get noticed :

As a beginner go through the required Discussion threads within Frequent TAB on Stack Overflow and start getting your hands dirty with code.

When you gather ample knowledge start Answering questions and become a StackOverflow Volunteer.

Earn Bronze/Silver/Gold badges on Selenium / WebDriver / Java / Python / C# / NodeJS / Ruby / PHP / Perl tags.

Start writing a Technical Blog Site

Prepare Videos on Technical Aspects of Selenium / WebDriver / Java / Python / C# / NodeJS / Ruby / PHP / Perl and publish them.

The best outcome can be, you can turn out to be a Selenium Commiter

ContentLicense: CC BY-SA 4.0


问:
React Js: Uncaught (in promise) SyntaxError:
I am trying to do a POST request through fetch in reactjs. I went through some docs but my error not solved.Can anyone please help me out?

Here is my reactjs code:

```<code> handleSubmit(e) {
       e.preventDefault();
       var self = this;

       const payload = {
       id: 111,
       studentName: 'param',
       age: 24,
       emailId: 2
    };
    fetch({
       method: 'POST',
       url: 'http://localhost:8083/students',
       body: payload,
       headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
     })
       .then(function(response) {
           return response.json()
         }).then(function(body) {
           console.log(body);
         });
     }

  }
</code>```

If any one familiar with reactjs, just give a simple example how to call post request.Either by using fetch or axios.

答:
Here is an example..</p>

```<code>  fetch('http://myAPiURL.io/login',{
    method:'POST',
    headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body:JSON.stringify({
    email: userName,
    password: password
  })
  }).then(function (response) {

    //Check if response is 200(OK)
    if(response.ok) {
      alert("welcome ");
    }
    //if not throw an error to be handled in catch block
    throw new Error(response);
  })
  .catch(function (error) {
    //Handle error
    console.log(error);
  });

for more info on how to use `fetch` https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
</code>```

Body:
I am trying to do a POST request through fetch in reactjs. I went through some docs but my error not solved.Can anyone please help me out?

Here is my reactjs code:

 handleSubmit(e) {
       e.preventDefault();
       var self = this;

       const payload = {
       id: 111,
       studentName: 'param',
       age: 24,
       emailId: 2
    };
    fetch({
       method: 'POST',
       url: 'http://localhost:8083/students',
       body: payload,
       headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
     })
       .then(function(response) {
           return response.json()
         }).then(function(body) {
           console.log(body);
         });
     }

  }

If any one familiar with reactjs, just give a simple example how to call post request.Either by using fetch or axios.

Body:
Here is an example..

  fetch('http://myAPiURL.io/login',{
    method:'POST',
    headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body:JSON.stringify({
    email: userName,
    password: password
  })
  }).then(function (response) {

    //Check if response is 200(OK)
    if(response.ok) {
      alert("welcome ");
    }
    //if not throw an error to be handled in catch block
    throw new Error(response);
  })
  .catch(function (error) {
    //Handle error
    console.log(error);
  });

for more info on how to use `fetch` https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch