问:
How to calculate path/diameter of edge attributes in igraph?
Here's an example of a data frame you can convert to an edgelist and then into a graph. Notice that I have added 'km' as an attribute to the edgelist.

I'm not sure how to add 'km' as an edge attribute (so the distance between two nodes), but pretend that it's been done.

```<code>inst2 = c(2, 3, 4, 5, 6)
motherinst2 = c(7, 8, 9, 10, 11)
km = c(20, 30, 40, 25, 60)
df2 = data.frame(inst2, motherinst2)
edgelist = cbind(df2, km)
g = graph_from_data_frame(edgelist)
</code>```

Now, how can I calculate the path lengths based on those km distances? I'm not interested in the number of edges or vertices in the path, just the sum of those km from a root to a leaf.

答:
The km edge attribute already exists. When using graph_from_data_frame() any information stored in the 3rd column and up are stored in the edge. You can pull information from an edge with the igraph::E() function.

```<code>E(g) #identifies all of the edges
E(g)$km #identifies all of the `km` attributes for each edge
E(g)$km[1] #identifies the `km` attribute for the first edge (connecting 2 -> 7)
</code>```

For completeness, let's say you have a node path that is greater than 1.

```<code>#lets add two more edges to the network
#and create a new and longer path between vertex named '2', and vertex named '7'
g <- g +
  edge('2', '6', km = 10) +
  edge('6', '7', km = 120)

#find all paths between 2 and 7
#don't forget that the names of vertices are strings, not numbers
paths <- igraph::all_simple_paths(g, '2', '7')
paths

#find the edge id for each of the connecting edges
#the below function accepts a vector of pairwise vectors.
#the ids are the edges between each pair of vectors
connecting_267 <- igraph::get.edge.ids(g, c('2','6' , '6','7'))
connecting_267

#get the km attribute for each of the edges
connecting_kms <- igraph::E(g)[connecting_267]$km
connecting_kms

sum(connecting_kms)
</code>```

igraph is pretty powerful. It is definitely worth spending time and exploring its documentation. Also, Katherine Ognyanova created an AWESOME tutorial that is definitely worth everyone's time.

Body:
Here's an example of a data frame you can convert to an edgelist and then into a graph. Notice that I have added 'km' as an attribute to the edgelist.

I'm not sure how to add 'km' as an edge attribute (so the distance between two nodes), but pretend that it's been done.

inst2 = c(2, 3, 4, 5, 6)
motherinst2 = c(7, 8, 9, 10, 11)
km = c(20, 30, 40, 25, 60)
df2 = data.frame(inst2, motherinst2)
edgelist = cbind(df2, km)
g = graph_from_data_frame(edgelist)

Now, how can I calculate the path lengths based on those km distances? I'm not interested in the number of edges or vertices in the path, just the sum of those km from a root to a leaf.

Body:
The km edge attribute already exists. When using graph_from_data_frame() any information stored in the 3rd column and up are stored in the edge. You can pull information from an edge with the igraph::E() function.

E(g) #identifies all of the edges
E(g)$km #identifies all of the `km` attributes for each edge
E(g)$km[1] #identifies the `km` attribute for the first edge (connecting 2 -> 7)

For completeness, let's say you have a node path that is greater than 1.

#lets add two more edges to the network
#and create a new and longer path between vertex named '2', and vertex named '7'
g <- g +
  edge('2', '6', km = 10) +
  edge('6', '7', km = 120)

#find all paths between 2 and 7
#don't forget that the names of vertices are strings, not numbers
paths <- igraph::all_simple_paths(g, '2', '7')
paths

#find the edge id for each of the connecting edges
#the below function accepts a vector of pairwise vectors.
#the ids are the edges between each pair of vectors
connecting_267 <- igraph::get.edge.ids(g, c('2','6' , '6','7'))
connecting_267

#get the km attribute for each of the edges
connecting_kms <- igraph::E(g)[connecting_267]$km
connecting_kms

sum(connecting_kms)

igraph is pretty powerful. It is definitely worth spending time and exploring its documentation. Also, Katherine Ognyanova created an AWESOME tutorial that is definitely worth everyone's time.


来源: stackexchange

问:
Prefill realm database swift 3.0
I'd like to use local realm database within the app without any backend connection and I would like to populate this database with initial data. I can't find any documentation on this.

I have:

Described models (as objects extended from RealmSwift)

Data that I
want to put in my realm db.

What is the correct flow for putting my data into the realm db and saving it?

Thank you!

答:
You can download the Realm Browser from the App Store and you can edit an empty realm file or you can import a scheme from a csv or xlsx file. Then save that and include it when you are shipping your app like @David-Pasztor said.

Note that you must have the scheme generated by your code first, and then you can copy the realm file generated and add rows and values.

ContentLicense: CC BY-SA 3.0

Title: Prefill realm database swift 3.0


问:
Explain how the following program works?
Here is the program in C language: (I removed some portion of the code which simply initializes VGA_COLOUR variables)

```<code>static inline uint8_t vga_entry_color(enum vga_color fg,
enum vga_color bg) {
    return fg | bg << 4;
}

static inline uint16_t vga_entry(unsigned char uc, uint8_t color) {
    return (uint16_t) uc | (uint16_t) color << 8;
}

size_t strlen(const char* str) {
size_t len = 0;
while (str[len])
    len++;
return len;
}

static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 25;

size_t terminal_row;
size_t terminal_column;
uint8_t terminal_color;
uint16_t* terminal_buffer;

void terminal_initialize(void) {
    terminal_row = 0;
    terminal_column = 0;
    terminal_color =
    vga_entry_color(VGA_COLOR_LIGHT_GREY,
    VGA_COLOR_BLACK);
    terminal_buffer = (uint16_t*) 0xB8000;
    for (size_t y = 0; y < VGA_HEIGHT; y++) {
        for (size_t x = 0; x < VGA_WIDTH; x++) {
            const size_t index = y * VGA_WIDTH + x;
            terminal_buffer[index] = vga_entry(' ', terminal_color);
        }
    }
}

void terminal_setcolor(uint8_t color) {
    terminal_color = color;
}

void terminal_putentryat(char c, uint8_t color, size_t x,
size_t y) {
    const size_t index = y * VGA_WIDTH + x;
    terminal_buffer[index] = vga_entry(c, color);
}

void terminal_putchar(char c) {
    terminal_putentryat(c, terminal_color, terminal_column, terminal_row);
    if (++terminal_column == VGA_WIDTH) {
        terminal_column = 0;
        if (++terminal_row == VGA_HEIGHT)
            terminal_row = 0;
    }
}

void terminal_write(const char* data, size_t size) {
    for (size_t i = 0; i < size; i++)
        terminal_putchar(data[i]);
}

void terminal_writestring(const char* data) {
    terminal_write(data, strlen(data));
}

#if defined(__cplusplus)
extern "C" /* Use C linkage for kernel_main. */
#endif
void kernel_main(void) {
    /* Initialize terminal interface */
    terminal_initialize();

    /* Newline support is left as an exercise. */
    terminal_writestring("Hello, kernel World!\n");
}
</code>```

It is from OSdev wiki, and although I do understand some parts of this program - actually kernel.c - I have problem with functions "terminal_initilialize", "terminal_putentryat", "terminal_putchar".  Any explanation is welcome.

答:
I hope that this explanations can give you some hints. By analyzing the code functions you should be able to figure out the rest.

VGA_WIDTH - width of the screen;
VGA_HEIGHT - height of the screen

x - horizontal position of the character on the screen

y - vertical position of the character on the screen

Since VGA card keeps all characters in a linear memory it has to use x, y,

VGA_WIDTH and VGA_WIDTH to calculate an index for its internal buffer to store a character at the proper memory location.

void terminal_initialize - this function initializes your terminal. It just puts spaces on the entire screen.

```<code>void terminal_putentryat(char c, uint8_t color, size_t x, size_t y)
</code>```

puts a character c, on the screen at the location (x,y).

void terminal_putchar(char c) - it puts a character c, at the screen.

This function  has terminal_column and terminal_row variables to track the current terminal column and row.

Body:
Here is the program in C language: (I removed some portion of the code which simply initializes VGA_COLOUR variables)

static inline uint8_t vga_entry_color(enum vga_color fg,
enum vga_color bg) {
    return fg | bg << 4;
}

static inline uint16_t vga_entry(unsigned char uc, uint8_t color) {
    return (uint16_t) uc | (uint16_t) color << 8;
}

size_t strlen(const char* str) {
size_t len = 0;
while (str[len])
    len++;
return len;
}

static const size_t VGA_WIDTH = 80;
static const size_t VGA_HEIGHT = 25;

size_t terminal_row;
size_t terminal_column;
uint8_t terminal_color;
uint16_t* terminal_buffer;

void terminal_initialize(void) {
    terminal_row = 0;
    terminal_column = 0;
    terminal_color =
    vga_entry_color(VGA_COLOR_LIGHT_GREY,
    VGA_COLOR_BLACK);
    terminal_buffer = (uint16_t*) 0xB8000;
    for (size_t y = 0; y < VGA_HEIGHT; y++) {
        for (size_t x = 0; x < VGA_WIDTH; x++) {
            const size_t index = y * VGA_WIDTH + x;
            terminal_buffer[index] = vga_entry(' ', terminal_color);
        }
    }
}

void terminal_setcolor(uint8_t color) {
    terminal_color = color;
}

void terminal_putentryat(char c, uint8_t color, size_t x,
size_t y) {
    const size_t index = y * VGA_WIDTH + x;
    terminal_buffer[index] = vga_entry(c, color);
}

void terminal_putchar(char c) {
    terminal_putentryat(c, terminal_color, terminal_column, terminal_row);
    if (++terminal_column == VGA_WIDTH) {
        terminal_column = 0;
        if (++terminal_row == VGA_HEIGHT)
            terminal_row = 0;
    }
}

void terminal_write(const char* data, size_t size) {
    for (size_t i = 0; i < size; i++)
        terminal_putchar(data[i]);
}

void terminal_writestring(const char* data) {
    terminal_write(data, strlen(data));
}

#if defined(__cplusplus)
extern "C" /* Use C linkage for kernel_main. */
#endif
void kernel_main(void) {
    /* Initialize terminal interface */
    terminal_initialize();

    /* Newline support is left as an exercise. */
    terminal_writestring("Hello, kernel World!\n");
}

It is from OSdev wiki, and although I do understand some parts of this program - actually kernel.c - I have problem with functions "terminal_initilialize", "terminal_putentryat", "terminal_putchar".  Any explanation is welcome.

Body:
I hope that this explanations can give you some hints. By analyzing the code functions you should be able to figure out the rest.

VGA_WIDTH - width of the screen;
VGA_HEIGHT - height of the screen

x - horizontal position of the character on the screen

y - vertical position of the character on the screen

Since VGA card keeps all characters in a linear memory it has to use x, y,

VGA_WIDTH and VGA_WIDTH to calculate an index for its internal buffer to store a character at the proper memory location.

void terminal_initialize - this function initializes your terminal. It just puts spaces on the entire screen.

void terminal_putentryat(char c, uint8_t color, size_t x, size_t y)

puts a character c, on the screen at the location (x,y).

void terminal_putchar(char c) - it puts a character c, at the screen.

This function  has terminal_column and terminal_row variables to track the current terminal column and row.


问:
Flask-SQLAlchemy (mssql+pyodbc) and Existing Models with Blueprint
I have this following Flask application/folder structure in python3.6 Enviroment:

```<code>site/
   __init__.py
   models.py
   static/
   templates/
     dashboard/
       index.html
     login/
       index.html
   views/
     __init__.py
     login.py
config.py
run.py
</code>```

My files looks like this:

run.py

```<code>from site import app
app.run()
</code>```

config.py

```<code>class BaseConfig(object):
  DEBUG = False
  TESTING = False
  WFT_CSRF_ENABLED = True

class DevConfig(BaseConfig):
  DEBUG = True
  SECRET_KEY = 'dev'
  SQLALCHEMY_DATABASE_URI = 'DRIVER={ODBC Driver 11 for SQL Server};SERVER=myServer;DATABASE=myDB;TRUSTED_CONNECTION=yes'
  SQLALCHEMY_TRACK_MODIFICATIONS = False
</code>```

site/init.py

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config.DevConfig')
db = SQLAlchemy(app)

from site.views import login
app.register_blueprint(login.mod)
</code>```

site/views/login.py

```<code>from flask import Blueprint, render_template

mod = Blueprint('login', __name__)

@mod.route('/')
def index():
  return render_template('login/index.html')
</code>```

site/models.py

```<code>class User(db.Model):
    __table__ = db.Model.metadata.tables['users']

    def __repr__(self):
        return '<User %r>' % self.username
</code>```

what i am trying to do is to connect and use a existing model in my ms-sql database which is called user.

I am very new with Flask, Flask-SQLAlchemy, Blueprint and Python and I am stucked on how to use the db.Model in my login.py. How to achieved this in a Blueprint paradigm?

Any help and direction will be much appriciated and thanks for the help in advanced!

regards,
maki

答:
you can add the following lines to your login.py:

```<code>from site import db
from site.models import User
</code>```

to add an new user to the database you can use this :

```<code>new_user = User()
db.session.add(new_user)
db.session.commit()
</code>```

and add this in your user table :

```<code>_tablename__ = 'user'
</code>```

you will need to change you database URI in the config by following the syntax suggested in the flask_sqlalchemy doc

replace what you have by this :

```<code>SQLALCHEMY_DATABASE_URI : mysql://username:password@server_adress/db_name
</code>```

for user authentification i can suggest you flask_login

Body:
I have this following Flask application/folder structure in python3.6 Enviroment:

site/
   __init__.py
   models.py
   static/
   templates/
     dashboard/
       index.html
     login/
       index.html
   views/
     __init__.py
     login.py
config.py
run.py

My files looks like this:

run.py

from site import app
app.run()

config.py

class BaseConfig(object):
  DEBUG = False
  TESTING = False
  WFT_CSRF_ENABLED = True

class DevConfig(BaseConfig):
  DEBUG = True
  SECRET_KEY = 'dev'
  SQLALCHEMY_DATABASE_URI = 'DRIVER={ODBC Driver 11 for SQL Server};SERVER=myServer;DATABASE=myDB;TRUSTED_CONNECTION=yes'
  SQLALCHEMY_TRACK_MODIFICATIONS = False

site/init.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config.DevConfig')
db = SQLAlchemy(app)

from site.views import login
app.register_blueprint(login.mod)

site/views/login.py

from flask import Blueprint, render_template

mod = Blueprint('login', __name__)

@mod.route('/')
def index():
  return render_template('login/index.html')

site/models.py

class User(db.Model):
    __table__ = db.Model.metadata.tables['users']

    def __repr__(self):
        return '<User %r>' % self.username

what i am trying to do is to connect and use a existing model in my ms-sql database which is called user.

I am very new with Flask, Flask-SQLAlchemy, Blueprint and Python and I am stucked on how to use the db.Model in my login.py. How to achieved this in a Blueprint paradigm?

Any help and direction will be much appriciated and thanks for the help in advanced!

regards,
maki

Body:
you can add the following lines to your login.py:

from site import db
from site.models import User

to add an new user to the database you can use this :

new_user = User()
db.session.add(new_user)
db.session.commit()

and add this in your user table :

_tablename__ = 'user'

you will need to change you database URI in the config by following the syntax suggested in the flask_sqlalchemy doc

replace what you have by this :

SQLALCHEMY_DATABASE_URI : mysql://username:password@server_adress/db_name

for user authentification i can suggest you flask_login


问:
jQuery not recognizing Symfony JSON?
I'm trying to get my JSON data from Symfony but it doesn't seem to be working right. Below is the snippet of symfony code:

```<code>$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
return $this->renderPartial('listJsonResponse',
array('jsonSlots' => json_encode($this->jsonQuery)));
</code>```

The above works fine and hits the partial. All that is in my partial is this:

```<code><?php echo $jsonSlots ?>
</code>```

Now according to Firebug this gets populated properly. Below is a copy of the response

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

Note if I take out the Content/Type header it changes slightly. I get the same response tab as above but also an html tab with the above parsed into html. Which shows like this:

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

I know the JSON function is hitting, but it isn't parsing the success function and alerting me any sort of data. the JavasScript is shown below and is wrapped in a jquery ready tag

```<code>$.getJSON('/frontend_dev.php/module/listJSONSlots', function(data) {
    alert(data);
});
</code>```

Any ideas why I can't get to the alert?

答: I don't know about Synfony and its renderPartial method. But clearly it replaces special characters by their &...; equivalent. You should look for a way to disable this

Title: jQuery not recognizing Symfony JSON?

Body:
I'm trying to get my JSON data from Symfony but it doesn't seem to be working right. Below is the snippet of symfony code:

$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
return $this->renderPartial('listJsonResponse',
array('jsonSlots' => json_encode($this->jsonQuery)));

The above works fine and hits the partial. All that is in my partial is this:

<?php echo $jsonSlots ?>

Now according to Firebug this gets populated properly. Below is a copy of the response

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

Note if I take out the Content/Type header it changes slightly. I get the same response tab as above but also an html tab with the above parsed into html. Which shows like this:

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

I know the JSON function is hitting, but it isn't parsing the success function and alerting me any sort of data. the JavasScript is shown below and is wrapped in a jquery ready tag

$.getJSON('/frontend_dev.php/module/listJSONSlots', function(data) {
    alert(data);
});

Any ideas why I can't get to the alert?

ContentLicense: CC BY-SA 2.5


问:
Reverse all words, set "." and do the same for the next sentences
I´m trying to program for so long now and it won´t work. I need a program, which does following:

User Input: I´m looking for some food. I love food.
System Print: Food some for looking I´m. Food love I.

Reverse the words, UpperWord the first word, start with next sentence a keep the "." at it´s place.

```<code>package finaledition;

public class finaledition {
    public static void main(String[] args) {
        StringBuilder outputString= new StringBuilder();
        String satz;
        String wort;

        System.out.print("Bitte geben Sie einen String ein: ");
        String text = Input.readString();

        while (text.indexOf('.') > 0) {
            satz = text.substring(0, text.indexOf('.'));
            text = text.substring(text.indexOf('.') + 1);

            while (satz.lastIndexOf(' ') > 0) {
                wort = satz.substring(satz.lastIndexOf(' ') + 1);
                outputString.append(wort);
                satz = satz.substring(0, satz.lastIndexOf(' '));
            }
            System.out.print(outputString);
        }
    }
}
</code>```

The actual result is:

```<code>foodsomeforlookingfoodsomeforlookingfoodlove
</code>```

答:
Nested loops is hard to understand and leads to errors and time wasting in attempts to dubug and understand that procedural code, instead of this you need to use oop, java is oop language. You need to create class Sentence that completely resolve your problem.

```<code>import java.util.*;
import java.util.stream.*;

public class Main {

    public static void main(String[] args) {
        final String userInput = "I´m looking for some food. I love food";
        final String expectedResult = "Food some for looking I´m. Food love I.";
        String[] sentences = userInput.split("\\. ");
        String reversedSentences = Stream.of(sentences)
                .map(sentenceString -> new Sentence(sentenceString))
                .map(sentence -> sentence.reverse())
                .map(sentence -> sentence.firstLetterToUpperCase())
                .map(sentence -> sentence.removeAllDots())
                .map(sentence -> sentence.dotInTheEnd())
                .map(sentence -> sentence.toString())
                .collect(Collectors.joining(" "));
        System.out.println(reversedSentences.equals(expectedResult)); //returns true
    }

}

final class Sentence {
    private final String sentence;

    Sentence(String sentence) {
        this.sentence = sentence;
    }

    Sentence reverse() {
        String[] words = sentence.split(" ");
        Collections.reverse(Arrays.asList(words));
        return new Sentence(String.join(" ", words));
    }

    Sentence firstLetterToUpperCase() {
        String firstLetter = sentence.substring(0, 1);
        String anotherPart = sentence.substring(1);
        return new Sentence(firstLetter.toUpperCase() + anotherPart);
    }

    Sentence dotInTheEnd() {
        return new Sentence(sentence + ".");
    }

    Sentence removeAllDots() {
        return new Sentence(sentence.replaceAll("//.", ""));
    }

    @Override
    public String toString() {
        return sentence;
    }
}
</code>```

Body:
I´m trying to program for so long now and it won´t work. I need a program, which does following:

User Input: I´m looking for some food. I love food.
System Print: Food some for looking I´m. Food love I.

Reverse the words, UpperWord the first word, start with next sentence a keep the "." at it´s place.

package finaledition;

public class finaledition {
    public static void main(String[] args) {
        StringBuilder outputString= new StringBuilder();
        String satz;
        String wort;

        System.out.print("Bitte geben Sie einen String ein: ");
        String text = Input.readString();

        while (text.indexOf('.') > 0) {
            satz = text.substring(0, text.indexOf('.'));
            text = text.substring(text.indexOf('.') + 1);

            while (satz.lastIndexOf(' ') > 0) {
                wort = satz.substring(satz.lastIndexOf(' ') + 1);
                outputString.append(wort);
                satz = satz.substring(0, satz.lastIndexOf(' '));
            }
            System.out.print(outputString);
        }
    }
}

The actual result is:

foodsomeforlookingfoodsomeforlookingfoodlove

Body:
Nested loops is hard to understand and leads to errors and time wasting in attempts to dubug and understand that procedural code, instead of this you need to use oop, java is oop language. You need to create class Sentence that completely resolve your problem.

import java.util.*;
import java.util.stream.*;

public class Main {

    public static void main(String[] args) {
        final String userInput = "I´m looking for some food. I love food";
        final String expectedResult = "Food some for looking I´m. Food love I.";
        String[] sentences = userInput.split("\\. ");
        String reversedSentences = Stream.of(sentences)
                .map(sentenceString -> new Sentence(sentenceString))
                .map(sentence -> sentence.reverse())
                .map(sentence -> sentence.firstLetterToUpperCase())
                .map(sentence -> sentence.removeAllDots())
                .map(sentence -> sentence.dotInTheEnd())
                .map(sentence -> sentence.toString())
                .collect(Collectors.joining(" "));
        System.out.println(reversedSentences.equals(expectedResult)); //returns true
    }

}

final class Sentence {
    private final String sentence;

    Sentence(String sentence) {
        this.sentence = sentence;
    }

    Sentence reverse() {
        String[] words = sentence.split(" ");
        Collections.reverse(Arrays.asList(words));
        return new Sentence(String.join(" ", words));
    }

    Sentence firstLetterToUpperCase() {
        String firstLetter = sentence.substring(0, 1);
        String anotherPart = sentence.substring(1);
        return new Sentence(firstLetter.toUpperCase() + anotherPart);
    }

    Sentence dotInTheEnd() {
        return new Sentence(sentence + ".");
    }

    Sentence removeAllDots() {
        return new Sentence(sentence.replaceAll("//.", ""));
    }

    @Override
    public String toString() {
        return sentence;
    }
}


问:
Script is telling me that it's not a function ERROR
Probably a really quick fix but I'm stuck on what it is - I'm getting information from an API (https://api.roleplay.co.uk/v1/player/76561198062083666) where the number of vehicles keeps changing, along with the classname and classtypes. I'm trying to create a list of the names of vehicles seperated by commas, and then give each vehicle name the class of its classtype as well so that I can colour them based on their type (i.e. car, boat, plane etc.). I believe my code down here isn't working because you can't put multiple variables behind the .join but how do i get past that?

```<code>var vehicleList = data.vehicles.map(v => v.classname);
var vehicleType = data.vehicles.map(v => v.classtype);

var content = ("<span class='" + vehicleType + "'>"+ vehicleList + "</span>).join(", ");

document.getElementById("vehicle").textContent = content;
</code>```

It's giving me the following error:

```<code>player.js:404 Uncaught TypeError: (((("<span class='" + vehicleType) + "'>") + vehicleList) + "</span>").join is not a function
    at Object.success (player.js:404)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)
</code>```

答:
I believe this achieves what you are trying to do.

var data = {
  vehicles: [
    { classtype: "test1", classname: "A" },
    { classtype: "test2", classname: "B" },
    { classtype: "test3", classname: "C" }
  ]
}

var content = data.vehicles.map(v => "" + v.classname + "").join(", ");

document.getElementById("vehicle").innerHTML = content;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="vehicle"></div></code>```

Edit:

var data = {
    "uid": 169243,
    "name": "PC Ant Arni",
    "steamid": "76561198062083666",
    "forumname": null,
    "forumid": null,
    "forumurl": null,
    "steam": {
        "name": "Ant Arni",
        "profileurl": "https:\/\/steamcommunity.com\/id\/Antarni\/",
        "avatarSmall": "https:\/\/steamcdn-a.akamaihd.net\/steamcommunity\/public\/images\/avatars\/25\/25f4a505cbce0a9b1deacb7468e18898bcff484f.jpg",
        "avatarMedium": "https:\/\/steamcdn-a.akamaihd.net\/steamcommunity\/public\/images\/avatars\/25\/25f4a505cbce0a9b1deacb7468e18898bcff484f_medium.jpg",
        "avatarLarge": "https:\/\/steamcdn-a.akamaihd.net\/steamcommunity\/public\/images\/avatars\/25\/25f4a505cbce0a9b1deacb7468e18898bcff484f_full.jpg"
    },
    "guid": "33b56e488b3d41d67ff3bc1f57b3d101",
    "cash": 0,
    "bank": 11048411,
    "adminlevel": 0,
    "wanted": false,
    "groupid": 204,
    "grouprank": 3,
    "groupname": "The Copper Kings",
    "unmcrank": 0,
    "unmcair": 0,
    "unmcranger": 0,
    "unmclastlogin": null,
    "policerank": 3,
    "npasrank": 0,
    "mporank": 2,
    "arrank": 0,
    "ncarank": 0,
    "rturank": 1,
    "undercoverrank": "0",
    "policelastlogin": "2017-12-03 19:19:15",
    "nhsrank": 4,
    "nhsarrank": 0,
    "nhsrirrank": 1,
    "nhslastlogin": "2017-11-05 21:27:15",
    "civ_licenses": [{
        "license": "driver",
        "owned": true
    }, {
        "license": "air",
        "owned": true
    }, {
        "license": "heroin",
        "owned": true
    }, {
        "license": "marijuana",
        "owned": true
    }, {
        "license": "boat",
        "owned": true
    }, {
        "license": "oil",
        "owned": true
    }, {
        "license": "dive",
        "owned": true
    }, {
        "license": "truck",
        "owned": true
    }, {
        "license": "gun",
        "owned": true
    }, {
        "license": "rebel",
        "owned": true
    }, {
        "license": "coke",
        "owned": true
    }, {
        "license": "diamond",
        "owned": true
    }, {
        "license": "copper",
        "owned": true
    }, {
        "license": "plastic",
        "owned": true
    }, {
        "license": "aluminium",
        "owned": true
    }, {
        "license": "silica",
        "owned": true
    }, {
        "license": "iron",
        "owned": true
    }, {
        "license": "sand",
        "owned": true
    }, {
        "license": "salt",
        "owned": true
    }, {
        "license": "cement",
        "owned": true
    }, {
        "license": "home",
        "owned": true
    }, {
        "license": "event",
        "owned": false
    }, {
        "license": "meth",
        "owned": true
    }, {
        "license": "taxi",
        "owned": true
    }, {
        "license": "arac",
        "owned": true
    }, {
        "license": "rebelimports",
        "owned": true
    }],
    "vehicles": [{
        "id": 360502,
        "classname": "B_Quadbike_01_F",
        "type": "Car",
        "color": 7
    }, {
        "id": 360505,
        "classname": "C_Offroad_01_F",
        "type": "Car",
        "color": 4
    }, {
        "id": 364532,
        "classname": "C_Van_01_box_F",
        "type": "Car",
        "color": 1
    }, {
        "id": 367013,
        "classname": "C_Kart_01_Vrana_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 373584,
        "classname": "O_MRAP_02_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 386845,
        "classname": "C_Hatchback_01_sport_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 392893,
        "classname": "C_Scooter_Transport_01_F",
        "type": "Ship",
        "color": 3
    }, {
        "id": 393490,
        "classname": "B_Truck_01_box_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 398146,
        "classname": "O_Plane_CAS_02_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 402207,
        "classname": "B_Truck_01_box_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 402335,
        "classname": "O_LSV_02_unarmed_F",
        "type": "Car",
        "color": 1
    }, {
        "id": 407171,
        "classname": "C_Scooter_Transport_01_F",
        "type": "Ship",
        "color": 4
    }, {
        "id": 414610,
        "classname": "C_Plane_Civil_01_racing_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 414696,
        "classname": "C_Hatchback_01_sport_F",
        "type": "Car",
        "color": 3
    }, {
        "id": 415938,
        "classname": "C_Plane_Civil_01_racing_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 415939,
        "classname": "I_Heli_light_03_unarmed_F",
        "type": "Air",
        "color": 2
    }, {
        "id": 419203,
        "classname": "I_C_Offroad_02_unarmed_F",
        "type": "Car",
        "color": 5
    }, {
        "id": 420228,
        "classname": "B_T_VTOL_01_infantry_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 420230,
        "classname": "B_Heli_Transport_03_unarmed_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 420248,
        "classname": "I_Truck_02_covered_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 427634,
        "classname": "O_MRAP_02_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 427635,
        "classname": "O_Heli_Light_02_unarmed_F",
        "type": "Air",
        "color": 3
    }, {
        "id": 427640,
        "classname": "C_Hatchback_01_sport_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 427641,
        "classname": "O_Heli_Transport_04_bench_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 429865,
        "classname": "I_Truck_02_fuel_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 438410,
        "classname": "C_Plane_Civil_01_racing_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 445053,
        "classname": "B_Heli_Light_01_F",
        "type": "Air",
        "color": 14
    }, {
        "id": 445054,
        "classname": "B_Heli_Light_01_F",
        "type": "Air",
        "color": 3
    }, {
        "id": 445857,
        "classname": "B_T_VTOL_01_infantry_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 447813,
        "classname": "C_Van_02_vehicle_F",
        "type": "Car",
        "color": 7
    }, {
        "id": 447814,
        "classname": "C_Van_02_transport_F",
        "type": "Car",
        "color": 7
    }, {
        "id": 448115,
        "classname": "I_G_Van_02_transport_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 448119,
        "classname": "I_G_Van_02_vehicle_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 453900,
        "classname": "C_Van_01_fuel_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 458437,
        "classname": "O_Plane_Fighter_02_Stealth_F",
        "type": "Air",
        "color": 0
    }]
};
var content = data.vehicles.map(v => "" + v.classname + "").join(", ");

document.getElementById("vehicle").innerHTML = content;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="vehicle"></div></code>```

Body:
Probably a really quick fix but I'm stuck on what it is - I'm getting information from an API (https://api.roleplay.co.uk/v1/player/76561198062083666) where the number of vehicles keeps changing, along with the classname and classtypes. I'm trying to create a list of the names of vehicles seperated by commas, and then give each vehicle name the class of its classtype as well so that I can colour them based on their type (i.e. car, boat, plane etc.). I believe my code down here isn't working because you can't put multiple variables behind the .join but how do i get past that?

var vehicleList = data.vehicles.map(v => v.classname);
var vehicleType = data.vehicles.map(v => v.classtype);

var content = (""+ vehicleList + ").join(", ");

document.getElementById("vehicle").textContent = content;

It's giving me the following error:

player.js:404 Uncaught TypeError: (((("") + vehicleList) + "").join is not a function
    at Object.success (player.js:404)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at A (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

Body:
I believe this achieves what you are trying to do.

var data = {
  vehicles: [
    { classtype: "test1", classname: "A" },
    { classtype: "test2", classname: "B" },
    { classtype: "test3", classname: "C" }
  ]
}

var content = data.vehicles.map(v => "<span class='" + v.classtype + "'>" + v.classname + "</span>").join(", ");

document.getElementById("vehicle").innerHTML = content;

<div id="vehicle"></div>

Edit:

var data = {
    "uid": 169243,
    "name": "PC Ant Arni",
    "steamid": "76561198062083666",
    "forumname": null,
    "forumid": null,
    "forumurl": null,
    "steam": {
        "name": "Ant Arni",
        "profileurl": "https:\/\/steamcommunity.com\/id\/Antarni\/",
        "avatarSmall": "https:\/\/steamcdn-a.akamaihd.net\/steamcommunity\/public\/images\/avatars\/25\/25f4a505cbce0a9b1deacb7468e18898bcff484f.jpg",
        "avatarMedium": "https:\/\/steamcdn-a.akamaihd.net\/steamcommunity\/public\/images\/avatars\/25\/25f4a505cbce0a9b1deacb7468e18898bcff484f_medium.jpg",
        "avatarLarge": "https:\/\/steamcdn-a.akamaihd.net\/steamcommunity\/public\/images\/avatars\/25\/25f4a505cbce0a9b1deacb7468e18898bcff484f_full.jpg"
    },
    "guid": "33b56e488b3d41d67ff3bc1f57b3d101",
    "cash": 0,
    "bank": 11048411,
    "adminlevel": 0,
    "wanted": false,
    "groupid": 204,
    "grouprank": 3,
    "groupname": "The Copper Kings",
    "unmcrank": 0,
    "unmcair": 0,
    "unmcranger": 0,
    "unmclastlogin": null,
    "policerank": 3,
    "npasrank": 0,
    "mporank": 2,
    "arrank": 0,
    "ncarank": 0,
    "rturank": 1,
    "undercoverrank": "0",
    "policelastlogin": "2017-12-03 19:19:15",
    "nhsrank": 4,
    "nhsarrank": 0,
    "nhsrirrank": 1,
    "nhslastlogin": "2017-11-05 21:27:15",
    "civ_licenses": [{
        "license": "driver",
        "owned": true
    }, {
        "license": "air",
        "owned": true
    }, {
        "license": "heroin",
        "owned": true
    }, {
        "license": "marijuana",
        "owned": true
    }, {
        "license": "boat",
        "owned": true
    }, {
        "license": "oil",
        "owned": true
    }, {
        "license": "dive",
        "owned": true
    }, {
        "license": "truck",
        "owned": true
    }, {
        "license": "gun",
        "owned": true
    }, {
        "license": "rebel",
        "owned": true
    }, {
        "license": "coke",
        "owned": true
    }, {
        "license": "diamond",
        "owned": true
    }, {
        "license": "copper",
        "owned": true
    }, {
        "license": "plastic",
        "owned": true
    }, {
        "license": "aluminium",
        "owned": true
    }, {
        "license": "silica",
        "owned": true
    }, {
        "license": "iron",
        "owned": true
    }, {
        "license": "sand",
        "owned": true
    }, {
        "license": "salt",
        "owned": true
    }, {
        "license": "cement",
        "owned": true
    }, {
        "license": "home",
        "owned": true
    }, {
        "license": "event",
        "owned": false
    }, {
        "license": "meth",
        "owned": true
    }, {
        "license": "taxi",
        "owned": true
    }, {
        "license": "arac",
        "owned": true
    }, {
        "license": "rebelimports",
        "owned": true
    }],
    "vehicles": [{
        "id": 360502,
        "classname": "B_Quadbike_01_F",
        "type": "Car",
        "color": 7
    }, {
        "id": 360505,
        "classname": "C_Offroad_01_F",
        "type": "Car",
        "color": 4
    }, {
        "id": 364532,
        "classname": "C_Van_01_box_F",
        "type": "Car",
        "color": 1
    }, {
        "id": 367013,
        "classname": "C_Kart_01_Vrana_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 373584,
        "classname": "O_MRAP_02_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 386845,
        "classname": "C_Hatchback_01_sport_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 392893,
        "classname": "C_Scooter_Transport_01_F",
        "type": "Ship",
        "color": 3
    }, {
        "id": 393490,
        "classname": "B_Truck_01_box_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 398146,
        "classname": "O_Plane_CAS_02_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 402207,
        "classname": "B_Truck_01_box_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 402335,
        "classname": "O_LSV_02_unarmed_F",
        "type": "Car",
        "color": 1
    }, {
        "id": 407171,
        "classname": "C_Scooter_Transport_01_F",
        "type": "Ship",
        "color": 4
    }, {
        "id": 414610,
        "classname": "C_Plane_Civil_01_racing_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 414696,
        "classname": "C_Hatchback_01_sport_F",
        "type": "Car",
        "color": 3
    }, {
        "id": 415938,
        "classname": "C_Plane_Civil_01_racing_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 415939,
        "classname": "I_Heli_light_03_unarmed_F",
        "type": "Air",
        "color": 2
    }, {
        "id": 419203,
        "classname": "I_C_Offroad_02_unarmed_F",
        "type": "Car",
        "color": 5
    }, {
        "id": 420228,
        "classname": "B_T_VTOL_01_infantry_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 420230,
        "classname": "B_Heli_Transport_03_unarmed_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 420248,
        "classname": "I_Truck_02_covered_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 427634,
        "classname": "O_MRAP_02_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 427635,
        "classname": "O_Heli_Light_02_unarmed_F",
        "type": "Air",
        "color": 3
    }, {
        "id": 427640,
        "classname": "C_Hatchback_01_sport_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 427641,
        "classname": "O_Heli_Transport_04_bench_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 429865,
        "classname": "I_Truck_02_fuel_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 438410,
        "classname": "C_Plane_Civil_01_racing_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 445053,
        "classname": "B_Heli_Light_01_F",
        "type": "Air",
        "color": 14
    }, {
        "id": 445054,
        "classname": "B_Heli_Light_01_F",
        "type": "Air",
        "color": 3
    }, {
        "id": 445857,
        "classname": "B_T_VTOL_01_infantry_F",
        "type": "Air",
        "color": 0
    }, {
        "id": 447813,
        "classname": "C_Van_02_vehicle_F",
        "type": "Car",
        "color": 7
    }, {
        "id": 447814,
        "classname": "C_Van_02_transport_F",
        "type": "Car",
        "color": 7
    }, {
        "id": 448115,
        "classname": "I_G_Van_02_transport_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 448119,
        "classname": "I_G_Van_02_vehicle_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 453900,
        "classname": "C_Van_01_fuel_F",
        "type": "Car",
        "color": 0
    }, {
        "id": 458437,
        "classname": "O_Plane_Fighter_02_Stealth_F",
        "type": "Air",
        "color": 0
    }]
};
var content = data.vehicles.map(v => "<span class='" + v.type + "'>" + v.classname + "</span>").join(", ");

document.getElementById("vehicle").innerHTML = content;

<div id="vehicle"></div>


问:
How to add class name on DropdownButton component in `react-bootstrap`
I use below components from react-bootstrap:

```<code>import { DropdownButton, MenuItem } from 'react-bootstrap';
</code>```

When I use DropdownButton in my component, it creates a
 with a nested <button>. If I set className on DropdownButton like below:

```<code><DropdownButton className='myDropdown'>
</code>```

the class name myDropdown will apply to the <button> DOM, how can I set the class name for the
 DOM?

答:
```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { DropdownButton, MenuItem } from 'react-bootstrap';
require('bootstrap/dist/css/bootstrap.css');

export default class MyMenu extends React.Component {

  render() {
    return (
    <DropdownButton title="Dropdownxs">
      <MenuItem href="#books">cricket</MenuItem>
      <MenuItem href="#podcasts">Podcasts</MenuItem>
      <MenuItem href="#">Football</MenuItem>
      <MenuItem href="#">Hockey</MenuItem>
      <MenuItem href="#addBlog">kabadi</MenuItem>
    </DropdownButton>
    );
  }
}

ReactDOM.render(
  React.createElement(ModuleMenu, null),
  document.getElementById('root')
);
</code>```

Body:
I use below components from react-bootstrap:

import { DropdownButton, MenuItem } from 'react-bootstrap';

When I use DropdownButton in my component, it creates a
 with a nested <button>. If I set className on DropdownButton like below:

<DropdownButton className='myDropdown'>

the class name myDropdown will apply to the <button> DOM, how can I set the class name for the
 DOM?


问:
how to create a pipe module Angular
I have a module which is a a group of pipes. When I try to install this module in my app, it says that the xxx pipe is not found

my app.module looks something like this:

```<code>import { PipesModule } from '@Pricetravel/pipes.module';
@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    PipesModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Is there a special way to create the pipe module? or a special way to import it?

thanks and greetings!

答:
This is example of pipes.module.ts :

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UnescapePipe } from './pipes/unescape.pipe';
import { HtmlDecodePipe } from './pipes/html-decode.pipe';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [UnescapePipe, HtmlDecodePipe],
  exports: [UnescapePipe, HtmlDecodePipe]
})
export class PipesModule { }```

ContentLicense: CC BY-SA 4.0

Title: how to create a pipe module Angular

Body:
I have a module which is a a group of pipes. When I try to install this module in my app, it says that the xxx pipe is not found

my app.module looks something like this:

import { PipesModule } from '@Pricetravel/pipes.module';
@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    PipesModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Is there a special way to create the pipe module? or a special way to import it?

thanks and greetings!


问:
How to search two driver.find_element_by_partial_link_text
I am trying to create an automated bot to purchase items from supreme python/selenium.

When I am on the products page and I use a driver.find_element_by_partial_link_text('Flight Pant') to find the product I want to buy, however I also want to select the colour of the product so I use a driver.find_element_by_partial_link_text('Black') but by doing this I am returned with the first Black product on the page instead of Flight pants that are Black. Any idea how I would achieve this goal?

here is the site link where I am try to achieve this,

http://www.supremenewyork.com/shop/all/pants

Note - I am unable to use xpaths for this, as the products change on a weekly bases so I would be unable to get the xpath for the product before it goes live on the site.

Any advice or guidance would be greatly appreciated.

答:
You can use XPath, but the maneuver is slightly trickier. The XPath would be:

```<code>driver.find_element_by_xpath('//*[contains(text(), "Flight Pant")]/../following-sibling::p/a[contains(text(), "Black")]')
</code>```

Assuming the structure of the page doesn't change on a weekly basis... To explain my XPath:

//*[contains(text(), "Flight Pant")]

Select any node that contains the text "Flight Pant". These are all  tags.

/../following-sibling::p

Notice how the DOM looks:

```<code><h1>
  <a class="name-link" href="/shop/pants/dfkjdafkj">Flight Pant</a>
</h1>
<p>
  <a class="name-link" href="/shop/pants/pvfcp0txzy">Black</a>
</p>
</code>```

So we need to go to the parent and find its sibling that is a
 element.

/a[contains(text(), "Black")]

Now go to the  tag that has the text Black.

The reason there's not really any other alternative to XPath is because there's no unique way to identify the desired element by any other means (tag name, class, link text, etc.)

Body:
You can use XPath, but the maneuver is slightly trickier. The XPath would be:

driver.find_element_by_xpath('//*[contains(text(), "Flight Pant")]/../following-sibling::p/a[contains(text(), "Black")]')

Assuming the structure of the page doesn't change on a weekly basis... To explain my XPath:

//*[contains(text(), "Flight Pant")]

Select any node that contains the text "Flight Pant". These are all <a> tags.

/../following-sibling::p

Notice how the DOM looks:

<h1>
  <a class="name-link" href="/shop/pants/dfkjdafkj">Flight Pant</a>
</h1>
<p>
  <a class="name-link" href="/shop/pants/pvfcp0txzy">Black</a>
</p>

So we need to go to the parent and find its sibling that is a <p> element.

/a[contains(text(), "Black")]

Now go to the <a> tag that has the text Black.

The reason there's not really any other alternative to XPath is because there's no unique way to identify the desired element by any other means (tag name, class, link text, etc.)


问:
Python Remote Procedure Call (Without the Remote Part)
I have a Python server which is not running as root, which fronts an application I am developing. However there are some application features which require access to RAW sockets which means root privileges.

Obviously I do not want to run the main server as root, and so my solution is to create a daemon process or command line script which runs as root providing guarded access to said features.

However I want put aside stdin/stdout communication and use an RPC style of interaction such as Pyro. But this exposes the RPC interface to anyone with network access to the machine, whereas I know that the process calling the RPC methods will be another process on the same machine.

Is there not a sort of inter-process procedure call standard which could be used in a similar (local machine only) fashion? I imagine the server doing something like this:

```<code># Server not running as root
pythonically, returned, values = other_process_running_as_root.some_method()
</code>```

And the process running as root exposing a method:

```<code># Daemon running as root
@expose_this_method
def some_method():
    # Play with RAW sockets
    return pythonically, returned, values
</code>```

Is anything like this possible?

答:
Following my comment, I was interested to see if it was possible, so I had a go at putting this together: https://github.com/takowl/ZeroRPC

Bear in mind that this is thrown together in an hour or so, so it's almost certainly inferior to any serious solution (e.g. any errors on the server side will crash it...). But it works as you suggested:

Server:

```<code>rpcserver = zerorpc.Server("ipc://myrpc.ipc")

@rpcserver.expose
def product(a, b):
    return a * b

rpcserver.run()
</code>```

Client:

```<code>rpcclient = zerorpc.Client("ipc://myrpc.ipc")

print(rpcclient.product(5, 7))
rpcclient._stopserver()
</code>```

Body:
I have a Python server which is not running as root, which fronts an application I am developing. However there are some application features which require access to RAW sockets which means root privileges.

Obviously I do not want to run the main server as root, and so my solution is to create a daemon process or command line script which runs as root providing guarded access to said features.

However I want put aside stdin/stdout communication and use an RPC style of interaction such as Pyro. But this exposes the RPC interface to anyone with network access to the machine, whereas I know that the process calling the RPC methods will be another process on the same machine.

Is there not a sort of inter-process procedure call standard which could be used in a similar (local machine only) fashion? I imagine the server doing something like this:

# Server not running as root
pythonically, returned, values = other_process_running_as_root.some_method()

And the process running as root exposing a method:

# Daemon running as root
@expose_this_method
def some_method():
    # Play with RAW sockets
    return pythonically, returned, values

Is anything like this possible?

Body:
Following my comment, I was interested to see if it was possible, so I had a go at putting this together: https://github.com/takowl/ZeroRPC

Bear in mind that this is thrown together in an hour or so, so it's almost certainly inferior to any serious solution (e.g. any errors on the server side will crash it...). But it works as you suggested:

Server:

rpcserver = zerorpc.Server("ipc://myrpc.ipc")

@rpcserver.expose
def product(a, b):
    return a * b

rpcserver.run()

Client:

rpcclient = zerorpc.Client("ipc://myrpc.ipc")

print(rpcclient.product(5, 7))
rpcclient._stopserver()


问:
Drone.io Invalid or missing image
I'm trying to use drone to run a mysql service

Here is my .drone.yml file

```<code>pipeline:
 clone:
  skip_verify: true
 services:
  database:
  image: mysql:latest
</code>```

I've try with library/mysql and mysql for the image but drone keep saying that the image is invalid or missing. Any idea anyone ? I've tried to look at the drone log but everything seem fine to me.

答:
Two things were off in your original .drone.yml file:

1) the services section needs to be configured outside the pipeline (you already got that fixed as per your comment)

2) image under database needs to be indented by two spaces

From the docs: http://docs.drone.io/mysql-example/#app-drawer

```<code>services:
  database:
    image: mysql
    environment:
      - MYSQL_DATABASE=test
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
</code>```

Title: Drone.io Invalid or missing image

Body:
I'm trying to use drone to run a mysql service

Here is my .drone.yml file

pipeline:
 clone:
  skip_verify: true
 services:
  database:
  image: mysql:latest

I've try with library/mysql and mysql for the image but drone keep saying that the image is invalid or missing. Any idea anyone ? I've tried to look at the drone log but everything seem fine to me.

Body:
Two things were off in your original .drone.yml file:

1) the services section needs to be configured outside the pipeline (you already got that fixed as per your comment)

2) image under database needs to be indented by two spaces

From the docs: http://docs.drone.io/mysql-example/#app-drawer

services:
  database:
    image: mysql
    environment:
      - MYSQL_DATABASE=test
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes


问:
How to read input from the text file until/after a specific location [C++]?
In my Project I need to get data about circuit from a text file then I need to parse it and produce to output data.
Here is a sample data for the text file

AND1 Adder1-3 Adder1-4  // Means AND1 gate gets its first input from
  Adder1's 3rd output and its second input from Adder1's 4th output

AND2 Adder1-4 Adder1-2

OR1 AND1-1 AND2-1    //OR1's two inputs are from AND1's 1st output and
  AND2's 1st output

now I need to read the component name first which is easy:

```<code>infile>>componentName;
</code>```

But for the second part I though I could to this in to ways

Read the whole data and seperate it into two parts : ComponentName -
thOutput.

Read until "-" and put it into string variable then read
    after "-" and put it into integer variable and repeat this for all
    lines.

I tried the first way but I really stuck at converting string into integer (I tried using stoi but its for C++ only :( and also encountered with couple of problems) but I though the second way would be much easier but I couldn't figure it how to do it.

So can you help me with this ?
Basicly I need to put component name(before "-") into string variable and put the integer (after "-") into integer variable.

NOTE: Sorry for my poor English not a Native Speaker. and since the Project is large I didn't put unnecessary codes above.

答:
This is rather basic, but should get you started. I prefer the scanf family for these tasks.

```<code>#include <stdio.h>
#include <iostream>

using namespace std;
int main() {
FILE *fp=fopen("tmpfile", "r");
char oper[5], dev1[10], dev2[10];
int op1, op2;
fscanf(fp, "%s %[^-]-%d %[^-]-%d", oper, dev1, &op1, dev2, &op2);
cout<<oper<<endl;
cout<<dev1<<endl;
cout<<op1<<endl;
cout<<dev1<<endl;
cout<<op2<<endl;
fclose(fp);

}
</code>```

Output Produced for AND2 Adder1-4 Adder1-2:

```<code>AND2
Adder1
4
Adder1
2
</code>```

Body:
In my Project I need to get data about circuit from a text file then I need to parse it and produce to output data.
Here is a sample data for the text file

AND1 Adder1-3 Adder1-4  // Means AND1 gate gets its first input from
  Adder1's 3rd output and its second input from Adder1's 4th output

AND2 Adder1-4 Adder1-2

OR1 AND1-1 AND2-1    //OR1's two inputs are from AND1's 1st output and
  AND2's 1st output

now I need to read the component name first which is easy:

infile>>componentName;

But for the second part I though I could to this in to ways

Read the whole data and seperate it into two parts : ComponentName -
thOutput.

Read until "-" and put it into string variable then read
    after "-" and put it into integer variable and repeat this for all
    lines.

I tried the first way but I really stuck at converting string into integer (I tried using stoi but its for C++ only :( and also encountered with couple of problems) but I though the second way would be much easier but I couldn't figure it how to do it.

So can you help me with this ?
Basicly I need to put component name(before "-") into string variable and put the integer (after "-") into integer variable.

NOTE: Sorry for my poor English not a Native Speaker. and since the Project is large I didn't put unnecessary codes above.

Body:
This is rather basic, but should get you started. I prefer the scanf family for these tasks.

#include <stdio.h>
#include <iostream>

using namespace std;
int main() {
FILE *fp=fopen("tmpfile", "r");
char oper[5], dev1[10], dev2[10];
int op1, op2;
fscanf(fp, "%s %[^-]-%d %[^-]-%d", oper, dev1, &op1, dev2, &op2);
cout<<oper<<endl;
cout<<dev1<<endl;
cout<<op1<<endl;
cout<<dev1<<endl;
cout<<op2<<endl;
fclose(fp);

}

Output Produced for AND2 Adder1-4 Adder1-2:

AND2
Adder1
4
Adder1
2


问:
CountdownTimer Service restarting when activity screen is re-opened
I'm trying to make a countdown timer screen on Android that will continue to count down if you back out of the app or go to different screens in the app or whatever. I'm running it as a Service but I'm still getting the problem of it starting over when I re-open the activity. Any help would be great. Here's my code.

Service Class

```<code>import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;

public class CountdownService extends Service{
public static final String
    ACTION_LOCATION_BROADCAST = CountdownService.class.getName() + "LocationBroadcast";

@Override
public void onCreate() {
super.onCreate();
new CountDownTimer(360000, 60000) {
    public void onTick(long millisUntilFinished) {
        int timeLeftInt = (int) Math.ceil((double) millisUntilFinished / 60000);    //Whole number of minutes left, ceiling
        sendBroadcastMessage(timeLeftInt);
        if(timeLeftInt == 5){
            Notify("Not Done");
        }

    }

    public void onFinish() {
        sendBroadcastMessage(0);
        Notify("done");

    }
}.start();

}

private void sendBroadcastMessage(int timeSent) {
    Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
    intent.putExtra("timeSent", timeSent);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

  }

@Override
public IBinder onBind(Intent intent) {
return null;
}
private void Notify(String doneness){

NotificationManager notificationManager = (NotificationManager)
        getSystemService(NOTIFICATION_SERVICE);

Intent intent = new Intent(this, Map.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
if(doneness.equals("done")) {
    Notification n = new Notification.Builder(this)
            .setContentTitle("Time to leave!")
            .setContentText("Your PrePark spot has expired, time to go home!")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();

    notificationManager.notify(0, n);
}

else{
    Notification n = new Notification.Builder(this)
            .setContentTitle("Ya got 5 minutes left in your PrePark spot!")
            .setContentText("Better get going soon here")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();

    notificationManager.notify(0, n);
}
}
</code>```

Main Activity

```<code>import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.os.Bundle;
import android.widget.TextView;

public class Countdown extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
LocalBroadcastManager.getInstance(this).registerReceiver(
        new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                TextView textView= findViewById(R.id.t1);
                int timeLeft = intent.getIntExtra("timeSent", 0);
                if(timeLeft>0) {
                    textView.setText("You have " + timeLeft + " minutes left");
                }
                else{
                    textView.setText("Y'all outta time, see ya again soon!");
                }
            }
        }, new IntentFilter(CountdownService.ACTION_LOCATION_BROADCAST)
);

}
@Override
protected void onResume() {
super.onResume();
startService(new Intent(this, CountdownService.class));
}

@Override
protected void onPause() {
super.onPause();
stopService(new Intent(this, CountdownService.class));
}
}
</code>```

XML for main activity

```<code><RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center">

<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerInParent="true"
android:textSize="32sp"

/>

</RelativeLayout>
</code>```

答:
Probably this happens because you're starting countdown service in onResume() and you're stopping the service in onPause()
And also in the onCreate() method of your service you're creating new instance from countdown timer.</p>

Body:
I'm trying to make a countdown timer screen on Android that will continue to count down if you back out of the app or go to different screens in the app or whatever. I'm running it as a Service but I'm still getting the problem of it starting over when I re-open the activity. Any help would be great. Here's my code.

Service Class

import android.app.Service;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;

public class CountdownService extends Service{
public static final String
    ACTION_LOCATION_BROADCAST = CountdownService.class.getName() + "LocationBroadcast";

@Override
public void onCreate() {
super.onCreate();
new CountDownTimer(360000, 60000) {
    public void onTick(long millisUntilFinished) {
        int timeLeftInt = (int) Math.ceil((double) millisUntilFinished / 60000);    //Whole number of minutes left, ceiling
        sendBroadcastMessage(timeLeftInt);
        if(timeLeftInt == 5){
            Notify("Not Done");
        }

    }

    public void onFinish() {
        sendBroadcastMessage(0);
        Notify("done");

    }
}.start();

}

private void sendBroadcastMessage(int timeSent) {
    Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
    intent.putExtra("timeSent", timeSent);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

  }

@Override
public IBinder onBind(Intent intent) {
return null;
}
private void Notify(String doneness){

NotificationManager notificationManager = (NotificationManager)
        getSystemService(NOTIFICATION_SERVICE);

Intent intent = new Intent(this, Map.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
if(doneness.equals("done")) {
    Notification n = new Notification.Builder(this)
            .setContentTitle("Time to leave!")
            .setContentText("Your PrePark spot has expired, time to go home!")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();

    notificationManager.notify(0, n);
}

else{
    Notification n = new Notification.Builder(this)
            .setContentTitle("Ya got 5 minutes left in your PrePark spot!")
            .setContentText("Better get going soon here")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pIntent)
            .setAutoCancel(true)
            .build();

    notificationManager.notify(0, n);
}
}

Main Activity

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.os.Bundle;
import android.widget.TextView;

public class Countdown extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
LocalBroadcastManager.getInstance(this).registerReceiver(
        new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                TextView textView= findViewById(R.id.t1);
                int timeLeft = intent.getIntExtra("timeSent", 0);
                if(timeLeft>0) {
                    textView.setText("You have " + timeLeft + " minutes left");
                }
                else{
                    textView.setText("Y'all outta time, see ya again soon!");
                }
            }
        }, new IntentFilter(CountdownService.ACTION_LOCATION_BROADCAST)
);

}
@Override
protected void onResume() {
super.onResume();
startService(new Intent(this, CountdownService.class));
}

@Override
protected void onPause() {
super.onPause();
stopService(new Intent(this, CountdownService.class));
}
}

XML for main activity

<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center">

<TextView
android:id="@+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerInParent="true"
android:textSize="32sp"

/>

</RelativeLayout>


问:
How to exit GUARD outside and inside a function - Swift
In the following code I am practicing the use of GUARD (Book: OReilly Learning Swift)

```<code>guard 2+2 == 4 else {
print("The universe makes no sense")
return // this is mandatory!
}
print("We can continue with our daily lives")
</code>```

Why do I get the following code error?

error: return invalid outside of a func

Or is GUARD only used within functions?

答:
Or is GUARD only used within functions?

Not necessarily.

From the documentation:

If that condition is not met, the code inside the else branch is executed. That branch must transfer control to exit the code block in which the guard statement appears. It can do this with a control transfer statement such as return, break, continue, or throw, or it can call a function or method that doesn’t return, such as fatalError(_:file:line:).

For example this can be used in a Playgound on the top level

```<code>for i in 0...10 {
    guard i % 2 == 0 else { continue }
    print(i)
}
</code>```

The error message is actually not related to guard. It just states that return cannot be used outside of a func

Body:
In the following code I am practicing the use of GUARD (Book: OReilly Learning Swift)

guard 2+2 == 4 else {
print("The universe makes no sense")
return // this is mandatory!
}
print("We can continue with our daily lives")

Why do I get the following code error?

error: return invalid outside of a func

Or is GUARD only used within functions?

Body:
Or is GUARD only used within functions?

Not necessarily.

From the documentation:

If that condition is not met, the code inside the else branch is executed. That branch must transfer control to exit the code block in which the guard statement appears. It can do this with a control transfer statement such as return, break, continue, or throw, or it can call a function or method that doesn’t return, such as fatalError(_:file:line:).

For example this can be used in a Playgound on the top level

for i in 0...10 {
    guard i % 2 == 0 else { continue }
    print(i)
}

The error message is actually not related to guard. It just states that return cannot be used outside of a func


问:
Strange letter print out from array c programming
I am trying to delete the blank space between a string and print out the first word with isalpha() function.

When I print out, only the first letter prints out. exempel "hello big panda" I get "hhhhh" but I want the hole word "hello" instead

```<code>int main()
{
    char inputString[]={"hello big panda"};
     int k=0;

    int i=0;
    do
    {
    inputString[i];
    i++;
    }
    while (inputString[i]=isalpha(inputString[i]));

    for(i=0; inputString[i] !='\0' ;i++)
    {
        for (k=i; inputString[k] != '\0'; k++)
        {
            inputString[k] =inputString[i];
        }
    }
    printf("%s", inputString);

    return 0;
}
</code>```

done this:

```<code>int printfirstword(char sentence[])
{
    int k=0;
    int i=0;
    while (isalpha(sentence[i])) //checking for the first blank space
    {
        i++;
    }
    sentence[i] = '\0';

    printf("%s\n", sentence);

    return 0;
}
int main()
{

        char sentence[100];
    int wordNumber;
    char answer;

    printfirstword("Hello there")
return0;
}
</code>```

But I don't want to change the string that is passed to it

答:
What you can simply do is use a while loop instead of your do-while. You can simply increment i until you find the index of first blank space. Then using the value of i you can insert '\0' in your string. Output it and you are done. :)

```<code>#include <stdio.h>
#include<ctype.h>

int main()
{
    char inputString[]={"hello big panda"};
    int k=0;

    int i=0;
    while (isalpha(inputString[i])) //checking for the first blank space
    {
        i++;
    }

     inputString[i] = '\0';
    printf("%s", inputString);

    return 0;

}
</code>```

If you would like to keep the original string then you could simply make a new string say newStr and then

```<code>while (isalpha(inputString[i])) //checking for the first blank space
    { newStr[i]=inputString[i]; //copy first word into newStr
        i++;
    }
newStr[i] = '\0';
    printf("%s", newStr);
</code>```

Body:
I am trying to delete the blank space between a string and print out the first word with isalpha() function.

When I print out, only the first letter prints out. exempel "hello big panda" I get "hhhhh" but I want the hole word "hello" instead

int main()
{
    char inputString[]={"hello big panda"};
     int k=0;

    int i=0;
    do
    {
    inputString[i];
    i++;
    }
    while (inputString[i]=isalpha(inputString[i]));

    for(i=0; inputString[i] !='\0' ;i++)
    {
        for (k=i; inputString[k] != '\0'; k++)
        {
            inputString[k] =inputString[i];
        }
    }
    printf("%s", inputString);

    return 0;
}

done this:

int printfirstword(char sentence[])
{
    int k=0;
    int i=0;
    while (isalpha(sentence[i])) //checking for the first blank space
    {
        i++;
    }
    sentence[i] = '\0';

    printf("%s\n", sentence);

    return 0;
}
int main()
{

        char sentence[100];
    int wordNumber;
    char answer;

    printfirstword("Hello there")
return0;
}

But I don't want to change the string that is passed to it

Body:
What you can simply do is use a while loop instead of your do-while. You can simply increment i until you find the index of first blank space. Then using the value of i you can insert '\0' in your string. Output it and you are done. :)

#include <stdio.h>
#include<ctype.h>

int main()
{
    char inputString[]={"hello big panda"};
    int k=0;

    int i=0;
    while (isalpha(inputString[i])) //checking for the first blank space
    {
        i++;
    }

     inputString[i] = '\0';
    printf("%s", inputString);

    return 0;

}

If you would like to keep the original string then you could simply make a new string say newStr and then

while (isalpha(inputString[i])) //checking for the first blank space
    { newStr[i]=inputString[i]; //copy first word into newStr
        i++;
    }
newStr[i] = '\0';
    printf("%s", newStr);


问:
Delete Loop in MS Access using SQL?
I have the following data generated by a SQL select query. The data is sorted ascending first by ID and then descending by AVO, as shown below:

```<code>+-------+----------------+------+-------+---------+----------+-----+
|  ID   |      Link      | Name | Type  | Subtype | Domicile | AVO |
+-------+----------------+------+-------+---------+----------+-----+
| 11111 | www.aaaaa3.com | AAAA | FUND  | 40 act  | USA      | 456 |
| 11111 | www.aaaaa2.com | AAAA | FUND  | 40 act  | USA      | 456 |
| 11111 | www.aaaaa6.com | AAAA | FUND  | 40 act  | UK       | 345 |
| 11111 | www.aaaaa1.com | AAAA | FUND  | 40 act  | USA      | 123 |
| 11111 | www.aaaaa4.com | AAAA | FUND  | 40 act  | USA      |     |
| 11111 | www.aaaaa5.com | AAAA | FUND  | 40 act  | USA      |     |
| 22222 | www.bbbb1.com  | BBBB | BANK  | Inv     | Canada   | 897 |
| 22222 | www.bbbb5.com  | BBBB | BANK  | Inv     | Brazil   | 586 |
| 22222 | www.bbbb3.com  | BBBB | BANK  | Inv     | Cayman   | 357 |
| 22222 | www.bbbb2com   | BBBB | BANK  | Inv     | Cayman   |     |
| 22222 | www.bbbb4.com  | BBBB | BANK  | Inv     | Cayman   |     |
+-------+----------------+------+-------+---------+----------+-----+
</code>```

What I need to do is to keep only one row per ID with the largest value in the field AVO for each ID and delete the others. If two identical values in the AVO field exist for any given ID (see first two rows in table above), then keep the first row and delete the other.

I think I could do it in VBA with a For...Next loop for every ID value but I'd rather run this in SQL. Is this even possible? Is it possible to nest a loop in a SQL Delete query in Access?

Thanks for your assistance.

答:
Assuming you've added an AutoNumber field named AN, you can use the following query:

```<code>DELETE * FROM MyTable
WHERE AN NOT IN(
    SELECT AN From (MyTable t1
    INNER JOIN (SELECT Max(AN) AS MaxAN, ID, AVO  FROM MyTable GROUP BY ID, AVO) t2 ON t1.AN = t2.MaxAN)
    INNER JOIN (SELECT ID, Max(AVO) As MaxAVO FROM MyTable GROUP BY ID) t3 ON (t2.ID = t3.ID AND t2.AVO = t3.MaxAVO)
)
</code>```

Title: Delete Loop in MS Access using SQL?

Body:
I have the following data generated by a SQL select query. The data is sorted ascending first by ID and then descending by AVO, as shown below:

+-------+----------------+------+-------+---------+----------+-----+
|  ID   |      Link      | Name | Type  | Subtype | Domicile | AVO |
+-------+----------------+------+-------+---------+----------+-----+
| 11111 | www.aaaaa3.com | AAAA | FUND  | 40 act  | USA      | 456 |
| 11111 | www.aaaaa2.com | AAAA | FUND  | 40 act  | USA      | 456 |
| 11111 | www.aaaaa6.com | AAAA | FUND  | 40 act  | UK       | 345 |
| 11111 | www.aaaaa1.com | AAAA | FUND  | 40 act  | USA      | 123 |
| 11111 | www.aaaaa4.com | AAAA | FUND  | 40 act  | USA      |     |
| 11111 | www.aaaaa5.com | AAAA | FUND  | 40 act  | USA      |     |
| 22222 | www.bbbb1.com  | BBBB | BANK  | Inv     | Canada   | 897 |
| 22222 | www.bbbb5.com  | BBBB | BANK  | Inv     | Brazil   | 586 |
| 22222 | www.bbbb3.com  | BBBB | BANK  | Inv     | Cayman   | 357 |
| 22222 | www.bbbb2com   | BBBB | BANK  | Inv     | Cayman   |     |
| 22222 | www.bbbb4.com  | BBBB | BANK  | Inv     | Cayman   |     |
+-------+----------------+------+-------+---------+----------+-----+

What I need to do is to keep only one row per ID with the largest value in the field AVO for each ID and delete the others. If two identical values in the AVO field exist for any given ID (see first two rows in table above), then keep the first row and delete the other.

I think I could do it in VBA with a For...Next loop for every ID value but I'd rather run this in SQL. Is this even possible? Is it possible to nest a loop in a SQL Delete query in Access?

Thanks for your assistance.

Body:
Assuming you've added an AutoNumber field named AN, you can use the following query:

DELETE * FROM MyTable
WHERE AN NOT IN(
    SELECT AN From (MyTable t1
    INNER JOIN (SELECT Max(AN) AS MaxAN, ID, AVO  FROM MyTable GROUP BY ID, AVO) t2 ON t1.AN = t2.MaxAN)
    INNER JOIN (SELECT ID, Max(AVO) As MaxAVO FROM MyTable GROUP BY ID) t3 ON (t2.ID = t3.ID AND t2.AVO = t3.MaxAVO)
)


问:
Alternative Y combinator definition
I've spent some time wrapping my head around the Y combinator lately, and I've found that it is usually defined (more or less) as follows (this is in C#, but the language of choice isn't important):

```<code>public delegate TResult SelfApplicable<TResult>(SelfApplicable<TResult> r);

public static TResult U<TResult>(SelfApplicable<TResult> r)
{
    return r(r);
}

public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return U<Func<TArg1, TReturn>>(r => arg1 => f(U(r))(arg1));
}
</code>```

While that's perfectly functional (pun intended), it would seem that my definition is much simpler:

```<code>public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return f(n => Y(f)(n));
}
</code>```

Is there any reason why the latter definition is not as common (I have yet to find it on the net)? Would it perhaps have something to do with defining Y in terms of itself?

答:
Haskell Curry invented the Y combinator to define and use anonymous recursive functions in the untyped lambda calculus, defined as follows:

Y = λf·(λx·f (x x)) (λx·f (x x))

My definition defeats the original purpose of the Y combinator as it relys upon C#'s inherent support for defining recursive functions. It is, however, still useful in that it allows one to define anonymous recursive functions in C#.

Title: Alternative Y combinator definition

Body:
I've spent some time wrapping my head around the Y combinator lately, and I've found that it is usually defined (more or less) as follows (this is in C#, but the language of choice isn't important):

public delegate TResult SelfApplicable<TResult>(SelfApplicable<TResult> r);

public static TResult U<TResult>(SelfApplicable<TResult> r)
{
    return r(r);
}

public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return U<Func<TArg1, TReturn>>(r => arg1 => f(U(r))(arg1));
}

While that's perfectly functional (pun intended), it would seem that my definition is much simpler:

public static Func<TArg1, TReturn> Y<TArg1, TReturn>(Func<Func<TArg1, TReturn>, Func<TArg1, TReturn>> f)
{
    return f(n => Y(f)(n));
}

Is there any reason why the latter definition is not as common (I have yet to find it on the net)? Would it perhaps have something to do with defining Y in terms of itself?


问:
Finding the max value in Spark RDD
From the following, how can I get the tuple with the highest value?

```<code>Array[(String, Int)] = Array((a,30),(b,50),(c,20))
</code>```

In this example the result I want would be (b,50)

答:
rdd.reduceByKey((a,b)=>a+b).collect.maxBy(_._2)

we can use maxBy on collect like this

Title: Finding the max value in Spark RDD

Body:
From the following, how can I get the tuple with the highest value?

Array[(String, Int)] = Array((a,30),(b,50),(c,20))

In this example the result I want would be (b,50)


问:
ReactJS: How to change value of specific field in an object array?
```<code>constructor (props) {
    super(props)
    this.state = { items: this.props.items }
    // items props is: [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}]
}

onClick () {
    const myArray = this.state.items
    const ids = ['45', '73']
    ids.forEach((id, index) => {
        myArray.find(x => x.id === id).foo = index
    })
}
</code>```

I need to change foo value to index value. So the result should look like

```<code>myArray = [{'id':'73','foo': 1},{'id':'45','foo': 0}]
</code>```

I think with this, I do get the current value, but the syntax is wrong to change its value:

```<code>myArray.find(x => x.id === '45').foo = 'new'
</code>```

I do get the error Uncaught TypeError: Cannot assign to read only property 'foo' of object '#<Object>'

答:
You can use map to change the property you want:

const myArray = [{ id: '73', foo: 'bar' }, { id: '45', foo: 'new' }, { id: '46', foo: 'do not change me' }]

const ids = ['45', '73']

const newArr = myArray.map(item => {
  if (ids.indexOf(item.id) !== -1) {
    return {
      ...item,
      foo: 'newFooValue'
    }
  }

  return item
})

console.log(newArr)```
</div>
</div>
</p>

<p>It's also important to note that change object properties directly (such as <code>myArray.find(x => x.id === '45').foo</code>) is not a good practice though. </p>

<p>In case <code>items</code>is in you <code>state</code>, you can simple change it by: </p>

```this.setState(prevState => ({
   items: prevState.items.map(/* same code as in the snippet above */),
}))
```

Body:
constructor (props) {
    super(props)
    this.state = { items: this.props.items }
    // items props is: [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'}]
}

onClick () {
    const myArray = this.state.items
    const ids = ['45', '73']
    ids.forEach((id, index) => {
        myArray.find(x => x.id === id).foo = index
    })
}

I need to change foo value to index value. So the result should look like

myArray = [{'id':'73','foo': 1},{'id':'45','foo': 0}]

I think with this, I do get the current value, but the syntax is wrong to change its value:

myArray.find(x => x.id === '45').foo = 'new'

I do get the error Uncaught TypeError: Cannot assign to read only property 'foo' of object '#<Object>'

Body:
You can use map to change the property you want:

const myArray = [{ id: '73', foo: 'bar' }, { id: '45', foo: 'new' }, { id: '46', foo: 'do not change me' }]

const ids = ['45', '73']

const newArr = myArray.map(item => {
  if (ids.indexOf(item.id) !== -1) {
    return {
      ...item,
      foo: 'newFooValue'
    }
  }

  return item
})

console.log(newArr)

It's also important to note that change object properties directly (such as myArray.find(x => x.id === '45').foo) is not a good practice though.

In case itemsis in you state, you can simple change it by:

this.setState(prevState => ({
   items: prevState.items.map(/* same code as in the snippet above */),
}))