问:
Buttons to replace lists
I'm trying to replace the 2017 events with the 2018 events under each different section when the buttons are clicked, and then vice versa, to only show one list at a time under each event. I know something isn't right, but I can't figure it out. Any advice for how I can make these buttons work please?

$(document).ready(function() {
  var v = false;
  $("button#2018b").click(function() {
    if (v == false) {
      v = true;
    }
  }); //end button
  $("button#2017b").click(function() {
    if (v == true) {
      v = false;
    }
  }); //end button
}); //end document ready

//$("2017".replacewith("
");
//$("2018".replacewith("
");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.panel {
  display: none;
}

ul {
  list-style-type: none;
}

button {
  margin-left: 180px;
}</code>```

Fox Valley Runners Club

 <button id="2018B">Future Events - 2018</button>

 <button id="2017B">Current Events - 2017</button>

5k/10k Events

5k/10 Events

Mini Sprint

Iron Horse

Twilight Trail

5K / 10K Events

Snowball Sprint
 1/14/18
Mosquito Hill
New London

Winter Warrior
2/06/18
Bay Beach
 Green Bay

Big Chill Run
2/24/18
 Mid Valley Golf Course
De Pere

    </button>

Half Marathon Events

Half Marathon Events

Fox River Marathon

N.E.W. Half Marathon

Winnebago Run

Half Marathon Events

Frosty Indoor Marathon
 1/15/18
TryIt Ice Arena
 Neenah

Valentine Run
2/12/18
Green Isle Park
 De Pere

Snowball Marathon
3/03/18
Menominee Park
Oshkosh

Full Marathon Events

Full Marathon Events

Cheesehead Marathon

Chain O'Lakes Marathon

Fox Cities Marathon

Full Marathon Events

Trailbreaker Marathon
 4/02/18
Leach Amphitheatre
 Oshkosh

Jailbreak Marathon
 4/16/18
Menominee Park
Oshkosh

Cellcom Marathon
5/20/18
 Lombardi Atrium
 Green Bay

```

答:
<!DOCTYPE html>

  <title>FV Runners</title>
  <meta charset="UTF-8">
  <link href="styles/normalize.css" rel="stylesheet" />
  <link href="styles/my_style.css" rel="stylesheet" />

Fox Valley Runners Club

 <button id="2018B">Future Events - 2018</button>

 <button id="2017B">Current Events - 2017</button>

5k/10k Events

5k/10 Events

Mini Sprint

Iron Horse

Twilight Trail

5K / 10K Events

Snowball Sprint
 1/14/18
Mosquito Hill
New London

Winter Warrior
2/06/18
Bay Beach
 Green Bay

Big Chill Run
2/24/18
 Mid Valley Golf Course
De Pere

      </button>

Half Marathon Events

Half Marathon Events

Fox River Marathon

N.E.W. Half Marathon

Winnebago Run

Half Marathon Events

Frosty Indoor Marathon
 1/15/18
TryIt Ice Arena
 Neenah

Valentine Run
2/12/18
Green Isle Park
 De Pere

Snowball Marathon
3/03/18
Menominee Park
Oshkosh

Full Marathon Events

Full Marathon Events

Cheesehead Marathon

Chain O'Lakes Marathon

Fox Cities Marathon

Full Marathon Events

Trailbreaker Marathon
 4/02/18
Leach Amphitheatre
 Oshkosh

Jailbreak Marathon
 4/16/18
Menominee Park
Oshkosh

Cellcom Marathon
5/20/18
 Lombardi Atrium
 Green Bay

```

You can just use jquery show and hide functions. Also you had mistyped the button ids in the click events (they are case sensitive)

Title: Buttons to replace lists

Body:
I'm trying to replace the 2017 events with the 2018 events under each different section when the buttons are clicked, and then vice versa, to only show one list at a time under each event. I know something isn't right, but I can't figure it out. Any advice for how I can make these buttons work please?

$(document).ready(function() {
  var v = false;
  $("button#2018b").click(function() {
    if (v == false) {
      v = true;
    }
  }); //end button
  $("button#2017b").click(function() {
    if (v == true) {
      v = false;
    }
  }); //end button
}); //end document ready

//$("2017".replacewith("
");
//$("2018".replacewith("
");

.panel {
  display: none;
}

ul {
  list-style-type: none;
}

button {
  margin-left: 180px;
}

Fox Valley Runners Club

 <button id="2018B">Future Events - 2018</button>

 <button id="2017B">Current Events - 2017</button>

5k/10k Events

5k/10 Events

Mini Sprint

Iron Horse

Twilight Trail

5K / 10K Events

Snowball Sprint
 1/14/18
Mosquito Hill
New London

Winter Warrior
2/06/18
Bay Beach
 Green Bay

Big Chill Run
2/24/18
 Mid Valley Golf Course
De Pere

    </button>

Half Marathon Events

Half Marathon Events

Fox River Marathon

N.E.W. Half Marathon

Winnebago Run

Half Marathon Events

Frosty Indoor Marathon
 1/15/18
TryIt Ice Arena
 Neenah

Valentine Run
2/12/18
Green Isle Park
 De Pere

Snowball Marathon
3/03/18
Menominee Park
Oshkosh

Full Marathon Events

Full Marathon Events

Cheesehead Marathon

Chain O'Lakes Marathon

Fox Cities Marathon

Full Marathon Events

Trailbreaker Marathon
 4/02/18
Leach Amphitheatre
 Oshkosh

Jailbreak Marathon
 4/16/18
Menominee Park
Oshkosh

Cellcom Marathon
5/20/18
 Lombardi Atrium
 Green Bay

Body:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <title>FV Runners</title>
  <meta charset="UTF-8">
  <link href="styles/normalize.css" rel="stylesheet" />
  <link href="styles/my_style.css" rel="stylesheet" />
  <style>
    .panel {
      display: none;
    }

    ul {
      list-style-type: none;
    }

    button {
      margin-left: 180px;
    }
  </style>
</head>

<body>
  <div id="header">
    <h1>Fox Valley Runners Club</h1>
  </div>

  <ul>
    <li class="nav"> <button id="2018B">Future Events - 2018</button> </li>
    <li class="nav"> <button id="2017B">Current Events - 2017</button> </li>

  </ul>

  <div id="main"></div>

  <div id="pics">
    <div class="race_box">
      <img src="images/run1.jpg" id="5kpic" /><br />

      <figcaption>5k/10k Events</figcaption>

      <div class="races" id="5k">
        <h3>5k/10 Events</h3>
        <ul>
          <li class="2017">Mini Sprint</li>
          <li class="2017">Iron Horse</li>
          <li class="2017">Twilight Trail</li>

        </ul>
      </div>
      <div class="races" id="5K">
        <h3>5K / 10K Events</h3>
        <ul>
          <li class="2018">Snowball Sprint</br> 1/14/18 </br>Mosquito Hill </br>New London</li>
          <li class="2018">Winter Warrior </br>2/06/18 </br>Bay Beach</br> Green Bay</li>
          <li class="2018">Big Chill Run </br>2/24/18</br> Mid Valley Golf Course </br>De Pere</li>
        </ul>
      </div>

    </div>

    <div class="race_box">
      <img src="images/run2.jpg" id="halfpic" /></button><br />
      <figcaption>Half Marathon Events</figcaption>

      <div class="races" id="half">
        <h3>Half Marathon Events</h3>
        <ul>
          <li class="2017">Fox River Marathon</li>
          <li class="2017">N.E.W. Half Marathon</li>
          <li class="2017">Winnebago Run</li>

        </ul>
      </div>
      <div class="races" id="half">
        <h3>Half Marathon Events</h3>
        <ul>
          <li class="2018">Frosty Indoor Marathon</br> 1/15/18 </br>TryIt Ice Arena</br> Neenah</li>
          <li class="2018">Valentine Run </br>2/12/18 </br>Green Isle Park</br> De Pere</li>
          <li class="2018">Snowball Marathon </br>3/03/18 </br>Menominee Park </br>Oshkosh</li>
        </ul>
      </div>
    </div>

    <div class="race_box">
      <img src="images/run3.jpg" id="fullpic" /><br />
      <figcaption>Full Marathon Events</figcaption>

      <div class="races" id="full">
        <h3>Full Marathon Events</h3>
        <ul>
          <li class="2017">Cheesehead Marathon</li>
          <li class="2017">Chain O'Lakes Marathon</li>
          <li class="2017">Fox Cities Marathon</li>
        </ul>
      </div>

      <div class="races" id="full">
        <h3>Full Marathon Events</h3>
        <ul>
          <li class="2018">Trailbreaker Marathon</br> 4/02/18 </br>Leach Amphitheatre</br> Oshkosh</li>
          <li class="2018">Jailbreak Marathon </br> 4/16/18 </br>Menominee Park </br>Oshkosh</li>
          <li class="2018">Cellcom Marathon </br>5/20/18</br> Lombardi Atrium</br> Green Bay </li>
        </ul>
      </div>

    </div>

  </div>

  <script>
    $(document).ready(function() {
      var v = false;
      $("button#2018B").click(function() {
        $(".2017").hide();
        $(".2018").show();
      }); //end button
      $("button#2017B").click(function() {
        $(".2018").hide();
        $(".2017").show();
      }); //end button
    }); //end document ready

  </script>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script type="text/javascript">
  </script>
</body>

</html>

You can just use jquery show and hide functions. Also you had mistyped the button ids in the click events (they are case sensitive)


来源: stackexchange

问:
Creating and Moving Shapes On Click with TKINTER and canvas
I hope this isn't too stupid for you guys

Am kinda stuck in this project first time working with canvas and tkinter all I know is the basic tutorial.

what I want is how to create an on click event after precision of the shape I want with buttons and move the form (updating the positing)

```<code> from tkinter import *
 from tkinter import messagebox
 def Click(event) :
     can.coords(cercle, event.x, event.y, event.x+10, event.y+10)
 def Rectangle() :
     can.create_rectangle(10, 10, 70, 70, fill='white', outline='blue', width=3)
 def Delete() :
      msg = messagebox.askyesnocancel('Info','Delete canevas ?')
      if msg == None :
        return
      elif msg == True :
        can.delete(ALL)
 def Line():
      can.create_line(200,200,100,100,fill='red', width=5)

 def Cercle():
      can.create_oval(10, 10, 70, 70, fill='orange', outline='blue')

 fenetre = Tk()
 fenetre.title('Dessin des objets')
 fenetre.resizable(width=False,height=False)
 fenetre.geometry('400x200+100+50')
 fenetre.configure(bg = 'light green')
 can = Canvas(fenetre, bg='white', height=300, width=300)
 can.pack(side = RIGHT)
 btnLine = Button(fenetre,text='Line',width=30,command=Line)
 btnLine.pack()
 btnRectangle = Button(fenetre,text='Rectangle',width=30,command=Rectangle)
 btnRectangle.pack()
 btnDelete = Button(fenetre, text='Effacer', width=30,command=Effacer)
 btnDelete.pack()

 btnCercle = Button(fenetre,text='Cercle',width=30,command=Cercle)
 btnCercle.pack()
 can.bind("<Button-1>", Click)

 can.pack(side = RIGHT)
 cercle = can.create_oval(10, 10, 10+10, 10+10, fill = 'orange', outline = 'gold')
 fenetre.mainloop()
</code>```

Am looking for a way to create shapes on click after click on a button, and I started to realise I went off road with this code.
here is a pic of what I did

thanks in advance

答:
create_oval() and other methods return object ID

```<code> object_id = can.create_oval(..)
</code>```

which you can use to work with this object.

```<code> can.move(object_id, offset_x, offset_y)

 can.coords(object_id, (new_x, new_y))
</code>```

More on effbot.org: Canvas

If you create object in function then use global variable to keep it

```<code>def Cercle():
    global object_id

    object_id = can.create_oval(10, 10, 70, 70, fill='orange', outline='blue')

def Click(event) :
    can.coords(object_id, event.x, event.y, event.x+10, event.y+10)
</code>```

Working example

```<code>import tkinter as tk

from tkinter import messagebox

def click(event):
    if object_id is not None:
        coord = can.coords(object_id)
        width = coord[2] - coord[0]
        height = coord[3] - coord[1]

        can.coords(object_id, event.x, event.y, event.x+width, event.y+height)

def delete():
    msg = messagebox.askyesnocancel('Info', 'Delete canvas ?')
    if msg == True:
       can.delete(tk.ALL)

def create_rectangle():
    global object_id

    object_id = can.create_rectangle(10, 10, 70, 70, fill='white', outline='blue', width=3)

def create_line():
    global object_id

    object_id = can.create_line(200, 200, 100, 100, fill='red', width=5)

def create_circle():
    global object_id

    object_id = can.create_oval(10, 10, 70, 70, fill='orange', outline='blue')

# --- main ---

object_id = None

fenetre = tk.Tk()
fenetre.title('Dessin des objets')
fenetre.resizable(width=False, height=False)
fenetre.geometry('400x200+100+50')
fenetre.configure(bg='light green')

can = tk.Canvas(fenetre, bg='white', height=300, width=300)
can.pack(side=tk.RIGHT)
can.bind("<Button-1>", click)

btn_line = tk.Button(fenetre, text='Line', width=30, command=create_line)
btn_line.pack()

btn_rectangle = tk.Button(fenetre, text='Rectangle', width=30, command=create_rectangle)
btn_rectangle.pack()

btn_circle = tk.Button(fenetre, text='Circle', width=30, command=create_circle)
btn_circle.pack()

btn_delete = tk.Button(fenetre, text='Delete', width=30, command=delete)
btn_delete.pack()

fenetre.mainloop()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I hope this isn't too stupid for you guys

Am kinda stuck in this project first time working with canvas and tkinter all I know is the basic tutorial.

what I want is how to create an on click event after precision of the shape I want with buttons and move the form (updating the positing)

 from tkinter import *
 from tkinter import messagebox
 def Click(event) :
     can.coords(cercle, event.x, event.y, event.x+10, event.y+10)
 def Rectangle() :
     can.create_rectangle(10, 10, 70, 70, fill='white', outline='blue', width=3)
 def Delete() :
      msg = messagebox.askyesnocancel('Info','Delete canevas ?')
      if msg == None :
        return
      elif msg == True :
        can.delete(ALL)
 def Line():
      can.create_line(200,200,100,100,fill='red', width=5)

 def Cercle():
      can.create_oval(10, 10, 70, 70, fill='orange', outline='blue')

 fenetre = Tk()
 fenetre.title('Dessin des objets')
 fenetre.resizable(width=False,height=False)
 fenetre.geometry('400x200+100+50')
 fenetre.configure(bg = 'light green')
 can = Canvas(fenetre, bg='white', height=300, width=300)
 can.pack(side = RIGHT)
 btnLine = Button(fenetre,text='Line',width=30,command=Line)
 btnLine.pack()
 btnRectangle = Button(fenetre,text='Rectangle',width=30,command=Rectangle)
 btnRectangle.pack()
 btnDelete = Button(fenetre, text='Effacer', width=30,command=Effacer)
 btnDelete.pack()

 btnCercle = Button(fenetre,text='Cercle',width=30,command=Cercle)
 btnCercle.pack()
 can.bind("<Button-1>", Click)

 can.pack(side = RIGHT)
 cercle = can.create_oval(10, 10, 10+10, 10+10, fill = 'orange', outline = 'gold')
 fenetre.mainloop()

Am looking for a way to create shapes on click after click on a button, and I started to realise I went off road with this code.
here is a pic of what I did

thanks in advance

Body:
create_oval() and other methods return object ID

 object_id = can.create_oval(..)

which you can use to work with this object.

 can.move(object_id, offset_x, offset_y)

 can.coords(object_id, (new_x, new_y))

More on effbot.org: Canvas

If you create object in function then use global variable to keep it

def Cercle():
    global object_id

    object_id = can.create_oval(10, 10, 70, 70, fill='orange', outline='blue')

def Click(event) :
    can.coords(object_id, event.x, event.y, event.x+10, event.y+10)

Working example

import tkinter as tk

from tkinter import messagebox

def click(event):
    if object_id is not None:
        coord = can.coords(object_id)
        width = coord[2] - coord[0]
        height = coord[3] - coord[1]

        can.coords(object_id, event.x, event.y, event.x+width, event.y+height)

def delete():
    msg = messagebox.askyesnocancel('Info', 'Delete canvas ?')
    if msg == True:
       can.delete(tk.ALL)

def create_rectangle():
    global object_id

    object_id = can.create_rectangle(10, 10, 70, 70, fill='white', outline='blue', width=3)

def create_line():
    global object_id

    object_id = can.create_line(200, 200, 100, 100, fill='red', width=5)

def create_circle():
    global object_id

    object_id = can.create_oval(10, 10, 70, 70, fill='orange', outline='blue')

# --- main ---

object_id = None

fenetre = tk.Tk()
fenetre.title('Dessin des objets')
fenetre.resizable(width=False, height=False)
fenetre.geometry('400x200+100+50')
fenetre.configure(bg='light green')

can = tk.Canvas(fenetre, bg='white', height=300, width=300)
can.pack(side=tk.RIGHT)
can.bind("<Button-1>", click)

btn_line = tk.Button(fenetre, text='Line', width=30, command=create_line)
btn_line.pack()

btn_rectangle = tk.Button(fenetre, text='Rectangle', width=30, command=create_rectangle)
btn_rectangle.pack()

btn_circle = tk.Button(fenetre, text='Circle', width=30, command=create_circle)
btn_circle.pack()

btn_delete = tk.Button(fenetre, text='Delete', width=30, command=delete)
btn_delete.pack()

fenetre.mainloop()


问:
React store.getState is not a function
Here is my code:

store.js

```<code>import {createStore, applyMiddleware, compose} from 'redux';
import {fromJS} from 'immutable';
import {routerMiddleware} from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history) {
    // Create the store with two middlewares
    // 1. sagaMiddleware: Makes redux-sagas work
    // 2. routerMiddleware: Syncs the location/URL path to the state
    const middlewares = [sagaMiddleware, routerMiddleware(history)];

    const enhancers = [applyMiddleware(...middlewares)];

    const store = createStore(createReducer, fromJS(initialState), enhancers);

    // Extensions
    store.runSaga = sagaMiddleware.run;
    store.asyncReducers = {}; // Async reducer registry

    return store;
}
</code>```

Routes.js

```<code>import React from 'react';
import {Route, Router, IndexRoute, browserHistory} from 'react-router';
import {syncHistoryWithStore} from 'react-router-redux';
import store from './store';

import Welcome from './containers/Welcome';

const history = syncHistoryWithStore(browserHistory, store);

const routes = (
    <Router history={history}>
        <Route path="/">
              <IndexRoute component={Welcome} />
        </Route>
    </Router>
);

export default routes;
</code>```

Index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {browserHistory} from 'react-router';
import { Providers } from 'react-redux';
import configureStore from './store';
import routes from './routes';

const initialState = {};
const store = configureStore(initialState, browserHistory);

ReactDOM.render(
    <Provider store={store}>
        {routes}
    </Provider>, document.getElementById('main-content')
);
</code>```

I can't find where the culprit is. I tried to debug it, but  can't found what really make it those error. error: Uncaught TypeError: store.getState is not a function

Any solution?

答:
I was doing this (a dynamic require) ..

```<code>    const store = require('../store/app')
    state = store.getState()
</code>```

but for some reason when using require instead of import you have to do this ..

```<code>    const store = require('../store/app')
    state = store.default.getState()
</code>```

Title: React store.getState is not a function

Body:
Here is my code:

store.js

import {createStore, applyMiddleware, compose} from 'redux';
import {fromJS} from 'immutable';
import {routerMiddleware} from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history) {
    // Create the store with two middlewares
    // 1. sagaMiddleware: Makes redux-sagas work
    // 2. routerMiddleware: Syncs the location/URL path to the state
    const middlewares = [sagaMiddleware, routerMiddleware(history)];

    const enhancers = [applyMiddleware(...middlewares)];

    const store = createStore(createReducer, fromJS(initialState), enhancers);

    // Extensions
    store.runSaga = sagaMiddleware.run;
    store.asyncReducers = {}; // Async reducer registry

    return store;
}

Routes.js

import React from 'react';
import {Route, Router, IndexRoute, browserHistory} from 'react-router';
import {syncHistoryWithStore} from 'react-router-redux';
import store from './store';

import Welcome from './containers/Welcome';

const history = syncHistoryWithStore(browserHistory, store);

const routes = (
    <Router history={history}>
        <Route path="/">
              <IndexRoute component={Welcome} />
        </Route>
    </Router>
);

export default routes;

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {browserHistory} from 'react-router';
import { Providers } from 'react-redux';
import configureStore from './store';
import routes from './routes';

const initialState = {};
const store = configureStore(initialState, browserHistory);

ReactDOM.render(
    <Provider store={store}>
        {routes}
    </Provider>, document.getElementById('main-content')
);

I can't find where the culprit is. I tried to debug it, but  can't found what really make it those error. error: Uncaught TypeError: store.getState is not a function

Any solution?

Body:
I was doing this (a dynamic require) ..

    const store = require('../store/app')
    state = store.getState()

but for some reason when using require instead of import you have to do this ..

    const store = require('../store/app')
    state = store.default.getState()


问:
Bulk DocumentDB insertion increase CPU usage
I am inserting 80 record/sec to DocumentDB using C#. Everything works well but somehow my server CPU usage reach to 90% and it crashes application.

I have taken care of everything which includes, Singleton DocumentClient, Indexing, Throughput limit, Direct connection mode, TCP connection, retry policy, open connection safely before first request.

Any one have idea on this?

答:
Have you followed the performance tips listed here: http://azure.microsoft.com/blog/2015/01/20/performance-tips-for-azure-documentdb-part-1-2/ and http://azure.microsoft.com/blog/2015/01/27/performance-tips-for-azure-documentdb-part-2/? You should see a performance of < 10 ms on writes with DocumentDB aside from network latency of your connection.

Reference: Fastest way to insert 100,000+ records into DocumentDB


问:
word() function returns the different results depending on gnuplot version 5.06 and 5.22
I recently updated gnuplot latest version, 5.22 and my code didn't work properly. I debugged and found the reasons.

```<code>str="1 2"
print word(str,3)+0
</code>```

In the previous version, 5.06 or older, the print shows 0 values without error.
But the latest version got error, "Non-numeric string found where a numeric expression was expected"

Without +0, both results are the same, blank (no output), but the latest version treats it as string I think.

My code has lots of routine related to word(), so how do I resolve this problem in the new version?

答:
Your code seems to make two potentially dangerous assumptions:

that requesting the third element from a list of two elements returns an empty string, rather than causing an error, and

that converting that empty string to a number will yield 0.

Assumption 1 seems to still hold in gnuplot 5.2.2, but assumption 2 does not. If you really wanted that then you could create a wrapper

```<code>f(x) = (x eq "" ? 0 : x)
</code>```

and use f(word(str,3)) instead of word(str,3). However, there might be a better way to deal with non-existing elements.

Body:
I recently updated gnuplot latest version, 5.22 and my code didn't work properly. I debugged and found the reasons.

str="1 2"
print word(str,3)+0

In the previous version, 5.06 or older, the print shows 0 values without error.
But the latest version got error, "Non-numeric string found where a numeric expression was expected"

Without +0, both results are the same, blank (no output), but the latest version treats it as string I think.

My code has lots of routine related to word(), so how do I resolve this problem in the new version?

Body:
Your code seems to make two potentially dangerous assumptions:

that requesting the third element from a list of two elements returns an empty string, rather than causing an error, and

that converting that empty string to a number will yield 0.

Assumption 1 seems to still hold in gnuplot 5.2.2, but assumption 2 does not. If you really wanted that then you could create a wrapper

f(x) = (x eq "" ? 0 : x)

and use f(word(str,3)) instead of word(str,3). However, there might be a better way to deal with non-existing elements.


问:
JMeter doesnt pass http post request sampler body data as json
I am using JMeter and i am currently facing this issue.

I want to perform a POST request to an API function but somehow when it gets sent to the call, my body data doesnt send in JSON format.

This is the body data sent

```<code>{
    "project_id": "2",
    "name": "Jaya Jadon",
    "phone": "0123456789",
    "email": "email@email.com",
    "remarks": "",
    "co_applicants":[
        {
            "name": "Wongg Feig Uncle",
            "phone": "0123476798",
            "email": "unclee@weie.com"
        },
        {
            "name": "Wineg Feie Father",
            "phone": "0123496897",
            "email": "fatheer@weie.com"
        }
    ],
    "documents": [
        {
            "booking_form": "",
            "consent_form": [
                "https://www.jjj.com/CF1.jpg"
            ],
            "ic_passport_no":[
                "https://www.jjj.com/IC1.jpg"
            ],
            "additional": ""
        }
    ]
}
</code>```

But this is what gets sent to when the POST request is sent

```<code>{
    "{\r\n\t\"project_id\"" => ">\"2\",\r\n\t\"name\"=>\"Jaya Jadon\",\r\n\t\"phone\"=>\"0123456789\",\r\n\t\"email\": \"email@email.com\",\r\n\t\"remarks\": \"\",\r\n\t\"co_applicants\":[\r\n\t\t{\r\n\t\t\t\"name\": \"Wongg Feig Uncle\",\r\n\t\t\t\"phone\": \"0123476798\",\r\n\t\t\t\"email\": \"unclee@weie.com\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"name\": \"Wineg Feie Father\",\r\n\t\t\t\"phone\": \"0123496897\",\r\n\t\t\t\"email\": \"fatheer@weie.com\"\r\n\t\t}\r\n\t],\r\n\t\"documents\": [\r\n\t\t{\r\n\t\t\t\"booking_form\": \"\",\r\n\t\t\t\"consent_form\": [\t\r\n\t\t\t\t\"https://www.jjj.com/CF1.jpg\"\r\n\t\t\t],\r\n\t\t\t\"ic_passport_no\":[\r\n\t\t\t\t\"https://www.jjj.com/IC1.jpg\"\r\n\t\t\t],\r\n\t\t\t\"additional\": \"\"\r\n\t\t}\r\n\t]\r\n}",
                   "format" => "json",
               "controller" => "v1/lp_developer_referrals",
                   "action" => "create"
}
</code>```

And this is what I am expecting to get

```<code>{
       "project_id" => "2",
             "name" => "Jaya Jadon",
            "phone" => "0123456789",
            "email" => "email@email.com",
          "remarks" => nil,
    "co_applicants" => nil,
        "documents" => [
        [0] {
              "booking_form" => nil,
              "consent_form" => [
                [0] "https://www.jjj.com/CF1.jpg"
            ],
            "ic_passport_no" => [
                [0] "https://www.jjj.com/IC1.jpg"
            ],
                "additional" => nil
        }
    ],
           "format" => "json",
       "controller" => "v1/lp_developer_referrals",
           "action" => "create"
}
</code>```

Can someone explain to me why my Jmeter is not taking my body data as json objects?

答: Please, try to add a "HTTP Header Manager" with a "Content-Type" with a value "application/json" before your requests, or inside them. Tell us if the behavior is correct.</p>

Body:
I am using JMeter and i am currently facing this issue.

I want to perform a POST request to an API function but somehow when it gets sent to the call, my body data doesnt send in JSON format.

This is the body data sent

{
    "project_id": "2",
    "name": "Jaya Jadon",
    "phone": "0123456789",
    "email": "email@email.com",
    "remarks": "",
    "co_applicants":[
        {
            "name": "Wongg Feig Uncle",
            "phone": "0123476798",
            "email": "unclee@weie.com"
        },
        {
            "name": "Wineg Feie Father",
            "phone": "0123496897",
            "email": "fatheer@weie.com"
        }
    ],
    "documents": [
        {
            "booking_form": "",
            "consent_form": [
                "https://www.jjj.com/CF1.jpg"
            ],
            "ic_passport_no":[
                "https://www.jjj.com/IC1.jpg"
            ],
            "additional": ""
        }
    ]
}

But this is what gets sent to when the POST request is sent

{
    "{\r\n\t\"project_id\"" => ">\"2\",\r\n\t\"name\"=>\"Jaya Jadon\",\r\n\t\"phone\"=>\"0123456789\",\r\n\t\"email\": \"email@email.com\",\r\n\t\"remarks\": \"\",\r\n\t\"co_applicants\":[\r\n\t\t{\r\n\t\t\t\"name\": \"Wongg Feig Uncle\",\r\n\t\t\t\"phone\": \"0123476798\",\r\n\t\t\t\"email\": \"unclee@weie.com\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"name\": \"Wineg Feie Father\",\r\n\t\t\t\"phone\": \"0123496897\",\r\n\t\t\t\"email\": \"fatheer@weie.com\"\r\n\t\t}\r\n\t],\r\n\t\"documents\": [\r\n\t\t{\r\n\t\t\t\"booking_form\": \"\",\r\n\t\t\t\"consent_form\": [\t\r\n\t\t\t\t\"https://www.jjj.com/CF1.jpg\"\r\n\t\t\t],\r\n\t\t\t\"ic_passport_no\":[\r\n\t\t\t\t\"https://www.jjj.com/IC1.jpg\"\r\n\t\t\t],\r\n\t\t\t\"additional\": \"\"\r\n\t\t}\r\n\t]\r\n}",
                   "format" => "json",
               "controller" => "v1/lp_developer_referrals",
                   "action" => "create"
}

And this is what I am expecting to get

{
       "project_id" => "2",
             "name" => "Jaya Jadon",
            "phone" => "0123456789",
            "email" => "email@email.com",
          "remarks" => nil,
    "co_applicants" => nil,
        "documents" => [
        [0] {
              "booking_form" => nil,
              "consent_form" => [
                [0] "https://www.jjj.com/CF1.jpg"
            ],
            "ic_passport_no" => [
                [0] "https://www.jjj.com/IC1.jpg"
            ],
                "additional" => nil
        }
    ],
           "format" => "json",
       "controller" => "v1/lp_developer_referrals",
           "action" => "create"
}

Can someone explain to me why my Jmeter is not taking my body data as json objects?


问:
How to move 12 digit numbers from richtextbox to textbox2
I want to move 12 digit numbers from richtextbox to textbox2 by a program.

I enter these words for richtextbox

```<code>sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd
</code>```

I need to get only these 12 digit numbers to  textbox2..

I tried this code but it types System.Text.RegularExpressions.MatchCollection not these digits

Here i use code for that

```<code>private void button2_Click(object sender, EventArgs e)
{
    Regex RX = new Regex("[0-9]{1,12}$");
    textBox2.Text = (RX.Matches(richTextBox1.Text)).ToString();
}
</code>```

I don't know how to move these numebrs to the textbox2.. Please help me enter image description here

答:
1) If you want to return all 12-digit numbers (no more, no less), your regex should be [0-9]{12}. The $ you had in your OP matches the end of a string or line, and the {1,12} in your OP matches any number of digits from 1 to 12. If the number has to be surrounded by commas or string anchors so that 13-digit numbers are not matched, your regex would look something like (?<=^|,)[0-9]{12}(?=,|$).

2) If you read this link, Regex.Matches(string) returns a MatchCollection. If you convert that to string, it is just the type name to string. You have to get to each item in the collection, like:

```<code>Match match = regex.Match(input);
while (match.Success) {
    // Your logic here
   match = match.NextMatch();
}
</code>```

3) I think string.Split(',') is easier to use. Then, loop through the array and return all strings that are 12 characters long and are numeric. Alternatively, you could use Linq as others have pointed out.

Body:
I want to move 12 digit numbers from richtextbox to textbox2 by a program.

I enter these words for richtextbox

sdgsjglksdjgkl,512025151988,512025151988,512025151988,512025151988,512025151988,sdgsgd

I need to get only these 12 digit numbers to  textbox2..

I tried this code but it types System.Text.RegularExpressions.MatchCollection not these digits

Here i use code for that

private void button2_Click(object sender, EventArgs e)
{
    Regex RX = new Regex("[0-9]{1,12}$");
    textBox2.Text = (RX.Matches(richTextBox1.Text)).ToString();
}

I don't know how to move these numebrs to the textbox2.. Please help me enter image description here

Body:
1) If you want to return all 12-digit numbers (no more, no less), your regex should be [0-9]{12}. The $ you had in your OP matches the end of a string or line, and the {1,12} in your OP matches any number of digits from 1 to 12. If the number has to be surrounded by commas or string anchors so that 13-digit numbers are not matched, your regex would look something like (?<=^|,)[0-9]{12}(?=,|$).

2) If you read this link, Regex.Matches(string) returns a MatchCollection. If you convert that to string, it is just the type name to string. You have to get to each item in the collection, like:

Match match = regex.Match(input);
while (match.Success) {
    // Your logic here
   match = match.NextMatch();
}

3) I think string.Split(',') is easier to use. Then, loop through the array and return all strings that are 12 characters long and are numeric. Alternatively, you could use Linq as others have pointed out.


问:
sql query to get all sub-categories and their sub-categories and so on of a category
my categories table is

```<code>id          parent_id
----------   -----------
1           0
2           1
3           1
4           2
5           3
6           2
7           4
8           3
9           5
10          6
11          7
12          4
13          10
14          9
</code>```

suppose I want to get categories of category_id 2 then output should be like as

```<code>id 2,4,6,7,10,11,12,13
</code>```

and for category 3 o/p should be

```<code>id 3,5,8,9,14
</code>```

and for 1 should be

```<code>id 1,2,3,4,5,6,7,8,9,10,11,12,13,14
</code>```

and for 4 should be

```<code>id 4,7,11,12
</code>```

please help to get this query

答:
Perhaps it should be something like that;

For SQL Server

```<code>WITH PR AS
(
    SELECT * , id AS parent
    FROM table c
    UNION ALL
    SELECT c.* , r.parent
    FROM table c
    INNER JOIN PR r ON c.parent_id = r.id
)
SELECT
  r.parent AS parent_id
, r.id AS Childid
FROM PR r
ORDER BY parent_id;
</code>```

Body:
my categories table is

id          parent_id
----------   -----------
1           0
2           1
3           1
4           2
5           3
6           2
7           4
8           3
9           5
10          6
11          7
12          4
13          10
14          9

suppose I want to get categories of category_id 2 then output should be like as

id 2,4,6,7,10,11,12,13

and for category 3 o/p should be

id 3,5,8,9,14

and for 1 should be

id 1,2,3,4,5,6,7,8,9,10,11,12,13,14

and for 4 should be

id 4,7,11,12

please help to get this query

Body:
Perhaps it should be something like that;

For SQL Server

WITH PR AS
(
    SELECT * , id AS parent
    FROM table c
    UNION ALL
    SELECT c.* , r.parent
    FROM table c
    INNER JOIN PR r ON c.parent_id = r.id
)
SELECT
  r.parent AS parent_id
, r.id AS Childid
FROM PR r
ORDER BY parent_id;


问:
How to create (Async)EventBus with ImmediateDispatcher?
I'm trying to create an AsyncEventBus, with a ThreadPoolExecutor. I noticed that AsyncEventBus is hardcoded to always use a LegacyAsyncDispatcher. The javadoc of Dispatcher.legacyAsync() states:

For async dispatch, an immediate dispatcher should generally be preferable.

But I can't find any way of actually creating an AsyncEventBus with Dispatcher.immediate(). And then EventBus is hardcoded to use Dispatcher.perThreadDispatchQueue().

How does one create an ImmediateDispatcher and wire it into an EventBus?

答:
I think you're reading too much into the source of this package. Notice that Dispatcher is a package-private class, so you can't create (or even reference) an instance of any type of Dispatcher. The docs on Dispatcher.legacyAsync() are therefore intended for other library maintainers, not for users of the eventbus package.

In other words, just use AsyncEventBus and pass in the executor you want it to use. Maybe one day the maintainers will change AsyncEventBus's implementation to not use legacyAsync(), but that shouldn't have any impact on you, the user.


问:
mean.io stack angular long running operations with http request
I am using the mean stack do develop a web application that performs several operations over several mongo db collections.

The systems overal intention is to perform data sinchronization between several systems. Each system data is stored in a different collections. Needless to say that these collection's documents have properties in common.

At the nodeJS, or the API level, I created get and post requests that will loop over the main collection asynchronouslye and will try to link documents on that collection with documents in other collections. Naturally this process takes for several minutes.

The documents that were possible to link are stored in a different mongodb collection. These will be later processed in another node js API call.

After the API is set I am creating a controller and a service with angular in order to connect to the api and perform the api get and post requests.

When I get to this point in the UI where I click in a button to perform this link operation, the operation starts without blocking the browser but eventually the browser get an ERR_EMPTY_RESPONSE because the operation is still undergoing so I never actually call the response.end().

What I thought could be a possible solution:

reply back as soon as the operation starts: PROBLEM -> I need to make sure this operation finishes in order to make other calls on the resulting collection. So I did this operation to finishs to allow others to be done on the resulting data set.

What can I do in order to avoid the browser to close the connection before the long running operation in the background is completed?

Code:

html-> Button which the user clicks to start linking records:

```<code><div>
    <md-button aria-label="link all records" ng-click="vm.linkRecords()">
        <md-icon class="mdi mdi-plus"></md-icon>Link Records
    </md-button>
</div>
</code>```

controller: the canLink, canGrade are all boolean variables so that When the server is undergoing one operation none of the others can be performed. Once the operation finishes, it returns true and all operations are allowed.

```<code>function linkRecords() {
    $state.go('app.records.link');
}// END linkRecords page

$scope.$on('linkRecords', function(event, batchSize){
    if ( canLink && canGrade) {
        showToast("Started linking records");
        canLink  = 0;
        canGrade = 0;
        recordService.linkRecords(batchSize).then(function(finished){
            canLink     = finished;
            canGrade    = finished;
        });
    }else if ( !canLink ){
        showToast('Cannot link records: - Currently undergoing grading records');
    }else if ( !canGrade ){
        showToast('Cannot link records: - Currently undergoing linking records');
    }
});//END linkingRecords
</code>```

Service

```<code>function linkRecords(batchSize){
    return $http.get(urlRoot+'/link/:'+batchSize);
}//END linkRecords
</code>```

Node js api:

routes.js:

```<code>//link all records
app.post('/link/:batchSize', function(req, res){
    var batchSize = req.params.batchSize;
    functions.linkRecords(batchSize, function(callback){
        res.end(true);
    });
});//END linkRecords
</code>```

functions.js:

```<code>linkRecords : function(batchSize, callback){
    //link all records in all collections a batchsize at a time
    async.parallel([
        function(callback){
            ...open cursor for collection1 and loops over the collections to stitch with other collections.
        },
        function(callback){
            ...open cursor for collection2 and loops over the collections to stitch with other collections.
        }
    ], function done(err, result){
        callback();
    });
}
</code>```

答:
I am not an expert on MEAN stack (yet) but I guess the way you design your service is not right. It will return a promise (result is not completed) and you call ends before the promise finish.

try to design your service and route.js call something like this.

service

```<code>angular.module('rugCoPro').factory('appraisalSearch', ['$resource', 'RugSession', function($resource, RugSession) {

        return $resource("/:org/api/models/appraisals/:func/:value", { org: "@org", func: "@func", value: "@value" }, {
            query: {
                method: 'GET',
                isArray: true,
                headers: { 'Content-Type': 'application/json', 'X-Auth-Token': authToken }
            }
        });

}])
</code>```

call

```<code>   appraisalSearch(RugSession.getAuthToken()).query({ org: org, func: "multi", value: orderNumber[0] }).$promise.then(function(data) {
       //success
    }, function(error) {
       //error
  })
</code>```

Body:
I am using the mean stack do develop a web application that performs several operations over several mongo db collections.

The systems overal intention is to perform data sinchronization between several systems. Each system data is stored in a different collections. Needless to say that these collection's documents have properties in common.

At the nodeJS, or the API level, I created get and post requests that will loop over the main collection asynchronouslye and will try to link documents on that collection with documents in other collections. Naturally this process takes for several minutes.

The documents that were possible to link are stored in a different mongodb collection. These will be later processed in another node js API call.

After the API is set I am creating a controller and a service with angular in order to connect to the api and perform the api get and post requests.

When I get to this point in the UI where I click in a button to perform this link operation, the operation starts without blocking the browser but eventually the browser get an ERR_EMPTY_RESPONSE because the operation is still undergoing so I never actually call the response.end().

What I thought could be a possible solution:

reply back as soon as the operation starts: PROBLEM -> I need to make sure this operation finishes in order to make other calls on the resulting collection. So I did this operation to finishs to allow others to be done on the resulting data set.

What can I do in order to avoid the browser to close the connection before the long running operation in the background is completed?

Code:

html-> Button which the user clicks to start linking records:

    <md-button aria-label="link all records" ng-click="vm.linkRecords()">
        <md-icon class="mdi mdi-plus"></md-icon>Link Records
    </md-button>

controller: the canLink, canGrade are all boolean variables so that When the server is undergoing one operation none of the others can be performed. Once the operation finishes, it returns true and all operations are allowed.

function linkRecords() {
    $state.go('app.records.link');
}// END linkRecords page

$scope.$on('linkRecords', function(event, batchSize){
    if ( canLink && canGrade) {
        showToast("Started linking records");
        canLink  = 0;
        canGrade = 0;
        recordService.linkRecords(batchSize).then(function(finished){
            canLink     = finished;
            canGrade    = finished;
        });
    }else if ( !canLink ){
        showToast('Cannot link records: - Currently undergoing grading records');
    }else if ( !canGrade ){
        showToast('Cannot link records: - Currently undergoing linking records');
    }
});//END linkingRecords

Service

function linkRecords(batchSize){
    return $http.get(urlRoot+'/link/:'+batchSize);
}//END linkRecords

Node js api:

routes.js:

//link all records
app.post('/link/:batchSize', function(req, res){
    var batchSize = req.params.batchSize;
    functions.linkRecords(batchSize, function(callback){
        res.end(true);
    });
});//END linkRecords

functions.js:

linkRecords : function(batchSize, callback){
    //link all records in all collections a batchsize at a time
    async.parallel([
        function(callback){
            ...open cursor for collection1 and loops over the collections to stitch with other collections.
        },
        function(callback){
            ...open cursor for collection2 and loops over the collections to stitch with other collections.
        }
    ], function done(err, result){
        callback();
    });
}

Body:
I am not an expert on MEAN stack (yet) but I guess the way you design your service is not right. It will return a promise (result is not completed) and you call ends before the promise finish.

try to design your service and route.js call something like this.

service

angular.module('rugCoPro').factory('appraisalSearch', ['$resource', 'RugSession', function($resource, RugSession) {

        return $resource("/:org/api/models/appraisals/:func/:value", { org: "@org", func: "@func", value: "@value" }, {
            query: {
                method: 'GET',
                isArray: true,
                headers: { 'Content-Type': 'application/json', 'X-Auth-Token': authToken }
            }
        });

}])

call

   appraisalSearch(RugSession.getAuthToken()).query({ org: org, func: "multi", value: orderNumber[0] }).$promise.then(function(data) {
       //success
    }, function(error) {
       //error
  })


问:
selecting using nth child selector jquery
I want to make a selection in jquery using nth child selector I have the index number as a variable suggestions;
but  $('.search_filter:nth-child('+suggestions+')').focus();
does not focus the 2 element if suggestions=1
so please tell me what I am doing wrong here.

答:
The nth-child-selector(docs)  uses a 1 based index to get the sibling at the given index. So if you want the second sibling, you'd use 2.

If they are not all siblings, or you just want a 0 based index, use the eq-selector(docs) instead..

ContentLicense: CC BY-SA 2.5


问:
Select an input after its inserted using `Ember.run`
Updated — The problem with my solution below was with if statement around Ember.run. Removing it solved the problem, but my approach was also incorrect. Instead of scheduling the focus for after rendering, I should make a custom component as acorncom suggested.

Original Question:

I'm building a list of text inputs based on an array on my model. On newline I'd like to insert a new text field and then select it. I'm trying to do this with Ember.run.scheduleOnce, but the function I provide is never called.

I've reopened the textfield to expose a data-index attribute binding, and in my template am rendering:

```<code>{{#each model.entries as |entry index|}}
  {{input value=entry.text class='field--entry' data-index=index insert-newline=(action 'insertEntry' index)}}
{{/each}}
</code>```

In my controller:

```<code>actions: {
  insertEntry(index){
    // This works fine and a new textfield is added.
    this.get('model.entries').addObject({text: 'Example'});

    if (index){
      Ember.run.scheduleOnce('afterRender', this, function(){
        // This doesn't seem to work at all.
        console.log("This is never logged");
        $(".field--entry[data-index='" + index + 1 + "']").focus();
      });
    }
  }
}
</code>```

答:
Per a work-in-progress branch here (https://github.com/ember-best-practices/recommendations/blob/initial-pass/guides/run.md), you generally want to steer clear of using afterRender if there are other approaches that would work better.

I'd suggest using a component to handle rendering your list of items, as you'd be able to use the  component lifecycle hooks to do what you're after. If you check the guides (specifically the section discussing didRender), you'll see an example that closely matches what you're after ... https://guides.emberjs.com/v2.17.0/components/the-component-lifecycle/#toc_making-updates-to-the-rendered-dom-with-code-didrender-code

Body:
Updated — The problem with my solution below was with if statement around Ember.run. Removing it solved the problem, but my approach was also incorrect. Instead of scheduling the focus for after rendering, I should make a custom component as acorncom suggested.

Original Question:

I'm building a list of text inputs based on an array on my model. On newline I'd like to insert a new text field and then select it. I'm trying to do this with Ember.run.scheduleOnce, but the function I provide is never called.

I've reopened the textfield to expose a data-index attribute binding, and in my template am rendering:

{{#each model.entries as |entry index|}}
  {{input value=entry.text class='field--entry' data-index=index insert-newline=(action 'insertEntry' index)}}
{{/each}}

In my controller:

actions: {
  insertEntry(index){
    // This works fine and a new textfield is added.
    this.get('model.entries').addObject({text: 'Example'});

    if (index){
      Ember.run.scheduleOnce('afterRender', this, function(){
        // This doesn't seem to work at all.
        console.log("This is never logged");
        $(".field--entry[data-index='" + index + 1 + "']").focus();
      });
    }
  }
}


问:
Store the Disposable when subscribed to a Mono in database
I am currently exploring the reactor-core. I am able to subscribe to a Mono and also save the disposable to handle the execution of the subscriber.

```<code>Mono<Object> task1 = Mono.just("Task1");
Mono<Object> task2 = Mono.just("Task2");
System.out.println(System.currentTimeMillis());
HashMap<Mono,Disposable> taskHandlerMap = new HashMap<>();
Disposable task1Handler = task1.delayElement(Duration.ofSeconds(5)).subscribe(
(Object x)->{
        System.out.println(x.toString() + "\t" + System.currentTimeMillis());
});
taskHandlerMap.put(task1,task1Handler);
Disposable task2Handler = task2.delayElement(Duration.ofSeconds(10)).subscribe(
(Object x)->{
        System.out.println(x.toString() + "\t" + System.currentTimeMillis());
});
taskHandlerMap.put(task2,task2Handler);
</code>```

I am able to dispose a scheduled task by using the handler map as follows.

```<code>taskHandlerMap.get(task2).dispose();
</code>```

Can I save this taskHandlerMap in a database? Is yes, how can I save it. Else is there a better way to store the disposable created at subscription.

答:
as @akarnokd points out, a Disposable is merely a reference to a live computation, and it makes no sense to try and save it and restore it to/from a database.

It is kind of like if you submitted an long HTTP call to an ExecutorService and expected to be able to save the Future to the DB and somehow restore it... If the application stops, the HTTP call is gone anyway. If the application keeps on running, there's no need to keep the Future in a DB (you'd keep it in memory, with the same lifespan as the HTTP call).

Body:
I am currently exploring the reactor-core. I am able to subscribe to a Mono and also save the disposable to handle the execution of the subscriber.

Mono<Object> task1 = Mono.just("Task1");
Mono<Object> task2 = Mono.just("Task2");
System.out.println(System.currentTimeMillis());
HashMap<Mono,Disposable> taskHandlerMap = new HashMap<>();
Disposable task1Handler = task1.delayElement(Duration.ofSeconds(5)).subscribe(
(Object x)->{
        System.out.println(x.toString() + "\t" + System.currentTimeMillis());
});
taskHandlerMap.put(task1,task1Handler);
Disposable task2Handler = task2.delayElement(Duration.ofSeconds(10)).subscribe(
(Object x)->{
        System.out.println(x.toString() + "\t" + System.currentTimeMillis());
});
taskHandlerMap.put(task2,task2Handler);

I am able to dispose a scheduled task by using the handler map as follows.

taskHandlerMap.get(task2).dispose();

Can I save this taskHandlerMap in a database? Is yes, how can I save it. Else is there a better way to store the disposable created at subscription.


问:
Why is PrincipalContext ValidateCredentials throwing an exception when given incorrect credentials?
I'm trying to authenticate the user.  Authentication through PrincipalContext works fine with the correct username and password, but when testing with incorrect credentials, ValidateCredentials throws a System.Exception rather than returning false.  The exception simply states that 'The user name or password is incorrect'.  The stack trace is as follows:

```<code>   at System.DirectoryServices.AccountManagement.UnsafeNativeMethods.IADs.Get(String bstrName)
   at System.DirectoryServices.AccountManagement.CredentialValidator.BindSam(String target, String userName, String password)
   at System.DirectoryServices.AccountManagement.PrincipalContext.ValidateCredentials(String userName, String password)
   at hcv.Core.AuthenticationSystem.Services.WindowsAuthenticationService.<>c__DisplayClass3_0.<AuthenticateAsync>b__0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)" string
</code>```

and the code is pretty straight forward:

```<code>using (var pc = new PrincipalContext(_contextType, _domain))
{
    var isAuthenticated = pc.ValidateCredentials(username, password);
    return isAuthenticated;
}
</code>```

I am currently working around this by catching the error, checking the message and returning false if it's the incorrect username or password message and rethrowing if not, but that feels hacky.

Does anyone have any idea why the exception is being thrown rather than simply returning false for invalid credentials?

答:
Add ContextOptionsto the method ValidateCredentials.

There is a variety of options depending on the ContextType.

Check here: https://msdn.microsoft.com/en-us/library/bb300969(v=vs.110).aspx

Body:
I'm trying to authenticate the user.  Authentication through PrincipalContext works fine with the correct username and password, but when testing with incorrect credentials, ValidateCredentials throws a System.Exception rather than returning false.  The exception simply states that 'The user name or password is incorrect'.  The stack trace is as follows:

   at System.DirectoryServices.AccountManagement.UnsafeNativeMethods.IADs.Get(String bstrName)
   at System.DirectoryServices.AccountManagement.CredentialValidator.BindSam(String target, String userName, String password)
   at System.DirectoryServices.AccountManagement.PrincipalContext.ValidateCredentials(String userName, String password)
   at hcv.Core.AuthenticationSystem.Services.WindowsAuthenticationService.<>c__DisplayClass3_0.<AuthenticateAsync>b__0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)" string

and the code is pretty straight forward:

using (var pc = new PrincipalContext(_contextType, _domain))
{
    var isAuthenticated = pc.ValidateCredentials(username, password);
    return isAuthenticated;
}

I am currently working around this by catching the error, checking the message and returning false if it's the incorrect username or password message and rethrowing if not, but that feels hacky.

Does anyone have any idea why the exception is being thrown rather than simply returning false for invalid credentials?


问:
Using @Column and @Formula in Hibernate at the same time
I've got a POJO and currently I'm getting a value from a single column. However, I'm moving to retrieve it using Hibernate @Formula (I select the latest record from another table). I want to go softly in order not to break anything.

So what I want to do is something like this:

```<code>class SomeDto {
    private someField;

    @Column("PREVIOUS_FIELD_COLUMN", nullable = false, length = 1)
    @Formula("@NEW RETRIEVING LOGIC@")
    public getSomeField() {
    ...
}
</code>```

so that I could be able to store the someField value in the PREVIOUS_FIELD_COLUMN and at the same time retrieve the value based on the new criteria.

However now it seems that Hibernate ignores the @Column annotation as I get the following error:

SQLIntegrityConstraintViolationException: ORA-01400: cannot insert
  NULL into

I see in logs that Hibernate skips PREVIOUS_FIELD_COLUMN in the insert statement being generated (doesn't list it and doesn't set the value from POJO).

Any help appreciated, thank you very much!

答:
I think you will use ColumnTransformer instead of formula like this

```<code>  class SomeDto {
    private someField;

    @Column("PREVIOUS_FIELD_COLUMN", nullable = false, length = 1)
    @ColumnTransformer(read = “@NEW RETRIEVING LOGIC@”)
    public getSomeField() {
    ...
  }
</code>```

for more information see this https://www.thoughts-on-java.org/map-encrypted-database-columns-hibernates-columntransformer-annotation/

Body:
I've got a POJO and currently I'm getting a value from a single column. However, I'm moving to retrieve it using Hibernate @Formula (I select the latest record from another table). I want to go softly in order not to break anything.

So what I want to do is something like this:

class SomeDto {
    private someField;

    @Column("PREVIOUS_FIELD_COLUMN", nullable = false, length = 1)
    @Formula("@NEW RETRIEVING LOGIC@")
    public getSomeField() {
    ...
}

so that I could be able to store the someField value in the PREVIOUS_FIELD_COLUMN and at the same time retrieve the value based on the new criteria.

However now it seems that Hibernate ignores the @Column annotation as I get the following error:

SQLIntegrityConstraintViolationException: ORA-01400: cannot insert
  NULL into

I see in logs that Hibernate skips PREVIOUS_FIELD_COLUMN in the insert statement being generated (doesn't list it and doesn't set the value from POJO).

Any help appreciated, thank you very much!

Body:
I think you will use ColumnTransformer instead of formula like this

  class SomeDto {
    private someField;

    @Column("PREVIOUS_FIELD_COLUMN", nullable = false, length = 1)
    @ColumnTransformer(read = “@NEW RETRIEVING LOGIC@”)
    public getSomeField() {
    ...
  }

for more information see this https://www.thoughts-on-java.org/map-encrypted-database-columns-hibernates-columntransformer-annotation/


问:
How can I load an image from my json file in angular 4?
I want to load an image from my json file in my angular 4 project. I had declared the path of my images in my json file. But instead of showing the images, the html template shows the path string directly of the images. I stored my images in the assets folder in my angular project

Html and json file is below

    <collapsible-list [type]="'expandable'">
      <collapsible-list-item>
        <collapsible-header class="waves-effect">

              {{ menu.Name }}

        </collapsible-header>
        <collapsible-body [expanded]="true">

                {{ setMenuItems.FoodItem.SetMenuImages }}

             Price: {{ menu.Price }} BDT

        </collapsible-body>
      </collapsible-list-item>
    </collapsible-list>

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

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    {
      "Name": "Set Menu A",
      "Price": "199",
      "Id": "1",
      "SetMenuImage": "'assets/set-menu-a.jpg'",
      "SetMenuItems": [
        {
          "FoodItem":
          {
            "Id": "1",
            "Name": "Fried Rice",
            "Price": "99"
          },
          "FoodItemId": "1",
          "Id": "1",
          "Quantity": "1",
          "SetMenuId": "1"
        },
        {
          "FoodItem":
          {
            "Id": "3",
            "Name": "Chicken Fry",
            "Price": "80"
          },
          "FoodItemId": "3",
          "Id": "2",
          "Quantity": "1",
          "SetMenuId": "1"
        },
        {
          "FoodItem":
          {
            "Id": "2",
            "Name": "CocaCola",
            "Price": "30"
          },
          "FoodItemId": "2",
          "Id": "3",
          "Quantity": "2",
          "SetMenuId": "1"
        }

      ]
    }</code>```

答: In your solution there is no img tag, provide one.</p>

Body:
I want to load an image from my json file in my angular 4 project. I had declared the path of my images in my json file. But instead of showing the images, the html template shows the path string directly of the images. I stored my images in the assets folder in my angular project

Html and json file is below

    <collapsible-list [type]="'expandable'">
      <collapsible-list-item>
        <collapsible-header class="waves-effect">

              {{ menu.Name }}

        </collapsible-header>
        <collapsible-body [expanded]="true">

                {{ setMenuItems.FoodItem.SetMenuImages }}

             Price: {{ menu.Price }} BDT

        </collapsible-body>
      </collapsible-list-item>
    </collapsible-list>

    {
      "Name": "Set Menu A",
      "Price": "199",
      "Id": "1",
      "SetMenuImage": "'assets/set-menu-a.jpg'",
      "SetMenuItems": [
        {
          "FoodItem":
          {
            "Id": "1",
            "Name": "Fried Rice",
            "Price": "99"
          },
          "FoodItemId": "1",
          "Id": "1",
          "Quantity": "1",
          "SetMenuId": "1"
        },
        {
          "FoodItem":
          {
            "Id": "3",
            "Name": "Chicken Fry",
            "Price": "80"
          },
          "FoodItemId": "3",
          "Id": "2",
          "Quantity": "1",
          "SetMenuId": "1"
        },
        {
          "FoodItem":
          {
            "Id": "2",
            "Name": "CocaCola",
            "Price": "30"
          },
          "FoodItemId": "2",
          "Id": "3",
          "Quantity": "2",
          "SetMenuId": "1"
        }

      ]
    }


问:
Making Variables Global in PHP?
Need to make $courseInfo and $row global so that they can be used for printing the row details in the header DIV.

Don't have a clue how to do this. Any help would be great.

```<code><?php

// Get Course ID From Link
$ID = mysql_real_escape_string($_REQUEST['ID']);

// Check the Course ID exists
$courseCheck = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");

if (mysql_num_rows($courseCheck) == 1) {

    $checkMember = mysql_query("SELECT * FROM CourseMembers WHERE CourseID = '".$ID."' AND UserID = '".$_SESSION['UserID']."'");

    if (mysql_num_rows($checkMember) == 1) {

        ?>
        <html>
        <head>
            <!-- Style Sheets -->
            <link rel="stylesheet" href="style/reset.css" type="text/css" media=screen />
            <link rel="stylesheet" href="style/style.css" type="text/css" media=screen />
        </head>
        <body>

        <?php
        if ($_SESSION['LoggedIn'] == 1){

            $courseInfo = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
            $row = mysql_fetch_assoc($courseInfo);

        ?>

            <div id="container">
                <div id="side">
                    <?php include("lib/sidebar.php"); ?>
                </div>
                <div id="main">
                    <div id="mainbox">
                        <div id="header"><b><?php echo $row['CourseName']; ?></b></div>
                        <p>Hello world, this is a test.</p>
                    </div>
                </div>
            </div>
            <div class="clear"></div>

            <?php
            }
        else {
            echo "Not logged in.";
        }

    }

    else {
        echo "You are not a member of this Course";
    }

}

else {
    echo "No Course Found";
}

?>
</body>
</code>```

答: You could store them in session variables, similarly to your $_SESSION['LoggedIn']

Title: Making Variables Global in PHP?

Body:
Need to make $courseInfo and $row global so that they can be used for printing the row details in the header DIV.

Don't have a clue how to do this. Any help would be great.

<?php

// Get Course ID From Link
$ID = mysql_real_escape_string($_REQUEST['ID']);

// Check the Course ID exists
$courseCheck = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");

if (mysql_num_rows($courseCheck) == 1) {

    $checkMember = mysql_query("SELECT * FROM CourseMembers WHERE CourseID = '".$ID."' AND UserID = '".$_SESSION['UserID']."'");

    if (mysql_num_rows($checkMember) == 1) {

        ?>

            <link rel="stylesheet" href="style/reset.css" type="text/css" media=screen />
            <link rel="stylesheet" href="style/style.css" type="text/css" media=screen />

        <?php
        if ($_SESSION['LoggedIn'] == 1){

            $courseInfo = mysql_query("SELECT * FROM Courses WHERE CourseID = '".$ID."'");
            $row = mysql_fetch_assoc($courseInfo);

        ?>

                    <?php include("lib/sidebar.php"); ?>

<?php echo $row['CourseName']; ?>

Hello world, this is a test.

            <?php
            }
        else {
            echo "Not logged in.";
        }

    }

    else {
        echo "You are not a member of this Course";
    }

}

else {
    echo "No Course Found";
}

?>


问:
How to scale prometheus in kubernetes environment
I have reached moment when I need to split my prometheus into smaller ones.
I have been reading about it here but it does not say anything about scaling in kubernetes. Below is my setup:

one node of prometheus

one node of kube state metrics

node exporter on each cluster node

and there are about 50 namespaces which produces thousands of metrics and one current setup with one prometheus is not enough. So I decided to split it to three instances like:

one for kube state metrics metrics

one for node exporter metrics

one for kubernetes metrics

But after while i realised that those metrics are scraped by kubernetes_sd_config and there is no way to tell which metrics I want to scrape by which instance of prometheus or I am wrong.
One solution would be to split kubernetes cluster into smaller one but it is too much work for now.

So my question is if there is any possibility to tell prometheus that I want scrape only kube state metrics, node exporter or native kubernetes metrics ?

答:
I had a similar task for federation. Here is how I did, following @brian-brazil answer:

setup a master prometheus with config:

      scrape_configs:
      - job_name: dc_prometheus
        honor_labels: true
        metrics_path: /federate
        params:
          match[]:
          - '{job="my-kubernetes-job"}'
        static_configs:
          - targets:
            - prometheus-slaveA:9090
            - prometheus-slaveB:9090

See how slaves are declared here. It's quite static for sure.
Also, the match[] param here tells to grab all slave metrics. You would have to be smarter than that of course.

setup slaves with that particular relabeling:

          relabel_configs:
          - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_slave]
            action: keep
            regex: slaveA

and similar for slaveB and so on.

Now for each pod, instead of having the well-known annotation prometheus.io/scrape: true|false, you would have prometheus.io/slave: slaveA|slaveB.

I described it with more details here: http://devlog.qaraywa.net/?p=176

Body:
I have reached moment when I need to split my prometheus into smaller ones.
I have been reading about it here but it does not say anything about scaling in kubernetes. Below is my setup:

one node of prometheus

one node of kube state metrics

node exporter on each cluster node

and there are about 50 namespaces which produces thousands of metrics and one current setup with one prometheus is not enough. So I decided to split it to three instances like:

one for kube state metrics metrics

one for node exporter metrics

one for kubernetes metrics

But after while i realised that those metrics are scraped by <a href="https://prometheus.io/docs/operating/configuration/#<kubernetes_sd_config" rel="nofollow noreferrer">kubernetes_sd_config and there is no way to tell which metrics I want to scrape by which instance of prometheus or I am wrong.
One solution would be to split kubernetes cluster into smaller one but it is too much work for now.

So my question is if there is any possibility to tell prometheus that I want scrape only kube state metrics, node exporter or native kubernetes metrics ?


问:
How do I execute the Java code after a few minutes? I want a very simple code or function
How do I execute the Java code after a few minutes?

I want very simple code or function. How do I pause a line of code in Java?

答:
Use Thread.sleep(long mills);. This function takes a long value in milliseconds (thousandths of a second) to pause

Hope this helps!

ContentLicense: CC BY-SA 4.0


问:
python ontimer vs thread
This is an extension of my recent post. Now that I know about onTimer and Thread, starting a new post.

I did away w/ the while loop in the main. Replaced with onTimer() and Thread. But same results, cant move both objects simultaneously. Code for both listed below: Any advice is appreciated...this is my first go at graphics w/ Python.

code using onTimer

```<code>import turtle
import math

screen = turtle.Screen()
screen.screensize(1000, 1000)
screen.bgcolor("light green")

player = turtle.Turtle()
player.hideturtle()
player.penup()
player.shape("circle")
player.color("red")
player.fillcolor("yellow")
player.setposition(-50, -40)
player.showturtle()
player.speed(0)

s = turtle.Turtle()
s.hideturtle()
s.penup()
s.shape("square")
s.color("black")
s.fillcolor("white")
s.setposition(-50, -60)
s.showturtle()

# first tier
s1 = turtle.Turtle()
s1.hideturtle()
s1.penup()
s1.shape("square")
s1.color("black")
s1.fillcolor("white")
s1.showturtle()

s2 = turtle.Turtle()
s2.hideturtle()
s2.penup()
s2.shape("square")
s2.color("black")
s2.fillcolor("white")
s2.setposition(s1.xcor() + 20, 0)
s2.showturtle()

s3 = turtle.Turtle()
s3.hideturtle()
s3.penup()
s3.shape("square")
s3.color("black")
s3.fillcolor("white")
s3.setposition(s2.xcor() + 20, 0)
s3.showturtle()

s4 = turtle.Turtle()
s4.hideturtle()
s4.penup()
s4.shape("square")
s4.color("black")
s4.fillcolor("white")
s4.setposition(s3.xcor() + 20, 0)
s4.showturtle()

# second tier
s5 = turtle.Turtle()
s5.hideturtle()
s5.penup()
s5.shape("square")
s5.color("black")
s5.fillcolor("white")
s5.setposition(s4.xcor() + 30, 60)
s5.showturtle()

s6 = turtle.Turtle()
s6.hideturtle()
s6.penup()
s6.shape("square")
s6.color("black")
s6.fillcolor("white")
s6.setposition(s5.xcor() + 20, 60)
s6.showturtle()

s7 = turtle.Turtle()
s7.hideturtle()
s7.penup()
s7.shape("square")
s7.color("black")
s7.fillcolor("white")
s7.setposition(s6.xcor() + 20, 60)
s7.showturtle()

s8 = turtle.Turtle()
s8.hideturtle()
s8.penup()
s8.shape("square")
s8.color("black")
s8.fillcolor("white")
s8.setposition(s7.xcor() + 20, 60)
s8.showturtle()

# third tier
s9 = turtle.Turtle()
s9.hideturtle()
s9.penup()
s9.shape("square")
s9.color("black")
s9.fillcolor("white")
s9.setposition(s8.xcor() + 30, 120)
s9.showturtle()

s10 = turtle.Turtle()
s10.hideturtle()
s10.penup()
s10.shape("square")
s10.color("black")
s10.fillcolor("white")
s10.setposition(s9.xcor() + 20, 120)
s10.showturtle()

s11 = turtle.Turtle()
s11.hideturtle()
s11.penup()
s11.shape("square")
s11.color("black")
s11.fillcolor("white")
s11.setposition(s10.xcor() + 20, 120)
s11.showturtle()

s12 = turtle.Turtle()
s12.hideturtle()
s12.penup()
s12.shape("square")
s12.color("black")
s12.fillcolor("white")
s12.setposition(s11.xcor() + 20, 120)
s12.showturtle()

#moving enemy
s13 = turtle.Turtle()
s13.hideturtle()
s13.penup()
s13.shape("square")
s13.color("black")
s13.fillcolor("red")
s13.setposition(s11.xcor() + 5, 140)
s13.showturtle()

#static turtle
s14 = turtle.Turtle()
s14.hideturtle()
s14.penup()
s14.shape("turtle")
s14.color("black")
s14.fillcolor("red")
s14.setposition(s6.xcor() + 20, 80)
s14.showturtle()

squareList = [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]

falling = False

def jump():
    speed = 2

    while speed > 0:
        y = player.ycor()
        x = player.xcor()
        y += 6
        x += 1.3
        speed -= 0.09
        player.setposition(x, y)
        collision()
    if speed < 0:
        falling = True
        while falling:
            y = player.ycor()
            x = player.xcor()
            y -= 2
            x += 1
            speed += .10
            player.setposition(x, y)
            collision()
            for squares in squareList:
                if (player.xcor() >= 0 and player.xcor() <= 80) and player.ycor() == 20:
                    falling = False
                if (player.xcor() >= 80 and player.xcor() <= 160) and player.ycor() == 80:
                    falling = False
                if (player.xcor() >= 160 and player.xcor() <= 240) and player.ycor() == 140:
                    falling = False

def right():
    x = player.xcor()
    x += 2
    player.setx(x)
    collision()

def moveEnemy():
    s13.backward(3)
    if s13.xcor() > 250:
        s13.setheading(0)
    if s13.xcor() < 180:
        s13.setheading(180)
    screen.ontimer(moveEnemy(), 5)
    collision()

def collision():
    distance1 = math.sqrt(math.pow(player.xcor()-s13.xcor(),2) + math.pow(player.ycor()-s13.ycor(), 2))
    if distance1 < 20:
        player.hideturtle()

    distance2 = math.sqrt(math.pow(player.xcor() - s14.xcor(), 2) + math.pow(player.ycor() - s14.ycor(), 2))
    if distance2 < 20:
        s14.hideturtle()

turtle.listen()
turtle.onkey(jump, "Up")
turtle.onkey(right, "Right")

screen.ontimer(moveEnemy(), 5)

turtle.mainloop()
</code>```

code using Thread

```<code>import turtle
import math
import threading
from threading import Thread

screen = turtle.Screen()
screen.screensize(1000, 1000)
screen.bgcolor("light green")

player = turtle.Turtle()
player.hideturtle()
player.penup()
player.shape("circle")
player.color("red")
player.fillcolor("yellow")
player.setposition(-50, -40)
player.showturtle()
player.speed(0)

s = turtle.Turtle()
s.hideturtle()
s.penup()
s.shape("square")
s.color("black")
s.fillcolor("white")
s.setposition(-50, -60)
s.showturtle()

# first tier
s1 = turtle.Turtle()
s1.hideturtle()
s1.penup()
s1.shape("square")
s1.color("black")
s1.fillcolor("white")
s1.showturtle()

s2 = turtle.Turtle()
s2.hideturtle()
s2.penup()
s2.shape("square")
s2.color("black")
s2.fillcolor("white")
s2.setposition(s1.xcor() + 20, 0)
s2.showturtle()

s3 = turtle.Turtle()
s3.hideturtle()
s3.penup()
s3.shape("square")
s3.color("black")
s3.fillcolor("white")
s3.setposition(s2.xcor() + 20, 0)
s3.showturtle()

s4 = turtle.Turtle()
s4.hideturtle()
s4.penup()
s4.shape("square")
s4.color("black")
s4.fillcolor("white")
s4.setposition(s3.xcor() + 20, 0)
s4.showturtle()

# second tier
s5 = turtle.Turtle()
s5.hideturtle()
s5.penup()
s5.shape("square")
s5.color("black")
s5.fillcolor("white")
s5.setposition(s4.xcor() + 30, 60)
s5.showturtle()

s6 = turtle.Turtle()
s6.hideturtle()
s6.penup()
s6.shape("square")
s6.color("black")
s6.fillcolor("white")
s6.setposition(s5.xcor() + 20, 60)
s6.showturtle()

s7 = turtle.Turtle()
s7.hideturtle()
s7.penup()
s7.shape("square")
s7.color("black")
s7.fillcolor("white")
s7.setposition(s6.xcor() + 20, 60)
s7.showturtle()

s8 = turtle.Turtle()
s8.hideturtle()
s8.penup()
s8.shape("square")
s8.color("black")
s8.fillcolor("white")
s8.setposition(s7.xcor() + 20, 60)
s8.showturtle()

# third tier
s9 = turtle.Turtle()
s9.hideturtle()
s9.penup()
s9.shape("square")
s9.color("black")
s9.fillcolor("white")
s9.setposition(s8.xcor() + 30, 120)
s9.showturtle()

s10 = turtle.Turtle()
s10.hideturtle()
s10.penup()
s10.shape("square")
s10.color("black")
s10.fillcolor("white")
s10.setposition(s9.xcor() + 20, 120)
s10.showturtle()

s11 = turtle.Turtle()
s11.hideturtle()
s11.penup()
s11.shape("square")
s11.color("black")
s11.fillcolor("white")
s11.setposition(s10.xcor() + 20, 120)
s11.showturtle()

s12 = turtle.Turtle()
s12.hideturtle()
s12.penup()
s12.shape("square")
s12.color("black")
s12.fillcolor("white")
s12.setposition(s11.xcor() + 20, 120)
s12.showturtle()

#moving enemy
s13 = turtle.Turtle()
s13.hideturtle()
s13.penup()
s13.shape("square")
s13.color("black")
s13.fillcolor("red")
s13.setposition(s11.xcor() + 5, 140)
s13.showturtle()

#static turtle
s14 = turtle.Turtle()
s14.hideturtle()
s14.penup()
s14.shape("turtle")
s14.color("black")
s14.fillcolor("red")
s14.setposition(s6.xcor() + 20, 80)
s14.showturtle()

squareList = [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]

falling = False

def jump():
    speed = 2

    while speed > 0:
        y = player.ycor()
        x = player.xcor()
        y += 6
        x += 1.3
        speed -= 0.09
        player.setposition(x, y)
        collision()
    if speed < 0:
        falling = True
        while falling:
            y = player.ycor()
            x = player.xcor()
            y -= 2
            x += 1
            speed += .10
            player.setposition(x, y)
            collision()
            for squares in squareList:
                if (player.xcor() >= 0 and player.xcor() <= 80) and player.ycor() == 20:
                    falling = False
                if (player.xcor() >= 80 and player.xcor() <= 160) and player.ycor() == 80:
                    falling = False
                if (player.xcor() >= 160 and player.xcor() <= 240) and player.ycor() == 140:
                    falling = False

def right():
    x = player.xcor()
    x += 2
    player.setx(x)
    collision()

def moveEnemy():
    s13.backward(3)
    if s13.xcor() > 250:
        s13.setheading(0)
    if s13.xcor() < 180:
        s13.setheading(180)
    screen.ontimer(moveEnemy(), 5)
    collision()

def collision():
    distance1 = math.sqrt(math.pow(player.xcor()-s13.xcor(),2) + math.pow(player.ycor()-s13.ycor(), 2))
    if distance1 < 20:
        player.hideturtle()

    distance2 = math.sqrt(math.pow(player.xcor() - s14.xcor(), 2) + math.pow(player.ycor() - s14.ycor(), 2))
    if distance2 < 20:
        s14.hideturtle()

turtle.listen()
turtle.onkey(jump, "Up")
turtle.onkey(right, "Right")

Thread(target = moveEnemy).start()

turtle.mainloop()
</code>```

答:
You made the same error as in your original code, where you made the motion atomic -- you can't stop everything while you implement the jump.  You need to break the jump into discrete steps.  Here's my ontimer() based solution:

```<code>from turtle import Turtle, Screen
import math

screen = Screen()
screen.screensize(1000, 1000)
screen.bgcolor('light green')

player = Turtle('circle', visible=False)
player.penup()
player.color('red', 'yellow')
player.setposition(-50, -40)
player.showturtle()
player.speed('fastest')

s = Turtle('square', visible=False)
s.penup()
s.color('black', 'white')
s.setposition(-50, -60)
s.showturtle()

# first tier
s1 = Turtle('square', visible=False)
s1.penup()
s1.color('black', 'white')

s2 = s1.clone()
s2.setx(s1.xcor() + 20)
s2.showturtle()

s3 = s1.clone()
s3.setx(s2.xcor() + 20)
s3.showturtle()

s4 = s1.clone()
s4.setx(s3.xcor() + 20)
s4.showturtle()

s1.showturtle()

# second tier
s5 = Turtle('square', visible=False)
s5.penup()
s5.color('black', 'white')
s5.setposition(s4.xcor() + 30, 60)

s6 = s5.clone()
s6.setx(s5.xcor() + 20)
s6.showturtle()

s7 = s5.clone()
s7.setx(s6.xcor() + 20)
s7.showturtle()

s8 = s5.clone()
s8.setx(s7.xcor() + 20)
s8.showturtle()

s5.showturtle()

# third tier
s9 = Turtle('square', visible=False)
s9.penup()
s9.color('black', 'white')
s9.setposition(s8.xcor() + 30, 120)

s10 = s9.clone()
s10.setx(s9.xcor() + 20)
s10.showturtle()

s11 = s9.clone()
s11.setx(s10.xcor() + 20)
s11.showturtle()

s12 = s9.clone()
s12.setx(s11.xcor() + 20)
s12.showturtle()

s9.showturtle()

# moving enemy
s13 = Turtle('square', visible=False)
s13.penup()
s13.color('black', 'red')
s13.setposition(s11.xcor() + 5, 140)
s13.showturtle()

# static turtle
s14 = Turtle('turtle', visible=False)
s14.penup()
s14.color('black', 'red')
s14.setposition(s6.xcor() + 20, 80)
s14.showturtle()

squareList = [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]

RISING, FALLING = 0, 1
state = None
speed = -1

def jump():
    global speed, state
    speed = 2
    state = RISING
    screen.ontimer(jumping, 7)

def jumping():
    global speed, state

    if state == RISING:
        x, y = player.position()
        y += 6
        x += 1.3
        speed -= 0.09
        player.setposition(x, y)
        collision()

    if speed < 0:
        state = FALLING

    if state == FALLING:
        x, y = player.position()
        y -= 2
        x += 1
        speed += 0.10
        player.setposition(x, y)
        collision()

        for _ in squareList:
            if (0 <= player.xcor() <= 80) and player.ycor() == 20:
                state = None
            if (80 <= player.xcor() <= 160) and player.ycor() == 80:
                state = None
            if (160 <= player.xcor() <= 240) and player.ycor() == 140:
                state = None

    if state in [RISING, FALLING]:
        screen.ontimer(jumping, 7)

def right():
    player.setx(player.xcor() + 2)
    collision()

def moveEnemy():
    s13.backward(3)
    if s13.xcor() > 250:
        s13.setheading(0)
    elif s13.xcor() < 180:
        s13.setheading(180)
    screen.ontimer(moveEnemy(), 5)
    collision()

def collision():
    distance = math.sqrt(math.pow(player.xcor() - s13.xcor(), 2) + math.pow(player.ycor() - s13.ycor(), 2))
    if distance < 20:
        player.hideturtle()

    distance = math.sqrt(math.pow(player.xcor() - s14.xcor(), 2) + math.pow(player.ycor() - s14.ycor(), 2))
    if distance < 20:
        s14.hideturtle()

screen.onkey(jump, 'Up')
screen.onkey(right, 'Right')
screen.listen()

screen.ontimer(moveEnemy(), 5)

screen.mainloop()
</code>```

I also reworked other stuff while I was at it, tossing 30% of your code.  There's still stuff you need to add about stopping the jumping timer when the player collides or falls off the bottom of the window.

Title: python ontimer vs thread

Body:
This is an extension of my recent post. Now that I know about onTimer and Thread, starting a new post.

I did away w/ the while loop in the main. Replaced with onTimer() and Thread. But same results, cant move both objects simultaneously. Code for both listed below: Any advice is appreciated...this is my first go at graphics w/ Python.

code using onTimer

import turtle
import math

screen = turtle.Screen()
screen.screensize(1000, 1000)
screen.bgcolor("light green")

player = turtle.Turtle()
player.hideturtle()
player.penup()
player.shape("circle")
player.color("red")
player.fillcolor("yellow")
player.setposition(-50, -40)
player.showturtle()
player.speed(0)

s = turtle.Turtle()
s.hideturtle()
s.penup()
s.shape("square")
s.color("black")
s.fillcolor("white")
s.setposition(-50, -60)
s.showturtle()

# first tier
s1 = turtle.Turtle()
s1.hideturtle()
s1.penup()
s1.shape("square")
s1.color("black")
s1.fillcolor("white")
s1.showturtle()

s2 = turtle.Turtle()
s2.hideturtle()
s2.penup()
s2.shape("square")
s2.color("black")
s2.fillcolor("white")
s2.setposition(s1.xcor() + 20, 0)
s2.showturtle()

s3 = turtle.Turtle()
s3.hideturtle()
s3.penup()
s3.shape("square")
s3.color("black")
s3.fillcolor("white")
s3.setposition(s2.xcor() + 20, 0)
s3.showturtle()

s4 = turtle.Turtle()
s4.hideturtle()
s4.penup()
s4.shape("square")
s4.color("black")
s4.fillcolor("white")
s4.setposition(s3.xcor() + 20, 0)
s4.showturtle()

# second tier
s5 = turtle.Turtle()
s5.hideturtle()
s5.penup()
s5.shape("square")
s5.color("black")
s5.fillcolor("white")
s5.setposition(s4.xcor() + 30, 60)
s5.showturtle()

s6 = turtle.Turtle()
s6.hideturtle()
s6.penup()
s6.shape("square")
s6.color("black")
s6.fillcolor("white")
s6.setposition(s5.xcor() + 20, 60)
s6.showturtle()

s7 = turtle.Turtle()
s7.hideturtle()
s7.penup()
s7.shape("square")
s7.color("black")
s7.fillcolor("white")
s7.setposition(s6.xcor() + 20, 60)
s7.showturtle()

s8 = turtle.Turtle()
s8.hideturtle()
s8.penup()
s8.shape("square")
s8.color("black")
s8.fillcolor("white")
s8.setposition(s7.xcor() + 20, 60)
s8.showturtle()

# third tier
s9 = turtle.Turtle()
s9.hideturtle()
s9.penup()
s9.shape("square")
s9.color("black")
s9.fillcolor("white")
s9.setposition(s8.xcor() + 30, 120)
s9.showturtle()

s10 = turtle.Turtle()
s10.hideturtle()
s10.penup()
s10.shape("square")
s10.color("black")
s10.fillcolor("white")
s10.setposition(s9.xcor() + 20, 120)
s10.showturtle()

s11 = turtle.Turtle()
s11.hideturtle()
s11.penup()
s11.shape("square")
s11.color("black")
s11.fillcolor("white")
s11.setposition(s10.xcor() + 20, 120)
s11.showturtle()

s12 = turtle.Turtle()
s12.hideturtle()
s12.penup()
s12.shape("square")
s12.color("black")
s12.fillcolor("white")
s12.setposition(s11.xcor() + 20, 120)
s12.showturtle()

#moving enemy
s13 = turtle.Turtle()
s13.hideturtle()
s13.penup()
s13.shape("square")
s13.color("black")
s13.fillcolor("red")
s13.setposition(s11.xcor() + 5, 140)
s13.showturtle()

#static turtle
s14 = turtle.Turtle()
s14.hideturtle()
s14.penup()
s14.shape("turtle")
s14.color("black")
s14.fillcolor("red")
s14.setposition(s6.xcor() + 20, 80)
s14.showturtle()

squareList = [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]

falling = False

def jump():
    speed = 2

    while speed > 0:
        y = player.ycor()
        x = player.xcor()
        y += 6
        x += 1.3
        speed -= 0.09
        player.setposition(x, y)
        collision()
    if speed < 0:
        falling = True
        while falling:
            y = player.ycor()
            x = player.xcor()
            y -= 2
            x += 1
            speed += .10
            player.setposition(x, y)
            collision()
            for squares in squareList:
                if (player.xcor() >= 0 and player.xcor() <= 80) and player.ycor() == 20:
                    falling = False
                if (player.xcor() >= 80 and player.xcor() <= 160) and player.ycor() == 80:
                    falling = False
                if (player.xcor() >= 160 and player.xcor() <= 240) and player.ycor() == 140:
                    falling = False

def right():
    x = player.xcor()
    x += 2
    player.setx(x)
    collision()

def moveEnemy():
    s13.backward(3)
    if s13.xcor() > 250:
        s13.setheading(0)
    if s13.xcor() < 180:
        s13.setheading(180)
    screen.ontimer(moveEnemy(), 5)
    collision()

def collision():
    distance1 = math.sqrt(math.pow(player.xcor()-s13.xcor(),2) + math.pow(player.ycor()-s13.ycor(), 2))
    if distance1 < 20:
        player.hideturtle()

    distance2 = math.sqrt(math.pow(player.xcor() - s14.xcor(), 2) + math.pow(player.ycor() - s14.ycor(), 2))
    if distance2 < 20:
        s14.hideturtle()

turtle.listen()
turtle.onkey(jump, "Up")
turtle.onkey(right, "Right")

screen.ontimer(moveEnemy(), 5)

turtle.mainloop()

code using Thread

import turtle
import math
import threading
from threading import Thread

screen = turtle.Screen()
screen.screensize(1000, 1000)
screen.bgcolor("light green")

player = turtle.Turtle()
player.hideturtle()
player.penup()
player.shape("circle")
player.color("red")
player.fillcolor("yellow")
player.setposition(-50, -40)
player.showturtle()
player.speed(0)

s = turtle.Turtle()
s.hideturtle()
s.penup()
s.shape("square")
s.color("black")
s.fillcolor("white")
s.setposition(-50, -60)
s.showturtle()

# first tier
s1 = turtle.Turtle()
s1.hideturtle()
s1.penup()
s1.shape("square")
s1.color("black")
s1.fillcolor("white")
s1.showturtle()

s2 = turtle.Turtle()
s2.hideturtle()
s2.penup()
s2.shape("square")
s2.color("black")
s2.fillcolor("white")
s2.setposition(s1.xcor() + 20, 0)
s2.showturtle()

s3 = turtle.Turtle()
s3.hideturtle()
s3.penup()
s3.shape("square")
s3.color("black")
s3.fillcolor("white")
s3.setposition(s2.xcor() + 20, 0)
s3.showturtle()

s4 = turtle.Turtle()
s4.hideturtle()
s4.penup()
s4.shape("square")
s4.color("black")
s4.fillcolor("white")
s4.setposition(s3.xcor() + 20, 0)
s4.showturtle()

# second tier
s5 = turtle.Turtle()
s5.hideturtle()
s5.penup()
s5.shape("square")
s5.color("black")
s5.fillcolor("white")
s5.setposition(s4.xcor() + 30, 60)
s5.showturtle()

s6 = turtle.Turtle()
s6.hideturtle()
s6.penup()
s6.shape("square")
s6.color("black")
s6.fillcolor("white")
s6.setposition(s5.xcor() + 20, 60)
s6.showturtle()

s7 = turtle.Turtle()
s7.hideturtle()
s7.penup()
s7.shape("square")
s7.color("black")
s7.fillcolor("white")
s7.setposition(s6.xcor() + 20, 60)
s7.showturtle()

s8 = turtle.Turtle()
s8.hideturtle()
s8.penup()
s8.shape("square")
s8.color("black")
s8.fillcolor("white")
s8.setposition(s7.xcor() + 20, 60)
s8.showturtle()

# third tier
s9 = turtle.Turtle()
s9.hideturtle()
s9.penup()
s9.shape("square")
s9.color("black")
s9.fillcolor("white")
s9.setposition(s8.xcor() + 30, 120)
s9.showturtle()

s10 = turtle.Turtle()
s10.hideturtle()
s10.penup()
s10.shape("square")
s10.color("black")
s10.fillcolor("white")
s10.setposition(s9.xcor() + 20, 120)
s10.showturtle()

s11 = turtle.Turtle()
s11.hideturtle()
s11.penup()
s11.shape("square")
s11.color("black")
s11.fillcolor("white")
s11.setposition(s10.xcor() + 20, 120)
s11.showturtle()

s12 = turtle.Turtle()
s12.hideturtle()
s12.penup()
s12.shape("square")
s12.color("black")
s12.fillcolor("white")
s12.setposition(s11.xcor() + 20, 120)
s12.showturtle()

#moving enemy
s13 = turtle.Turtle()
s13.hideturtle()
s13.penup()
s13.shape("square")
s13.color("black")
s13.fillcolor("red")
s13.setposition(s11.xcor() + 5, 140)
s13.showturtle()

#static turtle
s14 = turtle.Turtle()
s14.hideturtle()
s14.penup()
s14.shape("turtle")
s14.color("black")
s14.fillcolor("red")
s14.setposition(s6.xcor() + 20, 80)
s14.showturtle()

squareList = [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]

falling = False

def jump():
    speed = 2

    while speed > 0:
        y = player.ycor()
        x = player.xcor()
        y += 6
        x += 1.3
        speed -= 0.09
        player.setposition(x, y)
        collision()
    if speed < 0:
        falling = True
        while falling:
            y = player.ycor()
            x = player.xcor()
            y -= 2
            x += 1
            speed += .10
            player.setposition(x, y)
            collision()
            for squares in squareList:
                if (player.xcor() >= 0 and player.xcor() <= 80) and player.ycor() == 20:
                    falling = False
                if (player.xcor() >= 80 and player.xcor() <= 160) and player.ycor() == 80:
                    falling = False
                if (player.xcor() >= 160 and player.xcor() <= 240) and player.ycor() == 140:
                    falling = False

def right():
    x = player.xcor()
    x += 2
    player.setx(x)
    collision()

def moveEnemy():
    s13.backward(3)
    if s13.xcor() > 250:
        s13.setheading(0)
    if s13.xcor() < 180:
        s13.setheading(180)
    screen.ontimer(moveEnemy(), 5)
    collision()

def collision():
    distance1 = math.sqrt(math.pow(player.xcor()-s13.xcor(),2) + math.pow(player.ycor()-s13.ycor(), 2))
    if distance1 < 20:
        player.hideturtle()

    distance2 = math.sqrt(math.pow(player.xcor() - s14.xcor(), 2) + math.pow(player.ycor() - s14.ycor(), 2))
    if distance2 < 20:
        s14.hideturtle()

turtle.listen()
turtle.onkey(jump, "Up")
turtle.onkey(right, "Right")

Thread(target = moveEnemy).start()

turtle.mainloop()

Body:
You made the same error as in your original code, where you made the motion atomic -- you can't stop everything while you implement the jump.  You need to break the jump into discrete steps.  Here's my ontimer() based solution:

from turtle import Turtle, Screen
import math

screen = Screen()
screen.screensize(1000, 1000)
screen.bgcolor('light green')

player = Turtle('circle', visible=False)
player.penup()
player.color('red', 'yellow')
player.setposition(-50, -40)
player.showturtle()
player.speed('fastest')

s = Turtle('square', visible=False)
s.penup()
s.color('black', 'white')
s.setposition(-50, -60)
s.showturtle()

# first tier
s1 = Turtle('square', visible=False)
s1.penup()
s1.color('black', 'white')

s2 = s1.clone()
s2.setx(s1.xcor() + 20)
s2.showturtle()

s3 = s1.clone()
s3.setx(s2.xcor() + 20)
s3.showturtle()

s4 = s1.clone()
s4.setx(s3.xcor() + 20)
s4.showturtle()

s1.showturtle()

# second tier
s5 = Turtle('square', visible=False)
s5.penup()
s5.color('black', 'white')
s5.setposition(s4.xcor() + 30, 60)

s6 = s5.clone()
s6.setx(s5.xcor() + 20)
s6.showturtle()

s7 = s5.clone()
s7.setx(s6.xcor() + 20)
s7.showturtle()

s8 = s5.clone()
s8.setx(s7.xcor() + 20)
s8.showturtle()

s5.showturtle()

# third tier
s9 = Turtle('square', visible=False)
s9.penup()
s9.color('black', 'white')
s9.setposition(s8.xcor() + 30, 120)

s10 = s9.clone()
s10.setx(s9.xcor() + 20)
s10.showturtle()

s11 = s9.clone()
s11.setx(s10.xcor() + 20)
s11.showturtle()

s12 = s9.clone()
s12.setx(s11.xcor() + 20)
s12.showturtle()

s9.showturtle()

# moving enemy
s13 = Turtle('square', visible=False)
s13.penup()
s13.color('black', 'red')
s13.setposition(s11.xcor() + 5, 140)
s13.showturtle()

# static turtle
s14 = Turtle('turtle', visible=False)
s14.penup()
s14.color('black', 'red')
s14.setposition(s6.xcor() + 20, 80)
s14.showturtle()

squareList = [s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12]

RISING, FALLING = 0, 1
state = None
speed = -1

def jump():
    global speed, state
    speed = 2
    state = RISING
    screen.ontimer(jumping, 7)

def jumping():
    global speed, state

    if state == RISING:
        x, y = player.position()
        y += 6
        x += 1.3
        speed -= 0.09
        player.setposition(x, y)
        collision()

    if speed < 0:
        state = FALLING

    if state == FALLING:
        x, y = player.position()
        y -= 2
        x += 1
        speed += 0.10
        player.setposition(x, y)
        collision()

        for _ in squareList:
            if (0 <= player.xcor() <= 80) and player.ycor() == 20:
                state = None
            if (80 <= player.xcor() <= 160) and player.ycor() == 80:
                state = None
            if (160 <= player.xcor() <= 240) and player.ycor() == 140:
                state = None

    if state in [RISING, FALLING]:
        screen.ontimer(jumping, 7)

def right():
    player.setx(player.xcor() + 2)
    collision()

def moveEnemy():
    s13.backward(3)
    if s13.xcor() > 250:
        s13.setheading(0)
    elif s13.xcor() < 180:
        s13.setheading(180)
    screen.ontimer(moveEnemy(), 5)
    collision()

def collision():
    distance = math.sqrt(math.pow(player.xcor() - s13.xcor(), 2) + math.pow(player.ycor() - s13.ycor(), 2))
    if distance < 20:
        player.hideturtle()

    distance = math.sqrt(math.pow(player.xcor() - s14.xcor(), 2) + math.pow(player.ycor() - s14.ycor(), 2))
    if distance < 20:
        s14.hideturtle()

screen.onkey(jump, 'Up')
screen.onkey(right, 'Right')
screen.listen()

screen.ontimer(moveEnemy(), 5)

screen.mainloop()

I also reworked other stuff while I was at it, tossing 30% of your code.  There's still stuff you need to add about stopping the jumping timer when the player collides or falls off the bottom of the window.