问:
How to create ManyToOne relationship using JPA Hibernate annotation?
I had two POJO class named Task and Team.A team can have many tasks correspondingly but each task can be mapped only one team.

```<code>// Task POJO
@Entity
@Table(name = "Task")
public class Task extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long taskId;

//Mapping To Team
@ManyToOne
@JoinColumn(name="teamId")
private Team teamId;
</code>```

Team POJO

```<code>@Entity
@Table(name = "Team")
public class Team extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long teamId;
@Column(nullable = false)

@OneToMany(mappedBy="teamId")
private List<Task> task = new ArrayList<Task>();
</code>```

The issue is I couldn't  Map/Save/Update and which is not affecting my Team Pojo.

```<code>  //Task Table
  +-----------------+--------------+------+-----+---------+----------------+
  | Field           | Type         | Null | Key | Default | Extra          |
  +-----------------+--------------+------+-----+---------+----------------+
  | taskId          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
  | taskName        | varchar(255) | NO   |     | NULL    |                |
  | teamId          | bigint(20)   | YES  | MUL | NULL    |                |
  +-----------------+--------------+------+-----+---------+----------------+
</code>```

The Team Table

```<code> +----------+--------------+------+-----+---------+----------------+
 | Field    | Type         | Null | Key | Default | Extra          |
 +----------+--------------+------+-----+---------+----------------+
 | teamId   | bigint(20)   | NO   | PRI | NULL    | auto_increment |
 | teamName | varchar(255) | NO   |     | NULL    |                |
 +----------+--------------+------+-----+---------+----------------+
</code>```

So How do I map these two Pojo classes and affect when saving/deletion of data in the tables.

Thanks in Advance.

答:
Complete your @manyToOne mapping in the Task entity by adding the referenced column in the Team entity; and also name the member as 'team', not 'teamId' i.e.:

```<code>@ManyToOne
@JoinColumn(name="teamId",
   referencedColumnName="teamId")
private Team team;
</code>```

To understand relationship mapping in JPA in general, see this: https://en.wikibooks.org/wiki/Java_Persistence/Relationships#Nested_Collections.2C_Maps_and_Matrices

Body:
I had two POJO class named Task and Team.A team can have many tasks correspondingly but each task can be mapped only one team.

// Task POJO
@Entity
@Table(name = "Task")
public class Task extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long taskId;

//Mapping To Team
@ManyToOne
@JoinColumn(name="teamId")
private Team teamId;

Team POJO

@Entity
@Table(name = "Team")
public class Team extends Domain implements Serializable {

@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Long teamId;
@Column(nullable = false)

@OneToMany(mappedBy="teamId")
private List<Task> task = new ArrayList<Task>();

The issue is I couldn't  Map/Save/Update and which is not affecting my Team Pojo.

  //Task Table
  +-----------------+--------------+------+-----+---------+----------------+
  | Field           | Type         | Null | Key | Default | Extra          |
  +-----------------+--------------+------+-----+---------+----------------+
  | taskId          | bigint(20)   | NO   | PRI | NULL    | auto_increment |
  | taskName        | varchar(255) | NO   |     | NULL    |                |
  | teamId          | bigint(20)   | YES  | MUL | NULL    |                |
  +-----------------+--------------+------+-----+---------+----------------+

The Team Table

 +----------+--------------+------+-----+---------+----------------+
 | Field    | Type         | Null | Key | Default | Extra          |
 +----------+--------------+------+-----+---------+----------------+
 | teamId   | bigint(20)   | NO   | PRI | NULL    | auto_increment |
 | teamName | varchar(255) | NO   |     | NULL    |                |
 +----------+--------------+------+-----+---------+----------------+

So How do I map these two Pojo classes and affect when saving/deletion of data in the tables.

Thanks in Advance.

Body:
Complete your @manyToOne mapping in the Task entity by adding the referenced column in the Team entity; and also name the member as 'team', not 'teamId' i.e.:

@ManyToOne
@JoinColumn(name="teamId",
   referencedColumnName="teamId")
private Team team;

To understand relationship mapping in JPA in general, see this: https://en.wikibooks.org/wiki/Java_Persistence/Relationships#Nested_Collections.2C_Maps_and_Matrices


来源: stackexchange

问:
Programatically determining the URL of a MediaWiki image
I'm trying to download images from specific MediaWiki pages (Or just specific images) using a PHP script.

I can run a query through the api, by retrieving the page at the following URL

```<code>.../w/action=query&prop=images&titles=Abakanskiy
</code>```

and get a response

```<code><?xml version="1.0"?>
<api>
  <query>
    <pages>
      <page pageid="260" ns="0" title="Abakanskiy">
        <images>
          <im ns="6" title="File:Abakanskiy.jpg" />
        </images>
      </page>
    </pages>
  </query>
</api>
</code>```

So far, so good.

Now, no matter what I've done with the query, I haven't figured out how I can construct, or retrieve the image's actual URL - in this case, it is

```<code>.../w/images/3/38/Abakanskiy.jpg
</code>```

Am I missing something obvious?

I realise that there exists a naive solution - getting the source of the page containing the image, parsing it for the  tag, and then getting the image from the specified URL - however, if possible, I'd rather use the API.

Any help would be appreciated!

答:
Once you have the names of the image pages, you can do this:

```<code>action=query&prop=imageinfo&iiprop=url&titles=File:Foo.jpg|File:Bar.jpg
</code>```

to get the URLs of the actual images.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to download images from specific MediaWiki pages (Or just specific images) using a PHP script.

I can run a query through the api, by retrieving the page at the following URL

.../w/action=query&prop=images&titles=Abakanskiy

and get a response

<?xml version="1.0"?>
<api>
  <query>
    <pages>
      <page pageid="260" ns="0" title="Abakanskiy">
        <images>
          <im ns="6" title="File:Abakanskiy.jpg" />
        </images>
      </page>
    </pages>
  </query>
</api>

So far, so good.

Now, no matter what I've done with the query, I haven't figured out how I can construct, or retrieve the image's actual URL - in this case, it is

.../w/images/3/38/Abakanskiy.jpg

Am I missing something obvious?

I realise that there exists a naive solution - getting the source of the page containing the image, parsing it for the  tag, and then getting the image from the specified URL - however, if possible, I'd rather use the API.

Any help would be appreciated!

Body:
Once you have the names of the image pages, you can do this:

action=query&prop=imageinfo&iiprop=url&titles=File:Foo.jpg|File:Bar.jpg

to get the URLs of the actual images.


问:
Twitter Search API and Hadoop
I need to use Twitter Search API and get twitter data into my HDFS. The Search API uses REST calls and I am trying to understand how I would use that with Apache Flume. I have required keys for authorization to use Twitter's APIs but I just don't understand how I could implement the Search API using flume. Need Help! Thank you!</p>

答:
First you need to create application in twitter. Go to
https://apps.twitter.com/ and create application then remember the generated four keys- Consumer key, Consumer Secret key, Access Token and Access Token Secret.

Download apache-flume-1.x.0-bin.tar.gz.here x means latest version.After untar the file add following command into ~/.bashrc file:

```<code>export FLUME_HOME=location of untar flume file
export PATH=$PATH:$FLUME_HOME/bin
</code>```

after saving the above file run source ~/.bashrc in terminal.After this follow below site command:

https://acadgild.com/blog/streaming-twitter-data-using-flume/

ContentLicense: CC BY-SA 3.0

Title: Twitter Search API and Hadoop

Body:
First you need to create application in twitter. Go to
https://apps.twitter.com/ and create application then remember the generated four keys- Consumer key, Consumer Secret key, Access Token and Access Token Secret.

Download apache-flume-1.x.0-bin.tar.gz.here x means latest version.After untar the file add following command into ~/.bashrc file:

export FLUME_HOME=location of untar flume file
export PATH=$PATH:$FLUME_HOME/bin

after saving the above file run source ~/.bashrc in terminal.After this follow below site command:

https://acadgild.com/blog/streaming-twitter-data-using-flume/


问:
Strange button behavior XML selector enabled
I have a button that must be enabled/disabled dynamically. When the switch on the right is checked, the button must be enabled. When the switch is unchecked, the button must be disabled. I've done that using Bindings in MVVMlight.

The default state of the switch is unchecked, so the button must be disabled.

The button has it's own Color State List to be grayed when disabled and blue when enabled.

```<code><?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_enabled="false" android:color="@color/third_light_gray"/>
   <item android:state_enabled="true" android:color="@color/light_blue"/>
</selector>
</code>```

The binding works properly, the button gets enabled/disabled as expected.
However, the default state of the button should be disabled, but it is always enabled by default.

```<code><Button
        android:id="@+id/buttonListProtections"
        ...
        android:enabled="false"
        android:theme="@style/Gohy.Button" />
</code>```

Button style :

```<code>  <style name="Gohy.Button" parent="Widget.AppCompat.Button.Colored">
    <item name="android:textColor">@color/white</item>
    <item name="colorButtonNormal">@drawable/button_color_list</item>
    <item name="android:padding">30dp</item>
    </style>
</code>```

What have I done wrong ?

答:
I have found an answer to my question via this post :

Android custom view ignoring `android:enabled` in XML?

Since there is apparently no way to enable/disable view directly from XML, I had to set it programmatically.

Body:
I have a button that must be enabled/disabled dynamically. When the switch on the right is checked, the button must be enabled. When the switch is unchecked, the button must be disabled. I've done that using Bindings in MVVMlight.

The default state of the switch is unchecked, so the button must be disabled.

The button has it's own Color State List to be grayed when disabled and blue when enabled.

<?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_enabled="false" android:color="@color/third_light_gray"/>
   <item android:state_enabled="true" android:color="@color/light_blue"/>
</selector>

The binding works properly, the button gets enabled/disabled as expected.
However, the default state of the button should be disabled, but it is always enabled by default.

<Button
        android:id="@+id/buttonListProtections"
        ...
        android:enabled="false"
        android:theme="@style/Gohy.Button" />

Button style :

What have I done wrong ?


问:
$wpdb return empty with date selection
I'm working on a WordPress calendar plugin, with possibility to add events attached to one date. Events are stored in a custom database that works fine.

But I've got troubles with a function in wich I use a '$wpdb->get_results'
This function need a date as parameter.
This is my code :

```<code>function get_events_list($day) {

    global $wpdb
    $table = $wpdb->prefix . "mytable";

    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = $day)", ARRAY_A );

    var_dump($events_list);

}
</code>```

'var_dump($events_list)' returns an empty array, but I've got entries in the table.

I tried the function with no paramater, entering a well-formated date directly in the sql request, like that :

```<code>function get_events_list() {
    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '2017-03-30')", ARRAY_A );
}
</code>```

This works great.

I also did a 'var_dump($wpdb->last_query)', trying to find what happen.

Tested with no parameter (hard-coded '2017-03-30'), wich is working fine, the last_query returns :

```<code>'SELECT * FROM wp_mytable WHERE date = '2017-03-30')'
</code>```

With dynamic paramater, it returns the date without quote :

```<code>'SELECT * FROM wp_mytable WHERE date = 2017-03-30)'
</code>```

I think I'm pointing the problem but cannot resolve it (I tried a lot of things).
Could Someone help me please ? Thank you :)

答:
Hello_ mate,

first I dont't understand how could this ('SELECT * FROM wp_mytable WHERE date = '2017-03-30')') query work, this final bracket looks very very strange to me :).

Anyway if your query is working fine then simply change:

```<code>$events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = $day)", ARRAY_A );
</code>```

to

```<code>$events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '$day')", ARRAY_A );
</code>```

as you see we only put quotes when passing the variable.

Let me know if this works for you.

Good Luck!

Title: $wpdb return empty with date selection

Body:
I'm working on a WordPress calendar plugin, with possibility to add events attached to one date. Events are stored in a custom database that works fine.

But I've got troubles with a function in wich I use a '$wpdb->get_results'
This function need a date as parameter.
This is my code :

function get_events_list($day) {

    global $wpdb
    $table = $wpdb->prefix . "mytable";

    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = $day)", ARRAY_A );

    var_dump($events_list);

}

'var_dump($events_list)' returns an empty array, but I've got entries in the table.

I tried the function with no paramater, entering a well-formated date directly in the sql request, like that :

function get_events_list() {
    $events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '2017-03-30')", ARRAY_A );
}

This works great.

I also did a 'var_dump($wpdb->last_query)', trying to find what happen.

Tested with no parameter (hard-coded '2017-03-30'), wich is working fine, the last_query returns :

'SELECT * FROM wp_mytable WHERE date = '2017-03-30')'

With dynamic paramater, it returns the date without quote :

'SELECT * FROM wp_mytable WHERE date = 2017-03-30)'

I think I'm pointing the problem but cannot resolve it (I tried a lot of things).
Could Someone help me please ? Thank you :)

Body:
Hello_ mate,

first I dont't understand how could this ('SELECT * FROM wp_mytable WHERE date = '2017-03-30')') query work, this final bracket looks very very strange to me :).

Anyway if your query is working fine then simply change:

$events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = $day)", ARRAY_A );

to

$events_list = $wpdb->get_results( "SELECT * FROM $table WHERE date = '$day')", ARRAY_A );

as you see we only put quotes when passing the variable.

Let me know if this works for you.

Good Luck!


问:
What is the alternative to cursors to retrieve large amounts of data from a database?
Searching through stackoverflow I found a large number of answers condemning the use of cursors in database programming. However I don't really understand what the alternative is.

I'm creating a program which reads a large number of rows (hundreds of thousands) from the database and keeps them in memory, for performance reasons. I can't really run a SELECT * FROM table and process all the results at once, can I?

The best way I have found is to use cursors and retrieve the rows in increments, for example 10 at a time.

Could someone enlighten me? I use PostgreSQL 9 on linux.

Thanks

答:
You can straightly use the for loop using record:</p>

```<code>do
$$
declare r record;

begin

    for r in select product_id, name from products loop
        raise notice '% %', r.product_id, r.jname;
    end loop;

end$$
</code>```

Body:
You can straightly use the for loop using record:

do
$$
declare r record;

begin

    for r in select product_id, name from products loop
        raise notice '% %', r.product_id, r.jname;
    end loop;

end$$


问:
opencv: Segmenting a transparent border
I'm trying to find the active objects in a game screen like this:

Where active means that they have the a gray-white border, so here the square in the upper left and the five cards in the middle.

This looked easy at first but the border is translucent and a gradient, so the actual gray value depends a lot on the background and can range from ~180 to 240. Just inRange()'ing all these values produces a lot of noise. Here's a close up of the border for reference:

So then I tried template matching with one template for each edge, e.g. for the right edge I take a bunch of the black border pixels and the gradient of 4 gray pixels next to it, e.g.

Then I add threshold on the template matching results and it kinda works:

```<code>    k = ['right', 'left', 'top', 'bottom']
    mode = cv2.TM_CCOEFF_NORMED
    matches = {}
    addimg = []

    for side in k:
        template = cv2.imread('./img/ab_' + side + '.png', cv2.IMREAD_GRAYSCALE)
        matches[side] = cv2.matchTemplate(im0, template, mode)
        v  = cv2.inRange(matches[side], 0.987, 1)
        #Tools.show(side, v)
        addimg.append(v)

    im1 = sum(addimg)
</code>```

But it is still finnicky to get the right value for the TM coefficient. Also when the objects are bigger, the border gradient is wider than the gray pixels I use in the template, so the match gets way worse.

So all in all, I think I'm missing a smart algorithm that can match a gradient of varied size and intensity. Any good ideas?

PS there's many more of these screenshots in https://github.com/rc9000/modoscrape/tree/master/img

答:
OK, here's my two cents. This has nothing to do with gradient detection but rather another idea of how to detect these cards.

I take it that your only clue on how to detect the active cards is this border. So sure, you can try and detect the gradient and stuff, but my solution relies on the fact that

a/ the border is clearly seperable (as a component) from the rest of the image with a simple "inRange()" [EDIT after a comment from Piglet : this could also work -and would probably be easier- with working on the black border instead of the gradient]
b/ the border has a specific shape, and especially a bounding rectangle around it would be straight and have specific proportions. I mean since you're always selecting a playing card, its height/width ratio will always be the same.

So my idea is to

1/ threshold

2/ find components

3/ find bounding rectangles of these components

4/ select only bounding rectangles which have the specific proportions

The code follows. It is sort of "quick and dirty", some stuff may be optimized. For example, I'm not checking for rectangle orientation, which is a nice clue. Also, you may have some idea of the card's size even if it can vary from one image to another. Also, you could eliminate rectangles inside other ones, or rectangles significitavely smaller than others...

Take this as "another way" to explore, not a turnkey solution :)

```<code>import cv2
import sys
import numpy as np
import csv

#just converting formats of numpy arrays to pass it from one cv2 function to another.
def convert_for_bounding(coords):
    nb_pts=len(coords[0])
    coordz=np.zeros((nb_pts,2))
    for i in range(nb_pts):
        coordz[i,:]=np.array([int(coords[0][i]),int(coords[1][i])])
    return coordz

#finding width and length of bounding boxes
def find_wid(xs):
    maxx=0
    for i in range(4):
        for j in range(i+1,4):
            if abs(xs[i]-xs[j])>=maxx:
                maxx=abs(xs[i]-xs[j])
    return maxx

img=cv2.imread(your image)
orig=np.copy(img)
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
h,w=img.shape

#thresholding with your "180 - 240" range
img = cv2.inRange(img, 180, 240)

#finding all components
nb_edges, output, stats, centroids = cv2.connectedComponentsWithStats(img, connectivity=8)
size_edges = stats[1:, -1]; nb_edges = nb_edges - 1
contours=[]
for i in range(0, nb_edges):
    #eliminating small components
    if size_edges[i]>=100:
        img2=np.zeros((h,w))
        img2[output == i + 1] = 255
        contours.append(convert_for_bounding(np.nonzero(img2)))

#finding bounding rectangle for each component
for i in range(0,len(contours)):
    c=np.array(contours[i]).astype(int)
    ar=cv2.minAreaRect(c)
    box = cv2.boxPoints(ar)
    box = np.int0([box[:,1],box[:,0]]).T
    xs=box[:,0]
    ys=box[:,1]
    wid=find_wid(xs)
    hei=find_wid(ys)

    #for each rectangle, we'll check if its ratio is like a card one
    card_ratio = 285 / 205
    if hei!=0:
        if hei/wid <=card_ratio*1.05 and hei/wid >= card_ratio*0.95:
            cv2.drawContours(orig, [box], -1, (0,0,255), 2)
</code>```

Result (had to downsize to upload in this answer) :

Title: opencv: Segmenting a transparent border

Body:
I'm trying to find the active objects in a game screen like this:

Where active means that they have the a gray-white border, so here the square in the upper left and the five cards in the middle.

This looked easy at first but the border is translucent and a gradient, so the actual gray value depends a lot on the background and can range from ~180 to 240. Just inRange()'ing all these values produces a lot of noise. Here's a close up of the border for reference:

So then I tried template matching with one template for each edge, e.g. for the right edge I take a bunch of the black border pixels and the gradient of 4 gray pixels next to it, e.g.

Then I add threshold on the template matching results and it kinda works:

    k = ['right', 'left', 'top', 'bottom']
    mode = cv2.TM_CCOEFF_NORMED
    matches = {}
    addimg = []

    for side in k:
        template = cv2.imread('./img/ab_' + side + '.png', cv2.IMREAD_GRAYSCALE)
        matches[side] = cv2.matchTemplate(im0, template, mode)
        v  = cv2.inRange(matches[side], 0.987, 1)
        #Tools.show(side, v)
        addimg.append(v)

    im1 = sum(addimg)

But it is still finnicky to get the right value for the TM coefficient. Also when the objects are bigger, the border gradient is wider than the gray pixels I use in the template, so the match gets way worse.

So all in all, I think I'm missing a smart algorithm that can match a gradient of varied size and intensity. Any good ideas?

PS there's many more of these screenshots in https://github.com/rc9000/modoscrape/tree/master/img

Body:
OK, here's my two cents. This has nothing to do with gradient detection but rather another idea of how to detect these cards.

I take it that your only clue on how to detect the active cards is this border. So sure, you can try and detect the gradient and stuff, but my solution relies on the fact that

a/ the border is clearly seperable (as a component) from the rest of the image with a simple "inRange()" [EDIT after a comment from Piglet : this could also work -and would probably be easier- with working on the black border instead of the gradient]
b/ the border has a specific shape, and especially a bounding rectangle around it would be straight and have specific proportions. I mean since you're always selecting a playing card, its height/width ratio will always be the same.

So my idea is to

1/ threshold

2/ find components

3/ find bounding rectangles of these components

4/ select only bounding rectangles which have the specific proportions

The code follows. It is sort of "quick and dirty", some stuff may be optimized. For example, I'm not checking for rectangle orientation, which is a nice clue. Also, you may have some idea of the card's size even if it can vary from one image to another. Also, you could eliminate rectangles inside other ones, or rectangles significitavely smaller than others...

Take this as "another way" to explore, not a turnkey solution :)

import cv2
import sys
import numpy as np
import csv

#just converting formats of numpy arrays to pass it from one cv2 function to another.
def convert_for_bounding(coords):
    nb_pts=len(coords[0])
    coordz=np.zeros((nb_pts,2))
    for i in range(nb_pts):
        coordz[i,:]=np.array([int(coords[0][i]),int(coords[1][i])])
    return coordz

#finding width and length of bounding boxes
def find_wid(xs):
    maxx=0
    for i in range(4):
        for j in range(i+1,4):
            if abs(xs[i]-xs[j])>=maxx:
                maxx=abs(xs[i]-xs[j])
    return maxx

img=cv2.imread(your image)
orig=np.copy(img)
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
h,w=img.shape

#thresholding with your "180 - 240" range
img = cv2.inRange(img, 180, 240)

#finding all components
nb_edges, output, stats, centroids = cv2.connectedComponentsWithStats(img, connectivity=8)
size_edges = stats[1:, -1]; nb_edges = nb_edges - 1
contours=[]
for i in range(0, nb_edges):
    #eliminating small components
    if size_edges[i]>=100:
        img2=np.zeros((h,w))
        img2[output == i + 1] = 255
        contours.append(convert_for_bounding(np.nonzero(img2)))

#finding bounding rectangle for each component
for i in range(0,len(contours)):
    c=np.array(contours[i]).astype(int)
    ar=cv2.minAreaRect(c)
    box = cv2.boxPoints(ar)
    box = np.int0([box[:,1],box[:,0]]).T
    xs=box[:,0]
    ys=box[:,1]
    wid=find_wid(xs)
    hei=find_wid(ys)

    #for each rectangle, we'll check if its ratio is like a card one
    card_ratio = 285 / 205
    if hei!=0:
        if hei/wid <=card_ratio*1.05 and hei/wid >= card_ratio*0.95:
            cv2.drawContours(orig, [box], -1, (0,0,255), 2)

Result (had to downsize to upload in this answer) :


问:
How to pass string to module variable definitions?
I'm new to typescript and MVC, so I'm not even sure if I'm asking the right question. But I have functionally identical typescript files that are used for multiple search screens. So I'm trying to consolidate it to a single file, that takes the search screen name and area (strings) and takes off from there. Is there a way I can pass this information to the typescript file from the view?

Here's a little code of my typescript for context.

```<code>module HarSearch {
    const area = "";
    const searchScreen = "";
    const gridName = searchScreen + "SearchGrid";
    const searchGrid = $(`#${gridName}`);
    const gridOptionsStorageName =  searchScreen + "GridOptions";
    const filtersStorageName =  searchScreen + "SearchFilters";
    const filterFormName = "formFilters";
    var defaultGridOptions: kendo.ui.GridOptions;

    $(function(e) {
        var harSearchGridData = searchGrid.data("kendoGrid");
        KendoGridFunctions.resizeGrid(searchGrid, -25);
        defaultGridOptions = harSearchGridData.getOptions();
        loadSearchState();
    });

    // more functions...
}
</code>```

The area and searchName values are what I'd like to be able to set.

EDIT: thinking about Paleo's advice below, I thought maybe only breaking the variables I need into it's own class might get me closer. So I've edited my code a bit, but I still need a way to set these variables.

```<code>class definitions {
    public static area = "";
    public static searchName = "";
}

module HarSearch {
    const area = definitions.area;
    const searchName = definitions.searchName;
    .
    .
    .
    // rest is the same
}
</code>```

答:
Here's what I ended up doing. It's not my ideal solution, but it works. I didn't end up breaking my variables into their own class. They're still inside the module. I added a script in my view to set global variables which are then referenced by the module, where my Model.SearchArea and Model.SearchName are just strings.

VIEW

```<code><script type="text/javascript">
    $(function() {
        searchArea = @Html.Raw(Json.Encode(Model.SearchArea));
        searchName = @Html.Raw(Json.Encode(Model.SearchName));
    })
</script>
</code>```

TS File

```<code>module Search {
    declare var searchArea: string;
    declare var searchName: string;
    var gridName: string;
    var searchGrid: JQuery;
    var gridOptionsStorageName: string;
    var filtersStorageName: string;
    const filterFormName = "formFilters";
    var defaultGridOptions: kendo.ui.GridOptions;

    $(() => {
        gridName = searchName + "SearchGrid";
        searchGrid = $(`#${gridName}`);
        gridOptionsStorageName = searchName + "GridOptions";
        filtersStorageName = searchName + "SearchFilters";

        var searchGridData = searchGrid.data("kendoGrid");
        KendoGridFunctions.resizeGrid(searchGrid, -25);
        defaultGridOptions = searchGridData.getOptions();
        loadSearchState();
    });

    .
    .
    .
    //more functions
}
</code>```

Body:
I'm new to typescript and MVC, so I'm not even sure if I'm asking the right question. But I have functionally identical typescript files that are used for multiple search screens. So I'm trying to consolidate it to a single file, that takes the search screen name and area (strings) and takes off from there. Is there a way I can pass this information to the typescript file from the view?

Here's a little code of my typescript for context.

module HarSearch {
    const area = "";
    const searchScreen = "";
    const gridName = searchScreen + "SearchGrid";
    const searchGrid = $(`#${gridName}`);
    const gridOptionsStorageName =  searchScreen + "GridOptions";
    const filtersStorageName =  searchScreen + "SearchFilters";
    const filterFormName = "formFilters";
    var defaultGridOptions: kendo.ui.GridOptions;

    $(function(e) {
        var harSearchGridData = searchGrid.data("kendoGrid");
        KendoGridFunctions.resizeGrid(searchGrid, -25);
        defaultGridOptions = harSearchGridData.getOptions();
        loadSearchState();
    });

    // more functions...
}

The area and searchName values are what I'd like to be able to set.

EDIT: thinking about Paleo's advice below, I thought maybe only breaking the variables I need into it's own class might get me closer. So I've edited my code a bit, but I still need a way to set these variables.

class definitions {
    public static area = "";
    public static searchName = "";
}

module HarSearch {
    const area = definitions.area;
    const searchName = definitions.searchName;
    .
    .
    .
    // rest is the same
}

Body:
Here's what I ended up doing. It's not my ideal solution, but it works. I didn't end up breaking my variables into their own class. They're still inside the module. I added a script in my view to set global variables which are then referenced by the module, where my Model.SearchArea and Model.SearchName are just strings.

VIEW

<script type="text/javascript">
    $(function() {
        searchArea = @Html.Raw(Json.Encode(Model.SearchArea));
        searchName = @Html.Raw(Json.Encode(Model.SearchName));
    })
</script>

TS File

module Search {
    declare var searchArea: string;
    declare var searchName: string;
    var gridName: string;
    var searchGrid: JQuery;
    var gridOptionsStorageName: string;
    var filtersStorageName: string;
    const filterFormName = "formFilters";
    var defaultGridOptions: kendo.ui.GridOptions;

    $(() => {
        gridName = searchName + "SearchGrid";
        searchGrid = $(`#${gridName}`);
        gridOptionsStorageName = searchName + "GridOptions";
        filtersStorageName = searchName + "SearchFilters";

        var searchGridData = searchGrid.data("kendoGrid");
        KendoGridFunctions.resizeGrid(searchGrid, -25);
        defaultGridOptions = searchGridData.getOptions();
        loadSearchState();
    });

    .
    .
    .
    //more functions
}


问:
Should I use arial-label or a label element that is visually hidden
I am creating a search form that has two elements an input field and a button. The input field does not have an label associated with it.

To make the field more accessible I can add Search and visually hide it so it will e.g. be accessible for screenreaders.

I could also add aria-label="search" to the input field and leave the input field without an label.

I have tested with "Voice Over" on a Mac and I get the same result/output. My question is are these approaches equivalent? Or is one approach better than the other one?

Here is a pen.

答:
In the absence of having any knowledge of the site (how are other form fields labeled?) or the audience (what is their skill level or tech profile?), I approach these questions with a couple parameters:

The rules of ARIA (the first rule may apply here)

Progressive enhancement

That being said, I often code a page without ARIA and without CSS (as that may get blocked, chunked, etc) and make sure it is accessible.

That means I code a . Then I visually hide it. If the CSS breaks, all is still well. If the user's screen reader does not support ARIA, all is still well. As an aside, if you think all screen readers of your users support ARIA, I encourage you to do to a tech assessment of users (local blind associations are a good start in the absence of any real users). Many people still run older versions of browsers and SRs.

For sighted users, I make sure I lean on contextual clues, like a clear search icon (or the word) in the button (as Unor references). Or maybe a placeholder with appropriate contrast (though you could use the  as a visual placeholder with some CSS trickery to hide it on focus).

If your submit button uses SVG, then I would be folding ARIA into that given the inconsistent support around SVG alternative text methods.

FWIW, I am also not a fan of the title attribute, partly because of inconsistent accessible name calculation and partly because I think it looks meh.

So, to answer your questions:

My question is are these approaches equivalent?

No, but the distance between them is shrinking.

Or is one approach better than the other one?

That depends on context we do not have.

Body:
In the absence of having any knowledge of the site (how are other form fields labeled?) or the audience (what is their skill level or tech profile?), I approach these questions with a couple parameters:

The rules of ARIA (the first rule may apply here)

Progressive enhancement

That being said, I often code a page without ARIA and without CSS (as that may get blocked, chunked, etc) and make sure it is accessible.

That means I code a <label>. Then I visually hide it. If the CSS breaks, all is still well. If the user's screen reader does not support ARIA, all is still well. As an aside, if you think all screen readers of your users support ARIA, I encourage you to do to a tech assessment of users (local blind associations are a good start in the absence of any real users). Many people still run older versions of browsers and SRs.

For sighted users, I make sure I lean on contextual clues, like a clear search icon (or the word) in the button (as Unor references). Or maybe a placeholder with appropriate contrast (though you could use the <label> as a visual placeholder with some CSS trickery to hide it on focus).

If your submit button uses SVG, then I would be folding ARIA into that given the inconsistent support around SVG alternative text methods.

FWIW, I am also not a fan of the title attribute, partly because of inconsistent accessible name calculation and partly because I think it looks meh.

So, to answer your questions:

My question is are these approaches equivalent?

No, but the distance between them is shrinking.

Or is one approach better than the other one?

That depends on context we do not have.


问:
True value being duplicated into incorrect user object
I am having a very strange issue that hopefully someone can help me with. Here's what is happening:

A function called processServices is being used to take a large object called "flight" as well as GET values from a form on a previous page to add selected airline services to the appropriate user's 'profile' inside the object. It also then totals the price of the services for that particular user and adds it to the object.

These services are dynamic but that's not really relevant here apart from I can't expect any service code in my function and have to rely on the get data.

The PROBLEM is that if I have two users and the second one signs up for a service, the first user gets that service as well, even though that user's service total stays at zero.

Example of Flight object before running function:

```<code>[Flight] => stdClass Object
                (
                    [Adults] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [FirstName] => Test
                                    [MiddleName] =>
                                    [LastName] => Account
                                    [Services] => stdClass Object
                                        (
                                            [BLND] => 0
                                            [EMSA] => 0
                                            [PETH] => 0
                                            [SVAN] => 0
                                            [WCHR] => 0
                                        )

                                )

                            [1] => stdClass Object
                                (
                                    [FirstName] => The
                                    [MiddleName] =>
                                    [LastName] => Dude
                                    [Services] => stdClass Object
                                        (
                                            [BLND] => 0
                                            [EMSA] => 0
                                            [PETH] => 0
                                            [SVAN] => 0
                                            [WCHR] => 0
                                        )

                                )

                        )

                    [AdultNum] => 2
                    [Services] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => BLND
                                    [Description] => Can Choose Own Seat
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] =>
                                    [CategoryID] => 1
                                    [SSRCode] => BLND
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 8
                                    [Refundable] =>
                                    [PNLActive] => 1
                                    [CutoffHours] => -1
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 8
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Blind Passenger
                                )

                            [1] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => EMSA
                                    [Description] =>
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => EMSA
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] => 1
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 1
                                    [QuantityAvailable] => 1
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Emotional Support Animal
                                )

                            [2] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => PETH
                                    [Description] => PET IN HOLD
                                    [CurrencyCode] => USD
                                    [Amount] => 25
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => PETH
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] =>
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 0
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                )

                            [3] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => SVAN
                                    [Description] => SERVICE ANIMAL
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => SVAN
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] => 1
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 0
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                )

                            [4] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => WCHR
                                    [Description] =>
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] =>
                                    [CategoryID] => 1
                                    [SSRCode] => WCHR
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 8
                                    [Refundable] =>
                                    [PNLActive] => 1
                                    [CutoffHours] => -1
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 8
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Wheelchair (can Climb Stairs And Walk To Chair)
                                )

                        )

                )
</code>```

Below is the function. Note that the get data is structured as follows:
service-CODE-#, where CODE is the unique code for a service and # is the user id (starting with 0 and going up to 8). So, someone who is user 1 who wanted a pet in hold would have a get name like service-PETH-0

Function:

```<code>function processServices($flight, $get) {
    $totalCost = 0;
    for($i=0; $i<$flight->AdultNum; $i++) {
        $totalCost = 0;
        foreach($flight->Services as $s) {
            $code = $s->SSRCode;
            if ($get['service-'.$code.'-'.$i] == 'yes') {
                $flight->Adults[$i]->Services->$code = true;
                $totalCost += $s->Amount;
            } else {
                $flight->Adults[$i]->Services->$code = false;
            }
        }
        $flight->Adults[$i]->ServicesTotal = $totalCost;
        $totalCost = 0;
    }

    return $flight;
}
</code>```

In this example the following is in the $_GET variable:

```<code>service-BLND-0=no&service-EMSA-0=no&service-PETH-0=no&service-SVAN-0=no&service-WCHR-0=no&service-BLND-1=no&service-EMSA-1=no&service-PETH-1=yes&service-SVAN-1=no&service-WCHR-1=no&step=4
</code>```

But for some reason, after processing with that function, this is the new object (PETH is marked for BOTH users, even though it's only totaled for one):

```<code>[Flight] => stdClass Object
                (
                    [Adults] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [FirstName] => Test
                                    [MiddleName] =>
                                    [LastName] => Account
                                    [Services] => stdClass Object
                                        (
                                            [BLND] => 0
                                            [EMSA] => 0
                                            [PETH] => 1
                                            [SVAN] => 0
                                            [WCHR] => 0
                                        )
                                    [ServicesTotal] => 0
                                )

                            [1] => stdClass Object
                                (
                                    [FirstName] => The
                                    [MiddleName] =>
                                    [LastName] => Dude
                                    [Services] => stdClass Object
                                        (
                                            [BLND] => 0
                                            [EMSA] => 0
                                            [PETH] => 1
                                            [SVAN] => 0
                                            [WCHR] => 0
                                        )
                                    [ServicesTotal] => 25
                                )

                        )

                    [AdultNum] => 2
                    [Services] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => BLND
                                    [Description] => Can Choose Own Seat
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] =>
                                    [CategoryID] => 1
                                    [SSRCode] => BLND
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 8
                                    [Refundable] =>
                                    [PNLActive] => 1
                                    [CutoffHours] => -1
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 8
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Blind Passenger
                                )

                            [1] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => EMSA
                                    [Description] =>
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => EMSA
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] => 1
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 1
                                    [QuantityAvailable] => 1
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Emotional Support Animal
                                )

                            [2] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => PETH
                                    [Description] => PET IN HOLD
                                    [CurrencyCode] => USD
                                    [Amount] => 25
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => PETH
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] =>
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 0
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                )

                            [3] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => SVAN
                                    [Description] => SERVICE ANIMAL
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => SVAN
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] => 1
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 0
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                )

                            [4] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => WCHR
                                    [Description] =>
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] =>
                                    [CategoryID] => 1
                                    [SSRCode] => WCHR
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 8
                                    [Refundable] =>
                                    [PNLActive] => 1
                                    [CutoffHours] => -1
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 8
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Wheelchair (can Climb Stairs And Walk To Chair)
                                )

                        )

                )
</code>```

This function is the ONLY one in the code modifying these values. If I set the function to always set them to false, all of them will be false. Any help?

答:
No idea what is going on, but I ended up just adding this bit to the top of the for() inside the function and then set the Services equal to the ServicesTest and it fixed it.</p>

```<code>foreach($flight->Services as $serv) {
    $code = $serv->SSRCode;
    $flight->Adults[$i]->ServicesTest->$code = ($get['service-'.$code.'-'.$i] == 'yes' ? true : false);
}

...

$flight->Adults[$i]->Services = $flight->Adults[$i]->ServicesTest;
</code>```

Body:
I am having a very strange issue that hopefully someone can help me with. Here's what is happening:

A function called processServices is being used to take a large object called "flight" as well as GET values from a form on a previous page to add selected airline services to the appropriate user's 'profile' inside the object. It also then totals the price of the services for that particular user and adds it to the object.

These services are dynamic but that's not really relevant here apart from I can't expect any service code in my function and have to rely on the get data.

The PROBLEM is that if I have two users and the second one signs up for a service, the first user gets that service as well, even though that user's service total stays at zero.

Example of Flight object before running function:

[Flight] => stdClass Object
                (
                    [Adults] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [FirstName] => Test
                                    [MiddleName] =>
                                    [LastName] => Account
                                    [Services] => stdClass Object
                                        (
                                            [BLND] => 0
                                            [EMSA] => 0
                                            [PETH] => 0
                                            [SVAN] => 0
                                            [WCHR] => 0
                                        )

                                )

                            [1] => stdClass Object
                                (
                                    [FirstName] => The
                                    [MiddleName] =>
                                    [LastName] => Dude
                                    [Services] => stdClass Object
                                        (
                                            [BLND] => 0
                                            [EMSA] => 0
                                            [PETH] => 0
                                            [SVAN] => 0
                                            [WCHR] => 0
                                        )

                                )

                        )

                    [AdultNum] => 2
                    [Services] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => BLND
                                    [Description] => Can Choose Own Seat
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] =>
                                    [CategoryID] => 1
                                    [SSRCode] => BLND
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 8
                                    [Refundable] =>
                                    [PNLActive] => 1
                                    [CutoffHours] => -1
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 8
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Blind Passenger
                                )

                            [1] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => EMSA
                                    [Description] =>
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => EMSA
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] => 1
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 1
                                    [QuantityAvailable] => 1
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Emotional Support Animal
                                )

                            [2] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => PETH
                                    [Description] => PET IN HOLD
                                    [CurrencyCode] => USD
                                    [Amount] => 25
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => PETH
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] =>
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 0
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                )

                            [3] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => SVAN
                                    [Description] => SERVICE ANIMAL
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => SVAN
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] => 1
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 0
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                )

                            [4] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => WCHR
                                    [Description] =>
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] =>
                                    [CategoryID] => 1
                                    [SSRCode] => WCHR
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 8
                                    [Refundable] =>
                                    [PNLActive] => 1
                                    [CutoffHours] => -1
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 8
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Wheelchair (can Climb Stairs And Walk To Chair)
                                )

                        )

                )

Below is the function. Note that the get data is structured as follows:
service-CODE-#, where CODE is the unique code for a service and # is the user id (starting with 0 and going up to 8). So, someone who is user 1 who wanted a pet in hold would have a get name like service-PETH-0

Function:

function processServices($flight, $get) {
    $totalCost = 0;
    for($i=0; $i<$flight->AdultNum; $i++) {
        $totalCost = 0;
        foreach($flight->Services as $s) {
            $code = $s->SSRCode;
            if ($get['service-'.$code.'-'.$i] == 'yes') {
                $flight->Adults[$i]->Services->$code = true;
                $totalCost += $s->Amount;
            } else {
                $flight->Adults[$i]->Services->$code = false;
            }
        }
        $flight->Adults[$i]->ServicesTotal = $totalCost;
        $totalCost = 0;
    }

    return $flight;
}

In this example the following is in the $_GET variable:

service-BLND-0=no&service-EMSA-0=no&service-PETH-0=no&service-SVAN-0=no&service-WCHR-0=no&service-BLND-1=no&service-EMSA-1=no&service-PETH-1=yes&service-SVAN-1=no&service-WCHR-1=no&step=4

But for some reason, after processing with that function, this is the new object (PETH is marked for BOTH users, even though it's only totaled for one):

[Flight] => stdClass Object
                (
                    [Adults] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [FirstName] => Test
                                    [MiddleName] =>
                                    [LastName] => Account
                                    [Services] => stdClass Object
                                        (
                                            [BLND] => 0
                                            [EMSA] => 0
                                            [PETH] => 1
                                            [SVAN] => 0
                                            [WCHR] => 0
                                        )
                                    [ServicesTotal] => 0
                                )

                            [1] => stdClass Object
                                (
                                    [FirstName] => The
                                    [MiddleName] =>
                                    [LastName] => Dude
                                    [Services] => stdClass Object
                                        (
                                            [BLND] => 0
                                            [EMSA] => 0
                                            [PETH] => 1
                                            [SVAN] => 0
                                            [WCHR] => 0
                                        )
                                    [ServicesTotal] => 25
                                )

                        )

                    [AdultNum] => 2
                    [Services] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => BLND
                                    [Description] => Can Choose Own Seat
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] =>
                                    [CategoryID] => 1
                                    [SSRCode] => BLND
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 8
                                    [Refundable] =>
                                    [PNLActive] => 1
                                    [CutoffHours] => -1
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 8
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Blind Passenger
                                )

                            [1] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => EMSA
                                    [Description] =>
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => EMSA
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] => 1
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 1
                                    [QuantityAvailable] => 1
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Emotional Support Animal
                                )

                            [2] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => PETH
                                    [Description] => PET IN HOLD
                                    [CurrencyCode] => USD
                                    [Amount] => 25
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => PETH
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] =>
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 0
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                )

                            [3] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => SVAN
                                    [Description] => SERVICE ANIMAL
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] => Flat Fee
                                    [CategoryID] => 221
                                    [SSRCode] => SVAN
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 1
                                    [Refundable] => 1
                                    [PNLActive] => 1
                                    [CutoffHours] => 0
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 0
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                )

                            [4] => stdClass Object
                                (
                                    [LogicalFlightID] => 4569
                                    [ServiceID] => 0
                                    [DepartureDate] => 2017-04-03T00:00:00
                                    [OperatingCarrier] =>
                                    [MarketingCarrier] =>
                                    [CodeType] => WCHR
                                    [Description] =>
                                    [CurrencyCode] => USD
                                    [Amount] => 0.0
                                    [AmountActive] => 1
                                    [AmountType] =>
                                    [CategoryID] => 1
                                    [SSRCode] => WCHR
                                    [Display] => 1
                                    [MaxCountServiceLevel] => 8
                                    [Refundable] =>
                                    [PNLActive] => 1
                                    [CutoffHours] => -1
                                    [Commissionable] =>
                                    [DisplayOrder] => 0
                                    [RevenueCategoryID] => 7
                                    [IATAStandardCodeType] =>
                                    [ServiceActive] => 1
                                    [MaxCountFlightLevel] => 0
                                    [QuantityAvailable] => 8
                                    [StartSalesDays] => -1
                                    [ApplicableTaxes] => stdClass Object
                                        (
                                        )

                                    [BoardingPassSsrOrder] => 999
                                    [Name] => Wheelchair (can Climb Stairs And Walk To Chair)
                                )

                        )

                )

This function is the ONLY one in the code modifying these values. If I set the function to always set them to false, all of them will be false. Any help?

Body:
No idea what is going on, but I ended up just adding this bit to the top of the for() inside the function and then set the Services equal to the ServicesTest and it fixed it.

foreach($flight->Services as $serv) {
    $code = $serv->SSRCode;
    $flight->Adults[$i]->ServicesTest->$code = ($get['service-'.$code.'-'.$i] == 'yes' ? true : false);
}

...

$flight->Adults[$i]->Services = $flight->Adults[$i]->ServicesTest;


问:
adding values to variable array VBA
I am trying to loop through a table that has a column for "customers" and "dollar amount". If my loop finds a customer called "greg" or "henry" I want to add his "dollar amount" to an array of an unknown size.

Can someone please help me?

答:
```<code>Private Sub ArrayMy(DataRange)
  Dim DataIndex() As String
  i = 0
  On Error Resume Next
  ReDim DataIndex(0)
  For Each c In DataRange
      DataIndex(i) = c
      i = i + 1
      ReDim Preserve DataIndex(i)
  Next
End Sub
</code>```

Title: adding values to variable array VBA


问:
PGAdmin: Not connected to the server or the connection to the server has been closed
i got this problem with postgreSQL, when i do a simple query of anything (CRUD), sometimes it works and almost always shows this message:

Not connected to the server or the connection to the server has been closed.

I don't know how to solve it and it started to irritate me, anyone know how to fix it?

UPDATE 1

I have been searching and it seems the pgadmin4 the problem (it seems because it's not 100% developed yet), i have been using pgadmin3 and that error doesn't show up.

答:
This issue has been fixed.

Upgrade to pgAdmin4 version 2.0. https://www.pgadmin.org/download/


问:
Chef Ruby object and collections
I've dipped my toe in chef and am having a few difficulties with what should be simple concepts.

I'm obtains data from a node by running a search; my plan is to iterate over the results and create an object of type X setting its variables as I go.

I'd like to store these objects in a collection so that I can access them later in the recipe to carry out other tasks and so on.

My GoogleFu has so far come up short and I'm worried that I'm tackling this in the wrong way.  My search is fine and returning the values, my separate class is also fine but the storing of these objects into a collection and then persisting that is proving more difficult.  Many posts frown against using arrays for my purpose(if it's possible) and I've not found anything similar to an ArrayList or Map.  Additionally, if I use a ruby collection, does it need to be maintained inside a ruby block?

Thanks for any help / advice.

答:
With Chef, you have several ways of storing persistent data:
1) set node attributes
2) chef data bags
3) chef vault
4) environments
5) environment recipes
6) roles

IMHO, you should decide where this data should reside by determining which of the items I listed it belongs to.

What does it apply to? What does it describe?

Title: Chef Ruby object and collections


问:
Balanced Binary Tree Vs Balanced Binary Search Tree
For each of these operations would a balanced binary search tree complete the task in a faster big oh time than a balanced binary tree?

Finding the smallest item in the tree.

I think balanced BST would have a faster big oh time than a balanced Binary Tree since you can just keep traversing left and find the smallest item. I think it would be O(log n).

Creating a list of all elements in the tree that are smaller than some value v.

For 2 could someone offer me an explanation about which one would have a faster big oh time?

答:
Creating a list of all elements in the tree that are smaller than some
  value v.

Well, in Big O notation both balanced binary search tree and balanced binary tree would perform the same and time would be O(N), which is linear time complexity.

For the Balanced Binary Search tree, we would do an inorder traversal and keep adding all the keys to the list until we encounter the node with key v(inorder traversal of BST leads to ascending ordering of keys). Now worst case occurs when v is the largest key that is present in the BST, therefore, time complexity is O(N).

For a balanced binary tree, its as good as traversing the entire tree and adding all the keys to the list that are less than v. So time complexity here also is O(N).


问:
Django and Restful APIs
I have been struggling with choosing a methodology for creating a RESTful API with Django. None of the approaches I've tried seem to be the "silver" bullet. WAPI from http://fi.am is probably the closest to what I would like to accomplish, however I am not sure if it is acceptable in a true RESTful API to have parameters that are resource identifiers be in the querystring instead of in a "clean" URL format. Any suggestions for modifying WAPIs RestBinding.PATTERN to "clean" up the URLs? Another option I've explored is Django-Rest-Interface. However this framework seems to violate one of the most important pieces I need, and that is to include the full resource URL for references to other resources (see http://jacobian.org/writing/rest-worst-practices/ Improper Use of Links). The final option is to use django-multiresponse and basically do it the long way.

Please offer me your best advice, especially people that have dealt with this decision.

答:
I would suggest you look into Django Rest Framework (DRF), play around with this and see if it suits your requirements. The reason I recommend DRF is because it makes making the API views really simple with the use of GenericAPIView classes, Mixin Classes and Mixed in Generic views. You can easily make use of tried and tested design patterns for making your API endpoints as well as keeping your code base neat and concise. You also DRY when writing your code which is always great. Your API views are literally 2-3 lines long.

You can checkout this tutorial http://programmathics.com/programming/python/django-rest-framework-setup/ that begins from setting up your environment to going through the different ways to make your RESTful API using the django rest framework.

Disclaimer: I am the creator of that website.

OwnerDisplayName: gsiegman

Title: Django and Restful APIs

LastEditorDisplayName: gsiegman


问:
Average top n values where next cell equals value
Having below data I would like to calculate average of top n values or top n% of values in column B where values in column A = C1.

I tried many different formulas but I can't get it to working.

```<code>{=AVERAGEIFS(B1:B14,A1:A14,C1,B1:B14,(IF(B1:B14>PERCENTILE(B1:B14,0.7),B1:B14)))}
{=AVERAGE(IF(A1:A14=C1,IF(B1:B14>PERCENTILE(B1:B14,0.7),B1:B14)))}
</code>```

```<code>    A   B   C
1   a   1   a
2   a   1   cs
3   cs  1   ffs
4   a   1   .
5   a   1   .
6   ffs 1   .
7   a   1   .
8   a   1   .
9   as  1   .
10  a   1   .
11  sfaq    1   .
12  a   1   .
13  aasf    1   .
14  a   1   .
15  a   1   .
16  a   1   .
17  qw  1   .
.   .   .   .
.   .   .   .
.   .   .   .
</code>```

Image of worksheet

答:
I think your AVERAGE version is on the right lines but when you calculate the PERCENTILE you also need the column A condition included within that calculation, e.g. this array formula

=AVERAGE(IF(A1:A14=C1,IF(B1:B14>PERCENTILE(IF(A1:A14=C1,B1:B14),0.7),B1:B14)))

confirmed with CTRL+SHIFT+ENTER

You can get the same result with a regular (non array) formula using AVERAGEIFS if you use AGGREGATE function to calculate the PERCENTILE, i.e. like this

=AVERAGEIFS(B1:B14,A1:A14,C1,B1:B14,">"&AGGREGATE(16,6,B1:B14/(A1:A14=C1),0.7))

I expect the two formulas to give the same results

Body:
Having below data I would like to calculate average of top n values or top n% of values in column B where values in column A = C1.

I tried many different formulas but I can't get it to working.

{=AVERAGEIFS(B1:B14,A1:A14,C1,B1:B14,(IF(B1:B14>PERCENTILE(B1:B14,0.7),B1:B14)))}
{=AVERAGE(IF(A1:A14=C1,IF(B1:B14>PERCENTILE(B1:B14,0.7),B1:B14)))}

    A   B   C
1   a   1   a
2   a   1   cs
3   cs  1   ffs
4   a   1   .
5   a   1   .
6   ffs 1   .
7   a   1   .
8   a   1   .
9   as  1   .
10  a   1   .
11  sfaq    1   .
12  a   1   .
13  aasf    1   .
14  a   1   .
15  a   1   .
16  a   1   .
17  qw  1   .
.   .   .   .
.   .   .   .
.   .   .   .

Image of worksheet


问:
Jekyll: Display all posts in the same page
I have been reading everything at Jekyll Docs, but I couldn't find a way to do this.

By default when generating a web, jekyll displays a list of the links of all your blog posts. Is there a way to display the content of all your blog posts in the same page? (alla blogspot/wordpress/traditional blog...)

答:
Found my solution from: This tutorial, which consists of editing index.md and adding the following:</p>

```<code>  {% for post in site.posts %}
  <article>
    <h2>
      <a href="{{ post.url }}">
        {{ post.title }}
      </a>
    </h2>
    <time datetime="{{ post.date | date: "%Y-%m-%d" }}">{{ post.date | date_to_long_string }}</time>
    {{ post.content }}
  </article>
{% endfor %}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Found my solution from: This tutorial, which consists of editing index.md and adding the following:

  {% for post in site.posts %}
  <article>
    <h2>
      <a href="{{ post.url }}">
        {{ post.title }}
      </a>
    </h2>
    <time datetime="{{ post.date | date: "%Y-%m-%d" }}">{{ post.date | date_to_long_string }}</time>
    {{ post.content }}
  </article>
{% endfor %}


问:
Android TranslateAnimation - what parameters of a View does it change?
This code moves a View by 10dp to the right:

```<code>FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
params.leftMargin += 10;
view.setLayoutParams(params);
</code>```

But how does android.view.animation.TranslateAnimation do it?

How can I detect if View's position has changed after TranslateAnimation was performed?

It looks like on Android sdk < 21, View's position is reset after animation and not reset otherwise.

答:
TranslateAnimation does not change object features itself it only changes it visual features. If you apply the code below.

```<code>    view.animate().translationY(v.getHeight());
</code>```

It moves view to position in y axis. To get back the view in it's first position you do not have to know its first position. You can do that only with this:

```<code>    view.animate().translationY(0);
</code>```

I'd like to think of it as taking view snapshots and then move it to somewhere else. So you don't have to change view's position permanently to move it around.

And you can detect if that worked by simply checking view's translationX or translationY property. (getTranslationX() method for example) Normally those numbers are zero , no matter what view's position was.

I hope it helps.

Body:
This code moves a View by 10dp to the right:

FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
params.leftMargin += 10;
view.setLayoutParams(params);

But how does android.view.animation.TranslateAnimation do it?

How can I detect if View's position has changed after TranslateAnimation was performed?

It looks like on Android sdk < 21, View's position is reset after animation and not reset otherwise.

Body:
TranslateAnimation does not change object features itself it only changes it visual features. If you apply the code below.

    view.animate().translationY(v.getHeight());

It moves view to position in y axis. To get back the view in it's first position you do not have to know its first position. You can do that only with this:

    view.animate().translationY(0);

I'd like to think of it as taking view snapshots and then move it to somewhere else. So you don't have to change view's position permanently to move it around.

And you can detect if that worked by simply checking view's translationX or translationY property. (getTranslationX() method for example) Normally those numbers are zero , no matter what view's position was.

I hope it helps.