问:
Flask : session not working. Showing session object has no attribute 'modified'
I'm trying to pass a list of dictionaries between Flask pages through session
but it is giving me this error
enter image description here

I have an __init__.py file inside a package flaskapp that imports all the modules I created and runs app = Flask(__name__)

```<code>from flask import Flask

app = Flask(__name__)
from flaskapp import api_views
from flaskapp import admin_views
from flaskapp import utilities
from flaskapp import firebase_admin_views
</code>```

and doing this inside my admin_views.py

```<code>from flask import session
from flaskapp import app

app.config["SECRET_KEY"] = 'secret key'
app.config["SESSION_TYPE"] = 'filesystem'

@app.route('/get/result',methods=["GET", "POST"])
def get_result():
    '''
        Code to process my data
    '''
    session['DICT_DATA'] = dict_data

@app.route('/get/result/download',methods=["GET", "POST"])
def get_result():
    dict_data = session['DICT_DATA']
</code>```

Can anyone please tell me why is this happening

答: So your app.config settings should be in the same file as app = Flask(__name__). Then remove from flaskapp import app

Body:
I'm trying to pass a list of dictionaries between Flask pages through session
but it is giving me this error
enter image description here

I have an __init__.py file inside a package flaskapp that imports all the modules I created and runs app = Flask(__name__)

from flask import Flask

app = Flask(__name__)
from flaskapp import api_views
from flaskapp import admin_views
from flaskapp import utilities
from flaskapp import firebase_admin_views

and doing this inside my admin_views.py

from flask import session
from flaskapp import app

app.config["SECRET_KEY"] = 'secret key'
app.config["SESSION_TYPE"] = 'filesystem'

@app.route('/get/result',methods=["GET", "POST"])
def get_result():
    '''
        Code to process my data
    '''
    session['DICT_DATA'] = dict_data

@app.route('/get/result/download',methods=["GET", "POST"])
def get_result():
    dict_data = session['DICT_DATA']

Can anyone please tell me why is this happening


来源: stackexchange

问:
SAS-Append data to a table and increment a flag on the resultant table
I have two tables on SAS "Table_A" and "Table_A_Archive", as part my ETL process "Table_A" is created on a daily basis and the data should be archived on "Table_A_Archive". When the data is archived on "Table_A_Archive" a a flag will be created/updated "DT_FLAG".

On the first day this is how the table would look like

```<code> "Table_A"
 | ID  | Load_Date
 ------ -------------
 | 100 | 01JUN2020:12:13:56

 "Table_A_Archive"
  | ID  | Load_Date           | DT_FLAG
  ------ --------------------- ---------
  | 100 | 01JUN2020:12:13:56  | 1
</code>```

On Day 2

```<code> "Table_A"
 | ID  | Load_Date
 ------ ------------
 | 101 | 02JUN2020:12:13:56

 "Table_A_Archive"
 | ID  | Load_Date           | DT_FLAG
 ------ --------------------- ---------
 | 100 | 01JUN2020:12:13:56  | 2
 | 101 | 02JUN2020:12:13:56  | 1
</code>```

The new data should be loaded with the DT_FLAG of 1 and old records DT_FLAG should be incremented by 1. Load_Date is the pivotal point. I have written a SAS code but it seems a bit messy, can someone please help me with a SAS Datastep

```<code> %macro Cntl_archive(table_name=,arch_table_name=);
 %GLOBAL WRK;

 %if %sysfunc(exist(&arch_table_name.))  %then %do;

 proc append base=&arch_table_name. data=&table_name. force;
 run;

 proc sql;
 Create table TEMP as
 Select distinct Load_Date,Load_Date as WRK from &arch_table_name.
 order by Load_Date desc
 ;quit;

 proc rank data=TEMP descending out=TEMP;
 var WRK;
 ranks count;
 run;

 data &arch_table_name. (drop=DT_FLAG);
 set    &arch_table_name.;
 run;

 proc sql;
 Create table &arch_table_name. as
 Select T0.*,T1.count as DT_FLAG from &arch_table_name. T0
 inner join TEMP T1 on T0.Load_Date=T1.Load_Date
 ;quit
 %end;
 %else %do;

data &arch_table_name.;
set &table_name.;
DT_FLAG= 1;
IS_ACTIVE='';
run;
%end;
%mend Cntl_archive;
</code>```

答:
Use Proc APPEND and compute DT_FLAG on the fly when needed.  No need to mess with the archive other than add records to it.

On-the-fly would be DATA step view.

Example:

The example want data sets are in WORK. but would be some PERM. in your real word case.

```<code>* simulate a clean start and some ETL activity with APPEND archiving;

proc delete data=want;
proc delete data=want_archive;

* DAY 1,  load #1;

data DAILY_ETL;
  ID = 100;   load_date = today()-100;   format load_date yymmdd10.;
run;
data want;
  set DAILY_ETL;
run;
proc append base=want_archive data=want;
run;

* DAY 2, load #2;

data DAILY_ETL;
  ID = 100;   load_date = today()-99;   format load_date yymmdd10.;
run;
data want;
  set DAILY_ETL;
run;
proc append base=want_archive data=want;
run;

* DAY 4, load #3;
data DAILY_ETL;
  ID = 100;   load_date = today()-97;   format load_date yymmdd10.;
run;
data want;
  set DAILY_ETL;
run;
proc append base=want_archive data=want;
run;
</code>```

and viewing

```<code>* view for on-the-fly DT_FLAG (do once);

data want_archive_v;
  set want_archive nobs=N;
  dt_flag = N - _N_ + 1;
run;

dm 'viewtable want_archive_v';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two tables on SAS "Table_A" and "Table_A_Archive", as part my ETL process "Table_A" is created on a daily basis and the data should be archived on "Table_A_Archive". When the data is archived on "Table_A_Archive" a a flag will be created/updated "DT_FLAG".

On the first day this is how the table would look like

 "Table_A"
 | ID  | Load_Date
 ------ -------------
 | 100 | 01JUN2020:12:13:56

 "Table_A_Archive"
  | ID  | Load_Date           | DT_FLAG
  ------ --------------------- ---------
  | 100 | 01JUN2020:12:13:56  | 1

On Day 2

 "Table_A"
 | ID  | Load_Date
 ------ ------------
 | 101 | 02JUN2020:12:13:56

 "Table_A_Archive"
 | ID  | Load_Date           | DT_FLAG
 ------ --------------------- ---------
 | 100 | 01JUN2020:12:13:56  | 2
 | 101 | 02JUN2020:12:13:56  | 1

The new data should be loaded with the DT_FLAG of 1 and old records DT_FLAG should be incremented by 1. Load_Date is the pivotal point. I have written a SAS code but it seems a bit messy, can someone please help me with a SAS Datastep

 %macro Cntl_archive(table_name=,arch_table_name=);
 %GLOBAL WRK;

 %if %sysfunc(exist(&arch_table_name.))  %then %do;

 proc append base=&arch_table_name. data=&table_name. force;
 run;

 proc sql;
 Create table TEMP as
 Select distinct Load_Date,Load_Date as WRK from &arch_table_name.
 order by Load_Date desc
 ;quit;

 proc rank data=TEMP descending out=TEMP;
 var WRK;
 ranks count;
 run;

 data &arch_table_name. (drop=DT_FLAG);
 set    &arch_table_name.;
 run;

 proc sql;
 Create table &arch_table_name. as
 Select T0.*,T1.count as DT_FLAG from &arch_table_name. T0
 inner join TEMP T1 on T0.Load_Date=T1.Load_Date
 ;quit
 %end;
 %else %do;

data &arch_table_name.;
set &table_name.;
DT_FLAG= 1;
IS_ACTIVE='';
run;
%end;
%mend Cntl_archive;

Body:
Use Proc APPEND and compute DT_FLAG on the fly when needed.  No need to mess with the archive other than add records to it.

On-the-fly would be DATA step view.

Example:

The example want data sets are in WORK. but would be some PERM. in your real word case.

* simulate a clean start and some ETL activity with APPEND archiving;

proc delete data=want;
proc delete data=want_archive;

* DAY 1,  load #1;

data DAILY_ETL;
  ID = 100;   load_date = today()-100;   format load_date yymmdd10.;
run;
data want;
  set DAILY_ETL;
run;
proc append base=want_archive data=want;
run;

* DAY 2, load #2;

data DAILY_ETL;
  ID = 100;   load_date = today()-99;   format load_date yymmdd10.;
run;
data want;
  set DAILY_ETL;
run;
proc append base=want_archive data=want;
run;

* DAY 4, load #3;
data DAILY_ETL;
  ID = 100;   load_date = today()-97;   format load_date yymmdd10.;
run;
data want;
  set DAILY_ETL;
run;
proc append base=want_archive data=want;
run;

and viewing

* view for on-the-fly DT_FLAG (do once);

data want_archive_v;
  set want_archive nobs=N;
  dt_flag = N - _N_ + 1;
run;

dm 'viewtable want_archive_v';


问:
How to change the icon when selecting tab and make the main tab that is in the middle?
I'm starting to study flutter and tried to make a simple tabbar. Also enabled the package "material_design_icons_flutter". I need regular and outline icons in it. How do I make sure that when tab was not selected, there was one icon, and when selected, the icon changed to another? And how else can I make sure that when the app starts, the main tab is for example the one in the middle?

```<code>import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

void main() => runApp(TabLayoutDemo());

class TabLayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      color: Colors.yellow,
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          body: TabBarView(
            children: [
              Container(
                color: Colors.yellow,
              ),
              Container(
                color: Colors.orange,
              ),
              Container(
                color: Colors.lightGreen,
              ),
            ],
          ),
          bottomNavigationBar: TabBar(
            tabs: [
              Tab(
                icon: Icon(Icons.perm_identity),
              ),
              Tab(
                icon: Icon(MdiIcons.homeOutline),
              ),
              Tab(
                icon: Icon(Icons.settings),
              )
            ],
            labelColor: Colors.blue,
            unselectedLabelColor: Colors.black45,
            indicatorSize: TabBarIndicatorSize.tab,
//            indicatorPadding: EdgeInsets.all(5.0),
            indicatorColor: Colors.blue,
          ),
          backgroundColor: Colors.white,
        ),
      ),
    );
  }
}
</code>```

答:
TabBar is supposed to be used at the top and BottomNavigationBar at the bottom. You should use a BottomNavigationBar instead.

Set your scaffold like this:

```<code>            Scaffold(
              bottomNavigationBar: BottomNavigationBar(
                currentIndex: currentTab, //variable declared at top
                items: <BottomNavigationBarItem>[
                  BottomNavigationBarItem(
                      icon: Icon(Icons.perm_identity),
                      activeIcon:
                          Icon(Icons.grade) //Set to the icon when selected
                      ),
                  BottomNavigationBarItem(
                      icon: Icon(MdiIcons.homeOutline),
                      activeIcon:
                          Icon(Icons.grade) //Set to the icon when selected
                      ),
                  BottomNavigationBarItem(
                      icon: Icon(Icons.settings),
                      activeIcon:
                          Icon(Icons.grade) //Set to the icon when selected
                      ),
                ],
                onTap: (int index) {
                  setState(() {
                    currentTab = index;
                    currentPage = pages[index];
                  });
                },
              ),
              body: currentPage,
            ),
</code>```

Declare the variables outside of build function:

```<code>  int currentTab = 1; //Choose the index of the home tab
  List<Widget> pages;
  Widget currentPage;
</code>```

Set the value of variables inside init function

```<code>  @override
  void initState() {
    pages = [
      Container(
        color: Colors.yellow,
      ),
      Container(
        color: Colors.orange,
      ),
      Container(
        color: Colors.lightGreen,
      ),
    ];
    currentPage = pages[currentTab];

    super.initState();
  }
</code>```

Body:
I'm starting to study flutter and tried to make a simple tabbar. Also enabled the package "material_design_icons_flutter". I need regular and outline icons in it. How do I make sure that when tab was not selected, there was one icon, and when selected, the icon changed to another? And how else can I make sure that when the app starts, the main tab is for example the one in the middle?

import 'package:flutter/material.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

void main() => runApp(TabLayoutDemo());

class TabLayoutDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      color: Colors.yellow,
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          body: TabBarView(
            children: [
              Container(
                color: Colors.yellow,
              ),
              Container(
                color: Colors.orange,
              ),
              Container(
                color: Colors.lightGreen,
              ),
            ],
          ),
          bottomNavigationBar: TabBar(
            tabs: [
              Tab(
                icon: Icon(Icons.perm_identity),
              ),
              Tab(
                icon: Icon(MdiIcons.homeOutline),
              ),
              Tab(
                icon: Icon(Icons.settings),
              )
            ],
            labelColor: Colors.blue,
            unselectedLabelColor: Colors.black45,
            indicatorSize: TabBarIndicatorSize.tab,
//            indicatorPadding: EdgeInsets.all(5.0),
            indicatorColor: Colors.blue,
          ),
          backgroundColor: Colors.white,
        ),
      ),
    );
  }
}

Body:
TabBar is supposed to be used at the top and BottomNavigationBar at the bottom. You should use a BottomNavigationBar instead.

Set your scaffold like this:

            Scaffold(
              bottomNavigationBar: BottomNavigationBar(
                currentIndex: currentTab, //variable declared at top
                items: <BottomNavigationBarItem>[
                  BottomNavigationBarItem(
                      icon: Icon(Icons.perm_identity),
                      activeIcon:
                          Icon(Icons.grade) //Set to the icon when selected
                      ),
                  BottomNavigationBarItem(
                      icon: Icon(MdiIcons.homeOutline),
                      activeIcon:
                          Icon(Icons.grade) //Set to the icon when selected
                      ),
                  BottomNavigationBarItem(
                      icon: Icon(Icons.settings),
                      activeIcon:
                          Icon(Icons.grade) //Set to the icon when selected
                      ),
                ],
                onTap: (int index) {
                  setState(() {
                    currentTab = index;
                    currentPage = pages[index];
                  });
                },
              ),
              body: currentPage,
            ),

Declare the variables outside of build function:

  int currentTab = 1; //Choose the index of the home tab
  List<Widget> pages;
  Widget currentPage;

Set the value of variables inside init function

  @override
  void initState() {
    pages = [
      Container(
        color: Colors.yellow,
      ),
      Container(
        color: Colors.orange,
      ),
      Container(
        color: Colors.lightGreen,
      ),
    ];
    currentPage = pages[currentTab];

    super.initState();
  }


问:
Skewing both top and bottom of div
I am trying to skew both the top and bottom of a div to create a shape that I can then insert a background pattern to however, after a few hours of research I can't really come up with a solid solution. I'm nearly there in the sense that all I need to do is to skew the bottom but am looking for some help or guidance on doing so.

I would like the bottom to mirror the skew of the top. Any suggestions?

#test {
  position: relative;
  width: 100%;
  height: 400px;
}

.bg {
  width: 50%;
  height: 800px;
  -webkit-transition: all 300ms ease-in;
  background: black;
  border-radius: 80px 0px 0px 80px;
  position: absolute;
  right: 0;
  top: 0;
  -ms-transform: skewY(-9deg);
  -webkit-transform: skewY(-9deg);
  transform: skewY(-9deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="test">
  <div class="bg"></div>
</section></code>```

Example of what I currently have
https://jsfiddle.net/3atsj1e5/

答:
With some rotation and perspective you can do it:

.box {
  margin-left: auto;
  width: 200px;
  height: 450px;
  transform-origin: right;
  transform: perspective(100px) rotateY(-10deg);
  border-radius: 40px 0 0 40px;
  overflow: hidden;
}

.box::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url(https://picsum.photos/id/1074/400/800) center/cover;
  transform-origin:inherit;
  transform: perspective(100px) rotateY(10deg);
}

body {
  margin: 0;
  background:#eee;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code>```

Title: Skewing both top and bottom of div

Body:
I am trying to skew both the top and bottom of a div to create a shape that I can then insert a background pattern to however, after a few hours of research I can't really come up with a solid solution. I'm nearly there in the sense that all I need to do is to skew the bottom but am looking for some help or guidance on doing so.

I would like the bottom to mirror the skew of the top. Any suggestions?

#test {
  position: relative;
  width: 100%;
  height: 400px;
}

.bg {
  width: 50%;
  height: 800px;
  -webkit-transition: all 300ms ease-in;
  background: black;
  border-radius: 80px 0px 0px 80px;
  position: absolute;
  right: 0;
  top: 0;
  -ms-transform: skewY(-9deg);
  -webkit-transform: skewY(-9deg);
  transform: skewY(-9deg);
}

Example of what I currently have
https://jsfiddle.net/3atsj1e5/

Body:
With some rotation and perspective you can do it:

.box {
  margin-left: auto;
  width: 200px;
  height: 450px;
  transform-origin: right;
  transform: perspective(100px) rotateY(-10deg);
  border-radius: 40px 0 0 40px;
  overflow: hidden;
}

.box::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url(https://picsum.photos/id/1074/400/800) center/cover;
  transform-origin:inherit;
  transform: perspective(100px) rotateY(10deg);
}

body {
  margin: 0;
  background:#eee;
}

<div class="box"></div>


问:
Confirmation modal on Bitbucket merge click
Some of our developers forget to go through the pre-merge checklist.

Can we add some type of hook/script or Bitbucket package to show a confirmation modal when they click merge?

An alternative would be using a script to put a task on all open PRs and forcing the devs to check it off. Would that be easier than a modal?

答:
At my job, we have done something very similar to what you're asking. We have added a task to PR's when their build fails. They will have to complete that task, which means fix their code, until they can merge the PR.

This is all being done through a Powershell script that is being run at build time. We are using TeamCity, so we added the powershell script as another build step and setup the appropriate parameters so that the api would work properly.

The Bitbucket API documentation is very detailed and useful.

I think adding a task is the best option. I am not sure if you are able to produce a modal, but I think the task route would be much simpler.


问:
From master branch i created new branch called release1
From master branch i created new branch called release1. I switched to release1 branch and added one file then again i switched to master branch.Here without merging branch,the file which is in release1 branch is reflecting in master branch why?</p>

答:
If you don't add/commit your new file, it is moved as a pending modification to whichever branch you'll switch to.

To avoid this, commit on your release1 branch before switching back to master and it'll "stay" there.


问:
Pandas: how to treat strange time format
I have the following Pandas dataframe, where the time (duration) is given in a very strange format:

```<code>Person   Activity   Duration
1        A          1 00:00
2        A          1 00:00
3        B          0 21:17
4        C          0 17:11
</code>```

Where 1 00:00 means 24 hours, and 0 21:17 means 0 days and 21:17 hours, which is to say just 21:17 hours. A quick look at the dtypes returns:

```<code>In[1]: df.dtypes
Out[1]:
Person         object
Activity       object
Duration       object
dtype: object
</code>```

How can I consistently treat the Duration column to return 24 if the value is 1 00:00, and the decimal value of the duration if I have 0 21:17? The decimal value of 0 21:17 would be 21.283.

The outcome should be:

```<code>Person   Activity   Duration
1        A          24
2        A          24
3        B          21.283
4        C          17.183
</code>```

答:
```<code>a = np.array([24, 1, 1/60])
df.Duration = df.Duration.str.split(' |:', expand=True).astype(int).dot(a)
</code>```

Example:

```<code>df = pd.DataFrame({'Person': [1,2,3,4], "Activity": list('AABC') ,"Duration":['1 00:00', '1 00:00', '0 21:17', '0 17:11']})
df.Duration = df.Duration.str.split(' |:', expand=True).astype(int).dot(a)
print(df)
#   Person Activity   Duration
#0       1        A  24.000000
#1       2        A  24.000000
#2       3        B  21.283333
#3       4        C  17.183333
</code>```

Body:
I have the following Pandas dataframe, where the time (duration) is given in a very strange format:

Person   Activity   Duration
1        A          1 00:00
2        A          1 00:00
3        B          0 21:17
4        C          0 17:11

Where 1 00:00 means 24 hours, and 0 21:17 means 0 days and 21:17 hours, which is to say just 21:17 hours. A quick look at the dtypes returns:

In[1]: df.dtypes
Out[1]:
Person         object
Activity       object
Duration       object
dtype: object

How can I consistently treat the Duration column to return 24 if the value is 1 00:00, and the decimal value of the duration if I have 0 21:17? The decimal value of 0 21:17 would be 21.283.

The outcome should be:

Person   Activity   Duration
1        A          24
2        A          24
3        B          21.283
4        C          17.183

Body:
a = np.array([24, 1, 1/60])
df.Duration = df.Duration.str.split(' |:', expand=True).astype(int).dot(a)

Example:

df = pd.DataFrame({'Person': [1,2,3,4], "Activity": list('AABC') ,"Duration":['1 00:00', '1 00:00', '0 21:17', '0 17:11']})
df.Duration = df.Duration.str.split(' |:', expand=True).astype(int).dot(a)
print(df)
#   Person Activity   Duration
#0       1        A  24.000000
#1       2        A  24.000000
#2       3        B  21.283333
#3       4        C  17.183333


问:
How to keep the console window open in Visual C++?
I'm starting out in Visual C++ and I'd like to know how to keep the console window.

For instance this would be a typical "hello world" application:

```<code>int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World";
    return 0;
}
</code>```

What's the line I'm missing?

答:
As some have already pointed out, Zoidbergs solution does not attach the debugger, which is something you usually don't want.

The best option imo is to configure your VS accordingly (from VS 2017 onwards), by going to Tools > Options > Debugging > General. There you uncheck "Automatically close the console when debugging stops" (at the very bottom), which is probably checked in your case.

OwnerDisplayName: Raúl Roa

ContentLicense: CC BY-SA 3.0

Body:
I'm starting out in Visual C++ and I'd like to know how to keep the console window.

For instance this would be a typical "hello world" application:

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World";
    return 0;
}

What's the line I'm missing?


问:
How to Upload an Image to Django
I have spent over three days on this. It appears that something saved to the db, but when I try to access it in the template, I can only get the object of the db. I can not access it. I believe it was not saved successfully because I don't see a media folder where it would be saved. This is what I have so far.

# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
```

<pre class="lang-py prettyprint-override"><code># forms.py
from .models import Pic
from django import forms
class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]
</code>```

# models.py
class Pic(models.Model):
    picture = models.ImageField(upload_to = 'media/', default = 'media/None/no-img.jpg', null=True, blank= True)
```

<pre class="lang-py prettyprint-override"><code># views.py
def upload(request):
    form = ImageForm
    context = {}
    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    if request.method == 'POST':
        # .is_valid checks the models parameters via forms method
        form = ImageForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            print("succesful uploaded image")
            return redirect("/dashboard")
        else:
            print("Not a valid input from form....")
            messages.error(request,"Not a valid input")
    return redirect("/dashboard")
</code>```

<form rule="form" class="border border--secondary" method="POST" action="/manageFile" enctype="multipart/form-data">
    {% csrf_token%}
    <input type="file" name = "update">
    <input type = "submit">
</form>
{% if pictures %}
    {% for pic in pictures%}

    {% endfor %}
{% endif%}
```

<p>In the template, it appears as Pic object(1).
In the terminal, it appears as</p>

<blockquote>
  <p>Query set Pic: Pic object (1)</p>
</blockquote>

<p>Here's what I render to the template.</p>

<pre class="lang-py prettyprint-override"><code>def dash(request):
    try:
        _id = request.session['client']['id']
    except:
        return redirect("/loginPg")

    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    print("its right here")
    theUploads = Pic.objects.all()
    print("This image object -", theUploads)

    content = {
        "title" : userBio.title,
        "qA" : userBio.quoteA,
        "qB" : userBio.quoteB,
        "desc" : userBio.desc,
        "authorA" : userBio.authorA,
        "authorB" : userBio.authorB,
        "pictures" : theUploads
    }

    return render(request, "GoEnigma/dashboard.html", content)
</code>```

# urls.py
from django.conf.urls.static import static
from django.conf import settings
# urls []
if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```

答:
This was hard to spot, because you render the form field yourself:

class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]
```

<pre class="lang-html prettyprint-override"><code>    <input type="file" name = "update">
</code>```

So the name of the file field is update, not picture. Change that to picture and it should work, though it's much better to use django to render the form, so you don't mistakes like this and changes to the form get propagated to the html.

Title: How to Upload an Image to Django

Body:
I have spent over three days on this. It appears that something saved to the db, but when I try to access it in the template, I can only get the object of the db. I can not access it. I believe it was not saved successfully because I don't see a media folder where it would be saved. This is what I have so far.

# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# forms.py
from .models import Pic
from django import forms
class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]

# models.py
class Pic(models.Model):
    picture = models.ImageField(upload_to = 'media/', default = 'media/None/no-img.jpg', null=True, blank= True)

# views.py
def upload(request):
    form = ImageForm
    context = {}
    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    if request.method == 'POST':
        # .is_valid checks the models parameters via forms method
        form = ImageForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            print("succesful uploaded image")
            return redirect("/dashboard")
        else:
            print("Not a valid input from form....")
            messages.error(request,"Not a valid input")
    return redirect("/dashboard")

<form rule="form" class="border border--secondary" method="POST" action="/manageFile" enctype="multipart/form-data">
    {% csrf_token%}
    <input type="file" name = "update">
    <input type = "submit">
</form>
{% if pictures %}
    {% for pic in pictures%}

    {% endfor %}
{% endif%}

In the template, it appears as Pic object(1).
In the terminal, it appears as

Query set Pic: Pic object (1)

Here's what I render to the template.

def dash(request):
    try:
        _id = request.session['client']['id']
    except:
        return redirect("/loginPg")

    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    print("its right here")
    theUploads = Pic.objects.all()
    print("This image object -", theUploads)

    content = {
        "title" : userBio.title,
        "qA" : userBio.quoteA,
        "qB" : userBio.quoteB,
        "desc" : userBio.desc,
        "authorA" : userBio.authorA,
        "authorB" : userBio.authorB,
        "pictures" : theUploads
    }

    return render(request, "GoEnigma/dashboard.html", content)

# urls.py
from django.conf.urls.static import static
from django.conf import settings
# urls []
if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Body:
This was hard to spot, because you render the form field yourself:

class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]

    <input type="file" name = "update">

So the name of the file field is update, not picture. Change that to picture and it should work, though it's much better to use django to render the form, so you don't mistakes like this and changes to the form get propagated to the html.


问:
while calling the function, the same function_name and parameter_name in function creates obstruct! Can anyone explain whats happening?
<pre class="lang-py prettyprint-override"><code>#In simple form

def name(name):
    print(name)

name='arjun'

name(name) #In this line, what's happening?

#Error 'str' object is not callable
</code>```

答:
There are not separate namespaces for functions and other objects. If you write

```<code>def name1(name2):
    print(name2)
</code>```

you create an instance of type function, then assign that instance to the name name1. (A def statement is just a very fancy kind of assignment statement.)

Parameter names are local variables, belonging to the scope defined by the function, not the scope in which the function is defined. That means you can reuse the name, though it isn't recommended as it can be confusing.

```<code>   belongs to the scope in which the function is defined
      |
      |    +--- belongs to the scope inside the function
      |    |
      v    v
def name(name):
    print(name)
</code>```

However, the following assignment

```<code>name = 'arjun'
</code>```

is in the same scope as the function definition, so this makes name refer to a str object instead of the function object it used to refer to.

Body:
There are not separate namespaces for functions and other objects. If you write

def name1(name2):
    print(name2)

you create an instance of type function, then assign that instance to the name name1. (A def statement is just a very fancy kind of assignment statement.)

Parameter names are local variables, belonging to the scope defined by the function, not the scope in which the function is defined. That means you can reuse the name, though it isn't recommended as it can be confusing.

   belongs to the scope in which the function is defined
      |
      |    +--- belongs to the scope inside the function
      |    |
      v    v
def name(name):
    print(name)

However, the following assignment

name = 'arjun'

is in the same scope as the function definition, so this makes name refer to a str object instead of the function object it used to refer to.


问:
Opsgenie alert "Kube_Client_Certificate_Expiration"
We are receiving below alert in opsgenie, So please suggest how to do basic checks and fixing the issue

```<code>Labels
alertname = KubeClientCertificateExpiration
cluster = cluster.example.com
job = apiserver
prometheus = openshift-monitoring/k8s
severity = warning
Annotations
message = Kubernetes API certificate is expiring in less than 7 days.
</code>```

Thanks in advance

Ravi kumar G

答:
This could be because Kubernetes API Server Client certificate is expiring. This is the certificate that Kubernetes API Server uses to talk to kubelet.

You could verify this by capturing network traffic on the kubelet https port using tcpdump and analyzing the tcp handshakes using wireshark (filter "tls.handshake.client_cert_vrfy.sig") and inspecting the client certificates.

Also check if there is any pending csr by kubectl get csr --sort-by='{.metadata.creationTimestamp}' and approve them using kubectl certificate approve csrname

Body:
We are receiving below alert in opsgenie, So please suggest how to do basic checks and fixing the issue

Labels
alertname = KubeClientCertificateExpiration
cluster = cluster.example.com
job = apiserver
prometheus = openshift-monitoring/k8s
severity = warning
Annotations
message = Kubernetes API certificate is expiring in less than 7 days.

Thanks in advance

Ravi kumar G


问:
How can i add a full new Element (using ElementTree in Python) to a XML File
i have the code posted below, i could add a new Element "continent" to country "Singapore".
But i want to add a full Element to the XML File. Is it possible to do that?
The "data" variable contains the content of the Element i want to create in the XML File. I tried to append it but... no luck!

My XML File:

```<code><data>
  <country name="Liechtenstein">
    <rank updated="yes">5</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor direction="E" name="Austria" />
    <neighbor direction="W" name="Switzerland" />
  </country>
  <country name="Singapore">
    <rank updated="yes">8</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor direction="N" name="Malaysia" />
  </country>
  <country name="Panama">
    <rank updated="yes">72</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor direction="W" name="Costa Rica" />
    <neighbor direction="E" name="Colombia" />
  </country>
</data>
</code>```

Here is my Python code:

```<code>import xml.etree.ElementTree as et

for item in root.findall("country"):
  if(item.get("name") == "Singapore"):
    new1 = et.Element("continent")
    new1.text = "Asia"
    item.append(new1)
tree.write("countries.xml")

data = '''
  <country name="Portugal">
    <rank updated="yes">21</rank>
    <year>2000</year>
    <gdppc>150000</gdppc>
    <neighbor direction="E" name="Spain" />
  </country>
'''

new2 = et.Element("country")
new2.text = data
root.append(new2)
tree.write("countries.xml")
</code>```

答:
try this:

```<code>import xml.etree.ElementTree as et

xml = """
<data>
  <country name="Liechtenstein">
    <rank updated="yes">5</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor direction="E" name="Austria" />
    <neighbor direction="W" name="Switzerland" />
  </country>
  <country name="Singapore">
    <rank updated="yes">8</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor direction="N" name="Malaysia" />
  </country>
  <country name="Panama">
    <rank updated="yes">72</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor direction="W" name="Costa Rica" />
    <neighbor direction="E" name="Colombia" />
  </country>
</data>
"""

if __name__ == "__main__":
    tree = et.ElementTree(et.fromstring(xml))
    root = tree.getroot()

    data = '''
      <country name="Portugal">
        <rank updated="yes">21</rank>
        <year>2000</year>
        <gdppc>150000</gdppc>
        <neighbor direction="E" name="Spain" />
      </country>
    '''

    new2 = et.fromstring(data)
    root.append(new2)
    tree.write("countries2.xml")
</code>```

important is this part, where you generate an xml object hierarchy for your xml snippet (data) and attach it as child to your root node:

```<code>new2 = et.fromstring(data)
root.append(new2)
</code>```

Body:
i have the code posted below, i could add a new Element "continent" to country "Singapore".
But i want to add a full Element to the XML File. Is it possible to do that?
The "data" variable contains the content of the Element i want to create in the XML File. I tried to append it but... no luck!

My XML File:

<data>
  <country name="Liechtenstein">
    <rank updated="yes">5</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor direction="E" name="Austria" />
    <neighbor direction="W" name="Switzerland" />
  </country>
  <country name="Singapore">
    <rank updated="yes">8</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor direction="N" name="Malaysia" />
  </country>
  <country name="Panama">
    <rank updated="yes">72</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor direction="W" name="Costa Rica" />
    <neighbor direction="E" name="Colombia" />
  </country>
</data>

Here is my Python code:

import xml.etree.ElementTree as et

for item in root.findall("country"):
  if(item.get("name") == "Singapore"):
    new1 = et.Element("continent")
    new1.text = "Asia"
    item.append(new1)
tree.write("countries.xml")

data = '''
  <country name="Portugal">
    <rank updated="yes">21</rank>
    <year>2000</year>
    <gdppc>150000</gdppc>
    <neighbor direction="E" name="Spain" />
  </country>
'''

new2 = et.Element("country")
new2.text = data
root.append(new2)
tree.write("countries.xml")

Body:
try this:

import xml.etree.ElementTree as et

xml = """
<data>
  <country name="Liechtenstein">
    <rank updated="yes">5</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor direction="E" name="Austria" />
    <neighbor direction="W" name="Switzerland" />
  </country>
  <country name="Singapore">
    <rank updated="yes">8</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor direction="N" name="Malaysia" />
  </country>
  <country name="Panama">
    <rank updated="yes">72</rank>
    <year>2011</year>
    <gdppc>13600</gdppc>
    <neighbor direction="W" name="Costa Rica" />
    <neighbor direction="E" name="Colombia" />
  </country>
</data>
"""

if __name__ == "__main__":
    tree = et.ElementTree(et.fromstring(xml))
    root = tree.getroot()

    data = '''
      <country name="Portugal">
        <rank updated="yes">21</rank>
        <year>2000</year>
        <gdppc>150000</gdppc>
        <neighbor direction="E" name="Spain" />
      </country>
    '''

    new2 = et.fromstring(data)
    root.append(new2)
    tree.write("countries2.xml")

important is this part, where you generate an xml object hierarchy for your xml snippet (data) and attach it as child to your root node:

new2 = et.fromstring(data)
root.append(new2)


问:
Error when processing InDesign document in Applescript
Recently upgraded to Adobe CC 2020 and my script will now not work. Also Script Editor changed class names.

I am getting an error such that:

error "Can’t get every page of alias \"Untitled - Data:Users:gregory:Desktop:FORUM_MayJun_0414_B Folder:FORUM_MayJun_0414_fortesting.indd\"." number -1728 from every «class page» of alias "Untitled - Data:Users:gregory:Desktop:FORUM_MayJun_0414_B Folder:FORUM_MayJun_0414_fortesting.indd"

Here is my script:

```<code>global WordDocName
global wrongText
global myStories
--set uniqueInCopyStories to {}
--set wrongText to "BASE"

set theDoc to choose file without multiple selections allowed
--set theDoc to POSIX path of theDoc

set theDocInfo to info for theDoc
set theDocName to name of theDocInfo
set theDocName to characters 1 thru -6 of theDocName as text
set WordDocName to theDocName
set theDocName to theDocName & return

set myStories to {}

my processFiles(theDoc)

set mylist to items 1 thru -1 of myStories

set firstList to mylist

set secondList to RemoveDuplicates(firstList)

--secondList --> {1, 2, 3, 4}

set mynewlist to {}
repeat with i from 1 to (count of secondList)
    set myitem to item i of secondList as text
    set end of mynewlist to myitem
end repeat

set mystring to mynewlist as string
--return mystring

my processWordDoc(theDocName, mystring, WordDocName)

on processFiles(theDoc)

    tell application "Adobe InDesign 2020"
        activate
        open theDoc

        tell theDoc
            set myPages to every «class page»
            repeat with i from 1 to count of myPages
                tell item i of myPages
                    set myTextFrames to (every «class txtf» of item i of myPages)
                    repeat with aTextFrame in myTextFrames
                        if «class plnk» of «class strp» of aTextFrame is not «constant senmnada» then
                            if «class strp»'s «class plnk»'s «class lnkt» of aTextFrame is "InCopyInterchange" then
                                set mystorytitle to «class sTtl» of aTextFrame's «class strp»
                                set myLabel to «class ptag» of aTextFrame
                                set myText to characters 1 thru -1 of mystorytitle as text
                                --if myText does not contain wrongText then

                                set myStory to aTextFrame's «class strp»'s contents
                                copy "Page " & (name of item i of myPages) & " " & mystorytitle & return & myLabel & return & myStory & return & return to end of myStories
                            end if
                        end if
                        --end if
                    end repeat
                end tell
            end repeat

        end tell
    end tell
end processFiles

on processWordDoc(theDocName, mystring, WordDocName)
    tell application "Microsoft Word"
        activate
        set newDoc to make new document
        copy theDocName & mystring to content of text object of newDoc
        save as active document file name WordDocName
        my textblue()

    end tell
end processWordDoc

on textblue()
    with timeout of 60000 seconds
        tell application "Microsoft Word"
            set myPars to every paragraph of active document
            set myTitle to text object of paragraph 1 of active document
            set color index of font object of myTitle to blue
            repeat with aPar in myPars
                if content of text object of aPar starts with "Page" then

                    set myRange to text object of aPar

                    set color index of font object of myRange to blue
                end if
            end repeat
        end tell
    end timeout
end textblue

on RemoveDuplicates(inputList)

    set outputList to {}

    repeat with i from 1 to length of inputList

        --    We make testItem a single-item list to ensure
        --    that sublists of the inputList are properly
        --    looked for in the outputlist.
        --
        set thisItem to item i of inputList
        set testItem to {thisItem}

        if (outputList does not contain testItem) then

            set end of outputList to thisItem

        end if

    end repeat

    return outputList

end RemoveDuplicates
</code>```

What I don't understand is why my script thinks I am asking to get every page of every page, when it was automatic that every page would be every page of theDoc

答:
theDoc is an AppleScript alias specifier, but you are using it (also) as an InDesign document reference.

The easiest solution is to replace

```<code>tell theDoc
</code>```

with

```<code>tell active document
</code>```

Body:
Recently upgraded to Adobe CC 2020 and my script will now not work. Also Script Editor changed class names.

I am getting an error such that:

error "Can’t get every page of alias \"Untitled - Data:Users:gregory:Desktop:FORUM_MayJun_0414_B Folder:FORUM_MayJun_0414_fortesting.indd\"." number -1728 from every «class page» of alias "Untitled - Data:Users:gregory:Desktop:FORUM_MayJun_0414_B Folder:FORUM_MayJun_0414_fortesting.indd"

Here is my script:

global WordDocName
global wrongText
global myStories
--set uniqueInCopyStories to {}
--set wrongText to "BASE"

set theDoc to choose file without multiple selections allowed
--set theDoc to POSIX path of theDoc

set theDocInfo to info for theDoc
set theDocName to name of theDocInfo
set theDocName to characters 1 thru -6 of theDocName as text
set WordDocName to theDocName
set theDocName to theDocName & return

set myStories to {}

my processFiles(theDoc)

set mylist to items 1 thru -1 of myStories

set firstList to mylist

set secondList to RemoveDuplicates(firstList)

--secondList --> {1, 2, 3, 4}

set mynewlist to {}
repeat with i from 1 to (count of secondList)
    set myitem to item i of secondList as text
    set end of mynewlist to myitem
end repeat

set mystring to mynewlist as string
--return mystring

my processWordDoc(theDocName, mystring, WordDocName)

on processFiles(theDoc)

    tell application "Adobe InDesign 2020"
        activate
        open theDoc

        tell theDoc
            set myPages to every «class page»
            repeat with i from 1 to count of myPages
                tell item i of myPages
                    set myTextFrames to (every «class txtf» of item i of myPages)
                    repeat with aTextFrame in myTextFrames
                        if «class plnk» of «class strp» of aTextFrame is not «constant senmnada» then
                            if «class strp»'s «class plnk»'s «class lnkt» of aTextFrame is "InCopyInterchange" then
                                set mystorytitle to «class sTtl» of aTextFrame's «class strp»
                                set myLabel to «class ptag» of aTextFrame
                                set myText to characters 1 thru -1 of mystorytitle as text
                                --if myText does not contain wrongText then

                                set myStory to aTextFrame's «class strp»'s contents
                                copy "Page " & (name of item i of myPages) & " " & mystorytitle & return & myLabel & return & myStory & return & return to end of myStories
                            end if
                        end if
                        --end if
                    end repeat
                end tell
            end repeat

        end tell
    end tell
end processFiles

on processWordDoc(theDocName, mystring, WordDocName)
    tell application "Microsoft Word"
        activate
        set newDoc to make new document
        copy theDocName & mystring to content of text object of newDoc
        save as active document file name WordDocName
        my textblue()

    end tell
end processWordDoc

on textblue()
    with timeout of 60000 seconds
        tell application "Microsoft Word"
            set myPars to every paragraph of active document
            set myTitle to text object of paragraph 1 of active document
            set color index of font object of myTitle to blue
            repeat with aPar in myPars
                if content of text object of aPar starts with "Page" then

                    set myRange to text object of aPar

                    set color index of font object of myRange to blue
                end if
            end repeat
        end tell
    end timeout
end textblue

on RemoveDuplicates(inputList)

    set outputList to {}

    repeat with i from 1 to length of inputList

        --    We make testItem a single-item list to ensure
        --    that sublists of the inputList are properly
        --    looked for in the outputlist.
        --
        set thisItem to item i of inputList
        set testItem to {thisItem}

        if (outputList does not contain testItem) then

            set end of outputList to thisItem

        end if

    end repeat

    return outputList

end RemoveDuplicates

What I don't understand is why my script thinks I am asking to get every page of every page, when it was automatic that every page would be every page of theDoc

Body:
theDoc is an AppleScript alias specifier, but you are using it (also) as an InDesign document reference.

The easiest solution is to replace

tell theDoc

with

tell active document


答:
You can just multiply and add these numbers together easily:</p>

```<code>durations = [
    "1 00:00",
    "0 21:17",
]

for duration in durations:
    day, clock = duration.split()
    hour, minute = clock.split(':')
    print((int(day) * 24) + int(hour) + (int(minute) / 60))
</code>```

Title: Pandas: how to treat strange time format

Body:
You can just multiply and add these numbers together easily:

durations = [
    "1 00:00",
    "0 21:17",
]

for duration in durations:
    day, clock = duration.split()
    hour, minute = clock.split(':')
    print((int(day) * 24) + int(hour) + (int(minute) / 60))


问:
Is there an equivalent of tf.lite.Interpreter.get_input_details for C++?
In TensorFlow lite's Python API, there are methods to retrieve details concerning the input and output tensors, called tf.lite.Interpreter.get_input_details and tf.lite.Interpreter.get_output_details. I am after the 'quantization' entry in these dicts, which contain a value for mean and standard deviation each.

When deploying these models on another platform, I use the C++ API to set up an interpreter. To prepare the inputs for my model, I also need mean and standard deviation.

I was unable to find equivalents of these functions in C++. Do they exist?

答:
You can also fetch the same information using PrintInterpreterState(), in fact quite overwhelming:

```<code>tflite::PrintInterpreterState(interpreter.get());
</code>```

Body:
You can also fetch the same information using PrintInterpreterState(), in fact quite overwhelming:

tflite::PrintInterpreterState(interpreter.get());


问:
Makefile multiple dependency lines for a single target?
To generate dependency files I can use something like this to generate dependency files:

```<code>-include $(patsubst %.cpp,build/%.d,$(SRC))
build/%.o: %.cpp
    $(CC) $(CXXFLAGS) -c -o $@ $<
    $(CC) $(CXXFLAGS) -MM -MT $@ -MF $(patsubst %.o,%.d,%@) $<
</code>```

This generates everything and puts both the object and dependency files into the build dir where I want them. But this makes two dependency lines for the <file>.o targets, one from the -include rule and with all the header dependencies, and one which is from the pattern rule. Will this get interpreted correctly, i.e. when a header is modified, the object will be recompiled via the command specified for the pattern rule?

Edit: So this approach does in fact work quite well. I guess I'd like somebody to provide an answer which gives me some insight into what it is exactly that make does in these situations. For instance, what if a different command was given for both rules for the same target? My guess would be that it gives an error since it wouldn't be obvious which command to execute.

答:
Yes, you can specify several rules for one file, and they get merged into one.
See the GNU Make documentation.

[...] There can only be one recipe to be executed for a file. [...]
  An extra rule with just prerequisites can be used to give a few extra prerequisites to many files at once.

And I second that there should be separate rule for .d files. It's names in many projects are deps or depend.

Body:
To generate dependency files I can use something like this to generate dependency files:

-include $(patsubst %.cpp,build/%.d,$(SRC))
build/%.o: %.cpp
    $(CC) $(CXXFLAGS) -c -o $@ $<
    $(CC) $(CXXFLAGS) -MM -MT $@ -MF $(patsubst %.o,%.d,%@) $<

This generates everything and puts both the object and dependency files into the build dir where I want them. But this makes two dependency lines for the <file>.o targets, one from the -include rule and with all the header dependencies, and one which is from the pattern rule. Will this get interpreted correctly, i.e. when a header is modified, the object will be recompiled via the command specified for the pattern rule?

Edit: So this approach does in fact work quite well. I guess I'd like somebody to provide an answer which gives me some insight into what it is exactly that make does in these situations. For instance, what if a different command was given for both rules for the same target? My guess would be that it gives an error since it wouldn't be obvious which command to execute.


问:
What is the fastest way to populate one pandas dataframe based on values from another pandas dataframe?
I have a pandas dataframe position

```<code>        row    column
  1      3     Brazil
  2      6     USA
  3      3     USA
  4      7     Canada
</code>```

and another x

```<code>        Brazil   Canada  USA
  1     False    False   False
  2     False    False   False
  3     False    False   False
  4     False    False   False
  5     False    False   False
  6     False    False   False
  7     False    False   False
</code>```

I want to populate the second one based on the values from the first one, so the result is:

```<code>        Brazil   Canada  USA
  1     False    False   False
  2     False    False   False
  3     True     False   True
  4     False    False   False
  5     False    False   False
  6     False    False   True
  7     False    True    False
</code>```

I'm doing that using iterrows()

```<code>  for i, r in positions.iterrows():
      x.at[r['row'],r['column']] = True
</code>```

Is there a faster way to do that?

答:
You can pivot the positions table:

```<code>s = (df.assign(dummy=True).set_index(['row','column'])
       ['dummy'].unstack(fill_value=False)
    )
x |= s
</code>```

Output:

```<code>   Brazil  Canada    USA
1   False   False  False
2   False   False  False
3    True   False   True
4   False   False  False
5   False   False  False
6   False   False   True
7   False    True  False
</code>```

Body:
I have a pandas dataframe position

        row    column
  1      3     Brazil
  2      6     USA
  3      3     USA
  4      7     Canada

and another x

        Brazil   Canada  USA
  1     False    False   False
  2     False    False   False
  3     False    False   False
  4     False    False   False
  5     False    False   False
  6     False    False   False
  7     False    False   False

I want to populate the second one based on the values from the first one, so the result is:

        Brazil   Canada  USA
  1     False    False   False
  2     False    False   False
  3     True     False   True
  4     False    False   False
  5     False    False   False
  6     False    False   True
  7     False    True    False

I'm doing that using iterrows()

  for i, r in positions.iterrows():
      x.at[r['row'],r['column']] = True

Is there a faster way to do that?

Body:
You can pivot the positions table:

s = (df.assign(dummy=True).set_index(['row','column'])
       ['dummy'].unstack(fill_value=False)
    )
x |= s

Output:

   Brazil  Canada    USA
1   False   False  False
2   False   False  False
3    True   False   True
4   False   False  False
5   False   False  False
6   False   False   True
7   False    True  False


问:
How can I access my downloads folder using Dockerfile?
I have to following Dockerfile to create a container image. This works fine for some scripts.

```<code>FROM python:3.8-slim-buster

COPY . /work

WORKDIR /work

RUN apt-get update

RUN apt-get upgrade -y

RUN pip install -r requirements.txt
</code>```

However, I have a script which requires access to my local downloads folder. My understanding is that the container creates an image with the copy of the directory that the Dockerfile sits within. However, I do not understand how to give the container access to my downloads folder outside of this. Any help would be great!

答:
I have a solution using docker-compose

docker-compose

```<code>version: "3"

services:
  myservice:
    build:
      context: . # DOT (".") means in this root directory, have a dockerfile to build the image
    image: myDownloadAppBuild:latest
    container_name: myDownloadApp
    volumes:
      - <HOST-MACHINE-DIR-PATH>:/app # HOST_MACHINE-DIR-PATH E:/MyDownload AND /app path inside container which points to your download folder.
    ports:
      - <HOST-PORT-ID>:<CONTAINER-PORT-ID>
</code>```

dockerfile

```<code>FROM python:3.8-slim-buster
COPY . /work
WORKDIR /work
VOLUME /app #YOUR DOWNLOAD DIR PATH
RUN apt-get update
RUN apt-get upgrade -y
RUN pip install -r requirements.txt
</code>```

OR You already have an imperative command to do this

```<code>docker run <OTHER OPTIONS> -v /path/to/downloads:E:/myAppDownloadMount
</code>```

Body:
I have to following Dockerfile to create a container image. This works fine for some scripts.

FROM python:3.8-slim-buster

COPY . /work

WORKDIR /work

RUN apt-get update

RUN apt-get upgrade -y

RUN pip install -r requirements.txt

However, I have a script which requires access to my local downloads folder. My understanding is that the container creates an image with the copy of the directory that the Dockerfile sits within. However, I do not understand how to give the container access to my downloads folder outside of this. Any help would be great!

Body:
I have a solution using docker-compose

docker-compose

version: "3"

services:
  myservice:
    build:
      context: . # DOT (".") means in this root directory, have a dockerfile to build the image
    image: myDownloadAppBuild:latest
    container_name: myDownloadApp
    volumes:
      - <HOST-MACHINE-DIR-PATH>:/app # HOST_MACHINE-DIR-PATH E:/MyDownload AND /app path inside container which points to your download folder.
    ports:
      - <HOST-PORT-ID>:<CONTAINER-PORT-ID>

dockerfile

FROM python:3.8-slim-buster
COPY . /work
WORKDIR /work
VOLUME /app #YOUR DOWNLOAD DIR PATH
RUN apt-get update
RUN apt-get upgrade -y
RUN pip install -r requirements.txt

OR You already have an imperative command to do this

docker run <OTHER OPTIONS> -v /path/to/downloads:E:/myAppDownloadMount


问:
Json To Java list and verify
Hi, how I can retrieve information from my Json file to a list.
And check the information in the list

Please note that the number of servers may increase

My Json file

```<code>{
  "servers": {
    "server1": {
      "name": "Name1",
      "allowStart": true,
      "realIP": "0.0.0.0"
    },
    "server2": {
      "name": "Name2",
      "allowStart": false,
      "realIP": "0.0.0.0"
    },
    "server3": {
      "name": "Name3",
      "allowStart": true,
      "realIP": "0.0.0.0"
    }
  }
}
</code>```

i want to get something like this:

```<code>
String serverip = "0.0.0.0";

/* code for get ListServer.name ListServer.allowStart ListServer.realIP */

if (ListServer.realIP == serverip && ListServer.allowStart == true){

    System.out.print(ListServer.name + " allow to start? " + ListServer.allowStart);

}
</code>```

Ideally it would be good to recover this json file from a site.

Help me please.

答:
Your json file contains three separate server objects within the servers node. They are not in the form of a jsonArray. However,
You can try something like this with Gson dependency. Then you can map them to a List separately or to a new object and store in a List

```<code>    Gson g = new Gson();

    LinkedTreeMap o = ( LinkedTreeMap ) g.fromJson( x, Object.class ); // x is the variable holding json variable
    LinkedTreeMap servers = ( LinkedTreeMap ) o.get( "servers" );
    LinkedTreeMap server1 = ( LinkedTreeMap ) servers.get( "server1" );

    // if needed iterate the key set, here I am only providing values of a single entry
    System.out.println( "serverName : " + server1.get( "name" ) );
    System.out.println( "allowStart : " + server1.get( "allowStart" ) );
    System.out.println( "realIP : " + server1.get( "realIP" ) );
</code>```

Title: Json To Java list and verify

Body:
Hi, how I can retrieve information from my Json file to a list.
And check the information in the list

Please note that the number of servers may increase

My Json file

{
  "servers": {
    "server1": {
      "name": "Name1",
      "allowStart": true,
      "realIP": "0.0.0.0"
    },
    "server2": {
      "name": "Name2",
      "allowStart": false,
      "realIP": "0.0.0.0"
    },
    "server3": {
      "name": "Name3",
      "allowStart": true,
      "realIP": "0.0.0.0"
    }
  }
}

i want to get something like this:

String serverip = "0.0.0.0";

/* code for get ListServer.name ListServer.allowStart ListServer.realIP */

if (ListServer.realIP == serverip && ListServer.allowStart == true){

    System.out.print(ListServer.name + " allow to start? " + ListServer.allowStart);

}

Ideally it would be good to recover this json file from a site.

Help me please.

Body:
Your json file contains three separate server objects within the servers node. They are not in the form of a jsonArray. However,
You can try something like this with Gson dependency. Then you can map them to a List separately or to a new object and store in a List

    Gson g = new Gson();

    LinkedTreeMap o = ( LinkedTreeMap ) g.fromJson( x, Object.class ); // x is the variable holding json variable
    LinkedTreeMap servers = ( LinkedTreeMap ) o.get( "servers" );
    LinkedTreeMap server1 = ( LinkedTreeMap ) servers.get( "server1" );

    // if needed iterate the key set, here I am only providing values of a single entry
    System.out.println( "serverName : " + server1.get( "name" ) );
    System.out.println( "allowStart : " + server1.get( "allowStart" ) );
    System.out.println( "realIP : " + server1.get( "realIP" ) );


问:
Changing the format of date in the Date object
I am using Bootstrap 4. I am writing two functions "saveIssue" and "fetchIssue". The saveIssue function takes the details of the form filled through HTML and stores them in localStorage.In the function, it also notes the time of saving the issues with the new Date() object. fetchIssue function takes the details from localStorage and displays them on screen. While displaying the date of issue obtained through the new Date() object, it is displaying it in the format like 2020-06-02T14:51:21.482Z. How can I just display it in a more generalized form and also not int GMT?

1)fetchIssue function

```<code>function fetchIssues () {
var issues=JSON.parse(localStorage.getItem('issues'));
var I;
for(i=0;i<issues.length;i++)
{
    var id=issues[i].id;
    var description=issues[i].description;
    var severity=issues[i].severity;
    var assignto=issues[i].assignto;
    var status=issues[i].status;
    var deadline=issues[i].deadline;
    var started=issues[i].started;
if(status=="Open")
  {
document.getElementById('issuesList').innerHTML+='<div class="well">'+'<h5> Issue ID : '+ id+'</h5>'
+'<h4><span class="label label-info">'+ status +'</span></h4>'
+'<h3><span class="glyphicon glyphicon-paste"></span>'+"     "+  description + '</h3>'
+ '<p><span class="glyphicon glyphicon-bell"></span>'+'     '+ severity+'         '
+'<span class="glyphicon glyphicon-user"></span>'+'     '+ assignto + '</p>'+'   '
+'<p><span class="glyphicon glyphicon-calendar"></span>'+'  '+'Issued on :'+' '+started+'</p>'
+'<p><span class="glyphicon glyphicon-time"></span>'+'  '+'Deadline :'+' '+deadline+'</p>'
+'<button type="button" class="btn btn-success" onclick="Closed(\''+i+'\')">Close</button>'+' '
+'<button type="button" class="btn btn-danger" onclick="Deleted(\''+i+'\')">Delete</button>'+' '
+'<button type="button" class="btn btn-primary" onclick="Reassigned(\''+i+'\')">Reassign</button>';
  }

else
  {
document.getElementById('issuesList').innerHTML+='<div class="well">'+'<h5> Issue ID : '+ id+'</h5>'
+'<h4><span class="label label-warning">'+ status +'</span></h4>'
+'<h3><span class="glyphicon glyphicon-paste"></span>'+"     "+  description + '</h3>'
+ '<p><span class="glyphicon glyphicon-time"></span>'+'     '+ severity+'         '
+'<span class="glyphicon glyphicon-user"></span>'+'     '+ assignto + '</p>'
+'<button type="button" class="btn btn-info" onclick="Reopened(\''+i+'\')">Reopen</button>'+' '
+'<button type="button" class="btn btn-primary" onclick="Reassigned(\''+i+'\')">Reassign</button>';
  }
}
}
</code>```

2)saveIssue funtion

```<code>function saveIssue(e)
{
var id=chance.guid()
var description = document.getElementById("issueDescInput").value;
var severity = document.getElementById("issueSeverityInput").value;
var assignto = document.getElementById("issueAssignedToInput").value;
var status="Open";
var deadline=document.getElementById("deadline").value;
var started=new Date();
var summarized={
    id,
    description,
    severity,
    assignto,
    status,
    deadline,
    started
}
var final=JSON.stringify(summarized);
if(localStorage.getItem('issues')===null)
{
    var issues=[];
    issues.push(summarized);
    var finalissues=JSON.stringify(issues);
    localStorage.setItem('issues', finalissues);
    alert("saved");
}
else
{
    var issues = JSON.parse(localStorage.getItem('issues'));
    issues.push(summarized);
    var finalissues=JSON.stringify(issues);
    localStorage.setItem('issues', finalissues);
    alert("saved");
}
e.preventDefault();
window.location.reload();
}
</code>```

答:
You can also use these methods.

```<code>var started = new Date();
</code>```

Date.toLocaleDateString()

```<code>console.log(started.toLocaleDateString()); // "02/06/2020"
</code>```

Date.toDateString()

```<code>console.log(started.toDateString()); // "Tue Jun 02 2020"
</code>```

Date.toISOString()

```<code>console.log(started.toISOString()); // "2020-06-02T15:27:29.780Z"
</code>```

Date.toLocaleString()

```<code>console.log(started.toLocaleString()); // "02/06/2020, 23:27:29"
</code>```

Body:
I am using Bootstrap 4. I am writing two functions "saveIssue" and "fetchIssue". The saveIssue function takes the details of the form filled through HTML and stores them in localStorage.In the function, it also notes the time of saving the issues with the new Date() object. fetchIssue function takes the details from localStorage and displays them on screen. While displaying the date of issue obtained through the new Date() object, it is displaying it in the format like 2020-06-02T14:51:21.482Z. How can I just display it in a more generalized form and also not int GMT?

1)fetchIssue function

function fetchIssues () {
var issues=JSON.parse(localStorage.getItem('issues'));
var I;
for(i=0;i<issues.length;i++)
{
    var id=issues[i].id;
    var description=issues[i].description;
    var severity=issues[i].severity;
    var assignto=issues[i].assignto;
    var status=issues[i].status;
    var deadline=issues[i].deadline;
    var started=issues[i].started;
if(status=="Open")
  {
document.getElementById('issuesList').innerHTML+='
'+'
 Issue ID : '+ id+'
'
+'
'+ status +'
'
+'
'+"     "+  description + '
'
+ '
'+'     '+ severity+'         '
+''+'     '+ assignto + '
'+'   '
+'
'+'  '+'Issued on :'+' '+started+'
'
+'
'+'  '+'Deadline :'+' '+deadline+'
'
+'<button type="button" class="btn btn-success" onclick="Closed(\''+i+'\')">Close</button>'+' '
+'<button type="button" class="btn btn-danger" onclick="Deleted(\''+i+'\')">Delete</button>'+' '
+'<button type="button" class="btn btn-primary" onclick="Reassigned(\''+i+'\')">Reassign</button>';
  }

else
  {
document.getElementById('issuesList').innerHTML+='
'+'
 Issue ID : '+ id+'
'
+'
'+ status +'
'
+'
'+"     "+  description + '
'
+ '
'+'     '+ severity+'         '
+''+'     '+ assignto + '
'
+'<button type="button" class="btn btn-info" onclick="Reopened(\''+i+'\')">Reopen</button>'+' '
+'<button type="button" class="btn btn-primary" onclick="Reassigned(\''+i+'\')">Reassign</button>';
  }
}
}

2)saveIssue funtion

function saveIssue(e)
{
var id=chance.guid()
var description = document.getElementById("issueDescInput").value;
var severity = document.getElementById("issueSeverityInput").value;
var assignto = document.getElementById("issueAssignedToInput").value;
var status="Open";
var deadline=document.getElementById("deadline").value;
var started=new Date();
var summarized={
    id,
    description,
    severity,
    assignto,
    status,
    deadline,
    started
}
var final=JSON.stringify(summarized);
if(localStorage.getItem('issues')===null)
{
    var issues=[];
    issues.push(summarized);
    var finalissues=JSON.stringify(issues);
    localStorage.setItem('issues', finalissues);
    alert("saved");
}
else
{
    var issues = JSON.parse(localStorage.getItem('issues'));
    issues.push(summarized);
    var finalissues=JSON.stringify(issues);
    localStorage.setItem('issues', finalissues);
    alert("saved");
}
e.preventDefault();
window.location.reload();
}

Body:
You can also use these methods.

var started = new Date();

Date.toLocaleDateString()

console.log(started.toLocaleDateString()); // "02/06/2020"

Date.toDateString()

console.log(started.toDateString()); // "Tue Jun 02 2020"

Date.toISOString()

console.log(started.toISOString()); // "2020-06-02T15:27:29.780Z"

Date.toLocaleString()

console.log(started.toLocaleString()); // "02/06/2020, 23:27:29"


问:
ionic/angular app with firebase unit test (jasmine) issue
Currently I am developing an app using Ionic and Firebase, and I am facing an issue with the unit tests.
Following the error message:

Cannot read property 'subscribe' of undefined

The error happens when instantiating the component.

See bellow, pieces of the code:

The contructor of the component:

```<code>constructor(
    public angularFire: AngularFireAuth,
    public router: Router,
    private ngZone: NgZone,
    private authService: FirebaseAuthService
  ) {
    console.log("Constructor Initialized");
    this.signInForm = new FormGroup({
      email: new FormControl('', Validators.compose([
        Validators.required,
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
      ])),
      password: new FormControl('', Validators.compose([
        Validators.minLength(6),
        Validators.required
      ]))
    });

    this.authRedirectResult = this.authService.getRedirectResult()
    .subscribe(result => {
      if (result.user) {
        this.redirectLoggedUserToProfilePage();
      } else if (result.error) {
        this.submitError = result.error;
      }
    });

    console.log("Constructor Done");
  }
</code>```

The issue happen on getRedirectFunction method that is on my auth service:

```<code>redirectResult: Subject<any> = new Subject<any>();

getRedirectResult(): Observable<any> {
    return this.redirectResult.asObservable();
  }
</code>```

And my test until now:

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { AngularFireAuth } from '@angular/fire/auth';
import { Router } from '@angular/router';

import { SignInPage } from './sign-in.page';
import { FirebaseAuthService } from '../firebase-auth.service';

describe('SignInPage', () => {
  let component: SignInPage;
  let fixture: ComponentFixture<SignInPage>;
  let service: FirebaseAuthService;

  const authStub: FirebaseAuthService = jasmine.createSpyObj('authStub', ['getAuthInstance', 'getRedirectResult']);

  const fireStub: any = {
    authState: {},
    auth: {
      signInWithEmailAndPassword() {
        return Promise.resolve();
      }
    }
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SignInPage ],
      imports: [IonicModule.forRoot()],
      providers:[
        { provide: FirebaseAuthService, useValue: authStub},
        { provide: AngularFireAuth, useValue: fireStub},
        { provide: Router, useClass: class { navigate = jasmine.createSpy('navigate') } }
    ],
    }).compileComponents();
    service = TestBed.get(FirebaseAuthService);
    fixture = TestBed.createComponent(SignInPage);
    component = fixture.debugElement.componentInstance;
    fixture.detectChanges();
  }));

  it('should create the component', async(() => {
    expect(component).toBeTruthy();
  }));
});
</code>```

Any ideas about why the method getRedirectFunction is returning undefined? Note that I am mocking it..

I will apolozige now about the question but I am new with from-end code so any advise is welcome.

Thanks in advance!

答:
Your authStub spy declares a getRedirectResult method but it does not have a mock implementation. So when called in place of your real function it does nothing (returns undefined)

You can provide a return value like this:

```<code>authStub.getRedirectResult.and.returnValue(of());
</code>```

Body:
Currently I am developing an app using Ionic and Firebase, and I am facing an issue with the unit tests.
Following the error message:

Cannot read property 'subscribe' of undefined

The error happens when instantiating the component.

See bellow, pieces of the code:

The contructor of the component:

constructor(
    public angularFire: AngularFireAuth,
    public router: Router,
    private ngZone: NgZone,
    private authService: FirebaseAuthService
  ) {
    console.log("Constructor Initialized");
    this.signInForm = new FormGroup({
      email: new FormControl('', Validators.compose([
        Validators.required,
        Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
      ])),
      password: new FormControl('', Validators.compose([
        Validators.minLength(6),
        Validators.required
      ]))
    });

    this.authRedirectResult = this.authService.getRedirectResult()
    .subscribe(result => {
      if (result.user) {
        this.redirectLoggedUserToProfilePage();
      } else if (result.error) {
        this.submitError = result.error;
      }
    });

    console.log("Constructor Done");
  }

The issue happen on getRedirectFunction method that is on my auth service:

redirectResult: Subject<any> = new Subject<any>();

getRedirectResult(): Observable<any> {
    return this.redirectResult.asObservable();
  }

And my test until now:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { AngularFireAuth } from '@angular/fire/auth';
import { Router } from '@angular/router';

import { SignInPage } from './sign-in.page';
import { FirebaseAuthService } from '../firebase-auth.service';

describe('SignInPage', () => {
  let component: SignInPage;
  let fixture: ComponentFixture<SignInPage>;
  let service: FirebaseAuthService;

  const authStub: FirebaseAuthService = jasmine.createSpyObj('authStub', ['getAuthInstance', 'getRedirectResult']);

  const fireStub: any = {
    authState: {},
    auth: {
      signInWithEmailAndPassword() {
        return Promise.resolve();
      }
    }
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SignInPage ],
      imports: [IonicModule.forRoot()],
      providers:[
        { provide: FirebaseAuthService, useValue: authStub},
        { provide: AngularFireAuth, useValue: fireStub},
        { provide: Router, useClass: class { navigate = jasmine.createSpy('navigate') } }
    ],
    }).compileComponents();
    service = TestBed.get(FirebaseAuthService);
    fixture = TestBed.createComponent(SignInPage);
    component = fixture.debugElement.componentInstance;
    fixture.detectChanges();
  }));

  it('should create the component', async(() => {
    expect(component).toBeTruthy();
  }));
});

Any ideas about why the method getRedirectFunction is returning undefined? Note that I am mocking it..

I will apolozige now about the question but I am new with from-end code so any advise is welcome.

Thanks in advance!

Body:
Your authStub spy declares a getRedirectResult method but it does not have a mock implementation. So when called in place of your real function it does nothing (returns undefined)

You can provide a return value like this:

authStub.getRedirectResult.and.returnValue(of());


答:
I will do crosstab with update

```<code>x.update(pd.crosstab(df.row,df.column).eq(1))
x
Out[44]:
  Brazil Canada    USA
1  False  False  False
2  False  False  False
3   True  False   True
4  False  False  False
5  False  False  False
6  False  False   True
7  False   True  False
</code>```

Title: What is the fastest way to populate one pandas dataframe based on values from another pandas dataframe?

Body:
I will do crosstab with update

x.update(pd.crosstab(df.row,df.column).eq(1))
x
Out[44]:
  Brazil Canada    USA
1  False  False  False
2  False  False  False
3   True  False   True
4  False  False  False
5  False  False  False
6  False  False   True
7  False   True  False


问:
XMLHttpRequest.responseURL in IE
I'm looking a way to get XMLHttpRequest.responseURL in IE.

My code (myreq.responseURL) works correctly using Chrome, Firefox, and Safari.

Is there a way to do the same (also using another function) in IE?

Any help is really appreciated.

答:
If you have the response, you can use response.config. So in my case, this worked:

```<code>const originalUrl = response.request.responseURL || response.config.url
</code>```

Title: XMLHttpRequest.responseURL in IE

Body:
If you have the response, you can use response.config. So in my case, this worked:

const originalUrl = response.request.responseURL || response.config.url


问:
SQL (greater and equal) and (lesser or Equal) on datetime
Ok,  here is a super dumb SQL problem,

This is my Where Statement:

```<code>WHERE OM_ORDER_DATE >= CONVERT(datetime,'24/5/2020',104)
</code>```

Results of the query:

```<code>OM_ROWID    OM_ORDER_DATE
1           2020-05-24 01:19:44.360
2           2020-05-26 20:29:47.303
3           2020-05-27 20:36:39.707
4           2020-06-29 00:00:00.000
</code>```

now if I change my query to

```<code>WHERE OM_ORDER_DATE >= CONVERT(datetime,'24/5/2020',104) AND OM_ORDER_DATE <= CONVERT(datetime,'24/5/2020',104)
</code>```

I do not get any results, any help is appreciated

答:
This is because you have a time component.  One method is:

```<code>WHERE OM_ORDER_DATE >= '2020-05-24' AND
      OM_ORDER_DATE < DATEADD(DAY, 1, '2020-05-24')
</code>```

Or more simply:

```<code>WHERE CONVERT(DATE, OM_ORDER_DATE) = '2020-05-24'
</code>```

This is also index-safe -- one of the very few cases where a function on a column is also index-compatible.

Body:
Ok,  here is a super dumb SQL problem,

This is my Where Statement:

WHERE OM_ORDER_DATE >= CONVERT(datetime,'24/5/2020',104)

Results of the query:

OM_ROWID    OM_ORDER_DATE
1           2020-05-24 01:19:44.360
2           2020-05-26 20:29:47.303
3           2020-05-27 20:36:39.707
4           2020-06-29 00:00:00.000

now if I change my query to

WHERE OM_ORDER_DATE >= CONVERT(datetime,'24/5/2020',104) AND OM_ORDER_DATE <= CONVERT(datetime,'24/5/2020',104)

I do not get any results, any help is appreciated

Body:
This is because you have a time component.  One method is:

WHERE OM_ORDER_DATE >= '2020-05-24' AND
      OM_ORDER_DATE < DATEADD(DAY, 1, '2020-05-24')

Or more simply:

WHERE CONVERT(DATE, OM_ORDER_DATE) = '2020-05-24'

This is also index-safe -- one of the very few cases where a function on a column is also index-compatible.


问:
Are there any good captchas specifically designed for mobile apps?
Is there anything that is less intimidating than recaptcha for mobile apps?  My app is built with JQuery Mobile and most likely will never be available on the desktop.  I am hoping there is a more visual captcha that would not require typing.  So far most visual captchas I have found seem too large for a mobile app.  I am mainly looking for something that is visual and small enough to fit within the average mobile screen.  Any suggestions would be appreciated, I would even be willing to build something from scratch if someone has a good idea.</p>

答:
Damn, that MotionCAPTCHA link appears to be dead. I found this question looking for similar things to what we're working on at my current company.

We have a HumanDetect mobile SDK trying to solve a similar problem. The overall idea is we grab sensor data from the phone so we can determine "bot or not". You ask the SDK for a token, then send that token along with your REST request, and then that token can be validated. If everything works as expected only a mobile device in the hands of a human should produce a token that validates as "not a bot".

It's native code, not using the browser. For the end-user's point of view, it is transparent, the user isn't asked to perform any action.


问:
search tree in scala
I'm trying to put my first steps into Scala, and to practice I took a look at the google code jam storecredit excersize. I tried it in java first, which went well enough, and now I'm trying to port it to Scala. Now with the java collections framework, I could try to do a straight syntax conversion, but I'd end up writing java in scala, and that kind of defeats the purpose. In my Java implementation, I have a PriorityQueue that I empty into a Deque, and pop the ends off untill we have bingo. This all uses mutable collections, which give me the feeling is very 'un-scala'. What I think would be a more functional approach is to construct a datastructure that can be traversed both from highest to lowest, and from lowest to highest. Am I on the right path? Are there any suitable datastructures supplied in the Scala libraries, or should I roll my own here?

EDIT: full code of the much simpler version in Java. It should run in O(max(credit,inputchars)) and has become:

```<code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class StoreCredit {
    private static BufferedReader in;

    public static void main(String[] args) {
        in = new BufferedReader(new InputStreamReader(System.in));
        try {
            int numCases = Integer.parseInt(in.readLine());
            for (int i = 0; i < numCases; i++) {
                solveCase(i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void solveCase(int casenum) throws NumberFormatException,
            IOException {
        int credit = Integer.parseInt(in.readLine());
        int numItems = Integer.parseInt(in.readLine());
        int itemnumber = 0;
        int[] item_numbers_by_price = new int[credit];
        Arrays.fill(item_numbers_by_price, -1); // makes this O(max(credit,
                                                // items)) instead of O(items)
        int[] read_prices = readItems();
        while (itemnumber < numItems) {
            int next_price = read_prices[itemnumber];
            if (next_price <= credit) {
                if (item_numbers_by_price[credit - next_price] >= 0) {
                    // Bingo! DinoDNA!
                    printResult(new int[] {
                            item_numbers_by_price[credit - next_price],
                            itemnumber }, casenum);
                    break;
                }
                item_numbers_by_price[next_price] = itemnumber;
            }
            itemnumber++;
        }
    }

    private static int[] readItems() throws IOException {
        String line = in.readLine();
        String[] items = line.split(" "); // uh-oh, now it's O(max(credit,
                                          // inputchars))
        int[] result = new int[items.length];
        for (int i = 0; i < items.length; i++) {
            result[i] = Integer.parseInt(items[i]);
        }
        return result;
    }

    private static void printResult(int[] result, int casenum) {
        int one;
        int two;
        if (result[0] > result[1]) {
            one = result[1];
            two = result[0];
        } else {
            one = result[0];
            two = result[1];
        }
        one++;
        two++;
        System.out.println(String.format("Case #%d: %d %d", casenum + 1, one,
                two));
    }

}
</code>```

答:
I'm wondering what you are trying to accomplish using sophisticated data structures such as PriorityQueue and Deque for a problem such as this. It can be solved with a pair of nested loops:

```<code>for {
  i <- 2 to I
  j <- 1 until i
  if i != j && P(i-1) + P(j - 1) == C
} println("Case #%d: %d %d" format (n, j, i))
</code>```

Worse than linear, better than quadratic. Since the items are not sorted, and sorting them would require O(nlogn), you can't do much better than this -- as far as I can see.

Actually, having said all that, I now have figured a way to do it in linear time. The trick is that, for every number p you find, you know what its complement is: C - p. I expect there are a few ways to explore that -- I have so far thought of two.

One way is to build a map with O(n) characteristics, such as a bitmap or a hash map. For each element, make it point to its index. One then only has to find an element for which its complement also has an entry in the map. Trivially, this could be as easily as this:

```<code>val PM = P.zipWithIndex.toMap
val (p, i) = PM find { case (p, i) => PM isDefinedAt C - p }
val j = PM(C - p)
</code>```

However, that won't work if the number is equal to its complement. In other words, if there are two p such that p + p == C. There are quite a few such cases in the examples. One could then test for that condition, and then just use indexOf and lastIndexOf -- except that it is possible that there is only one p such that p + p == C, in which case that wouldn't be the answer either.

So I ended with something more complex, that tests the existence of the complement at the same time the map is being built. Here's the full solution:

```<code>import scala.io.Source

object StoreCredit3 extends App {
  val source = if (args.size > 0) Source fromFile args(0) else Source.stdin
  val input = source getLines ()
  val N = input.next.toInt
  1 to N foreach { n =>
    val C = input.next.toInt
    val I = input.next.toInt
    val Ps = input.next split ' ' map (_.toInt)
    val (_, Some((p1, p2))) = Ps.zipWithIndex.foldLeft((Map[Int, Int](), None: Option[(Int, Int)])) {
      case ((map, None), (p, i)) =>
        if (map isDefinedAt C - p) map -> Some(map(C - p) -> (i + 1))
        else (map updated (p, i + 1), None)
      case (answer, _) => answer
    }

    println("Case #%d: %d %d" format (n, p1, p2))
  }
}
</code>```

Title: search tree in scala

Body:
I'm trying to put my first steps into Scala, and to practice I took a look at the google code jam storecredit excersize. I tried it in java first, which went well enough, and now I'm trying to port it to Scala. Now with the java collections framework, I could try to do a straight syntax conversion, but I'd end up writing java in scala, and that kind of defeats the purpose. In my Java implementation, I have a PriorityQueue that I empty into a Deque, and pop the ends off untill we have bingo. This all uses mutable collections, which give me the feeling is very 'un-scala'. What I think would be a more functional approach is to construct a datastructure that can be traversed both from highest to lowest, and from lowest to highest. Am I on the right path? Are there any suitable datastructures supplied in the Scala libraries, or should I roll my own here?

EDIT: full code of the much simpler version in Java. It should run in O(max(credit,inputchars)) and has become:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class StoreCredit {
    private static BufferedReader in;

    public static void main(String[] args) {
        in = new BufferedReader(new InputStreamReader(System.in));
        try {
            int numCases = Integer.parseInt(in.readLine());
            for (int i = 0; i < numCases; i++) {
                solveCase(i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void solveCase(int casenum) throws NumberFormatException,
            IOException {
        int credit = Integer.parseInt(in.readLine());
        int numItems = Integer.parseInt(in.readLine());
        int itemnumber = 0;
        int[] item_numbers_by_price = new int[credit];
        Arrays.fill(item_numbers_by_price, -1); // makes this O(max(credit,
                                                // items)) instead of O(items)
        int[] read_prices = readItems();
        while (itemnumber < numItems) {
            int next_price = read_prices[itemnumber];
            if (next_price <= credit) {
                if (item_numbers_by_price[credit - next_price] >= 0) {
                    // Bingo! DinoDNA!
                    printResult(new int[] {
                            item_numbers_by_price[credit - next_price],
                            itemnumber }, casenum);
                    break;
                }
                item_numbers_by_price[next_price] = itemnumber;
            }
            itemnumber++;
        }
    }

    private static int[] readItems() throws IOException {
        String line = in.readLine();
        String[] items = line.split(" "); // uh-oh, now it's O(max(credit,
                                          // inputchars))
        int[] result = new int[items.length];
        for (int i = 0; i < items.length; i++) {
            result[i] = Integer.parseInt(items[i]);
        }
        return result;
    }

    private static void printResult(int[] result, int casenum) {
        int one;
        int two;
        if (result[0] > result[1]) {
            one = result[1];
            two = result[0];
        } else {
            one = result[0];
            two = result[1];
        }
        one++;
        two++;
        System.out.println(String.format("Case #%d: %d %d", casenum + 1, one,
                two));
    }

}

Body:
I'm wondering what you are trying to accomplish using sophisticated data structures such as PriorityQueue and Deque for a problem such as this. It can be solved with a pair of nested loops:

for {
  i <- 2 to I
  j <- 1 until i
  if i != j && P(i-1) + P(j - 1) == C
} println("Case #%d: %d %d" format (n, j, i))

Worse than linear, better than quadratic. Since the items are not sorted, and sorting them would require O(nlogn), you can't do much better than this -- as far as I can see.

Actually, having said all that, I now have figured a way to do it in linear time. The trick is that, for every number p you find, you know what its complement is: C - p. I expect there are a few ways to explore that -- I have so far thought of two.

One way is to build a map with O(n) characteristics, such as a bitmap or a hash map. For each element, make it point to its index. One then only has to find an element for which its complement also has an entry in the map. Trivially, this could be as easily as this:

val PM = P.zipWithIndex.toMap
val (p, i) = PM find { case (p, i) => PM isDefinedAt C - p }
val j = PM(C - p)

However, that won't work if the number is equal to its complement. In other words, if there are two p such that p + p == C. There are quite a few such cases in the examples. One could then test for that condition, and then just use indexOf and lastIndexOf -- except that it is possible that there is only one p such that p + p == C, in which case that wouldn't be the answer either.

So I ended with something more complex, that tests the existence of the complement at the same time the map is being built. Here's the full solution:

import scala.io.Source

object StoreCredit3 extends App {
  val source = if (args.size > 0) Source fromFile args(0) else Source.stdin
  val input = source getLines ()
  val N = input.next.toInt
  1 to N foreach { n =>
    val C = input.next.toInt
    val I = input.next.toInt
    val Ps = input.next split ' ' map (_.toInt)
    val (_, Some((p1, p2))) = Ps.zipWithIndex.foldLeft((Map[Int, Int](), None: Option[(Int, Int)])) {
      case ((map, None), (p, i)) =>
        if (map isDefinedAt C - p) map -> Some(map(C - p) -> (i + 1))
        else (map updated (p, i + 1), None)
      case (answer, _) => answer
    }

    println("Case #%d: %d %d" format (n, p1, p2))
  }
}


问:
Matlab-GUI warning when using parfeval(): "Unable to save App Designer app object."
I am trying to call parallel functions within my Matlab-GUI by pushing a startbutton.

For the beginning I tried to call one single function ("ReadTwinCAT") but I'm always getting the following error-message:

"Warning: Unable to save App Designer app object. Save not supported
  for matlab.apps.AppBase objects."

As I thought I already used parallel functions like this within a GUI, I don't know what I am doing wrong...

Matlab-App-Designer Code:

```<code>properties (Access = private)
    running_state = 0; % Description
    tcClient;
    db_conn;
end

methods (Access = private)

    function ReadTwinCAT(app)

        while app.running_state == 1
            disp('running')
            pause(0.1)
        end
        disp('stopped')

    end
end

% Callbacks that handle component events
methods (Access = private)

    function StartButtonPushed(app, event)

       app.running_state = 1;

       pool = gcp(); %Initialize pool of workers

       parfeval(pool, @ReadTwinCAT, 0, app); %Call parallel function

    end
end
</code>```

答:
Ok, I think I found an answer from Mathworks staff:
https://www.mathworks.com/matlabcentral/answers/366576-will-there-be-a-support-of-the-parallel-toolbox-in-matlab-app-designer#comment_720548

Note the limitation of accessing the app object inside the parfor loop or any other functions called though Parallel Computing Toolbox.

If you need to access properties of your app pass them down as values directly, e.g. instead of

```<code>b = [0,0];
parfor i=1:2
    b(i) = app.myprop*2
end
</code>```

use

```<code>tmp = app.myprop;
b = [0,0];
parfor i=1:2
    b(i) = tmp*2
end
</code>```

So it seems that you can't access (or it would seem set) the properties of the app object within a parallelized function. If you want to get data out, you'll probably have to set up a communication system using parallel.pool.DataQueue. Your example is tough to parallelize. A better option would probably be to add a listener to your running_state property, and/or use a timer function.

The major downside of this is that the function you call from the timer is not actually parallelized - it runs in the same thread, so if you have a lot of computation in ReadTwinCAT, I think it will cause lag/unresponsiveness in the GUI.

I've modified your code to use a timer instead of parfeval:

```<code>properties (Access = private)
    running_state = 0; % Description
    runningTimer;
    tcClient;
    db_conn;
end

methods (Access = private)

    function ReadTwinCAT(app, varargin)
        if app.running_state == 1
            disp('running')
        else
            stop(app.runningTimer);
            disp('stopped')
        end
    end

end

% Callbacks that handle component events
methods (Access = private)

    function StartButtonPushed(app, event)
        app.running_state = 1;

        app.runningTimer = timer;
        app.runningTimer.Period = 0.1;
        app.runningTimer.ExecutionMode = 'fixedRate';
        app.runningTimer.TimerFcn = @app.ReadTwinCAT;
        start(app.runningTimer)
    end

end
</code>```

Body:
I am trying to call parallel functions within my Matlab-GUI by pushing a startbutton.

For the beginning I tried to call one single function ("ReadTwinCAT") but I'm always getting the following error-message:

"Warning: Unable to save App Designer app object. Save not supported
  for matlab.apps.AppBase objects."

As I thought I already used parallel functions like this within a GUI, I don't know what I am doing wrong...

Matlab-App-Designer Code:

properties (Access = private)
    running_state = 0; % Description
    tcClient;
    db_conn;
end

methods (Access = private)

    function ReadTwinCAT(app)

        while app.running_state == 1
            disp('running')
            pause(0.1)
        end
        disp('stopped')

    end
end

% Callbacks that handle component events
methods (Access = private)

    function StartButtonPushed(app, event)

       app.running_state = 1;

       pool = gcp(); %Initialize pool of workers

       parfeval(pool, @ReadTwinCAT, 0, app); %Call parallel function

    end
end

Body:
Ok, I think I found an answer from Mathworks staff:
https://www.mathworks.com/matlabcentral/answers/366576-will-there-be-a-support-of-the-parallel-toolbox-in-matlab-app-designer#comment_720548

Note the limitation of accessing the app object inside the parfor loop or any other functions called though Parallel Computing Toolbox.

If you need to access properties of your app pass them down as values directly, e.g. instead of

b = [0,0];
parfor i=1:2
    b(i) = app.myprop*2
end

use

tmp = app.myprop;
b = [0,0];
parfor i=1:2
    b(i) = tmp*2
end

So it seems that you can't access (or it would seem set) the properties of the app object within a parallelized function. If you want to get data out, you'll probably have to set up a communication system using parallel.pool.DataQueue. Your example is tough to parallelize. A better option would probably be to add a listener to your running_state property, and/or use a timer function.

The major downside of this is that the function you call from the timer is not actually parallelized - it runs in the same thread, so if you have a lot of computation in ReadTwinCAT, I think it will cause lag/unresponsiveness in the GUI.

I've modified your code to use a timer instead of parfeval:

properties (Access = private)
    running_state = 0; % Description
    runningTimer;
    tcClient;
    db_conn;
end

methods (Access = private)

    function ReadTwinCAT(app, varargin)
        if app.running_state == 1
            disp('running')
        else
            stop(app.runningTimer);
            disp('stopped')
        end
    end

end

% Callbacks that handle component events
methods (Access = private)

    function StartButtonPushed(app, event)
        app.running_state = 1;

        app.runningTimer = timer;
        app.runningTimer.Period = 0.1;
        app.runningTimer.ExecutionMode = 'fixedRate';
        app.runningTimer.TimerFcn = @app.ReadTwinCAT;
        start(app.runningTimer)
    end

end