问:
session variables in flask keep changing
I have a very basic flask application that I have deployed to Heroku. I am trying to define a variable that I can change when a specific function is executed. For example, if I have a variable logged_in=True, I want to be able to change it to logged_in=False when the route @app.route('/logout') is executed. Here is the code:

```<code>import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session

app = Flask(__name__)

app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True

Session(app)

# Redirect to /login route
@app.route('/')
def index():
    return redirect(url_for("login"))

# Open main login page
@app.route("/login", methods=["POST","GET"])
def login():
    return render_template("login.html")

# Verify login credentials
@app.route("/login_check",methods=["POST"])
def login_check():
    return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")

@app.route("/main_page", methods=["POST"])
def main_page():
    return render_template("main_page.html",name="Main page")

@app.route("/log_out", methods=["POST"])
def log_out():
    app.config['logged_in']=False
    return redirect(url_for("login"))

if __name__ == '__main__':
    app.run(debug=True)
</code>```

When I launch the app locally, the value of logged_in is set to False when logout is executed and does not change if login is triggered again. However, when I deploy the app to Heroku, the value of logged_in goes back True when login is triggered again (it's weird, the value changes sometimes, but not always).

How can I set the value of logged_in so that it does not change until I update it with a function? I tried to use session.config['logged_in']instead of app.config['logged_in'], but I had the same issue. Ideally, I want the value to be unique for each session.

Thank you

答:
If you want to store one value to each session. No sql like redis is recommendation.

```<code>import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
import redis

app = Flask(__name__)

app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = redis.from_url('127.0.0.1:6379')
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True

Session(app)

# Redirect to /login route
@app.route('/')
def index():
    return redirect(url_for("login"))

# Open main login page
@app.route("/login", methods=["POST","GET"])
def login():
    return render_template("login.html")

# Verify login credentials
@app.route("/login_check",methods=["POST"])
def login_check():
    return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")

@app.route("/main_page", methods=["POST"])
def main_page():
    return render_template("main_page.html",name="Main page")

@app.route("/log_out", methods=["POST"])
def log_out():
    session['key'] = 'False'
    return redirect(url_for("login"))

if __name__ == '__main__':
    app.run(debug=True)
</code>```

Body:
I have a very basic flask application that I have deployed to Heroku. I am trying to define a variable that I can change when a specific function is executed. For example, if I have a variable logged_in=True, I want to be able to change it to logged_in=False when the route @app.route('/logout') is executed. Here is the code:

import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session

app = Flask(__name__)

app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True

Session(app)

# Redirect to /login route
@app.route('/')
def index():
    return redirect(url_for("login"))

# Open main login page
@app.route("/login", methods=["POST","GET"])
def login():
    return render_template("login.html")

# Verify login credentials
@app.route("/login_check",methods=["POST"])
def login_check():
    return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")

@app.route("/main_page", methods=["POST"])
def main_page():
    return render_template("main_page.html",name="Main page")

@app.route("/log_out", methods=["POST"])
def log_out():
    app.config['logged_in']=False
    return redirect(url_for("login"))

if __name__ == '__main__':
    app.run(debug=True)

When I launch the app locally, the value of logged_in is set to False when logout is executed and does not change if login is triggered again. However, when I deploy the app to Heroku, the value of logged_in goes back True when login is triggered again (it's weird, the value changes sometimes, but not always).

How can I set the value of logged_in so that it does not change until I update it with a function? I tried to use session.config['logged_in']instead of app.config['logged_in'], but I had the same issue. Ideally, I want the value to be unique for each session.

Thank you

Body:
If you want to store one value to each session. No sql like redis is recommendation.

import os
from flask import Flask, session, request, redirect, url_for, flash, g
from flask import render_template
from flask_session import Session
import redis

app = Flask(__name__)

app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_REDIS'] = redis.from_url('127.0.0.1:6379')
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['logged_in']=True

Session(app)

# Redirect to /login route
@app.route('/')
def index():
    return redirect(url_for("login"))

# Open main login page
@app.route("/login", methods=["POST","GET"])
def login():
    return render_template("login.html")

# Verify login credentials
@app.route("/login_check",methods=["POST"])
def login_check():
    return redirect(url_for("main_page"),code=307) if app.config['logged_in']==True else render_template("not_logged_in.html")

@app.route("/main_page", methods=["POST"])
def main_page():
    return render_template("main_page.html",name="Main page")

@app.route("/log_out", methods=["POST"])
def log_out():
    session['key'] = 'False'
    return redirect(url_for("login"))

if __name__ == '__main__':
    app.run(debug=True)


来源: stackexchange

问:
How can I mathematically compare two unknown types in Scala?
I'm writing a little script evaluator function.  It takes two arguments and a comparison operator like this:

    def compare[T,U](a:T, op:String, b:U): Boolean = {
      op match {
        case "==" => a == b
        case "<"  => a < b
        // and so on with other comparators...
      }
    }
```

This code won't compile.  The '<' operator doesn't work on the generic types.  I couldn't find a parent class for numeric types with the '<' operator, so I can't even do something like:  def compare[T<:Numeric,U<:Numeric](...)

Is there a way to do this (or a library)?  Right now I can only test equal/not-equal.

答:
In general, every time you want some kind of interface for common operations on multiple types, the answer is a Typeclass.

In this particular case, you can use scala.math.Ordering.

```<code>import scala.math.Ordering
import Ordering.Implicits._

def compare[T: Ordering](a: T, op: String, b: T): Boolean = op match {
  case "==" => a == b
  case "<"  => a < b
  // and so on with other comparators...
}
</code>```

And now you can use it like this.

```<code>compare(10, "==", 15) //false
compare(10, "==", 10) // true
compare(10, "<", 10) // false
compare(10, "<", 11) // true
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a little script evaluator function.  It takes two arguments and a comparison operator like this:

    def compare[T,U](a:T, op:String, b:U): Boolean = {
      op match {
        case "==" => a == b
        case "<"  => a < b
        // and so on with other comparators...
      }
    }

This code won't compile.  The '<' operator doesn't work on the generic types.  I couldn't find a parent class for numeric types with the '<' operator, so I can't even do something like:  def compare[T<:Numeric,U<:Numeric](...)

Is there a way to do this (or a library)?  Right now I can only test equal/not-equal.

Body:
In general, every time you want some kind of interface for common operations on multiple types, the answer is a Typeclass.

In this particular case, you can use scala.math.Ordering.

import scala.math.Ordering
import Ordering.Implicits._

def compare[T: Ordering](a: T, op: String, b: T): Boolean = op match {
  case "==" => a == b
  case "<"  => a < b
  // and so on with other comparators...
}

And now you can use it like this.

compare(10, "==", 15) //false
compare(10, "==", 10) // true
compare(10, "<", 10) // false
compare(10, "<", 11) // true


问:
i want use jsoup to grab news on my android app
I have a problem that I want to use jsoup to grab news but always fail.

this is news website.

https://www3.nhk.or.jp/news/

this is my picture .  which I circle is I wanted data.

https://drive.google.com/open?id=1KJAyOSdHO8APPD6_A9MjxkoFjekcQLXt

but no matter what I do. it always get wrong data or empty.

this is my program.

```<code>public class News extends AppCompatActivity {
Button ok;
private static final String url ="https://www3.nhk.or.jp/news/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
ok=(Button)findViewById(R.id.ok);
ok.setOnClickListener(okbtn);
}
private Button.OnClickListener okbtn=new Button.OnClickListener(){
public void onClick(View v){
try{
Connection.Response response = Jsoup.connect(url).execute();
String body = response.body();
Document data = Jsoup.parse(body);//visible-phone print_hide
Elements country=data.select("main");
Elements main=data.select("div[id=module module--news-main index-main]");

for(Element e1: country)
{
mytoast(e1+"");
}
}
catch(Exception ex){ex.printStackTrace() ;}
}
};
private void mytoast(String str)
{
Toast toast=Toast.makeText(this, str, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
</code>```

please help me
thanks

答:
You can try to see it's HTML first.

If you can't see it, you don't use jsoup.

There's a small hint in its comment:

このページではJavaScriptを使用しています

=>This is generated by JavaScript

If it's generated, you can't find it from Jsoup.

In this case, I'll use Chrome's tool to monitor the XHR tab

Look into each XHR request, and find the most possible one,

for example, I see this

https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640

A part of the response:

```<code>"id":"193411",
"title":"三菱ＵＦＪ銀行 新規口座は原則デジタル通帳に",
"pubDate":"Thu, 30 May 2019 04:03:11 +0900",
"cate":"5",
...
"id":"193437",
"title":"エアレース世界選手権 今季限りで終了",
"pubDate":"Thu, 30 May 2019 09:40:37 +0900",
</code>```

So this is exactly what you want. It comes from another link!

You don't need Jsoup, just HttpGet the link

https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640

And I think the numbers looks like UnixTime,

So I check the current time is : 1559184830782, that's it.

Just use that link as API and time as parameter.

Body:
I have a problem that I want to use jsoup to grab news but always fail.

this is news website.

https://www3.nhk.or.jp/news/

this is my picture .  which I circle is I wanted data.

https://drive.google.com/open?id=1KJAyOSdHO8APPD6_A9MjxkoFjekcQLXt

but no matter what I do. it always get wrong data or empty.

this is my program.

public class News extends AppCompatActivity {
Button ok;
private static final String url ="https://www3.nhk.or.jp/news/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
ok=(Button)findViewById(R.id.ok);
ok.setOnClickListener(okbtn);
}
private Button.OnClickListener okbtn=new Button.OnClickListener(){
public void onClick(View v){
try{
Connection.Response response = Jsoup.connect(url).execute();
String body = response.body();
Document data = Jsoup.parse(body);//visible-phone print_hide
Elements country=data.select("main");
Elements main=data.select("div[id=module module--news-main index-main]");

for(Element e1: country)
{
mytoast(e1+"");
}
}
catch(Exception ex){ex.printStackTrace() ;}
}
};
private void mytoast(String str)
{
Toast toast=Toast.makeText(this, str, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}

please help me
thanks

Body:
You can try to see it's HTML first.

If you can't see it, you don't use jsoup.

There's a small hint in its comment:

このページではJavaScriptを使用しています

=>This is generated by JavaScript

If it's generated, you can't find it from Jsoup.

In this case, I'll use Chrome's tool to monitor the XHR tab

Look into each XHR request, and find the most possible one,

for example, I see this

https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640

A part of the response:

"id":"193411",
"title":"三菱ＵＦＪ銀行 新規口座は原則デジタル通帳に",
"pubDate":"Thu, 30 May 2019 04:03:11 +0900",
"cate":"5",
...
"id":"193437",
"title":"エアレース世界選手権 今季限りで終了",
"pubDate":"Thu, 30 May 2019 09:40:37 +0900",

So this is exactly what you want. It comes from another link!

You don't need Jsoup, just HttpGet the link

https://www3.nhk.or.jp/news/json16/syuyo.json?_=1559183885640

And I think the numbers looks like UnixTime,

So I check the current time is : 1559184830782, that's it.

Just use that link as API and time as parameter.


问:
merge same keys data into one map with unique keys elixir
I have this json

```<code>[
  %{
    "159.69.136.31" => [
      %{"2015" => ["4"]},
      %{"2016" => []},
      %{"2017" => ["9"]},
      %{"2018" => []},
      %{"2019" => ["05"]}
    ]
  },
  %{
    "94.130.139.38" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => ["5", "8"]},
      %{"2019" => []}
    ]
  },
  %{
    "94.130.217.56" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => []},
      %{"2019" => []}
    ]
  }
]
</code>```

and I want to make it something like

```<code>[
  %{"2015" => ["4"]},
  %{"2016" => []},
  %{"2017" => ["9"]},
  %{"2018" => ["5", "8"]},
  %{"2019" => ["05"]}
]
</code>```

Basically, it's merging the same year's keys and the data available on the map. I have tried this solution with different approaches but it didn't work Elixir: Merge list with same map keys to one map

Update: years and IPs are constant
Update little bit more info about this..

```<code>years = ["2015", "2016", "2017", "2018", "2019"]
servers = [@seaweedfs_new, @seaweedfs_old, @seaweedfs_oldest]

  Enum.map(servers, fn server ->
    type = seaweefs_type(server)
    attribute = seaweedfs_attribute(server)
    url = "http://" <> server <> ":8888" <> "/#{camera.exid}/snapshots/recordings/"
    year_values =
      Enum.map(years, fn year ->
        final_url = url <> year <> "/"
        %{
          "#{year}" => request_from_seaweedfs(final_url, type, attribute)
        }
      end)
    %{
      "#{server}" => year_values
    }
  end)
</code>```

This is how I am getting year values and making them to the server object. If there is a possibility to break it down while even getting year values?

"#{year}" => request_from_seaweedfs(final_url, type, attribute) this request basically returns such as "2015"  => ["1", "2", "3"], is there any possiblity to merge years a head before going to into servers?

Body:
I have this json

[
  %{
    "159.69.136.31" => [
      %{"2015" => ["4"]},
      %{"2016" => []},
      %{"2017" => ["9"]},
      %{"2018" => []},
      %{"2019" => ["05"]}
    ]
  },
  %{
    "94.130.139.38" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => ["5", "8"]},
      %{"2019" => []}
    ]
  },
  %{
    "94.130.217.56" => [
      %{"2015" => []},
      %{"2016" => []},
      %{"2017" => []},
      %{"2018" => []},
      %{"2019" => []}
    ]
  }
]

and I want to make it something like

[
  %{"2015" => ["4"]},
  %{"2016" => []},
  %{"2017" => ["9"]},
  %{"2018" => ["5", "8"]},
  %{"2019" => ["05"]}
]

Basically, it's merging the same year's keys and the data available on the map. I have tried this solution with different approaches but it didn't work Elixir: Merge list with same map keys to one map

Update: years and IPs are constant
Update little bit more info about this..

years = ["2015", "2016", "2017", "2018", "2019"]
servers = [@seaweedfs_new, @seaweedfs_old, @seaweedfs_oldest]

  Enum.map(servers, fn server ->
    type = seaweefs_type(server)
    attribute = seaweedfs_attribute(server)
    url = "http://" <> server <> ":8888" <> "/#{camera.exid}/snapshots/recordings/"
    year_values =
      Enum.map(years, fn year ->
        final_url = url <> year <> "/"
        %{
          "#{year}" => request_from_seaweedfs(final_url, type, attribute)
        }
      end)
    %{
      "#{server}" => year_values
    }
  end)

This is how I am getting year values and making them to the server object. If there is a possibility to break it down while even getting year values?

"#{year}" => request_from_seaweedfs(final_url, type, attribute) this request basically returns such as "2015"  => ["1", "2", "3"], is there any possiblity to merge years a head before going to into servers?

Body:
You need to get to the flat list of maps and then merge all of them.

input
|> Enum.flat_map(&Map.values/1)
|> Enum.flat_map(& &1)
|> Enum.reduce(&Map.merge(&1, &2, fn _, v1, v2 ->
  v1 ++ v2
end))
#⇒ %{
#    "2015" => ["4"],
#    "2016" => [],
#    "2017" => ["9"],
#    "2018" => ["5", "8"],
#    "2019" => ["05"]
# }

To get a list of maps (which is IMHO the wrong design decision,) just do:

for {k, v} <- map, do: %{k => v}
#⇒ [
#    %{"2015" => ["4"]},
#    %{"2016" => []},
#    %{"2017" => ["9"]},
#    %{"2018" => ["5", "8"]},
#    %{"2019" => ["05"]}
# ]


问:
update view_count col in database, laravel, vue js
I am trying to update view_count column on every @click. but couldn't figure out the right way of it.

First made the controller --resources and fetch datas via api.

controller:

```<code>public function index()
{
    $articles = Article::all();

    return response()->json([
        "articles" => $articles
    ], 200);
}

public function show($id)
{
    $article = Article::whereId($id)->first();

    return response()->json([
        "article" => $article
    ], 200);
}
</code>```

also set the update function too.

```<code>public function update(Request $request, $id)
{
    $view = Article::find($id);
    $view->update($request->where("view_count"));
    return response()->json(["message" => "view_count updated"]);
}
</code>```

I set the api routes:

```<code>Route::get('/articles', 'ArticlesController@index');
Route::get('/articles/{id}', 'ArticlesController@show');
Route::get('/articles/{id}', 'ArticlesController@update');
</code>```

And finally in Vue.js

```<code><p class="button">
   <i @click.prevent="count" class="fas fa-chevron-right"></i>
</p>

data(){
    return {
        view: 0,
    };
},
methods: {
    count: function(){
        axios.post("/api/articles" + this.item.id).then(response => {
            this.view++;
        })
        window.location.href = "pages/" + this.item.id

    }
}
</code>```

it's counting but not update the col. also, when I refresh the page of course it will start to count from 0... it's not really efficient way to it. what is the best and right way to do it?

Thank you.

Not: By the way I am fetching and iterating api in the parent component:

```<code><div class="listWrap" :key="item.id" v-for="item in filterArticles">
   <list :item="item" />
</div>
</code>```

答:
your workflow to update views is wrong.

first, we should change our uri method of the update method to GET like below :

```<code>Route::get('/articles/update/{id}', 'ArticlesController@update');
</code>```

then, our update method within ArticlesController to increment view_count value:

```<code>public function update(int $id)
{
   // i have changed the $view by $article
    $article = Article::find($id);
    $article->view_count++;
    $article->save();
    return response()->json(["message" => "view_count updated", 201]);
}
</code>```

and within our Vue component, we should update the URI of the update method and the HTTP method name because we should use the same HTTP verb in both client and server sides.

```<code>    <p class="button">
       <i @click.prevent="count" class="fas fa-chevron-right"></i>
    </p>

    <script>
    export default {
// as you are using parent/child relationship betwen components, you should use props.
        props: { item: Object },
        data(){
            return {
                view: 0,
            };
        },
        methods: {
            count: function(){
                axios.get(`/api/articles/update/${this.item.id}`).then(response => {
                    this.view++;
                })
                window.location.href = "pages/" + this.item.id;
            }
        }
    }
    </script>
</code>```

Body:
I am trying to update view_count column on every @click. but couldn't figure out the right way of it.

First made the controller --resources and fetch datas via api.

controller:

public function index()
{
    $articles = Article::all();

    return response()->json([
        "articles" => $articles
    ], 200);
}

public function show($id)
{
    $article = Article::whereId($id)->first();

    return response()->json([
        "article" => $article
    ], 200);
}

also set the update function too.

public function update(Request $request, $id)
{
    $view = Article::find($id);
    $view->update($request->where("view_count"));
    return response()->json(["message" => "view_count updated"]);
}

I set the api routes:

Route::get('/articles', 'ArticlesController@index');
Route::get('/articles/{id}', 'ArticlesController@show');
Route::get('/articles/{id}', 'ArticlesController@update');

And finally in Vue.js

data(){
    return {
        view: 0,
    };
},
methods: {
    count: function(){
        axios.post("/api/articles" + this.item.id).then(response => {
            this.view++;
        })
        window.location.href = "pages/" + this.item.id

    }
}

it's counting but not update the col. also, when I refresh the page of course it will start to count from 0... it's not really efficient way to it. what is the best and right way to do it?

Thank you.

Not: By the way I am fetching and iterating api in the parent component:

   <list :item="item" />

Body:
your workflow to update views is wrong.

first, we should change our uri method of the update method to GET like below :

Route::get('/articles/update/{id}', 'ArticlesController@update');

then, our update method within ArticlesController to increment view_count value:

public function update(int $id)
{
   // i have changed the $view by $article
    $article = Article::find($id);
    $article->view_count++;
    $article->save();
    return response()->json(["message" => "view_count updated", 201]);
}

and within our Vue component, we should update the URI of the update method and the HTTP method name because we should use the same HTTP verb in both client and server sides.

    <p class="button">
       <i @click.prevent="count" class="fas fa-chevron-right"></i>
    </p>

    <script>
    export default {
// as you are using parent/child relationship betwen components, you should use props.
        props: { item: Object },
        data(){
            return {
                view: 0,
            };
        },
        methods: {
            count: function(){
                axios.get(`/api/articles/update/${this.item.id}`).then(response => {
                    this.view++;
                })
                window.location.href = "pages/" + this.item.id;
            }
        }
    }
    </script>


问:
How can you run a python function stored in a different file
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

```<code>main.py
map.py
Scripts/
  script1.py
</code>```

map.py contains just an array and a function to get the correct array index:

```<code>map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]
</code>```

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

```<code>selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.
</code>```

Any suggestions?

答:
In your Scripts/ directory, add a blank file called __init__.py

Then in your map.py file, do this:

```<code>from Scripts import script1

map = {"One" : script1.function_one, "Two" : script1.function_two]

def return_mapping(str):
    return map[str]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

main.py
map.py
Scripts/
  script1.py

map.py contains just an array and a function to get the correct array index:

map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.

Any suggestions?

Body:
In your Scripts/ directory, add a blank file called __init__.py

Then in your map.py file, do this:

from Scripts import script1

map = {"One" : script1.function_one, "Two" : script1.function_two]

def return_mapping(str):
    return map[str]


问:
Using Flexbox to Display Content Not Working HTML CSS
I have a flexbox with an image and text. Currently, I'm using margins and padding, but would it be better with justify content and align content?

Currently, what I'm doing isn't working correctly, I can't seem to get the images to line up with their text. Is there a way for me to put the text and image inline with each other.

Website:

/*flexbox*/
section {
    display: flex;
    flex-flow: wrap;
    width: 80%;

    margin: 1em auto;
    padding: 1em;

    border: solid .125em #00aaff;
    background-color: white;
    opacity:0.9;
}

section > * {
    flex: 1 1 40%;
    padding: 1em;
}

/*Images*/
figure img {
    width:50%;
    margin-left:5em;
}

/*Text*/
p{
    padding: 1em;
    margin-left:-3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="display">
        <figure id="image1">
            <img src="images/512x512.png" alt="Dynamo">
        </figure>

        <article>
                <p><span id="name">Houston Dynamo</span></p>
                <p>Sport Science/Sport Performance Intern</p>
                <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
        </article>

        <figure>
            <img src="images/UW-Logo.png" alt="UIC">
        </figure>

         <article>
                <p><span id="name">University of Madison Wisconsin-Madison</span></p>
                <p>Strength and Conditioning Coach, Graduate Assistant</p>
                <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
        </article></code>```

答:
Check this out too, I just removed margins that's causing the image / figure to go down that's why its not in same level as the article

/*flexbox*/
section {
    display: flex;
    flex-flow: wrap;
    width: 80%;
    margin: 1em auto;
    padding: 1em;
    border: solid .125em #00aaff;
    background-color: white;
    opacity:0.9;
}

section > * {
  margin-top:0;
    margin-bottom:0;
    flex: 1 1 40%;
    padding: 1em;
     border:2px solid black;
}
article{
  padding-left:20px;
}
figure,article{
  margin: 10px;
}
/*Images*/
figure img {
    width:100%;
}
/*Text*/
p{
    padding: 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="display">
        <figure id="image1">
            <img src="https://picsum.photos/200" alt="Dynamo">
        </figure>

        <article>
                <p><span id="name">Houston Dynamo</span></p>
                <p>Sport Science/Sport Performance Intern</p>
                <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
        </article>

        <figure>
            <img src="https://picsum.photos/201" alt="UIC">
        </figure>

         <article>
                <p><span id="name">University of Madison Wisconsin-Madison</span></p>
                <p>Strength and Conditioning Coach, Graduate Assistant</p>
                <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
        </article>
        </section></code>```

You may want to see this in full view. just hoping this help.

Body:
I have a flexbox with an image and text. Currently, I'm using margins and padding, but would it be better with justify content and align content?

Currently, what I'm doing isn't working correctly, I can't seem to get the images to line up with their text. Is there a way for me to put the text and image inline with each other.

Website:

/*flexbox*/
section {
    display: flex;
    flex-flow: wrap;
    width: 80%;

    margin: 1em auto;
    padding: 1em;

    border: solid .125em #00aaff;
    background-color: white;
    opacity:0.9;
}

section > * {
    flex: 1 1 40%;
    padding: 1em;
}

/*Images*/
figure img {
    width:50%;
    margin-left:5em;
}

/*Text*/
p{
    padding: 1em;
    margin-left:-3em;
}

Houston Dynamo

Sport Science/Sport Performance Intern

<time datetime="2018-01-01"></time>January 2019 - Present

University of Madison Wisconsin-Madison

Strength and Conditioning Coach, Graduate Assistant

<time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time>

Body:
Check this out too, I just removed margins that's causing the image / figure to go down that's why its not in same level as the article

/*flexbox*/
section {
    display: flex;
    flex-flow: wrap;
    width: 80%;
    margin: 1em auto;
    padding: 1em;
    border: solid .125em #00aaff;
    background-color: white;
    opacity:0.9;
}

section > * {
  margin-top:0;
    margin-bottom:0;
    flex: 1 1 40%;
    padding: 1em;
     border:2px solid black;
}
article{
  padding-left:20px;
}
figure,article{
  margin: 10px;
}
/*Images*/
figure img {
    width:100%;
}
/*Text*/
p{
    padding: 1em;
}

<section id="display">
        <figure id="image1">
            <img src="https://picsum.photos/200" alt="Dynamo">
        </figure>

        <article>
                <p><span id="name">Houston Dynamo</span></p>
                <p>Sport Science/Sport Performance Intern</p>
                <p><time datetime="2018-01-01"></time>January 2019 - Present</p>
        </article>

        <figure>
            <img src="https://picsum.photos/201" alt="UIC">
        </figure>

         <article>
                <p><span id="name">University of Madison Wisconsin-Madison</span></p>
                <p>Strength and Conditioning Coach, Graduate Assistant</p>
                <p><time datetime="2011-08-01"></time>August 2018 - <time datetime="2014-12-31">December 2018</time></p>
        </article>
        </section>

You may want to see this in full view. just hoping this help.


答:
In this command:

```<code>$ cat file.json | jq .document.page[].row | ["#text", "@x", "@y"] | @csv
</code>```

Everything after the jq is supposed to be the first argument to jq, which means you need to enclose it in quotation marks.  Moreover, cat file.json | is here a Useless Use of Cat; just pass the filename as an argument to jq.  Hence, the correct command is:

```<code>$ jq '.document.page[].row | ["#text", "@x", "@y"] | @csv' file.json
</code>```

Title: Parsing Json file with jq tool

Body:
I Have the following nested json file which I want to parse with jq tool and print in table form like I show at the end

The input.json structure is like this:

{
 "document":{
  "page":[
     {
        "@index":"0",
        "image":{
           "@data":"ABC",
           "@format":"png",
           "@height":"620.00",
           "@type":"base64encoded",
           "@width":"450.00",
           "@x":"85.00",
           "@y":"85.00"
        }
     },
     {
        "@index":"1",
        "row":[
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text1",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"71.04",
                       "@x":"121.10",
                       "@y":"83.42"
                    }
                 }
              ]
           },
           {
              "column":[
                 {
                    "text":""
                 },
                 {
                    "text":{
                       "#text":"Text2",
                       "@fontName":"Arial",
                       "@fontSize":"12.0",
                       "@height":"12.00",
                       "@width":"101.07",
                       "@x":"121.10",
                       "@y":"124.82"
                    }
                 }
              ]
           }
        ]
     },
     {
        "@index":"2",
        "row":[
           {
              "column":{
                 "text":{
                    "#text":"Text3",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"363.44",
                    "@x":"85.10",
                    "@y":"69.62"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text4",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"382.36",
                    "@x":"85.10",
                    "@y":"83.42"
                 }
              }
           },
           {
              "column":{
                 "text":{
                    "#text":"Text5",
                    "@fontName":"Arial",
                    "@fontSize":"12.0",
                    "@height":"12.00",
                    "@width":"435.05",
                    "@x":"85.10",
                    "@y":"97.22"
                 }
              }
           }
        ]
     },
     {
        "@index":"3"
     }
  ]
 }
}

Following the answers of the following question (Parsing nested json with jq) I've tried this code but doesn't work

$ cat file.json | jq .document.page[].row | ["#text", "@x", "@y"] | @csv

The output I'm trying to get is:

#text @x     @y
Text1 121.10 83.42
Text2 121.10 124.82
Text3 65.10  69.62
Text4 85.10  83.42
Text5 85.10  97.22

How can achieve this?

Thanks

UPDATE

Thanks so much for the help. I've tried with a real file a bit longer.

I was able to adapt the first peak's solution like below:

["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"],
( ..
| objects
| select(has("#text","@data"))
| [.["#text", "@data", "@fontName", "@fontSize", "@format", "@height", "@type", "@width", "@x", "@y"]]
)
| @tsv

and with new input I get this table:

+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| #text         | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
|               | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ä 1      |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text ¢76      |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text % 5      |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 7Ç8      |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text • 2 Wñ79 |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text          |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
|   » 1 A\\\\CÓ |       |           |           |         |         |               |        |        |        |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 12       |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 82       |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| Text 31       |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+---------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

If possible, how to add the follwing 3 columns (counter, page and row) to know the corresponding page and row for each line?

The expected output would be like this:

+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| counter | page | row | #text             | @data | @fontName | @fontSize | @format | @height | @type         | @width | @x     | @y     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 1     | 0    |     |                   | ABC   |           |           | png     | 620     | base64encoded | 450    | 85     | 85     |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 2     | 1    | 0   | Text ä 1          |       | Tahoma    | 12        |         | 12      |               | 427.79 | 85.1   | 69.62  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 3     | 1    | 1   | Text ¢76          |       | Tahoma    | 12        |         | 12      |               | 270.5  | 85.1   | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 4     | 1    | 1   | Text % 5          |       | Tahoma    | 12        |         | 12      |               | 130.84 | 358.86 | 690.72 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 5     | 2    | 2   | Text 7Ç8          |       | Tahoma    | 12        |         | 12      |               | 115.95 | 85.1   | 704.52 |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 6     | 2    | 0   | Text • 2 Wñ79     |       | Tahoma    | 8         |         | 8.04    |               | 398.16 | 121.1  | 68.06  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 7     | 2    | 1   | Text  » 1 A\\\\CÓ |       | Tahoma    | 12        |         | 12      |               | 101.5  | 85.1   | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 8     | 2    | 1   | Text 12           |       | Tahoma    | 12        |         | 12      |               | 312.26 | 189.83 | 83.42  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 9     | 2    | 2   | Text 82           |       | Tahoma    | 12        |         | 12      |               | 44.99  | 85.1   | 97.22  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+
| 10    | 2    | 2   | Text 31           |       | Tahoma    | 8         |         | 8.04    |               | 381.83 | 133.1  | 95.66  |
+-------+------+-----+-------------------+-------+-----------+-----------+---------+---------+---------------+--------+--------+--------+

This is new more representative input file input2.json.

And seeing the Json structure in image below gives and idea about page number and row number present in json file and values within them.

Body:
In this command:

$ cat file.json | jq .document.page[].row | ["#text", "@x", "@y"] | @csv

Everything after the jq is supposed to be the first argument to jq, which means you need to enclose it in quotation marks.  Moreover, cat file.json | is here a Useless Use of Cat; just pass the filename as an argument to jq.  Hence, the correct command is:

$ jq '.document.page[].row | ["#text", "@x", "@y"] | @csv' file.json


问:
What to put in package.json types field for typescript based libs
I'm a bit confused as to how best develop multiple typescript modules in parallel with code navigation and still publishing the right way. So what should I really put in package.json "types" field?

According to: Typescriptlang.org/publishing.html

I should put a reference to my generated index.d.ts like so:

```<code>{
    "name": "awesome",
    "author": "Vandelay Industries",
    "version": "1.0.0",
    "main": "./lib/main.js",
    "types": "./lib/main.d.ts"
}
</code>```

If I then develop a module in parallel that depends on this one with npm link, code navigation in for example vscode makes me just jump into this definitions file. Which is not what I want.

I want to go into the source file to be able to edit in the dep in parallel. No tsconfig setting with sourcemaps, inlined or not have helped in this regard. I might be missing something here. The only way I've managed my work flow to work decently is to actually point to the source main.ts file instead:

```<code>{
    "name": "awesome",
    "author": "Vandelay Industries",
    "version": "1.0.0",
    "main": "./lib/main.js",
    "types": "./src/main.ts"
}
</code>```

That however would make thing break when published right ?

At least if I put src under .npmignore. I'm failing to understand the best way to have a nice workflow with multiple typescript modules.

I mean, I wouldn't want to have to mangle package.json as part of release process…?

答:
TypeScript Project References

As far as I can tell, TypeScript Project References will fill your requirements:

VS Code navigation goes to the *.ts source file not to the *.d.ts file.

The package.json types value references the *.d.ts file.

That provides developer tooling without changing how/what you publish.

Demo

I created a simple demo project in GitHub. Here are the high-points of how to set up project references with code navigation.

package01

The tsconfig.json allows another TypeScript project to reference it (composite) and for code navigation to work (declarationMap). In the package.json, the NPM scope (@shaunluttin) is not entirely necessary; I included it to avoid naming collisions.

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "composite": true,
    "declarationMap": true
  }
}
</code>```

package.json

```<code>{
  "name": "@shaunluttin/package01",
  "version": "1.0.0",
  "main": "index.js",
  "types": "index.d.ts"
}
</code>```

package02

The tsconfig.json references package01. That's what sets up the tooling. The package.json depends on package01 in the same way it normally would.

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es5"
  },
  "references": [
    {
      "path": "../package01"
    }
  ]
}
</code>```

package.json

```<code>{
  "name": "@shaunluttin/package02",
  "version": "1.0.0",
  "main": "index.js",
  "types": "index.d.ts",
  "dependencies": {
    "@shaunluttin/package01": "1.0.0"
  }
}
</code>```

NPM Link

For local development, the two packages are connected with npm link.

```<code>cd package01
npm link

cd ../package01
npm link @shaunluttin/package01
</code>```

Final Thoughts

The documentation mentions a handful of caveats that are too involved to list in this answer.

Body:
I'm a bit confused as to how best develop multiple typescript modules in parallel with code navigation and still publishing the right way. So what should I really put in package.json "types" field?

According to: Typescriptlang.org/publishing.html

I should put a reference to my generated index.d.ts like so:

{
    "name": "awesome",
    "author": "Vandelay Industries",
    "version": "1.0.0",
    "main": "./lib/main.js",
    "types": "./lib/main.d.ts"
}

If I then develop a module in parallel that depends on this one with npm link, code navigation in for example vscode makes me just jump into this definitions file. Which is not what I want.

I want to go into the source file to be able to edit in the dep in parallel. No tsconfig setting with sourcemaps, inlined or not have helped in this regard. I might be missing something here. The only way I've managed my work flow to work decently is to actually point to the source main.ts file instead:

{
    "name": "awesome",
    "author": "Vandelay Industries",
    "version": "1.0.0",
    "main": "./lib/main.js",
    "types": "./src/main.ts"
}

That however would make thing break when published right ?

At least if I put src under .npmignore. I'm failing to understand the best way to have a nice workflow with multiple typescript modules.

I mean, I wouldn't want to have to mangle package.json as part of release process…?

Body:
TypeScript Project References

As far as I can tell, TypeScript Project References will fill your requirements:

VS Code navigation goes to the *.ts source file not to the *.d.ts file.

The package.json types value references the *.d.ts file.

That provides developer tooling without changing how/what you publish.

Demo

I created a simple demo project in GitHub. Here are the high-points of how to set up project references with code navigation.

package01

The tsconfig.json allows another TypeScript project to reference it (composite) and for code navigation to work (declarationMap). In the package.json, the NPM scope (@shaunluttin) is not entirely necessary; I included it to avoid naming collisions.

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "composite": true,
    "declarationMap": true
  }
}

package.json

{
  "name": "@shaunluttin/package01",
  "version": "1.0.0",
  "main": "index.js",
  "types": "index.d.ts"
}

package02

The tsconfig.json references package01. That's what sets up the tooling. The package.json depends on package01 in the same way it normally would.

tsconfig.json

{
  "compilerOptions": {
    "target": "es5"
  },
  "references": [
    {
      "path": "../package01"
    }
  ]
}

package.json

{
  "name": "@shaunluttin/package02",
  "version": "1.0.0",
  "main": "index.js",
  "types": "index.d.ts",
  "dependencies": {
    "@shaunluttin/package01": "1.0.0"
  }
}

NPM Link

For local development, the two packages are connected with npm link.

cd package01
npm link

cd ../package01
npm link @shaunluttin/package01

Final Thoughts

The documentation mentions a handful of caveats that are too involved to list in this answer.


问:
can I change the result language of Google Places API for iOS?
I am using Google Places Api for iOS(GMSAutocompleteFilter) to search nearby places,

if I set English(US) as my system language, it will return Traditional Chinese results(which is acceptable since I am in taiwan).

but if I set Traditional Chinese as my system language, the api will return simplified Chinese results(what is the logic behind?)

How can I change the language of api search results?

```<code>- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
// filter.type = kGMSPlacesAutocompleteTypeFilterCity;

[placesClient autocompleteQuery:searchText
                         bounds:nil
                         filter:filter
                       callback:^(NSArray *results, NSError *error) {
                           if (error != nil) {
                               NSLog(@"Autocomplete error %@", [error localizedDescription]);
                               return;
                           }

                           self.placeResults = results;
                           [self.resultsList reloadData];

                           for (GMSAutocompletePrediction* result in results) {
                               NSLog(@"Result '%@' with placeID %@", result.attributedFullText.string, result.placeID);
                           }
                       }];
</code>```

答:
I've found a workaround for this issue.

Since Google Place iOS SDK doesn't allow us to specify the language used (which is very weird indeed), we'll have to look up a place with the Google Place API (Web-based).

Install the swift wrapper API for the Google Place API

https://github.com/honghaoz/Swift-Google-Maps-API

When you get the place with its placeID, use it to look up in the language you want.

The following is the code snippet from my GMSAutocompleteResultsViewControllerDelegate

```<code>func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                       didAutocompleteWith place: GMSPlace) {

    Log.debug("Place name: \(String(describing: place.name))")
    Log.debug("Place address: \(String(describing: place.formattedAddress))")
    Log.debug("Place attributions: \(String(describing: place.attributions))")

    guard let placeID = place.placeID else {
        return
    }

    /// Use Google Place API to lookup place information in English
    /// https://developers.google.com/places/web-service/intro
    GooglePlacesAPI.GooglePlaces.placeDetails(forPlaceID: placeID, language: "en") { (response, error) -> Void in

        guard let place = response?.result, response?.status == GooglePlaces.StatusCode.ok else {
            Log.debug("Error = \(String(describing: response?.errorMessage))")
            return
        }

        let postalCode = place.addressComponents.filter({ (components) -> Bool in
            return components.types.contains(kGMSPlaceTypePostalCode)
        }).first?.longName

        /// Save Selection
        let location = Location(name: place.name ?? MessageSource.getString("landmark.unknown_loc"), addr: place.formattedAddress, postal: postalCode)

        self.currentLocation = location

        self.searchController?.isActive = false

        ///Set text in search bar
        self.searchController?.searchBar.text = place.name

    }
}
</code>```

Body:
I am using Google Places Api for iOS(GMSAutocompleteFilter) to search nearby places,

if I set English(US) as my system language, it will return Traditional Chinese results(which is acceptable since I am in taiwan).

but if I set Traditional Chinese as my system language, the api will return simplified Chinese results(what is the logic behind?)

How can I change the language of api search results?

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
// filter.type = kGMSPlacesAutocompleteTypeFilterCity;

[placesClient autocompleteQuery:searchText
                         bounds:nil
                         filter:filter
                       callback:^(NSArray *results, NSError *error) {
                           if (error != nil) {
                               NSLog(@"Autocomplete error %@", [error localizedDescription]);
                               return;
                           }

                           self.placeResults = results;
                           [self.resultsList reloadData];

                           for (GMSAutocompletePrediction* result in results) {
                               NSLog(@"Result '%@' with placeID %@", result.attributedFullText.string, result.placeID);
                           }
                       }];

Body:
I've found a workaround for this issue.

Since Google Place iOS SDK doesn't allow us to specify the language used (which is very weird indeed), we'll have to look up a place with the Google Place API (Web-based).

Install the swift wrapper API for the Google Place API

https://github.com/honghaoz/Swift-Google-Maps-API

When you get the place with its placeID, use it to look up in the language you want.

The following is the code snippet from my GMSAutocompleteResultsViewControllerDelegate

func resultsController(_ resultsController: GMSAutocompleteResultsViewController,
                       didAutocompleteWith place: GMSPlace) {

    Log.debug("Place name: \(String(describing: place.name))")
    Log.debug("Place address: \(String(describing: place.formattedAddress))")
    Log.debug("Place attributions: \(String(describing: place.attributions))")

    guard let placeID = place.placeID else {
        return
    }

    /// Use Google Place API to lookup place information in English
    /// https://developers.google.com/places/web-service/intro
    GooglePlacesAPI.GooglePlaces.placeDetails(forPlaceID: placeID, language: "en") { (response, error) -> Void in

        guard let place = response?.result, response?.status == GooglePlaces.StatusCode.ok else {
            Log.debug("Error = \(String(describing: response?.errorMessage))")
            return
        }

        let postalCode = place.addressComponents.filter({ (components) -> Bool in
            return components.types.contains(kGMSPlaceTypePostalCode)
        }).first?.longName

        /// Save Selection
        let location = Location(name: place.name ?? MessageSource.getString("landmark.unknown_loc"), addr: place.formattedAddress, postal: postalCode)

        self.currentLocation = location

        self.searchController?.isActive = false

        ///Set text in search bar
        self.searchController?.searchBar.text = place.name

    }
}


问:
Delete all files from an array, including some with *
I have an array that has a list of various files/folders to delete, including deleting all files in a folder.

```<code>server_dir="/srv/data/"
removeLocalFiles=("logs/*.log.gz" "plugins/file.txt" "other.txt")
for serverFile in "${removeLocalFiles[@]}"; do
    rm "$server_dir/$serverFile"
done
</code>```

The array would be files, folders, and as you can see, files with a specific extension.

This doesn't work, the files with * doesn't delete.

What can I use to delete all files, in a specific directory? The list would go exactly to that file or folder, so it shouldn't delete anything other then that specific file./

答:
You can add this to your line to test if the directory not empty.If string is not empty rm will work just fine.[ ! -z "$(ls -A $server_dir/$serverFile")" ] && rm
"$server_dir/$serverFile"

Body:
I have an array that has a list of various files/folders to delete, including deleting all files in a folder.

server_dir="/srv/data/"
removeLocalFiles=("logs/*.log.gz" "plugins/file.txt" "other.txt")
for serverFile in "${removeLocalFiles[@]}"; do
    rm "$server_dir/$serverFile"
done

The array would be files, folders, and as you can see, files with a specific extension.

This doesn't work, the files with * doesn't delete.

What can I use to delete all files, in a specific directory? The list would go exactly to that file or folder, so it shouldn't delete anything other then that specific file./


问:
JQuery to swap input and select-box data between two or more forms
I'm basically trying to create a 'directions' form with each 'stop' having an address input and a couple of select-box options. I want to be able to 'swap' the forms so that the data from the first 'stop' is swapped with the data from the second 'stop'. The tricky part is that there could be more than two 'stops', so the swap would need to be able to handle swapping stops 3-4, 4-5, 5-6, etc.

Here is the basic form template:

```<code><div class="forms">
<div class="address"><input type="text" /></div>
<div class="loc">
    <select name="region">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>
</div>
<div class="loc">
    <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
        <option>d</option>
        <option>e</option>
    </select>
</div>
</div>
<div class="swap"><a>swap</a></div>
<div class="forms">
<div class="address"><input type="text" /></div>
<div class="loc">
    <select name="region">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>
</div>
<div class="loc">
    <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
        <option>d</option>
        <option>e</option>
    </select>
</div>
</code>```

I would like to use JQuery if possible, but am really stumped on how to get started.

Thanks,
Brian

答:
In general in jQuery you can just set the value of an input using .val() and it'll figure it out depending on its form type (drop down, text input, textarea, etc).

Taking that into consideration along with your requirements for only swapping neighboring values, you can do something simply like this:

```<code>$('.swap a').click(function() {
    //Swaps previous and next address values
    var prevAddress = $(this).parent().prev('.forms').find('.address input');
    var nextAddress = $(this).parent().next('.forms').find('.address input');
    var tmp = prevAddress.val();
    prevAddress.val(nextAddress.val());
    nextAddress.val(tmp);
});
</code>```

Here I've only done the address field, but it should be about the same for any of them.

The proof is in the fiddle.

Body:
I'm basically trying to create a 'directions' form with each 'stop' having an address input and a couple of select-box options. I want to be able to 'swap' the forms so that the data from the first 'stop' is swapped with the data from the second 'stop'. The tricky part is that there could be more than two 'stops', so the swap would need to be able to handle swapping stops 3-4, 4-5, 5-6, etc.

Here is the basic form template:

<input type="text" />

    <select name="region">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>

    <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
        <option>d</option>
        <option>e</option>
    </select>

swap

<input type="text" />

    <select name="region">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
    </select>

    <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
        <option>d</option>
        <option>e</option>
    </select>

I would like to use JQuery if possible, but am really stumped on how to get started.

Thanks,
Brian

Body:
In general in jQuery you can just set the value of an input using .val() and it'll figure it out depending on its form type (drop down, text input, textarea, etc).

Taking that into consideration along with your requirements for only swapping neighboring values, you can do something simply like this:

$('.swap a').click(function() {
    //Swaps previous and next address values
    var prevAddress = $(this).parent().prev('.forms').find('.address input');
    var nextAddress = $(this).parent().next('.forms').find('.address input');
    var tmp = prevAddress.val();
    prevAddress.val(nextAddress.val());
    nextAddress.val(tmp);
});

Here I've only done the address field, but it should be about the same for any of them.

The proof is in the fiddle.


问:
Reshape the data from long to wide format
I am looking for swift way of reshaping the data from long to wide format. Right now I have tried a code with nest for loops, though the job gets done, it takes a long time to generate the output.

```<code>SN NN EE Service_tier
A  B  C  economy
B  C  C  economy
P  Q  R  regular
Q  S  R  regular
S  R  R  regular
H  I  L  economy
I  J  L  economy
J  K  L  economy
K  L  L  economy
</code>```

The output expected is as below

```<code>SN hop1 hop2 hop3 hop4 service_tier
A   B    C              economy
P   Q    S    R         regular
H   I    J    K    L    economy
</code>```

currently the below code gets the job done. Am sure there is an effective and clean way to do this.

```<code>for (i in 1:lasrow){
  sn <- raw_d[i,1]
  nn <- raw_d[i,2]
  en <- raw_d[i,3]

  lc <- 1

  if(nn == en){
    d[lr,lc]<-sn
    d[lr,lc+1]<-nn
    d[lr,lc+2]<-en
    lr <- lr+1
  }
  else{
    while(nn!=en){
      d[lr,lc]<-sn
      lc <- lc+1
      next_d <- filter(raw_d,raw_d$SN==sn,raw_d$EN==en)
      if(dim(next_d)[1]==0){
        d[lr,lc]<-"broken bf"
        lc <- lc+1
        break
      }else{
        sn <- next_d$NN
        nn <- next_d$NN
        }
      }
    d[lr,lc]<-en
    lr<-lr+1
  }
}
</code>```

答:
One option is to create a unique sequence using rleid from data.table, gather the dataframe to long format, remove the duplicates from each group, assign column names and spread it back to wide format.

```<code>library(dplyr)
library(tidyr)

df %>%
  mutate(row = data.table::rleid(Service_tier)) %>%
  gather(key, value, -Service_tier, -row) %>%
  group_by(row) %>%
  filter(!duplicated(value)) %>%
  mutate(key = c("SN", paste0("hop", 1:(n() - 1)))) %>%
  spread(key, value) %>%
  ungroup() %>%
  select(-row) %>%
  select(SN, starts_with("hop"), Service_tier)

# A tibble: 3 x 6
#  SN    hop1  hop2  hop3  hop4  Service_tier
#  <chr> <chr> <chr> <chr> <chr> <fct>
#1  A     B     C     NA    NA    economy
#2  H     I     J     K     L     economy
#3  P     Q     S     R     NA    regular
</code>```

Body:
I am looking for swift way of reshaping the data from long to wide format. Right now I have tried a code with nest for loops, though the job gets done, it takes a long time to generate the output.

SN NN EE Service_tier
A  B  C  economy
B  C  C  economy
P  Q  R  regular
Q  S  R  regular
S  R  R  regular
H  I  L  economy
I  J  L  economy
J  K  L  economy
K  L  L  economy

The output expected is as below

SN hop1 hop2 hop3 hop4 service_tier
A   B    C              economy
P   Q    S    R         regular
H   I    J    K    L    economy

currently the below code gets the job done. Am sure there is an effective and clean way to do this.

for (i in 1:lasrow){
  sn <- raw_d[i,1]
  nn <- raw_d[i,2]
  en <- raw_d[i,3]

  lc <- 1

  if(nn == en){
    d[lr,lc]<-sn
    d[lr,lc+1]<-nn
    d[lr,lc+2]<-en
    lr <- lr+1
  }
  else{
    while(nn!=en){
      d[lr,lc]<-sn
      lc <- lc+1
      next_d <- filter(raw_d,raw_d$SN==sn,raw_d$EN==en)
      if(dim(next_d)[1]==0){
        d[lr,lc]<-"broken bf"
        lc <- lc+1
        break
      }else{
        sn <- next_d$NN
        nn <- next_d$NN
        }
      }
    d[lr,lc]<-en
    lr<-lr+1
  }
}

Body:
One option is to create a unique sequence using rleid from data.table, gather the dataframe to long format, remove the duplicates from each group, assign column names and spread it back to wide format.

library(dplyr)
library(tidyr)

df %>%
  mutate(row = data.table::rleid(Service_tier)) %>%
  gather(key, value, -Service_tier, -row) %>%
  group_by(row) %>%
  filter(!duplicated(value)) %>%
  mutate(key = c("SN", paste0("hop", 1:(n() - 1)))) %>%
  spread(key, value) %>%
  ungroup() %>%
  select(-row) %>%
  select(SN, starts_with("hop"), Service_tier)

# A tibble: 3 x 6
#  SN    hop1  hop2  hop3  hop4  Service_tier
#  <chr> <chr> <chr> <chr> <chr> <fct>
#1  A     B     C     NA    NA    economy
#2  H     I     J     K     L     economy
#3  P     Q     S     R     NA    regular


问:
Passive variable in JavaScript for a pet is not working correctly
So I have a pet tied to a radio button. When you change radio buttons the passive should go away. I have it where exp stops increasing but my strength value won't go back down to the default (strength is number under radio button)

Default is 2 for strength so when the radio button is on strength is 2 + turtlestrength, I need it to go back down to 2 when you change buttons.

I've tried to mess around with if statements / settimeout but nothing seems to be working.

I expect on level up for Turtlestrength to go up by 1 in value and on radio button change for the passive addition to strength to be taken away( for it to go back down to 2 in this case).  But the actual result on the button changes the value of strength stays combined with Turtlestrength and when I click back on the button it adds Turtlestrength to strength. This 2nd part should be an easy fix if strength just gets updated correctly on button change. Also on level up, Turtlestrength is not updating to be 1 higher ( for example at lv 1 I had 3 total strength passively but when I level It should go up to 4 but it stays at 3.

var Turtle = 1;
var Turtlelv = 1;
var TurtleCexp = 0;
var TurtleMexp = 100;
var NextMaxTurtleExp = TurtleMexp;
var Turtlestrength = 1;
var Strength = 2;

function turtleandstrength (){
  if (document.getElementById("turtle-radio").checked) {
    Strength = Strength + Turtlestrength
    document.getElementById("Strength").innerHTML = Strength;
  } else {
    Strength = Strength - Turtlestrength
    document.getElementById("Strength").innerHTML = Strength;
  }
}

function turtleXpUp() {
  if (document.getElementById("turtle-radio").checked && TurtleCexp <
    TurtleMexp) {
    setTimeout(turtleXpUp, 200)
    TurtleCexp = TurtleCexp + 1;
    document.getElementById("TurtleCexp").innerHTML = TurtleCexp;
  }

  if (TurtleCexp >= TurtleMexp) {
    Turtlelv = Turtlelv + 1;
    TurtleCexp = 0;
    Turtle = Turtle + 1;
    Turtlestrength = Turtlestrength + 1;
    NextMaxTurtleExp = NextMaxTurtleExp * 1.5;
  }

  document.getElementById("Strength").innerHTML = Strength;
  document.getElementById('TurtleMexp').innerHTML = NextMaxTurtleExp;
  document.getElementById('Turtlelv').innerHTML = Turtlelv;
  document.getElementById('TurtleCexp').innerHTML = TurtleCexp;
  //document.getElementById('Turtle').innerHTML = Turtle;
}

document.getElementById("turtle-radio").addEventListener("change", turtleXpUp);
document.getElementById("turtle-radio").addEventListener("change", turtleandstrength);
document.getElementById("Strength").innerHTML = Strength;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="control">
    <label class="radio">
        <input type="radio" name="Pets" id="turtle-radio">
    </label>
    <img src="turtle.png" alt="turtle" height="100" width="100">Lv
    <span id="Turtlelv">1</span>
    <span id="TurtleCexp">0</span> /
    <span id="TurtleMexp">100</span>
    <br />
    <span id="Strength">0</span>
    <br />
    <label class="radio">
        <input type="radio" name="Pets" id="dog-radio">
    </label></code>```

答:
This is because the change event doesn't fire on a radio button when it becomes unchecked, only when it is checked. You can add a simple console.log() message at the top of your function to see that the function only runs when the radio button is checked. This means that your else condition where you remove the strength never happens.

You'll have to add a change event to all of the radio buttons and check which one is checked. There are several answers on stackoverflow that cover a similar scenario, but something like this would work:

var turtleRadio = document.getElementById("turtle-radio");
var dogRadio = document.getElementById("dog-radio");
var turtleInterval;

var Turtle = 1;
var Turtlelv = 1;
var TurtleCexp = 0;
var TurtleMexp = 100;
var NextMaxTurtleExp = TurtleMexp;
var Turtlestrength = 1;
var Strength = 2;

// This is an event dispatcher function. Based on the radio
// button that was clicked, run different functions.
function radioChanged(event) {
  if (event.target === turtleRadio) {
    turtleandstrength(true);
    turtleXpUp(true);
    // Run other functions...
  } else if (event.target === dogRadio) {
    turtleandstrength(false);
    turtleXpUp(false);
    // Run other functions...
  }
}

function turtleandstrength(turtleChecked) {
  if (turtleChecked) {
    Strength = Strength + Turtlestrength
    document.getElementById("Strength").innerHTML = Strength;
  } else {
    Strength = Strength - Turtlestrength;
    if (Strength < 2) Strength = 2;
    document.getElementById("Strength").innerHTML = Strength;
  }
}

function turtleXpUp(turtleChecked) {
  clearInterval(turtleInterval);

  if (turtleChecked && TurtleCexp < TurtleMexp) {
    turtleInterval = setInterval(function () { turtleXpUp(turtleChecked); }, 200);
    TurtleCexp = TurtleCexp + 1;
    document.getElementById("TurtleCexp").innerHTML = TurtleCexp;
  }

  if (TurtleCexp >= TurtleMexp) {
    Turtlelv = Turtlelv + 1;
    TurtleCexp = 0;
    Turtle = Turtle + 1;
    Turtlestrength = Turtlestrength + 1;
    Strength = Strength + 1;
    NextMaxTurtleExp = NextMaxTurtleExp * 1.5;
  }

  document.getElementById("Strength").innerHTML = Strength;
  document.getElementById('TurtleMexp').innerHTML = NextMaxTurtleExp;
  document.getElementById('Turtlelv').innerHTML = Turtlelv;
  document.getElementById('TurtleCexp').innerHTML = TurtleCexp;
  //document.getElementById('Turtle').innerHTML = Turtle;
}

//document.getElementById("turtle-radio").addEventListener("change", turtleXpUp);
//document.getElementById("turtle-radio").addEventListener("change", turtleandstrength);
turtleRadio.addEventListener("change", radioChanged);
dogRadio.addEventListener("change", radioChanged);
document.getElementById("Strength").innerHTML = Strength;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="control">
    <label class="radio">
        <input type="radio" name="Pets" id="turtle-radio">
    </label>
    <img src="turtle.png" alt="turtle" height="100" width="100">Lv
    <span id="Turtlelv">1</span>
    <span id="TurtleCexp">0</span> /
    <span id="TurtleMexp">100</span>
    <br />
    <span id="Strength">0</span>
    <br />
    <label class="radio">
        <input type="radio" name="Pets" id="dog-radio">
    </label></code>```

Note I also changed setTimeout to setInterval as that is the functionality you're really looking for.

Body:
So I have a pet tied to a radio button. When you change radio buttons the passive should go away. I have it where exp stops increasing but my strength value won't go back down to the default (strength is number under radio button)

Default is 2 for strength so when the radio button is on strength is 2 + turtlestrength, I need it to go back down to 2 when you change buttons.

I've tried to mess around with if statements / settimeout but nothing seems to be working.

I expect on level up for Turtlestrength to go up by 1 in value and on radio button change for the passive addition to strength to be taken away( for it to go back down to 2 in this case).  But the actual result on the button changes the value of strength stays combined with Turtlestrength and when I click back on the button it adds Turtlestrength to strength. This 2nd part should be an easy fix if strength just gets updated correctly on button change. Also on level up, Turtlestrength is not updating to be 1 higher ( for example at lv 1 I had 3 total strength passively but when I level It should go up to 4 but it stays at 3.

var Turtle = 1;
var Turtlelv = 1;
var TurtleCexp = 0;
var TurtleMexp = 100;
var NextMaxTurtleExp = TurtleMexp;
var Turtlestrength = 1;
var Strength = 2;

function turtleandstrength (){
  if (document.getElementById("turtle-radio").checked) {
    Strength = Strength + Turtlestrength
    document.getElementById("Strength").innerHTML = Strength;
  } else {
    Strength = Strength - Turtlestrength
    document.getElementById("Strength").innerHTML = Strength;
  }
}

function turtleXpUp() {
  if (document.getElementById("turtle-radio").checked && TurtleCexp <
    TurtleMexp) {
    setTimeout(turtleXpUp, 200)
    TurtleCexp = TurtleCexp + 1;
    document.getElementById("TurtleCexp").innerHTML = TurtleCexp;
  }

  if (TurtleCexp >= TurtleMexp) {
    Turtlelv = Turtlelv + 1;
    TurtleCexp = 0;
    Turtle = Turtle + 1;
    Turtlestrength = Turtlestrength + 1;
    NextMaxTurtleExp = NextMaxTurtleExp * 1.5;
  }

  document.getElementById("Strength").innerHTML = Strength;
  document.getElementById('TurtleMexp').innerHTML = NextMaxTurtleExp;
  document.getElementById('Turtlelv').innerHTML = Turtlelv;
  document.getElementById('TurtleCexp').innerHTML = TurtleCexp;
  //document.getElementById('Turtle').innerHTML = Turtle;
}

document.getElementById("turtle-radio").addEventListener("change", turtleXpUp);
document.getElementById("turtle-radio").addEventListener("change", turtleandstrength);
document.getElementById("Strength").innerHTML = Strength;

        <input type="radio" name="Pets" id="turtle-radio">

    Lv
    1
    0 /
    100

    0

        <input type="radio" name="Pets" id="dog-radio">

Body:
This is because the change event doesn't fire on a radio button when it becomes unchecked, only when it is checked. You can add a simple console.log() message at the top of your function to see that the function only runs when the radio button is checked. This means that your else condition where you remove the strength never happens.

You'll have to add a change event to all of the radio buttons and check which one is checked. There are several answers on stackoverflow that cover a similar scenario, but something like this would work:

var turtleRadio = document.getElementById("turtle-radio");
var dogRadio = document.getElementById("dog-radio");
var turtleInterval;

var Turtle = 1;
var Turtlelv = 1;
var TurtleCexp = 0;
var TurtleMexp = 100;
var NextMaxTurtleExp = TurtleMexp;
var Turtlestrength = 1;
var Strength = 2;

// This is an event dispatcher function. Based on the radio
// button that was clicked, run different functions.
function radioChanged(event) {
  if (event.target === turtleRadio) {
    turtleandstrength(true);
    turtleXpUp(true);
    // Run other functions...
  } else if (event.target === dogRadio) {
    turtleandstrength(false);
    turtleXpUp(false);
    // Run other functions...
  }
}

function turtleandstrength(turtleChecked) {
  if (turtleChecked) {
    Strength = Strength + Turtlestrength
    document.getElementById("Strength").innerHTML = Strength;
  } else {
    Strength = Strength - Turtlestrength;
    if (Strength < 2) Strength = 2;
    document.getElementById("Strength").innerHTML = Strength;
  }
}

function turtleXpUp(turtleChecked) {
  clearInterval(turtleInterval);

  if (turtleChecked && TurtleCexp < TurtleMexp) {
    turtleInterval = setInterval(function () { turtleXpUp(turtleChecked); }, 200);
    TurtleCexp = TurtleCexp + 1;
    document.getElementById("TurtleCexp").innerHTML = TurtleCexp;
  }

  if (TurtleCexp >= TurtleMexp) {
    Turtlelv = Turtlelv + 1;
    TurtleCexp = 0;
    Turtle = Turtle + 1;
    Turtlestrength = Turtlestrength + 1;
    Strength = Strength + 1;
    NextMaxTurtleExp = NextMaxTurtleExp * 1.5;
  }

  document.getElementById("Strength").innerHTML = Strength;
  document.getElementById('TurtleMexp').innerHTML = NextMaxTurtleExp;
  document.getElementById('Turtlelv').innerHTML = Turtlelv;
  document.getElementById('TurtleCexp').innerHTML = TurtleCexp;
  //document.getElementById('Turtle').innerHTML = Turtle;
}

//document.getElementById("turtle-radio").addEventListener("change", turtleXpUp);
//document.getElementById("turtle-radio").addEventListener("change", turtleandstrength);
turtleRadio.addEventListener("change", radioChanged);
dogRadio.addEventListener("change", radioChanged);
document.getElementById("Strength").innerHTML = Strength;

<div class="control">
    <label class="radio">
        <input type="radio" name="Pets" id="turtle-radio">
    </label>
    <img src="turtle.png" alt="turtle" height="100" width="100">Lv
    <span id="Turtlelv">1</span>
    <span id="TurtleCexp">0</span> /
    <span id="TurtleMexp">100</span>
    <br />
    <span id="Strength">0</span>
    <br />
    <label class="radio">
        <input type="radio" name="Pets" id="dog-radio">
    </label>

Note I also changed setTimeout to setInterval as that is the functionality you're really looking for.


问:
Have two different strings that represent dates in two different hive tables , and I want to use them to join
So I have two external tables in Hive, in my Hadoop cluster.

One table has a (date STRING) column, with this format '2019-05-24 11:16:31.0'

and the other one has (date STRING) column, with this format '23/May/2019:22:15:04', they are both strings. I need to transform them to the same type of date format and use them to join these two tables.

How would you aproach this problem solving it all within hive? Would it be possible?  I'm quite the rookie in Hadoop, And I'm not fully aware of the possibilities of hive.

Ps: My hive version does not support !hive --version command to check what version I'm working with, so I'm not pretty sure how to understand what version I'm working on. Not my cluster and I'm not a root user.

答:
OK, you can use the String Functions and Operators in hive to make the two different date format to be same, like below:

```<code>select regexp_replace(substring('2019-05-24 11:16:31.0',0,10),'-','') as date;
+-----------+
|   date    |
+-----------+
| 20190524  |
+-----------+

select concat(split(substring_index('23/May/2019:22:15:04',':',1),'/')[2],case when split(substring_index('23/May/2019:22:15:04',':',1),'/')[1]='May' then '05' end,split(substring_index('23/May/2019:22:15:04',':',1),'/')[0]) as date;
+-----------+
|   date    |
+-----------+
| 20190523  |
+-----------+
</code>```

And then join them, below is a simple example to clarify how to use, you can refine the details.

```<code>select
    *
from
    table1 t1
join
    table2 t2 regexp_replace(substring(t1.date,0,10),'-','') = select concat(split(substring_index(t2.date,':',1),'/')[2],case when split(substring_index(t2.date,':',1),'/')[1]='May' then '05' end,split(substring_index(t2.date,':',1),'/')[0])
</code>```

Am I make it clear?

Body:
OK, you can use the String Functions and Operators in hive to make the two different date format to be same, like below:

select regexp_replace(substring('2019-05-24 11:16:31.0',0,10),'-','') as date;
+-----------+
|   date    |
+-----------+
| 20190524  |
+-----------+

select concat(split(substring_index('23/May/2019:22:15:04',':',1),'/')[2],case when split(substring_index('23/May/2019:22:15:04',':',1),'/')[1]='May' then '05' end,split(substring_index('23/May/2019:22:15:04',':',1),'/')[0]) as date;
+-----------+
|   date    |
+-----------+
| 20190523  |
+-----------+

And then join them, below is a simple example to clarify how to use, you can refine the details.

select
    *
from
    table1 t1
join
    table2 t2 regexp_replace(substring(t1.date,0,10),'-','') = select concat(split(substring_index(t2.date,':',1),'/')[2],case when split(substring_index(t2.date,':',1),'/')[1]='May' then '05' end,split(substring_index(t2.date,':',1),'/')[0])

Am I make it clear?


答:
If you add an event listener on the other radio button, the Strength will go down when you switch the button.

Add this after event listener for turtle-radio:

```<code>document.getElementById("dog-radio").addEventListener("change", turtleandstrength);
</code>```

Title: Passive variable in JavaScript for a pet is not working correctly

Body:
If you add an event listener on the other radio button, the Strength will go down when you switch the button.

Add this after event listener for turtle-radio:

document.getElementById("dog-radio").addEventListener("change", turtleandstrength);


问:
type mismatch when referencing value of cells to values in another sheet
I want to delete entire row if value in column B (sheet "Track") is the same as value in column B (sheet "Active").
But run time error 13 (type mismatch) always occur even though both values I refer are string type

Here is the code:

```<code>Sub delete_row()
Dim active As Worksheet: Set activeSH = ThisWorkbook.Sheets("Active")
Dim Tracksheet As Worksheet: Set KPI = ThisWorkbook.Sheets("Track")
Dim i As Integer
Dim name As String

    With Tracksheet
         For i = .Cells(.Rows.Count, 1).End(xlUp).Row To 4 Step -1
         name = .Range("B" & i).Value

            'Here I loop through each value in col B of Track sheet
            'and reference it to values in col B of sheet "active"
            If name = active.Range("B:B").Value Then 'this line where run time error 13 (type mismatch occurs)

                .Rows(i).EntireRow.Delete

            Else
            End If
        i = i - 1
        Next i
    End With
 End Sub
</code>```

I really appreciate your help!

答:
You might wanna try something like this:

```<code>Sub delete_row()

Dim active As Worksheet
Dim Tracksheet As Worksheet
Dim i As Integer
Dim name As String
Dim cl As Range

Set active = ThisWorkbook.Sheets("Active")
Set Tracksheet = ThisWorkbook.Sheets("Track")

    With Tracksheet

         For i = .Cells(.Rows.Count, 1).End(xlUp).Row To 4 Step -1

                 name = .Range("B" & i).Value

                    For Each cl In active.Range("B1:B100")

                        If name = cl.Value Then

                            .Rows(i).EntireRow.Delete

                        End If

                    Next cl

                    i = i - 1

        Next i

    End With

 End Sub
</code>```

You can change the Range B1:B100 as per your requirement.

Body:
I want to delete entire row if value in column B (sheet "Track") is the same as value in column B (sheet "Active").
But run time error 13 (type mismatch) always occur even though both values I refer are string type

Here is the code:

Sub delete_row()
Dim active As Worksheet: Set activeSH = ThisWorkbook.Sheets("Active")
Dim Tracksheet As Worksheet: Set KPI = ThisWorkbook.Sheets("Track")
Dim i As Integer
Dim name As String

    With Tracksheet
         For i = .Cells(.Rows.Count, 1).End(xlUp).Row To 4 Step -1
         name = .Range("B" & i).Value

            'Here I loop through each value in col B of Track sheet
            'and reference it to values in col B of sheet "active"
            If name = active.Range("B:B").Value Then 'this line where run time error 13 (type mismatch occurs)

                .Rows(i).EntireRow.Delete

            Else
            End If
        i = i - 1
        Next i
    End With
 End Sub

I really appreciate your help!

Body:
You might wanna try something like this:

Sub delete_row()

Dim active As Worksheet
Dim Tracksheet As Worksheet
Dim i As Integer
Dim name As String
Dim cl As Range

Set active = ThisWorkbook.Sheets("Active")
Set Tracksheet = ThisWorkbook.Sheets("Track")

    With Tracksheet

         For i = .Cells(.Rows.Count, 1).End(xlUp).Row To 4 Step -1

                 name = .Range("B" & i).Value

                    For Each cl In active.Range("B1:B100")

                        If name = cl.Value Then

                            .Rows(i).EntireRow.Delete

                        End If

                    Next cl

                    i = i - 1

        Next i

    End With

 End Sub

You can change the Range B1:B100 as per your requirement.


问:
Allowing only alphanumeric characters through prompt box in angularjs
I have an angularjs function which provides a promptbox to the user to enter a name. I want the user to not to enter any non-alphanumeric values. For a promptbox how can I restrict the input? Please find the below function which gives the promptbox to the user.</p>

```<code>$scope.userInput = function(inputName)
{
  var name = prompt("Please Enter your name", inputName);
};
</code>```

答:
I used regex expression and it works successfully.Please find the following code.

js

```<code>$scope.userInput = function(inputName)
{
  var name = prompt("Please Enter your name", inputName);
var regPattern = /^[A-Za-z0-9]{2,}$/;
var regResult = regPattern.test(inputName);
if(regResult === true)
{
alert("correct name is given");
}
}
</code>```

Body:
I have an angularjs function which provides a promptbox to the user to enter a name. I want the user to not to enter any non-alphanumeric values. For a promptbox how can I restrict the input? Please find the below function which gives the promptbox to the user.

$scope.userInput = function(inputName)
{
  var name = prompt("Please Enter your name", inputName);
};

Body:
I used regex expression and it works successfully.Please find the following code.

js

$scope.userInput = function(inputName)
{
  var name = prompt("Please Enter your name", inputName);
var regPattern = /^[A-Za-z0-9]{2,}$/;
var regResult = regPattern.test(inputName);
if(regResult === true)
{
alert("correct name is given");
}
}


问:
Back button and creating new entry causes app to crash (UUID cannot be amended) Realm Swift
When I go back to VC1 (which allows the user to input a title for a book and create an entry in realm including the title and a UUID for that book) from VC2 (using the provided back button as part of the navigation controller not a custom segue) and then create a new book object in Realm (by adding another title to the text field in VC1), the app crashes saying I cannot amend the primary key once set.

I am intending to create a new entry (in theory I could add one, go back, add another etc) rather than try to overwrite an existing entry.

I've read the docs (and even looked at an old project where a similar thing is working) but I can't understand why it isn't just creating a new entry. I looked at the Realm docs (e.g. referenced in this answer Realm in IOS: Primary key can't be changed after an object is inserted)

Code here is VC1 allowing the user to create a new novel (by adding a title into a text field which is earlier in the code)

```<code>func createNewNovel() {

        let realm = try! Realm()
        novelCreated.novelID = UUID().uuidString
        novelCreated.novelTitle = novelTitleInput.text!
        novelCreated.createdDate = Date()

        do {
            try realm.write {
                realm.add(novelCreated)
                print ("Novel Created Successfully")
            }
        } catch {
            print("error adding novel")
        }
</code>```

Then I prepare to pass the novelID to VC2 :

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let novelData = NovelObject()
        novelData.novelID = novelCreated.novelID

        if let destVC = segue.destination as? WriteVC {
        destVC.novelIDPassed = novelData.novelID

        }
    }
</code>```

This works fine and the segue triggers from a button press on VC1. I can also print the ID of the novel in VC2 so that's working fine.

BUT... when I go back from VC2 and input a new title in the text field in VC1 it should create a new NovelObject, not try to update the existing one (which is causing it to crash). You could even theoretically have the same book title twice but they should have a different UUID (which is the primary key)

I must be missing something trivial I suppose but can't work it out!

The novel is created as at the top :

```<code>class NewNovelVC: UIViewController {

let novelCreated = NovelObject()

@IBOutlet weak var novelTitleInput: UITextField!
@IBOutlet weak var createButtonOutlet: UIButton!
</code>```

then it is populated with variables

答:
This is due to classic issue of same object being in the memory re-instantiated which points to the same value of primary key. Creating a singleton class can be very handy here as well.

Create a service file. This will keep your RealSwift initialized on a specific thread as your current block.

RealService.swift

```<code>import RealmSwift

    class RealmService {

        static let uirealm = RealmService()

        private var _initRS = try! Realm()

        var realm: Realm! {
            return _initRS
        }
    }
</code>```

Novel.swift :

```<code>import RealmSwift

    class Novel : Object {

        @objc dynamic var uid : String? = nil
        @objc dynamic var title: String? = nil

        override static func primaryKey() -> String {
            return "uid"
        }

    }

    extension Novel {

        func writeToRealm(){
            try? RealmService.uirealm.realm.write {
                print("Creating the Novel Object")
                RealmService.uirealm.realm.add(self, update: true)
            }
        }

        func DeleteFromRealm(object: Results<Novel>){
            try? RealmService.uirealm.realm.write {
                print("Deleting the Novel Object")
                RealmService.uirealm.realm.delete(object)
            }
        }

    }
</code>```

and just implement as @Don mentioned, write in the block where you are setting the title.

```<code>   var novel: Novel! // Declare this in above in the class.

    novel = Novel()
    novel.title = title
    novel.uid = uid
    novel.writeToRealm()
</code>```

Hope that helped.

Body:
When I go back to VC1 (which allows the user to input a title for a book and create an entry in realm including the title and a UUID for that book) from VC2 (using the provided back button as part of the navigation controller not a custom segue) and then create a new book object in Realm (by adding another title to the text field in VC1), the app crashes saying I cannot amend the primary key once set.

I am intending to create a new entry (in theory I could add one, go back, add another etc) rather than try to overwrite an existing entry.

I've read the docs (and even looked at an old project where a similar thing is working) but I can't understand why it isn't just creating a new entry. I looked at the Realm docs (e.g. referenced in this answer Realm in IOS: Primary key can't be changed after an object is inserted)

Code here is VC1 allowing the user to create a new novel (by adding a title into a text field which is earlier in the code)

func createNewNovel() {

        let realm = try! Realm()
        novelCreated.novelID = UUID().uuidString
        novelCreated.novelTitle = novelTitleInput.text!
        novelCreated.createdDate = Date()

        do {
            try realm.write {
                realm.add(novelCreated)
                print ("Novel Created Successfully")
            }
        } catch {
            print("error adding novel")
        }

Then I prepare to pass the novelID to VC2 :

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let novelData = NovelObject()
        novelData.novelID = novelCreated.novelID

        if let destVC = segue.destination as? WriteVC {
        destVC.novelIDPassed = novelData.novelID

        }
    }

This works fine and the segue triggers from a button press on VC1. I can also print the ID of the novel in VC2 so that's working fine.

BUT... when I go back from VC2 and input a new title in the text field in VC1 it should create a new NovelObject, not try to update the existing one (which is causing it to crash). You could even theoretically have the same book title twice but they should have a different UUID (which is the primary key)

I must be missing something trivial I suppose but can't work it out!

The novel is created as at the top :

class NewNovelVC: UIViewController {

let novelCreated = NovelObject()

@IBOutlet weak var novelTitleInput: UITextField!
@IBOutlet weak var createButtonOutlet: UIButton!

then it is populated with variables

Body:
This is due to classic issue of same object being in the memory re-instantiated which points to the same value of primary key. Creating a singleton class can be very handy here as well.

Create a service file. This will keep your RealSwift initialized on a specific thread as your current block.

RealService.swift

import RealmSwift

    class RealmService {

        static let uirealm = RealmService()

        private var _initRS = try! Realm()

        var realm: Realm! {
            return _initRS
        }
    }

Novel.swift :

import RealmSwift

    class Novel : Object {

        @objc dynamic var uid : String? = nil
        @objc dynamic var title: String? = nil

        override static func primaryKey() -> String {
            return "uid"
        }

    }

    extension Novel {

        func writeToRealm(){
            try? RealmService.uirealm.realm.write {
                print("Creating the Novel Object")
                RealmService.uirealm.realm.add(self, update: true)
            }
        }

        func DeleteFromRealm(object: Results<Novel>){
            try? RealmService.uirealm.realm.write {
                print("Deleting the Novel Object")
                RealmService.uirealm.realm.delete(object)
            }
        }

    }

and just implement as @Don mentioned, write in the block where you are setting the title.

   var novel: Novel! // Declare this in above in the class.

    novel = Novel()
    novel.title = title
    novel.uid = uid
    novel.writeToRealm()

Hope that helped.