问:
What is causing inefficiency when parsing this QuerySet into tuples?
In a django app, I am attempting to parse a Queryset, representing individual time-series values x from n sensors, into tuples (t, x1, x2 ... xn), and thence into a json object in the format specified by google charts here: https://developers.google.com/chart/interactive/docs/gallery/linechart

None values are used as placeholders if no value was logged for a given timestamp from a particular sensor

The page load time is significant for a QuerySet with ~6500 rows (~3 seconds, run locally)

It's significantly longer on the server

http://54.162.202.222/pulogger/simpleview/?device=test

Profiling indicates that 99.9% of the time is spent on _winapi.WaitForSingleObject, (which I can't interpret) and manual profiling with a timer indicates that the server-side culprit is the while loop that iterates over the QuerySet and groups the values into tuples (line 23 in my code example)

Results are as-follows:

basic gets (took 5ms)

queried data (took 0ms)

split data by sensor (took 981ms)

prepared column labels/types (took 0ms)

prepared json (took 27ms)

created context (took 0ms)

For the sake of completeness, the timing function is as follows:

```<code>def print_elapsed_time(ref_datetime, description):
    print('{} (took {}ms)'.format(description, floor((datetime.now()-ref_datetime).microseconds/1000)))
    return datetime.now()
</code>```

The code performing the processing and generating the view is as-follows:

```<code>def simpleview(request):
    time_marker = datetime.now()
    device_name = request.GET['device']
    device = Datalogger.objects.get(device_name=device_name)

    sensors = Sensor.objects.filter(datalogger=device).order_by('pk')
    sensor_count = len(sensors)  # should be no worse than count() since already-evaluated and cached.  todo: confirm

    #assign each sensor an index for the tuples (zero is used for time/x-axis)
    sensor_indices = {}
    for idx, sensor in enumerate(sensors, start=1):
        sensor_indices.update({sensor.sensor_name:idx})

    time_marker = print_elapsed_time(time_marker, 'basic gets')

    # process data into timestamp-grouped tuples accessible by sensor-index ([0] is timestamp)
    raw_data = SensorDatum.objects.filter(sensor__datalogger__device_name=device_name).order_by('timestamp', 'sensor')
    data = []
    data_idx = 0

    time_marker = print_elapsed_time(time_marker, 'queried data')

    while data_idx < len(raw_data):
        row_list = [raw_data[data_idx].timestamp]
        row_list.extend([None]*sensor_count)
        row_idx = 1

        while data_idx < len(raw_data) and raw_data[data_idx].timestamp == row_list[0]:
            row_idx = sensor_indices.get(raw_data[data_idx].sensor.sensor_name)
            row_list[row_idx] = raw_data[data_idx].value
            data_idx += 1
        data.append(tuple(row_list))

    time_marker = print_elapsed_time(time_marker, 'split data by sensor')

    column_labels = ['Time']
    column_types = ["datetime"]
    for sensor in sensors:
        column_labels.append(sensor.sensor_name)
        column_types.append("number")

    time_marker = print_elapsed_time(time_marker, 'prepared column labels/types')

    gchart_json = prepare_data_for_gchart(column_labels, column_types, data)

    time_marker = print_elapsed_time(time_marker, 'prepared json')

    context = {
        'device': device_name,
        'sensor_count': sensor_count,
        'sensor_indices': sensor_indices,
        'gchart_json': gchart_json,
    }

    time_marker = print_elapsed_time(time_marker, 'created context')

    return render(request, 'pulogger/simpleTimeSeriesView.html', context)
</code>```

I'm new to python, so I expect that there's a poor choice of operation/collection I've used somewhere.  Unless I'm blind, it should run in O(n).

Obviously this isn't the whole problem since it only accounts for a part of the apparent load-time, but I figure this is a good place to start.

答:
The "queried data" section is taking 0ms because that section is constructing the query, not executing your query against the database.

The query is being executed when it gets to this line: while data_idx < len(raw_data):, because to calculate the length of the iterable it must evaluate it.

So it may not be the loop that's taking most of the time, it's probably the query execution and evaluation.  You can evaluate the query before the main loop by wrapping the queryset in a list(), this will allow your time_marker to display how long the query is actually taking to execute.

Do you need the queryset evaluated to a model?  Alternatively you could use .values() or .values_list() to return an actual list of values, which skips serializing the query results into Model objects.  By doing this you also avoid having to return all the columns from the database, you only return the ones you need.

You could potential remove the table join in this query SensorDatum.objects.filter(sensor__datalogger__device_name=device_name).order_by('timestamp', 'sensor') by denormalizing your schema (if possible) to have the device_name field on the sensor.

Body:
In a django app, I am attempting to parse a Queryset, representing individual time-series values x from n sensors, into tuples (t, x1, x2 ... xn), and thence into a json object in the format specified by google charts here: https://developers.google.com/chart/interactive/docs/gallery/linechart

None values are used as placeholders if no value was logged for a given timestamp from a particular sensor

The page load time is significant for a QuerySet with ~6500 rows (~3 seconds, run locally)

It's significantly longer on the server

http://54.162.202.222/pulogger/simpleview/?device=test

Profiling indicates that 99.9% of the time is spent on _winapi.WaitForSingleObject, (which I can't interpret) and manual profiling with a timer indicates that the server-side culprit is the while loop that iterates over the QuerySet and groups the values into tuples (line 23 in my code example)

Results are as-follows:

basic gets (took 5ms)

queried data (took 0ms)

split data by sensor (took 981ms)

prepared column labels/types (took 0ms)

prepared json (took 27ms)

created context (took 0ms)

For the sake of completeness, the timing function is as follows:

def print_elapsed_time(ref_datetime, description):
    print('{} (took {}ms)'.format(description, floor((datetime.now()-ref_datetime).microseconds/1000)))
    return datetime.now()

The code performing the processing and generating the view is as-follows:

def simpleview(request):
    time_marker = datetime.now()
    device_name = request.GET['device']
    device = Datalogger.objects.get(device_name=device_name)

    sensors = Sensor.objects.filter(datalogger=device).order_by('pk')
    sensor_count = len(sensors)  # should be no worse than count() since already-evaluated and cached.  todo: confirm

    #assign each sensor an index for the tuples (zero is used for time/x-axis)
    sensor_indices = {}
    for idx, sensor in enumerate(sensors, start=1):
        sensor_indices.update({sensor.sensor_name:idx})

    time_marker = print_elapsed_time(time_marker, 'basic gets')

    # process data into timestamp-grouped tuples accessible by sensor-index ([0] is timestamp)
    raw_data = SensorDatum.objects.filter(sensor__datalogger__device_name=device_name).order_by('timestamp', 'sensor')
    data = []
    data_idx = 0

    time_marker = print_elapsed_time(time_marker, 'queried data')

    while data_idx < len(raw_data):
        row_list = [raw_data[data_idx].timestamp]
        row_list.extend([None]*sensor_count)
        row_idx = 1

        while data_idx < len(raw_data) and raw_data[data_idx].timestamp == row_list[0]:
            row_idx = sensor_indices.get(raw_data[data_idx].sensor.sensor_name)
            row_list[row_idx] = raw_data[data_idx].value
            data_idx += 1
        data.append(tuple(row_list))

    time_marker = print_elapsed_time(time_marker, 'split data by sensor')

    column_labels = ['Time']
    column_types = ["datetime"]
    for sensor in sensors:
        column_labels.append(sensor.sensor_name)
        column_types.append("number")

    time_marker = print_elapsed_time(time_marker, 'prepared column labels/types')

    gchart_json = prepare_data_for_gchart(column_labels, column_types, data)

    time_marker = print_elapsed_time(time_marker, 'prepared json')

    context = {
        'device': device_name,
        'sensor_count': sensor_count,
        'sensor_indices': sensor_indices,
        'gchart_json': gchart_json,
    }

    time_marker = print_elapsed_time(time_marker, 'created context')

    return render(request, 'pulogger/simpleTimeSeriesView.html', context)

I'm new to python, so I expect that there's a poor choice of operation/collection I've used somewhere.  Unless I'm blind, it should run in O(n).

Obviously this isn't the whole problem since it only accounts for a part of the apparent load-time, but I figure this is a good place to start.


来源: stackexchange

问:
How to save grayscale image in Python?
I am trying to save a grayscale image using matplotlib savefig(). I find that the png file which is saved after the use of matplotlib savefig() is a bit different from the output image which is showed when the code runs. The output image which is generated when the code is running contains more details than the saved figure.

How can I save the output plot in such a manner that all details are stored in the output image?

My my code is given below:

```<code>import cv2
import matplotlib.pyplot as plt

plt.figure(1)
img_DR = cv2.imread(‘image.tif',0)
edges_DR = cv2.Canny(img_DR,20,40)
plt.imshow(edges_DR,cmap = 'gray')
plt.savefig('DR.png')
plt.show()
</code>```

The input file (‘image.tif’) can be found from here.

Following is the output image which is generated when the code is running:

Below is the saved image:

Although the two aforementioned images denote the same picture, one can notice that they are slightly different. A keen look at the circular periphery of the two images shows that they are different.

答:
Since you are using cv2 to load the image, why not using it also to save it.
I think the command you are looking for is :

cv2.imwrite('gray.jpg', gray_image)

ContentLicense: CC BY-SA 4.0

Title: How to save grayscale image in Python?

Body:
I am trying to save a grayscale image using matplotlib savefig(). I find that the png file which is saved after the use of matplotlib savefig() is a bit different from the output image which is showed when the code runs. The output image which is generated when the code is running contains more details than the saved figure.

How can I save the output plot in such a manner that all details are stored in the output image?

My my code is given below:

import cv2
import matplotlib.pyplot as plt

plt.figure(1)
img_DR = cv2.imread(‘image.tif',0)
edges_DR = cv2.Canny(img_DR,20,40)
plt.imshow(edges_DR,cmap = 'gray')
plt.savefig('DR.png')
plt.show()

The input file (‘image.tif’) can be found from here.

Following is the output image which is generated when the code is running:

Below is the saved image:

Although the two aforementioned images denote the same picture, one can notice that they are slightly different. A keen look at the circular periphery of the two images shows that they are different.


问:
Do I still need to install MySQL in Django virtual env while I already have MySQL in my machine?
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from  python by :

```<code>import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
</code>```

then I download django frame and try to use it to connect mysql  ,  what I do is :

create a my.cnf file content is :

```<code>[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
</code>```

change settings.py to :

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
        },
    }
}
</code>```

then run :

```<code>python manage.py runserver
</code>```

but got a error :

```<code>django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
</code>```

Do I still need to install an addition MySQL in Django virtual env?  if I can use the existing MySQL instead

答: Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip.</p>

Body:
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from  python by :

import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')

then I download django frame and try to use it to connect mysql  ,  what I do is :

create a my.cnf file content is :

[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8

change settings.py to :

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
        },
    }
}

then run :

python manage.py runserver

but got a error :

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?

Do I still need to install an addition MySQL in Django virtual env?  if I can use the existing MySQL instead


答:
I guess you dont have mysqlclient python library installed in virtual environment.

Since you are using Windows, you need to download and install mysqlclient python library from here

Title: Do I still need to install MySQL in Django virtual env while I already have MySQL in my machine?


问:
ng-2 chart not responsive
I am using ng2-charts. I have a date tab where I can choose today, week, month and particular dates. According to that my data varies in chart. My datas are working well according to date. But my chart is not responsive enough to plot the values corresponding to the dates.

Today View: https://ibb.co/bHDdwLG  data[100,105,120],

Week View: https://ibb.co/SfWxyMr   data[100,105,120,140]

If you see week's view, before completing value:140 graph cuts down it's not responsive it seems.

Code

TS

```<code>public lineChartOptions: any = {
responsive: true,
};

getabc(start?: moment.Moment, end?: moment.Moment) {
this.abcService.getabc(this.token, start, end).subscribe(
  data => {
    this.a = data.map(k => k.a);
    this.date_time = data.map(k => k.datetime.toLocaleTimeString());
    this.lineChartData = [
      { data: this.a, label: 'abc' }
  ]
  this.lineChartLabels=this.date_time
    console.log(this.a);
    console.log(this.date_time); // I can get the values correctly
   according to the date
  }
);
}
</code>```

HTML

```<code><div style="display: block;" *ngIf="lineChartData.length > 0">
<canvas baseChart width="400" height="180" style="margin-
left:5%;margin-top: 5%;" [datasets]="lineChartData"
[labels]="lineChartLabels" [options]="lineChartOptions"
[colors]="lineChartColors" [legend]="lineChartLegend"
[chartType]="lineChartType" (chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
</div>
</code>```

答:
Here's the solution (class must be called chart)

```<code><div class="chart">
      <canvas baseChart
              [datasets]="barChartData"
              [labels]="barChartLabels"
              [options]="chartOptions"
              legend="true"
              chartType="bar">
      </canvas>
    </div>
</code>```

CSS

```<code>.chart {
  position: relative;
  min-height: unset;
}
</code>```

Title: ng-2 chart not responsive

Body:
I am using ng2-charts. I have a date tab where I can choose today, week, month and particular dates. According to that my data varies in chart. My datas are working well according to date. But my chart is not responsive enough to plot the values corresponding to the dates.

Today View: https://ibb.co/bHDdwLG  data[100,105,120],

Week View: https://ibb.co/SfWxyMr   data[100,105,120,140]

If you see week's view, before completing value:140 graph cuts down it's not responsive it seems.

Code

TS

public lineChartOptions: any = {
responsive: true,
};

getabc(start?: moment.Moment, end?: moment.Moment) {
this.abcService.getabc(this.token, start, end).subscribe(
  data => {
    this.a = data.map(k => k.a);
    this.date_time = data.map(k => k.datetime.toLocaleTimeString());
    this.lineChartData = [
      { data: this.a, label: 'abc' }
  ]
  this.lineChartLabels=this.date_time
    console.log(this.a);
    console.log(this.date_time); // I can get the values correctly
   according to the date
  }
);
}

HTML

 0">
<canvas baseChart width="400" height="180" style="margin-
left:5%;margin-top: 5%;" [datasets]="lineChartData"
[labels]="lineChartLabels" [options]="lineChartOptions"
[colors]="lineChartColors" [legend]="lineChartLegend"
[chartType]="lineChartType" (chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>

Body:
Here's the solution (class must be called chart)

<div class="chart">
      <canvas baseChart
              [datasets]="barChartData"
              [labels]="barChartLabels"
              [options]="chartOptions"
              legend="true"
              chartType="bar">
      </canvas>
    </div>

CSS

.chart {
  position: relative;
  min-height: unset;
}


问:
How to generate hash512 in pre-request from request that has {{variables}} in uri
So I m working on API when i need to set x-auth header for every request in PRE-REQUEST script.

I have variables in my request url i.e {{baseUrl}}{{basePath}}{{businessID}}/users?name={{userName}}......etc

I need to take whole address and add secretKey variable to the end of address, then get hash512 from it.

I was able to achieve that if i have no variables in my address i.e.: dummy.com/12321-e213-21-3e?name=John

I did this by :

```<code>var secret = "1234qwerHr2";
var url = request.url.slice(9); //sliced because I don't need to include baseUrl to hash

var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(url+secret));
</code>```

This will return the desired result.

Here is what I logged when trying the same code with variables

```<code>console.log(url); =>>>>>>> asePath}}{{businessID}}/users?name={{userName}}......etc
</code>```

All variables defined , that`s for sure

Basically question is : how to get url with values of variables using var url = request.url; I need not {{businessID}}/users?name={{userName}} but 12321-e213-21-3e?name=John

答:
I lost source where i found it. Somewhere on postman github issue thread

```<code>var secret = pm.globals.get("devSecretKey");

pm.myUtility = {
    interpolateVariable: function (str) {
        return str.replace(/\{\{([^}]+)\}\}/g, function (match, $1) {
            // console.log(match)
            let result = match; //default to return the exactly the same matchd variable string
            if ($1) {
                let realone = pm.variables.get($1);
                if (realone) {
                    result = realone
                }
            }
            return result;
        });
    },
    getUrl: function () {
        let url = pm.request.url.getRaw();
        url = this.interpolateVariable(url)
        let {
            Url
        } = require('postman-collection')
        return new Url(url);
    },
    getUrlTest: function () {
        let url = pm.request.url.getRaw();
        url = this.interpolateVariable(url)
        // let {
        //     Url
        // } = require('postman-collection')
        //return new Url(url);
        return pm.request.url.parse(url);
    }

}

var requestPath = pm.myUtility.getUrl().getPath();
var requestQuery =pm.myUtility.getUrl().getQueryString();
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(requestPath+"?"+requestQuery+secret)); //I added '?' because when you use getQueryString() i does not have '?' before query

pm.environment.set("tempAuthHash", hashedPayload);// use this in your header
</code>```

This function he wrote is converting your {{variable}} to 'variableValue'
No need to change anything in his functions if you are not good with coding. Guy who created it has golden hands. Just place in your pre request

Body:
So I m working on API when i need to set x-auth header for every request in PRE-REQUEST script.

I have variables in my request url i.e {{baseUrl}}{{basePath}}{{businessID}}/users?name={{userName}}......etc

I need to take whole address and add secretKey variable to the end of address, then get hash512 from it.

I was able to achieve that if i have no variables in my address i.e.: dummy.com/12321-e213-21-3e?name=John

I did this by :

var secret = "1234qwerHr2";
var url = request.url.slice(9); //sliced because I don't need to include baseUrl to hash

var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(url+secret));

This will return the desired result.

Here is what I logged when trying the same code with variables

console.log(url); =>>>>>>> asePath}}{{businessID}}/users?name={{userName}}......etc

All variables defined , that`s for sure

Basically question is : how to get url with values of variables using var url = request.url; I need not {{businessID}}/users?name={{userName}} but 12321-e213-21-3e?name=John

Body:
I lost source where i found it. Somewhere on postman github issue thread

var secret = pm.globals.get("devSecretKey");

pm.myUtility = {
    interpolateVariable: function (str) {
        return str.replace(/\{\{([^}]+)\}\}/g, function (match, $1) {
            // console.log(match)
            let result = match; //default to return the exactly the same matchd variable string
            if ($1) {
                let realone = pm.variables.get($1);
                if (realone) {
                    result = realone
                }
            }
            return result;
        });
    },
    getUrl: function () {
        let url = pm.request.url.getRaw();
        url = this.interpolateVariable(url)
        let {
            Url
        } = require('postman-collection')
        return new Url(url);
    },
    getUrlTest: function () {
        let url = pm.request.url.getRaw();
        url = this.interpolateVariable(url)
        // let {
        //     Url
        // } = require('postman-collection')
        //return new Url(url);
        return pm.request.url.parse(url);
    }

}

var requestPath = pm.myUtility.getUrl().getPath();
var requestQuery =pm.myUtility.getUrl().getQueryString();
var hashedPayload = CryptoJS.enc.Hex.stringify(CryptoJS.SHA512(requestPath+"?"+requestQuery+secret)); //I added '?' because when you use getQueryString() i does not have '?' before query

pm.environment.set("tempAuthHash", hashedPayload);// use this in your header

This function he wrote is converting your {{variable}} to 'variableValue'
No need to change anything in his functions if you are not good with coding. Guy who created it has golden hands. Just place in your pre request


答:
Yes you have to reinstall the mysql for django in the virtual environment again. For windows you can do:-

pip install django mysqlclient


问:
Facelets: new location for "xmlns:h" and "xmlns:f"?
I'm trying to use some xml name spaces here,

```<code><html xmlns="http://www.w3.org/1999/xhtml"
              xmlns:h="http://java.sun.com/jsf/html"
              xmlns:a4j="http://richfaces.org/a4j"
              xmlns:rich="http://richfaces.org/rich"
              xmlns:f="http://java.sun.com/jsf/core"
                >
</code>```

but since Oracle've eaten Java, the http://java.sun.com/jsf/* links are broken now (thank you Oracle).

Anybody knows their new locations? Or which maven dependency solves that (com.sun.facelets.jsf-facelets, javax.faces.jsf-api, javax.faces.jsf-impl don't)?

答:
It doesn't matter that they are broken. These are just identifiers and no links (though they look like links).

If your page doesn't work, it's rather a problem of missing libraries.

Replacing "Sun" with "Oracle" won't work either ;-)

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use some xml name spaces here,

but since Oracle've eaten Java, the http://java.sun.com/jsf/* links are broken now (thank you Oracle).

Anybody knows their new locations? Or which maven dependency solves that (com.sun.facelets.jsf-facelets, javax.faces.jsf-api, javax.faces.jsf-impl don't)?


答:
Basically you need to put the following code on top of both manage.py and wsgi.py like this:

```<code>#!/usr/bin/env python
import os
import sys
<b>import pymysql</b>
<b>pymysql.install_as_MySQLdb()</b>
# rest of the code
</code>```

Also you need to ensure you have pymysql installed in your virtual environment.

FYI: Using pymysql might not work in django>=2.2 properly. You will find some solution which might work, like mentioned in this ticket. Also, django does not support pymysql as mysql connector officially(ticket #12500, #22391).

Body:
Basically you need to put the following code on top of both manage.py and wsgi.py like this:

#!/usr/bin/env python
import os
import sys
import pymysql
pymysql.install_as_MySQLdb()
# rest of the code

Also you need to ensure you have pymysql installed in your virtual environment.

FYI: Using pymysql might not work in django>=2.2 properly. You will find some solution which might work, like mentioned in this ticket. Also, django does not support pymysql as mysql connector officially(ticket #12500, #22391).


问:
Angular 7 - deploy workspace applications (projects) in isolation
In my cli-generated workspace I have the root-application which lazy loads numerous application (sitting in the projects folder).

When I run "ng build root-application", all the chunks are placed in the dist/root-application folder, and I could copy this folder across to my server, and we're good to go.

However, these applications are almost never at the same stage in their development life-cycle (still in development, some being QA'd), and I want to de able to deploy them in isolation, rather than having to deploy the whole site.

Does anyone have a strategy for this?

答: Ok Doing All this work manually will be a cumbersome process, there are tools which can help automate this work. Nx (nrwl.io) can help you solve your problem, it uses a Monorepo approach where you can build multiple angular/react application/libraries in one workspace, all this application can be independent of each other. To get started click here. To read about why to use Nx click here. Nx has been designed by Victor Savkin (Core Angular Team Member who has designed lots of features for angular)</p>


问:
How can I Access to variable in public in laravel
I have a project in Laravel and I want to show a article form my database in index.blade

so in Controller I get the article and keep it in a variable
problem is this : the image of that article is not in index.blade and it is in css in public directory so How Can I change it with that image that I've gotten form database? in my css file you can see that image as a url

Contorller

```<code> public function home(Request $request)
{
    $headerIntroduction=Category::where('name','معرفی کسب و کار')->get()->first()->articles()->get()->values()[1];

    return view('app.index',compact('headerIntroduction'));
</code>```

css

```<code>#slider-section, #home-section{
background-image:url(../../images/app/slider/1.jpg);
background-repeat:no-repeat;
background-size:cover;
background-color:#282f1f;
position:relative;
color:#fff;
padding: 130px 0;
</code>```

}

答:
You should have your css for beackground-image in the balde file.

```<code><style>
#slider-section, #home-section{
background-image:url({{$headerIntroduction->image}});
background-repeat:no-repeat;
background-size:cover;
background-color:#282f1f;
position:relative;
color:#fff;
padding: 130px 0;
}
</style>
</code>```

Here image is the name of column in your DB table.

Body:
I have a project in Laravel and I want to show a article form my database in index.blade

so in Controller I get the article and keep it in a variable
problem is this : the image of that article is not in index.blade and it is in css in public directory so How Can I change it with that image that I've gotten form database? in my css file you can see that image as a url

Contorller

 public function home(Request $request)
{
    $headerIntroduction=Category::where('name','معرفی کسب و کار')->get()->first()->articles()->get()->values()[1];

    return view('app.index',compact('headerIntroduction'));

css

#slider-section, #home-section{
background-image:url(../../images/app/slider/1.jpg);
background-repeat:no-repeat;
background-size:cover;
background-color:#282f1f;
position:relative;
color:#fff;
padding: 130px 0;

}

Body:
You should have your css for beackground-image in the balde file.

<style>
#slider-section, #home-section{
background-image:url({{$headerIntroduction->image}});
background-repeat:no-repeat;
background-size:cover;
background-color:#282f1f;
position:relative;
color:#fff;
padding: 130px 0;
}
</style>

Here image is the name of column in your DB table.


问:
Transmission parameter into <?= ?>

I have list <?= total ?> length 7 and I want get element in list push array different.

I'm running google app script and page error

"ReferenceError: "k" is not defined. (line 328, file "Code")"

```<code>var tmp = [];

for(var k = 0; k < <?= total.length ?> ; k ++){

 tmp.push(<?= total[k] ?>);

}
</code>```

答:
Scriptlets (<?= ... ?>) gets executed first before the client side script does. You might want to do this instead

```<code>var tmp = [];

<? for( var k = 0; k < total.length; k++ ){ ?>
      tmp.push(<?= total[k] ?>);
<? } ?>
</code>```

Title: Transmission parameter into <?= ?>

Body:
I have list <?= total ?> length 7 and I want get element in list push array different.

I'm running google app script and page error

"ReferenceError: "k" is not defined. (line 328, file "Code")"

var tmp = [];

for(var k = 0; k < <?= total.length ?> ; k ++){

 tmp.push(<?= total[k] ?>);

}

Body:
Scriptlets (<?= ... ?>) gets executed first before the client side script does. You might want to do this instead

var tmp = [];

<? for( var k = 0; k < total.length; k++ ){ ?>
      tmp.push(<?= total[k] ?>);
<? } ?>


问:
What does DoCmd.FindRecord reveal and how to get it?
What does DoCmd.FindRecord actually do? Does it have an output or value, and how do I see it?

I am in Access VBA and trying to find a specific table record based upon an individual name.

Why have FindRecord if it does not yield a Yes/No or True/False?

I am using a form to allow/input an employee's details in a shift schedule.

```<code>X = "Jim3"
DoCmd.FindRecord "X", , False, , True
</code>```

答:
https://learn.microsoft.com/en-us/office/vba/api/access.docmd.findrecord

When a procedure calls the FindRecord method, Access searches for the specified data in the records (the order of the search is determined by the setting of the Search argument). When Access finds the specified data, the data is selected in the record.

The FindRecord method does not return a value indicating its success or failure. To determine whether a value exists in a recordset, use the FindFirst, FindNext, FindPrevious, or FindLast method of the Recordset object. These methods set the value of the NoMatch property to True if the specified value is not found.

Note that you'd have to use DoCmd.FindRecord X (not "X") to find anything.

Body:
What does DoCmd.FindRecord actually do? Does it have an output or value, and how do I see it?

I am in Access VBA and trying to find a specific table record based upon an individual name.

Why have FindRecord if it does not yield a Yes/No or True/False?

I am using a form to allow/input an employee's details in a shift schedule.

X = "Jim3"
DoCmd.FindRecord "X", , False, , True


问:
MongoDB index construction in the background as the default behavior for all connections
We need to override the default value for background option in createIndex method of MongoDB, to true, so that if a developer forgets to pass the option, it runs in the background.

Is there any way to override this option at the driver, connection or any other levels?

Specifically for, but not only limited to, Java.

答:
Using Spring Data MongoDB you'd have to override the ensureIndex method of IndexOperations via DefaultIndexOperations and return that one for MongoOperations#indexOps(...).

By doing so you'll be able to capture all index creation, also the annotation driven one.

@Configuration
public class Config extends AbstractMongoConfiguration {

    @Override
    public MongoTemplate mongoTemplate() throws Exception {

        return new MongoTemplate(mongoDbFactory(), mappingMongoConverter()) {

            @Override
            public IndexOperations indexOps(Class<?> entityClass) {

                return new DefaultIndexOperations(this, getCollectionName(entityClass), entityClass) {

                    @Override
                    public String ensureIndex(IndexDefinition indexDefinition) {

                        if(indexDefinition instanceof Index) {
                            ((Index)indexDefinition).background();
                        }

                        return super.ensureIndex(indexDefinition);
                    }
                };
            }
        };
    }

    // ...
}
```

<p>For annotations you may also use your own custom annotation pinning the <code>background</code> attribute to a fixed value without the option to override it, while opening up modifiable values via <code>@AliasFor</code>.<br>
Something like in the sample below works without having to customize <code>MongoOperations</code> / <code>IndexOperations</code>.</p>

<pre class="lang-java prettyprint-override"><code>@Indexed(background = true) // fix attribute values here
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
public @interface ComposedIndexedAnnotation {

    @AliasFor(annotation = Indexed.class, attribute = "unique")
    boolean unique() default false;

    @AliasFor(annotation = Indexed.class, attribute = "name")
    String indexName() default "";
}
</code>```

Body:
Using Spring Data MongoDB you'd have to override the ensureIndex method of IndexOperations via DefaultIndexOperations and return that one for MongoOperations#indexOps(...).

By doing so you'll be able to capture all index creation, also the annotation driven one.

@Configuration
public class Config extends AbstractMongoConfiguration {

    @Override
    public MongoTemplate mongoTemplate() throws Exception {

        return new MongoTemplate(mongoDbFactory(), mappingMongoConverter()) {

            @Override
            public IndexOperations indexOps(Class<?> entityClass) {

                return new DefaultIndexOperations(this, getCollectionName(entityClass), entityClass) {

                    @Override
                    public String ensureIndex(IndexDefinition indexDefinition) {

                        if(indexDefinition instanceof Index) {
                            ((Index)indexDefinition).background();
                        }

                        return super.ensureIndex(indexDefinition);
                    }
                };
            }
        };
    }

    // ...
}

For annotations you may also use your own custom annotation pinning the background attribute to a fixed value without the option to override it, while opening up modifiable values via @AliasFor.

Something like in the sample below works without having to customize MongoOperations / IndexOperations.

@Indexed(background = true) // fix attribute values here
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
public @interface ComposedIndexedAnnotation {

    @AliasFor(annotation = Indexed.class, attribute = "unique")
    boolean unique() default false;

    @AliasFor(annotation = Indexed.class, attribute = "name")
    String indexName() default "";
}


问:
Android bitmap saving error. saving image is wrong , update gallery after saving image to sd card
I created a function to save a selected image from gallery.I realize that when the image is saved for the first time it is ok.But if the process start again, it seems that the image is saved (with the same name) but the image don't change in the explorer.It just keep the old bitmap image.I tested on two different devices but the same result.Actually on an Infinix hot 7 but same result.

```<code>public static String saveImage(Bitmap bitmap, File[] folders, File file, Context context) {

    for (File folder:folders) {
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    if (file.exists ()) {
        file.delete();
    }

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
</code>```

You can see that i chose a photo of green nature but it registers an old red tree photo

答:
After saving the image in gallery you should update image to the system for gallery and file explorer</p>

```<code>sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));
</code>```

Body:
I created a function to save a selected image from gallery.I realize that when the image is saved for the first time it is ok.But if the process start again, it seems that the image is saved (with the same name) but the image don't change in the explorer.It just keep the old bitmap image.I tested on two different devices but the same result.Actually on an Infinix hot 7 but same result.

public static String saveImage(Bitmap bitmap, File[] folders, File file, Context context) {

    for (File folder:folders) {
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    if (file.exists ()) {
        file.delete();
    }

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

You can see that i chose a photo of green nature but it registers an old red tree photo

Body:
After saving the image in gallery you should update image to the system for gallery and file explorer

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myNewFile)));


问:
Unchecked Cast warning: cast Object to Generic
I'm trying to implement a DoublyLinkedList with genenerics.
According to Java Docs, the argument of remove() method must be an Object.

If I try to cast Object o to T data, I will get the warning: Unchecked Cast: 'Java.lang.Object' to 'T'.

```<code>public boolean remove(Object o) {
        T data = (T) o; // warning here
...
}
</code>```

To avoid this, I have to suppress the warning by "@SuppressWarning("Unchecked")"

```<code>@SuppressWarnings("unchecked")
public boolean remove(Object o) {
        T data = (T) o;
...
}
</code>```

My understanding is every T is an Object but not every Object is a T. That's why it shows the warning.

But what if when I use my DoublyLinkedList class, I'm 100% sure the Object argument is a T, is there a way to avoid the warning or @suppresswarning is the only choice here?

If my assumption is not correct, what is the correct way to cast an Object to a T?
Thank you.

答:
The only way to avoid the @SuppressWarning would be to have a field holding the element's class:

```<code>public class DoublyLinkedList<T> ... {
    ...
    private final Class<T> elementClass;

    ...

    public DoublyLinkedList(Class<T> elementClass) {
        this.clazz = elementClass;
    }

    ...
    public boolean remove(Object o) {
        T data = elementClass.cast(o);
        ...
    }
    ...
}
</code>```

Body:
I'm trying to implement a DoublyLinkedList with genenerics.
According to Java Docs, the argument of remove() method must be an Object.

If I try to cast Object o to T data, I will get the warning: Unchecked Cast: 'Java.lang.Object' to 'T'.

public boolean remove(Object o) {
        T data = (T) o; // warning here
...
}

To avoid this, I have to suppress the warning by "@SuppressWarning("Unchecked")"

@SuppressWarnings("unchecked")
public boolean remove(Object o) {
        T data = (T) o;
...
}

My understanding is every T is an Object but not every Object is a T. That's why it shows the warning.

But what if when I use my DoublyLinkedList class, I'm 100% sure the Object argument is a T, is there a way to avoid the warning or @suppresswarning is the only choice here?

If my assumption is not correct, what is the correct way to cast an Object to a T?
Thank you.

Body:
The only way to avoid the @SuppressWarning would be to have a field holding the element's class:

public class DoublyLinkedList<T> ... {
    ...
    private final Class<T> elementClass;

    ...

    public DoublyLinkedList(Class<T> elementClass) {
        this.clazz = elementClass;
    }

    ...
    public boolean remove(Object o) {
        T data = elementClass.cast(o);
        ...
    }
    ...
}


问:
Hide and show on button click in angularjs
I want to hide the value by default and show the value when I click on button for 1st time. When you click on the same button for a 2nd time, it should hide the value instead of displaying. Vice versa it should happen.

Here is my html

```<code><!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>AngularJS</title>
  <script
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js">
  </script>
  <script th:src="@{/main.js}"></script>
<head>
<body ng-app="EmployeeManagement" ng-controller="EmployeeController">
<input type="button" value="Show Angular" ng-click="ShowHide()"/>
 <div ng-show = "IsVisible"> yes </div>
</body>
</html>
</code>```

here is my JS File:

```<code>var app = angular.module("EmployeeManagement", []);
app.controller("EmployeeController", function($scope, $http) {
 $scope.ShowHide = function(){
     $scope.IsVisible =  true;
 }
</code>```

can anyone tell me how to achieve this scenario?

答:
You should use negation of $scope.IsVisible on button click. So that if it is visible then it will hide and if it is hide then visible:

Try this:

<!DOCTYPE HTML>

  <title>AngularJS</title>

<input type="button" value="Show Angular" ng-click="ShowHide()"/>

 yes

```

Body:
I want to hide the value by default and show the value when I click on button for 1st time. When you click on the same button for a 2nd time, it should hide the value instead of displaying. Vice versa it should happen.

Here is my html

<!DOCTYPE HTML>

  <title>AngularJS</title>

<input type="button" value="Show Angular" ng-click="ShowHide()"/>

 yes

here is my JS File:

var app = angular.module("EmployeeManagement", []);
app.controller("EmployeeController", function($scope, $http) {
 $scope.ShowHide = function(){
     $scope.IsVisible =  true;
 }

can anyone tell me how to achieve this scenario?

Body:
You should use negation of $scope.IsVisible on button click. So that if it is visible then it will hide and if it is hide then visible:

Try this:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>AngularJS</title>
  <script
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js">
  </script>
  <script >
  var app = angular.module("EmployeeManagement", []);
    app.controller("EmployeeController", function($scope, $http) {
    $scope.ShowHide = function(){
        $scope.IsVisible =  !$scope.IsVisible;
    }
  })
 </script>
<head>
<body ng-app="EmployeeManagement" ng-controller="EmployeeController">
<input type="button" value="Show Angular" ng-click="ShowHide()"/>
 <div ng-show = "IsVisible"> yes </div>
</body>
</html>


问:
Create Component without folder
I need to create a component without the folder. I am using Angular-Cli command ng g c testing to create the component. But, the command creates an folder wrapper for the newly created component.

答:
You can create components anywhere inside the app folder without using commands
if you are using any IDE for development like Visual Studio Code or Atom. Use the new file icon or  New File option from File Menu,

but I would suggest you use a folder structure for better maintenance

Title: Create Component without folder


问:
How to get the version of ionic framework?
I wonder how to check the version of ionic. If I do ionic -v I get back 1.4.3

Can that be? Wasn't 1.0.0 just released?

答:
Ionic projects structure are similar as Angular projects, you can get use

ionic info

command to Print project, system, and environment information.

This command is an easy way to share information about your setup. If applicable, be sure to run ionic info within your project directory to display even more information.

We may use --json after ionic info to print system/environment info in JSON format

```<code>ionic info --json
</code>```

Body:
Ionic projects structure are similar as Angular projects, you can get use

ionic info

command to Print project, system, and environment information.

This command is an easy way to share information about your setup. If applicable, be sure to run ionic info within your project directory to display even more information.

We may use --json after ionic info to print system/environment info in JSON format

ionic info --json


问:
elasticsearch connection problems on windows (found.io)
On my Windows I want to connect my python program to my elasticsearch cluster hosted on found.io (via heroku.)

The connection to elasticsearch times out and gives me an exception saying the "the target machine actively refused it".

es = Elasticsearch(
      [elastic],
        # port=443,
        use_ssl=True,
        verify_certs=True,
        ca_certs=certifi.where(),
    )
```

<p>I expected an indexation but received the following error message: </p>

```elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x03A0EC70>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x03A0EC70>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it)
```

答:
It could be a PROXY issue, as in heroku/legacy-cli issue 642, and documented in using the CLI / using an HTTP proxy.

Another reason is simply when the remote elasticsearch cluster is not started, as in this thread.

Body:
On my Windows I want to connect my python program to my elasticsearch cluster hosted on found.io (via heroku.)

The connection to elasticsearch times out and gives me an exception saying the "the target machine actively refused it".

es = Elasticsearch(
      [elastic],
        # port=443,
        use_ssl=True,
        verify_certs=True,
        ca_certs=certifi.where(),
    )

I expected an indexation but received the following error message:

elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x03A0EC70>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x03A0EC70>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it)


问:
jQuery function not firing before Ajax code
My jQuery code won't fire before my Ajax code. (What the jQuery code does is change my select element to an input). However, it only fires after my Ajax code, but gives an unwanted result - it will insert the value for the (now hidden) select element to the database instead of the value of the visible input element. How do I get my jQuery code to work so that it will successfully change my select element to an input and insert the right value into the database?

答:
I made some minor correction in script

```<code>$(function(){
    $(document).on("submit", "#toctform", function(event){
        event.preventDefault();
        var selectValue = $('#quantsel').val();
        var inputValue = $('#inphid').val();
        var strid = '<?php echo $prodtab->strid; ?>';
        var prodid = '<?php echo $prodtab->prodid; ?>';
        $.ajax({
            type: 'POST',
            url: "jtest.php?strid="+strid+"&prodid="+prodid,
            data: {selectValueBox: selectValue, inputValueBox: inputValue},
            success: function(data){
                alert("Data Save: " + data);
            }
        });
    });
});
</code>```

Check it and let me know it fix the issue.

Body:
I made some minor correction in script

$(function(){
    $(document).on("submit", "#toctform", function(event){
        event.preventDefault();
        var selectValue = $('#quantsel').val();
        var inputValue = $('#inphid').val();
        var strid = '<?php echo $prodtab->strid; ?>';
        var prodid = '<?php echo $prodtab->prodid; ?>';
        $.ajax({
            type: 'POST',
            url: "jtest.php?strid="+strid+"&prodid="+prodid,
            data: {selectValueBox: selectValue, inputValueBox: inputValue},
            success: function(data){
                alert("Data Save: " + data);
            }
        });
    });
});

Check it and let me know it fix the issue.


问:
Calling function that stores integers in an array in C
I have a homework assignment that I need assistance with.

I have written a function that should take user input using scanf and store it into an array. It will also count the number of times an integer is entered (except 0, which terminates the program)
I am specifically having an issue calling this function within main()
Any suggestions on how to fix it?

I've tried using defining the function at the bottom, and using different variables within the function: getVals

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

#define ARRAYSIZE 20 //defines the size of the array to 20

int nVals = 0;
int getVals(int myVals[], int maxVals);
int input[ARRAYSIZE+1] = {'0'};

int getVals(int myVals[], int maxVals)
{
  for (maxVals = 0; maxVals < ARRAYSIZE; maxVals++) { //When the row is    less than ten, it will run the loop and increment the row
    printf("Please Enter up to 20 integers "); //which will allow the name to be stored in the next row
    scanf("%d", &myVals[maxVals]);

    if ((myVals[maxVals] <= 0) || (maxVals == ARRAYSIZE -1))
       return nVals;
    if (myVals[maxVals] > 0)
       nVals++;

  }
}

int main() {
  printf("This program will receive up to 20 inputs from you, and sort them from least to greatest\n\n");
  printf("Enter 0 or a negative number to exit the program.\n");

  getVals(int ARRAYSIZE, int input[ARRAYSIZE]);

  printf("You have entered %d numbers\n", nVals);
  printf("%d", input[]);
  printf("\n");
  printf("Now sorting....\n");

  return 0;
}
</code>```

答:
Error: in this line in main function

```<code>getVals(int ARRAYSIZE, int input[ARRAYSIZE]);
</code>```

The correct way:

```<code>getVals(input, input[ARRAYSIZE]);
</code>```

First: you shouldn't use data type to your attribute when you call the function.

Second: Your array name is "input", as you're passing array so you should use array name that is input not ARRAYSIZE...

Body:
I have a homework assignment that I need assistance with.

I have written a function that should take user input using scanf and store it into an array. It will also count the number of times an integer is entered (except 0, which terminates the program)
I am specifically having an issue calling this function within main()
Any suggestions on how to fix it?

I've tried using defining the function at the bottom, and using different variables within the function: getVals

#include <stdio.h>

#define ARRAYSIZE 20 //defines the size of the array to 20

int nVals = 0;
int getVals(int myVals[], int maxVals);
int input[ARRAYSIZE+1] = {'0'};

int getVals(int myVals[], int maxVals)
{
  for (maxVals = 0; maxVals < ARRAYSIZE; maxVals++) { //When the row is    less than ten, it will run the loop and increment the row
    printf("Please Enter up to 20 integers "); //which will allow the name to be stored in the next row
    scanf("%d", &myVals[maxVals]);

    if ((myVals[maxVals] <= 0) || (maxVals == ARRAYSIZE -1))
       return nVals;
    if (myVals[maxVals] > 0)
       nVals++;

  }
}

int main() {
  printf("This program will receive up to 20 inputs from you, and sort them from least to greatest\n\n");
  printf("Enter 0 or a negative number to exit the program.\n");

  getVals(int ARRAYSIZE, int input[ARRAYSIZE]);

  printf("You have entered %d numbers\n", nVals);
  printf("%d", input[]);
  printf("\n");
  printf("Now sorting....\n");

  return 0;
}

Body:
Error: in this line in main function

getVals(int ARRAYSIZE, int input[ARRAYSIZE]);

The correct way:

getVals(input, input[ARRAYSIZE]);

First: you shouldn't use data type to your attribute when you call the function.

Second: Your array name is "input", as you're passing array so you should use array name that is input not ARRAYSIZE...


问:
How to convert a column in a csv file using Nifi?
I Have a raw csv file as below

```<code>   SVEIS , SVESID,SVETIME
   Quneter,53553,01122003010005
   renchure,37151,12092008011005
</code>```

now I need to change the data  from day month year to year day month as below

```<code>   SVEIS , SVESID,SVETIME
  Quneter,53553,2003-01-12 01:00:05
  renchure,37151,2008-12-09 01:10:05
</code>```

I need to change this using NIFI

I have used replace text processor but I am getting error like unable to process 10 of 10 records in nifi

Body:
I Have a raw csv file as below

   SVEIS , SVESID,SVETIME
   Quneter,53553,01122003010005
   renchure,37151,12092008011005

now I need to change the data  from day month year to year day month as below

   SVEIS , SVESID,SVETIME
  Quneter,53553,2003-01-12 01:00:05
  renchure,37151,2008-12-09 01:10:05

I need to change this using NIFI

I have used replace text processor but I am getting error like unable to process 10 of 10 records in nifi

Body:
If awk can be used, this is possible to solve like this:

awk -F, '{
    f1=substr($3,1,2);
    f2=substr($3,3,2);
    f3=substr($3,5,2);
    f4=substr($3,7,2);
    f5=substr($3,9,2);
    f6=substr($3,11,2);
    f7=substr($3,13,2)}
    NR<2 {print $1,$2,$3;next}
    {print $1,$2,f3 f4"-"f1"-"f2,f5":"f6":"f7}' file

   SVEIS   SVESID SVETIME
   Quneter 53553 2003-01-12 01:00:05
   renchure 37151 2008-12-09 01:10:05


问:
How to leave a div and an image over a carousel?
I want to make a carousel and over it, a div and then to give that effect to be superimposed.
Try to make as this EXAMPLE, but without success. When I add such properties (absolute and relative) the code of the carousel it does not.

My DIV Overlay => id="faixa"

The slide in background shaped carousel. The green div and logo superimposed on the carousel.

I tried something like:

#myCarousel{
 position: absolute;
}

#fixa{
 position: absolute;
 width: 20%;
 height: 400px;
 background: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div id="myCarousel" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#myCarousel" data-slide-to="1"></li>
  </ol>

  <div class="carousel-inner" role="listbox">

    <div id="fixa">
   DIV QUE SERÁ SOBREPOSTA
    </div>

    <div class="item active">
      <img src="http://s3.amazonaws.savoir.com.br/cea.com.br/imagem/cadastrocqlv/imagem/cadastrocqlv-53440.jpg">
    </div>

    <div class="item">
      <img src="http://www.asia-turismo.com/imagens/asia-imagem.jpg">
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script></code>```

How to make this?

答:
As a small point, note that the z-index is applied to the
, and not to the  tag.

I had the same question of wanting to position an image within a div on top of a carousel.

(Not enough karma to comment on KrisD's answer above)

Body:
I want to make a carousel and over it, a div and then to give that effect to be superimposed.
Try to make as this EXAMPLE, but without success. When I add such properties (absolute and relative) the code of the carousel it does not.

My DIV Overlay => id="faixa"

The slide in background shaped carousel. The green div and logo superimposed on the carousel.

I tried something like:

#myCarousel{
 position: absolute;
}

#fixa{
 position: absolute;
 width: 20%;
 height: 400px;
 background: black;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

   DIV QUE SERÁ SOBREPOSTA

How to make this?

Body:
As a small point, note that the z-index is applied to the <div>, and not to the <img> tag.

I had the same question of wanting to position an image within a div on top of a carousel.

(Not enough karma to comment on KrisD's answer above)


问:
React routing on click event is not working
I am doing routing on button click event

```<code>  redirect(){

       return <Redirect to='/chat' />;

    }
</code>```

Its not working.

my home page- base component:

```<code>import React, { Fragment } from 'react';

  render() {

    const { value } = this.state;

    return (

        <Router>

          <div>
             <Switch>
            <Route exact={true} path="/" component={Home} />
            <Route path="/notify" component={Notify} />
            <Route path="/chat" component={Chat}/>
</Switch>

          </div>
          <footer className="foot">
            <BottomNavigation className="navbar navbar-default navbar-static-bottom navbar-fixed-bottom" value={value} onChange={this.handleChange} className={this.props.root}>

                <div className="navi">
                  <Link   to="/"> <BottomNavigationAction label="Home" value="Home" icon={<HomeIcon />} /></Link>
                </div>
                <div  className="navi">
                <Link to="/notify"><BottomNavigationAction label="Notification" value="Notification" icon={<NotifyIcon />} /></Link>
                </div>
                <div className="navi">
                <Link to="/chat"> <BottomNavigationAction label="Listen" value="Listen" icon={<LocationOnIcon />} /></Link>
                </div>

            </BottomNavigation>
          </footer>
</code>```

From my child component I have to redirect to another component,
here is my child component:

```<code>  <IconButton className={this.props.iconButton} aria-label="Search" onClick={this.redirect}>
        <SearchIcon />
      </IconButton>

redirect(){

       return <Redirect to='/chat' />;

    }
</code>```

So but I am not getting any console error too.

答:
<Redirect /> is a component. So, you should use it like this.

```<code>class App extends React.Component{
  state = {
    isRedirect: false,
  }

  redirect = () => {
    this.setState({ isRedirect: true });
  }

  render() {
    return (
      <>
        <button onclick={this.redirect}> Redirect</button>

        {this.state.isRedirect ? <Redirect to="/" /> : null }
      </>
    )
  }

}

</code>```

OR

You can use history API

but you should add withRouter()

```<code>class App extends React.Component{
  render(){
    return(
      <>
        <button onClick={()=>{this.props.history.push('/')}}>Redirect</button>
      </>
    )
  }
}

export default withRouter(App);

</code>```

Body:
I am doing routing on button click event

  redirect(){

       return <Redirect to='/chat' />;

    }

Its not working.

my home page- base component:

import React, { Fragment } from 'react';

  render() {

    const { value } = this.state;

    return (

        <Router>

             <Switch>
            <Route exact={true} path="/" component={Home} />
            <Route path="/notify" component={Notify} />
            <Route path="/chat" component={Chat}/>
</Switch>

            <BottomNavigation className="navbar navbar-default navbar-static-bottom navbar-fixed-bottom" value={value} onChange={this.handleChange} className={this.props.root}>

                  <Link   to="/"> <BottomNavigationAction label="Home" value="Home" icon={<HomeIcon />} /></Link>

                <Link to="/notify"><BottomNavigationAction label="Notification" value="Notification" icon={<NotifyIcon />} /></Link>

                <Link to="/chat"> <BottomNavigationAction label="Listen" value="Listen" icon={<LocationOnIcon />} /></Link>

            </BottomNavigation>

From my child component I have to redirect to another component,
here is my child component:

  <IconButton className={this.props.iconButton} aria-label="Search" onClick={this.redirect}>
        <SearchIcon />
      </IconButton>

redirect(){

       return <Redirect to='/chat' />;

    }

So but I am not getting any console error too.

Body:
<Redirect /> is a component. So, you should use it like this.

class App extends React.Component{
  state = {
    isRedirect: false,
  }

  redirect = () => {
    this.setState({ isRedirect: true });
  }

  render() {
    return (
      <>
        <button onclick={this.redirect}> Redirect</button>

        {this.state.isRedirect ? <Redirect to="/" /> : null }
      </>
    )
  }

}

OR

You can use history API

but you should add withRouter()

class App extends React.Component{
  render(){
    return(
      <>
        <button onClick={()=>{this.props.history.push('/')}}>Redirect</button>
      </>
    )
  }
}

export default withRouter(App);


问:
In a python list which is sorted, find the closest value to target value and its index in the list
I am trying to get both the closest value and its index in a sorted list in python.

In MATLAB this is possible with:

```<code>[closest_val,index] = min(abs(array - target))
</code>```

I was wondering if there is a similar way this can be implemented in python.

I've seen posts which do one or the other, but I haven't seen both done together.

Link to finding closest value in list post.

答:
this is an option:

```<code>lst = [
    13.09409,
    12.18347,
    11.33447,
    10.32184,
    9.544922,
    8.813385,
]

target = 11.5

res = min(enumerate(lst), key=lambda x: abs(target - x[1]))
# (2, 11.33447)
</code>```

enumerate iterates over your list in index, value pairs. the key of the min method tells it to only consider the value.

note that python starts indexing at 0; matlab at 1 as far as i remember. if you want that same behavior:

```<code>res = min(enumerate(lst, start=1), key=lambda x: abs(target - x[1]))
# (3, 11.33447)
</code>```

if the list is big, i strongly suggest you use bisect as suggested in this answer.

Body:
I am trying to get both the closest value and its index in a sorted list in python.

In MATLAB this is possible with:

[closest_val,index] = min(abs(array - target))

I was wondering if there is a similar way this can be implemented in python.

I've seen posts which do one or the other, but I haven't seen both done together.

Link to finding closest value in list post.

Body:
this is an option:

lst = [
    13.09409,
    12.18347,
    11.33447,
    10.32184,
    9.544922,
    8.813385,
]

target = 11.5

res = min(enumerate(lst), key=lambda x: abs(target - x[1]))
# (2, 11.33447)

enumerate iterates over your list in index, value pairs. the key of the min method tells it to only consider the value.

note that python starts indexing at 0; matlab at 1 as far as i remember. if you want that same behavior:

res = min(enumerate(lst, start=1), key=lambda x: abs(target - x[1]))
# (3, 11.33447)

if the list is big, i strongly suggest you use bisect as suggested in this answer.


问:
Error: your connection to this site is not private Asp.Net. MVC5
I'm setting up a new server with windows Azure VM for a asp.net mvc 5 application. I'm able to open every page of the application without a problem with an exception of one controller. i.e. whenever I try to open a page belong to a specific controller, it prompts me for user name & password as below.

I use the same application in a different Windows Server 2016 VM without any issues.

I don't see any errors of the application/IIS logs either. I don't have any https requirements in the application.

What may be causing this behaviour?

```<code>namespace App.Controllers
{
    public class ReportsController : BaseController
    {
        private readonly IReportRepository reportRepository;
        public ReportsController(): this(new ReportRepository()){
        }

        public ReportsController(IReportRepository reportRepository){
        this.reportRepository = reportRepository;
        }

        public ViewResult Action()
        {
           return View(reportRepository.All);
        }
    }
 }

namespace App.Controllers
{
    [Authorize]
    public class BaseController : Controller
    {
    }
 }
</code>```

UPDATE: I renamed the ReportsController to AppReportsController and the issue disappeared.
i.e. I get the above prompt when I try to access

http://domain/Reports/Action

but not for

http://domain/AppReports/Action

Could you please someone explain to me what's going on here? Does it mean that "Reports" is reserved by the framework or something?

答:
I know this was an old post however I stumble on this one because I encountered the same error as the OP does.

I have solved this one in case there's someone encounters the same as this.
but the solution may vary depends if we have the same applications installed.

check if the web server / server has an installation of sql server.

check if there is reporting services installed.

remove / uninstall the reporting services from the application control panel
follow this link if you don't know how to remove the report service How to remove Report Service

Please check again if you still encounter the same error. Cheers!

Body:
I'm setting up a new server with windows Azure VM for a asp.net mvc 5 application. I'm able to open every page of the application without a problem with an exception of one controller. i.e. whenever I try to open a page belong to a specific controller, it prompts me for user name & password as below.

I use the same application in a different Windows Server 2016 VM without any issues.

I don't see any errors of the application/IIS logs either. I don't have any https requirements in the application.

What may be causing this behaviour?

namespace App.Controllers
{
    public class ReportsController : BaseController
    {
        private readonly IReportRepository reportRepository;
        public ReportsController(): this(new ReportRepository()){
        }

        public ReportsController(IReportRepository reportRepository){
        this.reportRepository = reportRepository;
        }

        public ViewResult Action()
        {
           return View(reportRepository.All);
        }
    }
 }

namespace App.Controllers
{
    [Authorize]
    public class BaseController : Controller
    {
    }
 }

UPDATE: I renamed the ReportsController to AppReportsController and the issue disappeared.
i.e. I get the above prompt when I try to access

http://domain/Reports/Action

but not for

http://domain/AppReports/Action

Could you please someone explain to me what's going on here? Does it mean that "Reports" is reserved by the framework or something?


问:
Comment Replies adding only to a particular comment
I am writing a webapp and would like to add comment/reply functionality. The comments work well, but while trying to add replies, all replies are saved to the first comment alone even when added from other comments.

I would like to make replies be linked to other comments.

Replies are linked to a particular comment using a ForeignKey() relationship and a related_manager.
I have tried a for loop to get each comment from the Comment() models in the template, and while it renders each comment well, I can't seem to link them to their specific replies.

# models.py

class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    name = models.CharField(max_length=400)
    email = models.EmailField()
    text = models.TextField()
    time_stamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "Comment %s by %s" %(str(self.text)[:20], self.name)

class ReplyComment(models.Model):
    comment_reply = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name="replies")
    name_reply = models.CharField(max_length=400)
    text_reply = models.TextField()
    time_stamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "Reply by %s to %s" %(self.name_reply, str(self.comment_reply))

```

<pre class="lang-py prettyprint-override"><code># views.py
def article(request, slug):
   article = Article.objects.get(slug=slug)
   comments = Comment.objects.filter(article=article)

    # comment form
   if request.method == 'POST':
      form = CommentForm(request.POST or None)
      reply_form = ReplyCommentForm(request.POST or None)

      if form.is_valid():
         text = form.cleaned_data['text']
         email = form.cleaned_data['email']
         name = form.cleaned_data['name']

            # create the comment
         comment = Comment(article=article, text=text,
                              email=email, name=name)
         comment.save()

      if reply_form.is_valid():
         name_reply = reply_form.cleaned_data['name_reply']
         text_reply = reply_form.cleaned_data['text_reply']
         comment = Comment.objects.get(id=request.POST.get('comment_id'))
         reply_comment = ReplyComment(name_reply=name_reply, text_reply=text_reply, comment_reply=comment)
         reply_comment.save()

   else:
      form = CommentForm()
      reply_form = ReplyCommentForm()

   context = {'article': article, 'form': form, 'reply_form' : reply_form, 'comments': comments}

   return render(request, 'main/article.html', context)
</code>```

            {% for comment in comments %}

                {{ comment.time_stamp }}

{{ comment.name }}

{{ comment.text }}

                reply

                        <form action="" method="post">
                            <input type="hidden" name="comment_id" value="{{ comment.id }}">
                            {% csrf_token %}

Add a Reply

                                    {{ reply_form.name_reply }}

                                    {{ reply_form.text_reply }}

                            <button type="submit" class="black white-text btn-small waves-effect">Reply</button>
                        </form>

                    {% for reply in comment.replies.all %}

                    {{ reply.name_reply }}

                    {{ reply.text_reply }}

                    {% endfor %}

            {% endfor %}

```

I expect each reply added to be linked to their specific comments and linked as such.

I'm grateful for any help.

答:
The problem was that the id on the modal element was stuck to a single comment, and as such every comment rendered the same modal id. I fixed it by adding {{ comment.id }} to the id to make it dynamic. Thanks so much for responding.

reply

```

Body:
I am writing a webapp and would like to add comment/reply functionality. The comments work well, but while trying to add replies, all replies are saved to the first comment alone even when added from other comments.

I would like to make replies be linked to other comments.

Replies are linked to a particular comment using a ForeignKey() relationship and a related_manager.
I have tried a for loop to get each comment from the Comment() models in the template, and while it renders each comment well, I can't seem to link them to their specific replies.

# models.py

class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    name = models.CharField(max_length=400)
    email = models.EmailField()
    text = models.TextField()
    time_stamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "Comment %s by %s" %(str(self.text)[:20], self.name)

class ReplyComment(models.Model):
    comment_reply = models.ForeignKey(Comment, on_delete=models.CASCADE, related_name="replies")
    name_reply = models.CharField(max_length=400)
    text_reply = models.TextField()
    time_stamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "Reply by %s to %s" %(self.name_reply, str(self.comment_reply))

# views.py
def article(request, slug):
   article = Article.objects.get(slug=slug)
   comments = Comment.objects.filter(article=article)

    # comment form
   if request.method == 'POST':
      form = CommentForm(request.POST or None)
      reply_form = ReplyCommentForm(request.POST or None)

      if form.is_valid():
         text = form.cleaned_data['text']
         email = form.cleaned_data['email']
         name = form.cleaned_data['name']

            # create the comment
         comment = Comment(article=article, text=text,
                              email=email, name=name)
         comment.save()

      if reply_form.is_valid():
         name_reply = reply_form.cleaned_data['name_reply']
         text_reply = reply_form.cleaned_data['text_reply']
         comment = Comment.objects.get(id=request.POST.get('comment_id'))
         reply_comment = ReplyComment(name_reply=name_reply, text_reply=text_reply, comment_reply=comment)
         reply_comment.save()

   else:
      form = CommentForm()
      reply_form = ReplyCommentForm()

   context = {'article': article, 'form': form, 'reply_form' : reply_form, 'comments': comments}

   return render(request, 'main/article.html', context)

            {% for comment in comments %}

                {{ comment.time_stamp }}

{{ comment.name }}

{{ comment.text }}

                reply

                        <form action="" method="post">
                            <input type="hidden" name="comment_id" value="{{ comment.id }}">
                            {% csrf_token %}

Add a Reply

                                    {{ reply_form.name_reply }}

                                    {{ reply_form.text_reply }}

                            <button type="submit" class="black white-text btn-small waves-effect">Reply</button>
                        </form>

                    {% for reply in comment.replies.all %}

                    {{ reply.name_reply }}

                    {{ reply.text_reply }}

                    {% endfor %}

            {% endfor %}

I expect each reply added to be linked to their specific comments and linked as such.

I'm grateful for any help.

Body:
The problem was that the id on the modal element was stuck to a single comment, and as such every comment rendered the same modal id. I fixed it by adding {{ comment.id }} to the id to make it dynamic. Thanks so much for responding.

<a href="#reply-modal{{ comment.id }}" class="modal-trigger" data-target="reply-modal{{ comment.id }}"><i class="material-icons">reply</i></a>
       <div class="modal" id="reply-modal{{ comment.id }}">
            <div class="modal-content">


问:
"Not Supported by this Version of Xcode” and After Update Xcode Raises "Unsupported Swift Version"
After updating iPhone to iOS 12.2 I encountered this error in Xcode 10.1:

“This iPhone is running iOS 12.2, which may not be supported by this
  version of Xcode.”

So I have to update Xcode to latest version and after updating Xcode to 10.2, when I open the project, Xcode show another error that say:

Unsupported Swift Version

“MyProject” contains source code developed with Swift 3.x. This version of Xcode does not support building or migrating Swift 3.x
  targets.

Use Xcode 10.1 to migrate the code to Swift 4.

Now I couldn't run the project correctly in neither Xcode 10.1 nor 10.2!

I think I have to update my code to Swift 5 to Xcode 10.2 be able to compile the code. Am I right?

But updating the whole project is overwhelming.

Is there any other way to resolve the problem?

答:
The situation is neither dire nor daunting. All you really have to do is open the project with Xcode 10.1, mark the code as Swift 4, and close the project again. It would be good to migrate the code to Swift 4, though you don't have to; if you do, you certainly don't have to run it on a device — all you need to do is compile it as valid Swift 4. And the migrator will help you do that.

You will then be able to open the project in Xcode 10.2 and proceed however you like. Optimally you would then migrate again, to Swift 5, but you can postpone that step if you like.

But updating the whole project is overwhelming.

That is a matter of opinion, really. And after all, you got yourself into this situation by not migrating out of Swift 3 earlier (you have had literally years to do that, but you didn't), and by updating the system on your device.

Is there any other way to resolve the problem?

Not given your specifications. If you wish to run on this device that you have updated, you must update to Xcode 10.2, and you can do that only if you migrate out of Swift 3, which you can do with Xcode 10.1.


问:
Sql query in ASP.NET
I am using the following query to update record in asp.net, what's wrong with it?</p>

```<code>Dim updateSqlString As String = "UPDATE Subscriber_Communication SET([[marketing_rec_id]=?, [Currently_own]=?,[Purchase_date]=?, [Interested_in_owning]=?, [Product_of_interest]=?," & _
"[Time_frame_to_own]=?, [Referred_by]=?, [Campaign_Code]=?,[Last_Update]=?, [record_created_on]=?, [Comments]=?, [Comment_Date]=?, [Community_id]=?," & _
"[Certification]=?, [subscriber_Type]=?, [unsubscribe_comment]=?" & _
"WHERE [Communication_id]=" & Communication_id
  Using conn As New SqlConnection(ConnString)
            Using cmd As New SqlCommand(insertSqlString, conn)
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("marketing_rec_id", marketing_rec_id)
                cmd.Parameters.AddWithValue("Currently_own", Currently_own)
                cmd.Parameters.AddWithValue("Purchase_date", Purchase_date)
                cmd.Parameters.AddWithValue("Interested_in_owning", Interested_in_owning)
                cmd.Parameters.AddWithValue("Product_of_interest", Product_of_interest)
                cmd.Parameters.AddWithValue("Time_frame_to_own", Time_frame_to_own)
                cmd.Parameters.AddWithValue("Referred_by", Referred_by)
                cmd.Parameters.AddWithValue("Campaign_Code", Campaign_Code)
                cmd.Parameters.AddWithValue("Last_Update", Last_Update)
                cmd.Parameters.AddWithValue("record_created_on", record_created_on)
                cmd.Parameters.AddWithValue("Comments", Comments)
                cmd.Parameters.AddWithValue("Comment_Date", Comment_Date)
                cmd.Parameters.AddWithValue("Community_id", Community_id)
                cmd.Parameters.AddWithValue("Certification", Certification)
                cmd.Parameters.AddWithValue("subscriber_Type", subscriber_Type)
                cmd.Parameters.AddWithValue("unsubscribe_comment", unsubscribe_comment)
                conn.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Using
</code>```

答:
I believe you want:</p>

```<code>Dim updateSqlString As String =
    "UPDATE Subscriber_Communication SET [marketing_rec_id]=@marketing_rec_id, [Currently_own]=@Currently_own,   ..." etc
</code>```

Title: Sql query in ASP.NET

Body:
I am using the following query to update record in asp.net, what's wrong with it?

Dim updateSqlString As String = "UPDATE Subscriber_Communication SET([[marketing_rec_id]=?, [Currently_own]=?,[Purchase_date]=?, [Interested_in_owning]=?, [Product_of_interest]=?," & _
"[Time_frame_to_own]=?, [Referred_by]=?, [Campaign_Code]=?,[Last_Update]=?, [record_created_on]=?, [Comments]=?, [Comment_Date]=?, [Community_id]=?," & _
"[Certification]=?, [subscriber_Type]=?, [unsubscribe_comment]=?" & _
"WHERE [Communication_id]=" & Communication_id
  Using conn As New SqlConnection(ConnString)
            Using cmd As New SqlCommand(insertSqlString, conn)
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("marketing_rec_id", marketing_rec_id)
                cmd.Parameters.AddWithValue("Currently_own", Currently_own)
                cmd.Parameters.AddWithValue("Purchase_date", Purchase_date)
                cmd.Parameters.AddWithValue("Interested_in_owning", Interested_in_owning)
                cmd.Parameters.AddWithValue("Product_of_interest", Product_of_interest)
                cmd.Parameters.AddWithValue("Time_frame_to_own", Time_frame_to_own)
                cmd.Parameters.AddWithValue("Referred_by", Referred_by)
                cmd.Parameters.AddWithValue("Campaign_Code", Campaign_Code)
                cmd.Parameters.AddWithValue("Last_Update", Last_Update)
                cmd.Parameters.AddWithValue("record_created_on", record_created_on)
                cmd.Parameters.AddWithValue("Comments", Comments)
                cmd.Parameters.AddWithValue("Comment_Date", Comment_Date)
                cmd.Parameters.AddWithValue("Community_id", Community_id)
                cmd.Parameters.AddWithValue("Certification", Certification)
                cmd.Parameters.AddWithValue("subscriber_Type", subscriber_Type)
                cmd.Parameters.AddWithValue("unsubscribe_comment", unsubscribe_comment)
                conn.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Using

Body:
I believe you want:

Dim updateSqlString As String =
    "UPDATE Subscriber_Communication SET [marketing_rec_id]=@marketing_rec_id, [Currently_own]=@Currently_own,   ..." etc


答: Instead of a showHide function, the better name would be toggle(). Inside this function instead of setting the $scope.IsVisible = true, you can toggle the value of that variable like !$scope.IsVisible.

Title: Hide and show on button click in angularjs

Body:
I want to hide the value by default and show the value when I click on button for 1st time. When you click on the same button for a 2nd time, it should hide the value instead of displaying. Vice versa it should happen.

Here is my html

<!DOCTYPE HTML>

  <title>AngularJS</title>

<input type="button" value="Show Angular" ng-click="ShowHide()"/>

 yes

here is my JS File:

var app = angular.module("EmployeeManagement", []);
app.controller("EmployeeController", function($scope, $http) {
 $scope.ShowHide = function(){
     $scope.IsVisible =  true;
 }

can anyone tell me how to achieve this scenario?


问:
Why does PyTorch gather function require index argument to be of type LongTensor?
I'm writing some code in PyTorch and I came across the gather function. Checking the documentation I saw that the index argument takes in a LongTensor, why is that? Why does it need to take in a LongTensor instead of another type such as IntTensor? What are the benefits?</p>

答: By default all indices in pytorch are represented as long tensors - allowing for indexing very large tensors beyond just 4GB elements (maximal value of "regular" int).</p>


问:
Need help making an object bounce off another object us JavaScript and P5
I need to make a program that has a ball that moves on the screen and when it hits the rectangle it needs to bounce off of it. I have the ball bouncing already when it hits the canvas sides but i cant figure out how to make it bounce off the rectangle using functions.

I have tried to make another "if" statement to say if it hits this area to bounce off but i get errors if i do that and the ball will not move at all.

I am using CodePen here is the link. I have used to comments to make it easier to read as well

https://codepen.io/Vanilla_thick/pen/eaKaVw

Here is what I have so far:`

//Varibles
let circleX=40
let circleY=40
let velocityX=5
let velocityY=5
//Function for rectangle

function rectangle(color, sizeX, sizeY){
  fill(color)
  let r =rect(300,550,sizeX,sizeY)
}

function setup(){
  //Make canvas
  createCanvas(800,600)
}

function draw(){
  //Set backgound to black
  background(0)
  //Make ball
  circle(circleX,circleY,40)

   //Give the ball a volicity on the "X" and "Y" axis so it will move
//both ways whenever it needs to
   //Have ball start by moving down to make it bounce vertically
  circleY= circleY + velocityY

  circleX = circleX + velocityX

  //Have it call the function to add the rectangle
  rectangle("#ff0000",400,20)

  //Make "Ifs" statement so whenever the ball hits the edge of the canvas it will bounce and go somewhere else in the canvas

  if (circleY > height){
      velocityY= -5
  }
  if (circleY == 0){
      velocityY= 5
  }
  else if (circleX > width){
      velocityX= -5
  }
  else if(circleX < 0){
      velocityX= 5
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script></code>```

I expect it to kind of work like the game Breakout (as I will be adding more to this program in the future)

答:
Add position coordinates for the rectangle:

let rectX = 200, rectY = 550
```

<pre class="lang-js prettyprint-override"><code>function rectangle(color, posX, posY, sizeX, sizeY){
    fill(color)
    rect(posX, posY, sizeX, sizeY)
}
</code>```

rectangle("#ff0000", rectX, rectY, 400, 20)
```

<p>If the bottom of the circle is below the top of the rectangle, and the center of the circle is somewhere between the let and the right of the rectangle, then the the ball "bounce" and the y direction has to be changed:</p>

```rectTop      = rectY;
rectLeft     = rectX;
rectRight    = rectX + 400;
circleBottom = circleY + 20
if (circleBottom > rectTop && circleX >= rectLeft && circleX <= rectRight ) {
    velocityY= -5
}
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//Varibles
let rectX = 200, rectY = 550
let circleX = 40
let circleY = 40
let velocityX = 5
let velocityY = 5
//Function for rectangle

function rectangle(color, posX, posY, sizeX, sizeY){
    fill(color)
    rect(posX, posY, sizeX, sizeY)
}

function setup(){
    //Make canvas
    createCanvas(800,600)
}

function draw(){
    //Set backgound to black
    background(0)
    //Make ball
    circle(circleX, circleY, 40)

    //Give the ball a volicity on the "X" and "Y" axis so it will move
    //both ways whenever it needs to
    //Have ball start by moving down to make it bounce vertically
    circleY= circleY + velocityY

    circleX = circleX + velocityX

    //Have it call the function to add the rectangle
    rectangle("#ff0000", rectX, rectY, 400, 20)

    //Make "Ifs" statement so whenever the ball hits the edge
    // of the canvas it will bounce and go somewhere else in the canvas

    rectTop      = rectY;
    rectLeft     = rectX;
    rectRight    = rectX + 400;
    circleBottom = circleY + 20
    if (circleBottom > rectTop && circleX >= rectLeft && circleX <= rectRight ) {
        velocityY= -5
    }
    else if (circleY > height){
        velocityY= -5
    }
    if (circleY == 0){
        velocityY= 5
    }
    else if (circleX > width){
        velocityX= -5
    }
    else if(circleX < 0){
        velocityX= 5
    }
}</code>```

```

Body:
I need to make a program that has a ball that moves on the screen and when it hits the rectangle it needs to bounce off of it. I have the ball bouncing already when it hits the canvas sides but i cant figure out how to make it bounce off the rectangle using functions.

I have tried to make another "if" statement to say if it hits this area to bounce off but i get errors if i do that and the ball will not move at all.

I am using CodePen here is the link. I have used to comments to make it easier to read as well

https://codepen.io/Vanilla_thick/pen/eaKaVw

Here is what I have so far:`

//Varibles
let circleX=40
let circleY=40
let velocityX=5
let velocityY=5
//Function for rectangle

function rectangle(color, sizeX, sizeY){
  fill(color)
  let r =rect(300,550,sizeX,sizeY)
}

function setup(){
  //Make canvas
  createCanvas(800,600)
}

function draw(){
  //Set backgound to black
  background(0)
  //Make ball
  circle(circleX,circleY,40)

   //Give the ball a volicity on the "X" and "Y" axis so it will move
//both ways whenever it needs to
   //Have ball start by moving down to make it bounce vertically
  circleY= circleY + velocityY

  circleX = circleX + velocityX

  //Have it call the function to add the rectangle
  rectangle("#ff0000",400,20)

  //Make "Ifs" statement so whenever the ball hits the edge of the canvas it will bounce and go somewhere else in the canvas

  if (circleY > height){
      velocityY= -5
  }
  if (circleY == 0){
      velocityY= 5
  }
  else if (circleX > width){
      velocityX= -5
  }
  else if(circleX < 0){
      velocityX= 5
  }
}

I expect it to kind of work like the game Breakout (as I will be adding more to this program in the future)

Body:
Add position coordinates for the rectangle:

let rectX = 200, rectY = 550

function rectangle(color, posX, posY, sizeX, sizeY){
    fill(color)
    rect(posX, posY, sizeX, sizeY)
}

rectangle("#ff0000", rectX, rectY, 400, 20)

If the bottom of the circle is below the top of the rectangle, and the center of the circle is somewhere between the let and the right of the rectangle, then the the ball "bounce" and the y direction has to be changed:

rectTop      = rectY;
rectLeft     = rectX;
rectRight    = rectX + 400;
circleBottom = circleY + 20
if (circleBottom > rectTop && circleX >= rectLeft && circleX <= rectRight ) {
    velocityY= -5
}

//Varibles
let rectX = 200, rectY = 550
let circleX = 40
let circleY = 40
let velocityX = 5
let velocityY = 5
//Function for rectangle

function rectangle(color, posX, posY, sizeX, sizeY){
    fill(color)
    rect(posX, posY, sizeX, sizeY)
}

function setup(){
    //Make canvas
    createCanvas(800,600)
}

function draw(){
    //Set backgound to black
    background(0)
    //Make ball
    circle(circleX, circleY, 40)

    //Give the ball a volicity on the "X" and "Y" axis so it will move
    //both ways whenever it needs to
    //Have ball start by moving down to make it bounce vertically
    circleY= circleY + velocityY

    circleX = circleX + velocityX

    //Have it call the function to add the rectangle
    rectangle("#ff0000", rectX, rectY, 400, 20)

    //Make "Ifs" statement so whenever the ball hits the edge
    // of the canvas it will bounce and go somewhere else in the canvas

    rectTop      = rectY;
    rectLeft     = rectX;
    rectRight    = rectX + 400;
    circleBottom = circleY + 20
    if (circleBottom > rectTop && circleX >= rectLeft && circleX <= rectRight ) {
        velocityY= -5
    }
    else if (circleY > height){
        velocityY= -5
    }
    if (circleY == 0){
        velocityY= 5
    }
    else if (circleX > width){
        velocityX= -5
    }
    else if(circleX < 0){
        velocityX= 5
    }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.js"></script>


问:
Do I still need to install MySQL in Django virtual env while I already have MySQL in my machine?
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from  python by :

```<code>import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
</code>```

then I download django frame and try to use it to connect mysql  ,  what I do is :

create a my.cnf file content is :

```<code>[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8
</code>```

change settings.py to :

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
        },
    }
}
</code>```

then run :

```<code>python manage.py runserver
</code>```

but got a error :

```<code>django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?
</code>```

Do I still need to install an addition MySQL in Django virtual env?  if I can use the existing MySQL instead

答:
Both PyMySQL and MySQLdb are db connectors. I assume that your django framework by default searches for MySQLdb and throws exception because it couldn't find one.

You can either install MySQLdb or follow @ruddra's answer on that. I would recommend you to go with @ruddra's answer incase of development machine. Because there are lot of issues you might(50/50 chances) face while installing and making MySQLdb to work properly.

Read What is PyMySQL and how does it differ from MySQLdb? Can it affect Django deployment? to understand more on this.

Body:
I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from  python by :

import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')

then I download django frame and try to use it to connect mysql  ,  what I do is :

create a my.cnf file content is :

[client]
database = shfuture
host = localhost
user = root
password = MYSQLTB
default-character-set = utf8

change settings.py to :

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': os.path.join(BASE_DIR, 'my.cnf'),
        },
    }
}

then run :

python manage.py runserver

but got a error :

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install the MySQL client?

Do I still need to install an addition MySQL in Django virtual env?  if I can use the existing MySQL instead


问:
Is there a way to write to a file on server in react one page app?
Long story short I was asked to create an interface for an API in my internship. Then I don't know why i decided to try react and made a one page static app with it. Now my supervisor wants to keep a log of how people are using the site. Basically I want to add one more line to a file on server everytime a specific button is clicked. I found no answer for this except with a server like nodejs+express. I can add that but I am wondering if its possible without implementing a server myself. Thanks.</p>

答: That is not possible and that is by design. If you want to track user events without a backend, try using a third-party integration like amplitude</p>


问:
What does letter D represent in floating-point data
I have attached two pictures below in which I am stuck on one thing which is letter  D. In floating-point why letter D is used? Letter E represents exponent but what letter D represents?

Please tell me the use of D
Thanks

答:
Another way to convert a single precision string to the original value:</p>

```<code>REM Convert 4-byte IEEE string to single variable
S! = -3.1415
S$ = MKS$(S!)
Byte0 = ASC(MID$(S$, 1, 1))
Byte1 = ASC(MID$(S$, 2, 1))
Byte2 = ASC(MID$(S$, 3, 1))
Byte3 = ASC(MID$(S$, 4, 1))
Exponent = Byte3 AND &H7F
Exponent = Exponent * 2 + Byte2 \ 128 - &H7F
Mantissa! = Byte2 AND &H7F
Mantissa! = Mantissa! * &H10000 + Byte1 * &H100 + Byte0
Mantissa! = 1 + Mantissa! / (&H1000000 / 2)
Mantissa! = Mantissa! * 2 ^ Exponent
IF (Byte3 AND &H80) = &H80 THEN
    Mantissa! = -Mantissa!
END IF
PRINT Mantissa!
END
</code>```

Body:
Another way to convert a single precision string to the original value:

REM Convert 4-byte IEEE string to single variable
S! = -3.1415
S$ = MKS$(S!)
Byte0 = ASC(MID$(S$, 1, 1))
Byte1 = ASC(MID$(S$, 2, 1))
Byte2 = ASC(MID$(S$, 3, 1))
Byte3 = ASC(MID$(S$, 4, 1))
Exponent = Byte3 AND &H7F
Exponent = Exponent * 2 + Byte2 \ 128 - &H7F
Mantissa! = Byte2 AND &H7F
Mantissa! = Mantissa! * &H10000 + Byte1 * &H100 + Byte0
Mantissa! = 1 + Mantissa! / (&H1000000 / 2)
Mantissa! = Mantissa! * 2 ^ Exponent
IF (Byte3 AND &H80) = &H80 THEN
    Mantissa! = -Mantissa!
END IF
PRINT Mantissa!
END