问:
classnotfoundException getting if i start activity which is in dynamic module after successful download
From internal test i could download the dynamic feature module. After successful download i am opening activity which is in dynamic module using package name but i got class not found exception. And i checked APK size but size is not increased. below is my code. Please Help

below is my code for download the module. i used from internal testing which is available in playstore.

```<code>     public void loadFeatureTwo() {
    // Builds a request to install the feature1 module
    SplitInstallRequest request =
            SplitInstallRequest
                    .newBuilder()
                    // You can download multiple on demand modules per
                    // request by invoking the following method for each
                    // module you want to install.
                    .addModule("feature2")
                    .build();

    // Begin the installation of the feature1 module and handle success/failure
    splitInstallManager
            .startInstall(request)
            .addOnSuccessListener(new OnSuccessListener<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    // Module download successful
                   /* Intent intent = new Intent().setClassName(getPackageName(), "com.bapspatil.feature2.FeatureTwoActivity");
                    startActivity(intent);*/

                    Toast.makeText(getApplicationContext(), "successfully download feature2: ", Toast.LENGTH_LONG).show();
                    try {
                        Intent myIntent = new Intent(MainActivity.this, Class.forName("com.bapspatil.feature2.FeatureTwoActivity"));
                        startActivity(myIntent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    // Module download failed; handle the error here
                    Toast.makeText(getApplicationContext(), "Couldn't download feature: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
}
</code>```

答:
Make sure you integrate with SplitCompat correctly.

In particular, you seem not to be listening to the correct event. You should call registerListener and provide a custom SplitInstallStateUpdatedListener. Check out the examples of the documentation

```<code>// Creates a listener for request status updates.
SplitInstallStateUpdatedListener listener = state -> {
    if (state.sessionId() == mySessionId) {
      // Read the status of the request to handle the state update.
    }
};

// Registers the listener.
splitInstallManager.registerListener(listener);
</code>```

Body:
From internal test i could download the dynamic feature module. After successful download i am opening activity which is in dynamic module using package name but i got class not found exception. And i checked APK size but size is not increased. below is my code. Please Help

below is my code for download the module. i used from internal testing which is available in playstore.

     public void loadFeatureTwo() {
    // Builds a request to install the feature1 module
    SplitInstallRequest request =
            SplitInstallRequest
                    .newBuilder()
                    // You can download multiple on demand modules per
                    // request by invoking the following method for each
                    // module you want to install.
                    .addModule("feature2")
                    .build();

    // Begin the installation of the feature1 module and handle success/failure
    splitInstallManager
            .startInstall(request)
            .addOnSuccessListener(new OnSuccessListener<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    // Module download successful
                   /* Intent intent = new Intent().setClassName(getPackageName(), "com.bapspatil.feature2.FeatureTwoActivity");
                    startActivity(intent);*/

                    Toast.makeText(getApplicationContext(), "successfully download feature2: ", Toast.LENGTH_LONG).show();
                    try {
                        Intent myIntent = new Intent(MainActivity.this, Class.forName("com.bapspatil.feature2.FeatureTwoActivity"));
                        startActivity(myIntent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    // Module download failed; handle the error here
                    Toast.makeText(getApplicationContext(), "Couldn't download feature: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
}

Body:
Make sure you integrate with SplitCompat correctly.

In particular, you seem not to be listening to the correct event. You should call registerListener and provide a custom SplitInstallStateUpdatedListener. Check out the examples of the documentation

// Creates a listener for request status updates.
SplitInstallStateUpdatedListener listener = state -> {
    if (state.sessionId() == mySessionId) {
      // Read the status of the request to handle the state update.
    }
};

// Registers the listener.
splitInstallManager.registerListener(listener);


来源: stackexchange

问:
Find mixed indentation whitespace
I'm trying to write regex to match mixed indentation (i.e. tabs and spaces).

Here is what I have currently:

```<code>.*((\t )|( \t))\s*
</code>```

Results:

(---> stands for tabs, dots for spaces).

```<code>....--->....foo    matched
--->....--->foo    matched
--->....foo        matched
....--->foo        matched
</code>```

The problem is that it matches mixed whitespace in the middle of the line. I want to get rid of this matching, i.e. I want to match indentation only:

```<code>....foo....--->....bar    should not be matched
</code>```

答:
As stated in comments, the most important feature you were missing is the start-of-string anchor (^) and you should not use .* as that will also match non-white space, which you want to avoid.

You can get the match with either ^\s*(\t | \t)\s* or ^(\t+ | +\t)\s*. The second one would be more efficient.

Depending on your environment, you may need to add a m modifier (or equivalent) so that ^ matches with the start of a line (instead of the start of the whole input).

ContentLicense: CC BY-SA 4.0

Title: Find mixed indentation whitespace

Body:
I'm trying to write regex to match mixed indentation (i.e. tabs and spaces).

Here is what I have currently:

.*((\t )|( \t))\s*

Results:

(---> stands for tabs, dots for spaces).

....--->....foo    matched
--->....--->foo    matched
--->....foo        matched
....--->foo        matched

The problem is that it matches mixed whitespace in the middle of the line. I want to get rid of this matching, i.e. I want to match indentation only:

....foo....--->....bar    should not be matched


问:
How do I copy a row in joined tables in postgesql?
For example I have two tables main_table and ref_table which are joined on primary key of main table :

```<code>create table table main (
    id serial primary key,
    name varchar(100)
);

create table table_ref (
    main_id bigint references table_main(id),
    vals varchar(100)
);
</code>```

What I want to do is to copy row in both tables based on id. When I do it like this it works, but I can't understand how to copy vals column from table_ref:

```<code>with copy_main as (
    insert into table_main (name)
        select name
        from table_main inner join
             table_ref
             on id=main_id
             where id=1
        returning id, 'I need vals from table_ref here!!!' as vals
       )
insert into table_ref (main_id, vals)
    select id, vals
    from copy_main;
</code>```

How do I do it?

答:
I think you want this:</p>

```<code>with copy_main as (
    insert into table_main (name)
        select m.name
        from table_main m
        where m.id = 1
        returning id
       )
insert into table_ref (main_id, vals)
    select cm.id, r.vals
    from copy_main cm cross join
         table_ref r
    where r.main_id = 1;
</code>```

Body:
For example I have two tables main_table and ref_table which are joined on primary key of main table :

create table table main (
    id serial primary key,
    name varchar(100)
);

create table table_ref (
    main_id bigint references table_main(id),
    vals varchar(100)
);

What I want to do is to copy row in both tables based on id. When I do it like this it works, but I can't understand how to copy vals column from table_ref:

with copy_main as (
    insert into table_main (name)
        select name
        from table_main inner join
             table_ref
             on id=main_id
             where id=1
        returning id, 'I need vals from table_ref here!!!' as vals
       )
insert into table_ref (main_id, vals)
    select id, vals
    from copy_main;

How do I do it?

Body:
I think you want this:

with copy_main as (
    insert into table_main (name)
        select m.name
        from table_main m
        where m.id = 1
        returning id
       )
insert into table_ref (main_id, vals)
    select cm.id, r.vals
    from copy_main cm cross join
         table_ref r
    where r.main_id = 1;


问:
How do i limit the number of rows updated in postgres
I am trying to update records in customer table by limiting them to n number of records but i am having an error when i am using offset and limit keywords.

Where do i put

```<code>offset 0 limit 1
</code>```

in update statement sub query as the sub query is like:

```<code>update customer set name = 'sample name' where customer_id in (142, 143, 144, 145 offset 0 limit 1);
</code>```

When i tried executing update statement above, i get an error:

ERROR: syntax error at or near "offset"

Note: limit does not have to be 1, it can be any number and same is true for offset

答:
offset and limit work on rows, not on a list.

You can transform the in() clause to use a subquery that return a row from each of your input

update customer

```<code>set name = 'sample name'
where customer_id in (select unnest(array[142, 143, 144, 145]) offset 0 limit 1);
</code>```

Body:
I am trying to update records in customer table by limiting them to n number of records but i am having an error when i am using offset and limit keywords.

Where do i put

offset 0 limit 1

in update statement sub query as the sub query is like:

update customer set name = 'sample name' where customer_id in (142, 143, 144, 145 offset 0 limit 1);

When i tried executing update statement above, i get an error:

ERROR: syntax error at or near "offset"

Note: limit does not have to be 1, it can be any number and same is true for offset

Body:
offset and limit work on rows, not on a list.

You can transform the in() clause to use a subquery that return a row from each of your input

update customer

set name = 'sample name'
where customer_id in (select unnest(array[142, 143, 144, 145]) offset 0 limit 1);


问:
Stuck with a ValueError, How to solve it?
I am doing a assignment and I need to extract text from PDF using PyPDF2 and while trying to do that am getting this error. How to fix this?
can someone help me? thank you in advance.</p>

```<code>import PyPDF2
textFile = open('foo.txt', 'w')
file = open('foo.pdf','rb')
readpdf = PyPDF2.PdfFileReader(file)
print(readpdf.getNumPages())
1
read_pdf = readpdf.getPage(0)
textFile.write(read_pdf.extractText())

--------------------------------------------------------------------------
ValueError                                Traceback (most recent call
last)
<ipython-input-42-5a892ea3012b> in <module>
----> 1 textFile.write(read_pdf.extractText())

ValueError: I/O operation on closed file.

file.close
textFile.close()
</code>```

答:
I am not sure how you ended up with this error, but this might help:

textFile = open('foo.txt', 'w')
read_pdf = readpdf.getPage(0)
textFile.write(read_pdf.extractText())
```

Opening the file right before you do something with it seems to work for me, so give it a try and we'll see ;]

Body:
I am doing a assignment and I need to extract text from PDF using PyPDF2 and while trying to do that am getting this error. How to fix this?
can someone help me? thank you in advance.

import PyPDF2
textFile = open('foo.txt', 'w')
file = open('foo.pdf','rb')
readpdf = PyPDF2.PdfFileReader(file)
print(readpdf.getNumPages())
1
read_pdf = readpdf.getPage(0)
textFile.write(read_pdf.extractText())

--------------------------------------------------------------------------
ValueError                                Traceback (most recent call
last)
<ipython-input-42-5a892ea3012b> in <module>
----> 1 textFile.write(read_pdf.extractText())

ValueError: I/O operation on closed file.

file.close
textFile.close()

Body:
I am not sure how you ended up with this error, but this might help:

textFile = open('foo.txt', 'w')
read_pdf = readpdf.getPage(0)
textFile.write(read_pdf.extractText())

Opening the file right before you do something with it seems to work for me, so give it a try and we'll see ;]


问:
List all ".csv" filename and then enter corresponding code to plot the graph
There is a folder which contains lot of data for example the folder contains ".html" files , ".jpeg" files, ".pdf"files, ".csv" files(There are plenty of ".csv" excel sheets in the folder containing different file names). Here is the code which list only csv files.

Is there a way where in when i list all ".csv" files i will enter the corresponding code to plot graph.

```<code>    import os
    path = "F:\\Users\\Desktop\\Data\\Summary"
    files = []
    # r=root, d=directories, f = files
    for r, d, f in os.walk(path):
        for file in f:
            if '.csv' in file:
                files.append(os.path.join(r, file))
    for f in files:
        print(f)
</code>```

When i run the above code i get output as:

```<code>F:\\Users\\Desktop\\Data\\Summary\Test_Summary_1.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_2.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_3.csv
</code>```

Actually i want Output to be displayed as:

```<code>0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc
</code>```

How do i modify it to get as said above??

答:
If you run into trouble that the files aren't listed in the right order you can just sort the list of filenames as follows:

```<code>>>> x = ['abc_1.csv', 'abc_2.csv', 'abc_0.csv']
>>> x.sort()
>>> x
['abc_0.csv', 'abc_1.csv', 'abc_2.csv']
</code>```

If you know which csv data you'd like to plot. You can read the file into a numpy array as follows

```<code>from numpy import loadtxt
data = loadtxt(filename, delimiter=',')
</code>```

Then you can just plot the data using matplotlib

```<code>import matplotlib.pyplot as plt
plt.plot(data[:,0], data[:,1], 'ro')
plt.show()
</code>```

Body:
There is a folder which contains lot of data for example the folder contains ".html" files , ".jpeg" files, ".pdf"files, ".csv" files(There are plenty of ".csv" excel sheets in the folder containing different file names). Here is the code which list only csv files.

Is there a way where in when i list all ".csv" files i will enter the corresponding code to plot graph.

    import os
    path = "F:\\Users\\Desktop\\Data\\Summary"
    files = []
    # r=root, d=directories, f = files
    for r, d, f in os.walk(path):
        for file in f:
            if '.csv' in file:
                files.append(os.path.join(r, file))
    for f in files:
        print(f)

When i run the above code i get output as:

F:\\Users\\Desktop\\Data\\Summary\Test_Summary_1.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_2.csv
F:\\Users\\Desktop\\Data\\Summary\Test_Summary_3.csv

Actually i want Output to be displayed as:

0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc

How do i modify it to get as said above??

Body:
If you run into trouble that the files aren't listed in the right order you can just sort the list of filenames as follows:

>>> x = ['abc_1.csv', 'abc_2.csv', 'abc_0.csv']
>>> x.sort()
>>> x
['abc_0.csv', 'abc_1.csv', 'abc_2.csv']

If you know which csv data you'd like to plot. You can read the file into a numpy array as follows

from numpy import loadtxt
data = loadtxt(filename, delimiter=',')

Then you can just plot the data using matplotlib

import matplotlib.pyplot as plt
plt.plot(data[:,0], data[:,1], 'ro')
plt.show()


问:
Terraform/GCP: ssh-keys not being added to metdata
I'm trying to add ssh-keys to my Google Cloud project at the project level with terraform:

```<code>resource "google_compute_project_metadata_item" "oslogin" {
  project = "${google_project_services.myproject.project}"
  key     = "enable-oslogin"
  value   = "false"
}

resource "google_compute_project_metadata_item" "block-project-ssh-keys" {
  project = "${google_project_services.myproject.project}"
  key     = "block-project-ssh-keys"
  value   = "false"
}

resource "google_compute_project_metadata_item" "ssh-keys" {
  key   = "ssh-keys"
  value = "user:ssh-rsa myverylongpublickeythatireplacewithtexthereforobviousreasons user@computer.local"

  depends_on = [
    "google_project_services.myproject",
  ]
}
</code>```

I tried all types of combinations of the 2 metadata flags oslogin and block-project-ssh-keys, which always get set without issues. But the ssh keys never appear in GCPs web GUI let alone the authorized_keys file. I even tried adding the depends_on, to make sure the project is existent before adding the keys, but that didn't help either.

Yet, Terraform says:

```<code>google_compute_project_metadata_item.ssh-keys: Creation complete after 8s (ID: ssh-keys)
</code>```

Adding the exact same key manually on the web GUI works fine. At this point I believe I have tried everything, read all the first page Google results to 'terraform gcp add ssh key' and similar queries ... I'm at my wits end.

答:
The issue was that the ssh key was being added to a different project.
I started with Google's tutorial on GCP/Terraform. This creates a generic project with the gcloud tool first. Then proceeds to create accounts using that generic project. This is necessary because you need a user to run terraform against their API. Then they create a new project facilitating these users with terraform each time you apply. The generic project created with gcloud is not being touched after the initial creation.
If you omit the "project" parameter from the google_compute_project_metadata_item.ssh-keys resource, it used the generic project and added the ssh keys there - at least in my case.

Solution: explicitly add the project parameter to the metadata resource item to make sure it's being added to the right project

Body:
I'm trying to add ssh-keys to my Google Cloud project at the project level with terraform:

resource "google_compute_project_metadata_item" "oslogin" {
  project = "${google_project_services.myproject.project}"
  key     = "enable-oslogin"
  value   = "false"
}

resource "google_compute_project_metadata_item" "block-project-ssh-keys" {
  project = "${google_project_services.myproject.project}"
  key     = "block-project-ssh-keys"
  value   = "false"
}

resource "google_compute_project_metadata_item" "ssh-keys" {
  key   = "ssh-keys"
  value = "user:ssh-rsa myverylongpublickeythatireplacewithtexthereforobviousreasons user@computer.local"

  depends_on = [
    "google_project_services.myproject",
  ]
}

I tried all types of combinations of the 2 metadata flags oslogin and block-project-ssh-keys, which always get set without issues. But the ssh keys never appear in GCPs web GUI let alone the authorized_keys file. I even tried adding the depends_on, to make sure the project is existent before adding the keys, but that didn't help either.

Yet, Terraform says:

google_compute_project_metadata_item.ssh-keys: Creation complete after 8s (ID: ssh-keys)

Adding the exact same key manually on the web GUI works fine. At this point I believe I have tried everything, read all the first page Google results to 'terraform gcp add ssh key' and similar queries ... I'm at my wits end.


问:
why the confusion_matrix is different when I execute it again?
I wonder why the confusion_matrix changes as I execute it in a second time and whether it is avoidable. To be more exact, I got [[53445 597] [958 5000]] for the first time, however, I get [[52556 1486][805 5153]] when I execute it again.</p>

```<code># get the data from dataset and split into training-set and test-set
mnist = fetch_openml('mnist_784')
X, y = mnist['data'], mnist['target']
X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]
# make the data random
shuffle_index = np.random.permutation(60000)
X_train, y_train = X_train[shuffle_index], y_train[shuffle_index]
# true for all y_train='2', false for all others
y_train_2 = (y_train == '2')
y_test_2 = (y_test == '2')

# train the data with a label of T/F depends on whether the data is 2
# I use the random_state as 0, so it will not change, am I right?
sgd_clf = SGDClassifier(random_state=0)
sgd_clf.fit(X_train, y_train_2)

# get the confusion_matrix
y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_2, cv=3)
print('confusion_matrix is', confusion_matrix(y_train_2, y_train_pred))
</code>```

答:
You are using different data on each run (shuffle_index) - so there is no reason for the ML run and resulting confusion matrix to be exactly the same - though results should be close if the algorithm is doing a good job.

To get rid of the randomness either specify indices:

```<code>shuffle_index = np.arange(60000) #Rather "not_shuffled_index"
</code>```

Or use the same seed:

```<code>np.random.seed(1) #Or any number
shuffle_index = np.random.permutation(60000) #Will be the same for a given seed
</code>```

Body:
I wonder why the confusion_matrix changes as I execute it in a second time and whether it is avoidable. To be more exact, I got [[53445 597] [958 5000]] for the first time, however, I get [[52556 1486][805 5153]] when I execute it again.

# get the data from dataset and split into training-set and test-set
mnist = fetch_openml('mnist_784')
X, y = mnist['data'], mnist['target']
X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]
# make the data random
shuffle_index = np.random.permutation(60000)
X_train, y_train = X_train[shuffle_index], y_train[shuffle_index]
# true for all y_train='2', false for all others
y_train_2 = (y_train == '2')
y_test_2 = (y_test == '2')

# train the data with a label of T/F depends on whether the data is 2
# I use the random_state as 0, so it will not change, am I right?
sgd_clf = SGDClassifier(random_state=0)
sgd_clf.fit(X_train, y_train_2)

# get the confusion_matrix
y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_2, cv=3)
print('confusion_matrix is', confusion_matrix(y_train_2, y_train_pred))

Body:
You are using different data on each run (shuffle_index) - so there is no reason for the ML run and resulting confusion matrix to be exactly the same - though results should be close if the algorithm is doing a good job.

To get rid of the randomness either specify indices:

shuffle_index = np.arange(60000) #Rather "not_shuffled_index"

Or use the same seed:

np.random.seed(1) #Or any number
shuffle_index = np.random.permutation(60000) #Will be the same for a given seed


问:
Draw a line at specific position/annotate a Facetgrid in seaborn
A have produced a boxplot with Facetgrid in seaborn the following way

```<code># Import the dataset
tips = sns.load_dataset("tips")

# Plot using FacetGrid, separated by smoke
plt.style.use('ggplot')
g = sns.FacetGrid(tips, col="smoker", size=5, aspect=1.5)
g.map(sns.boxplot, "sex", "total_bill", palette='viridis', order=['Male', 'Female'])
plt.show()
</code>```

I now want to draw to distinct horizontal lines in each of the plot. For instance one horizontal line (with coordinated (0,10)) only in the left-hand side plot and another horizontal line (with coordinates (0,30)) only in the right-hand side plot.

How can I go about doing that?

答:
There is axhline and hlines. Simple example:

```<code>chart = sns.relplot(x="x", y="y", kind="line", data=df)

chart.axes[0][0].axhline(y = 10, color='black', linewidth=2, alpha=.7)
chart.axes[0][0].hlines( y = 20, color='black', linewidth=2, alpha=.7,
                         xmin = 30, xmax = 50)
</code>```

Seems like hlines allows for min-max (documentation) but axhline doesn't.

Body:
A have produced a boxplot with Facetgrid in seaborn the following way

# Import the dataset
tips = sns.load_dataset("tips")

# Plot using FacetGrid, separated by smoke
plt.style.use('ggplot')
g = sns.FacetGrid(tips, col="smoker", size=5, aspect=1.5)
g.map(sns.boxplot, "sex", "total_bill", palette='viridis', order=['Male', 'Female'])
plt.show()

I now want to draw to distinct horizontal lines in each of the plot. For instance one horizontal line (with coordinated (0,10)) only in the left-hand side plot and another horizontal line (with coordinates (0,30)) only in the right-hand side plot.

How can I go about doing that?

Body:
There is axhline and hlines. Simple example:

chart = sns.relplot(x="x", y="y", kind="line", data=df)

chart.axes[0][0].axhline(y = 10, color='black', linewidth=2, alpha=.7)
chart.axes[0][0].hlines( y = 20, color='black', linewidth=2, alpha=.7,
                         xmin = 30, xmax = 50)

Seems like hlines allows for min-max (documentation) but axhline doesn't.


问:
How to display input Form Horizontally in CSS?
i am trying to style form in flask python..instead of vertical i want to show form in horizontal manner..i tried display:inline in CSS but doesn't work for me..how to show form input in horizontal manner..any help would be appreciated ..thanks in advance..

```<code>    <div class="container">
    <div class="jumbotron">
    <form class="form-signin" action="/validateLogin" method="post">
    <label for="inputEmail" class="sr-only">Email address</label>
    <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password">
    <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
    </div>

    <footer class="footer">
    </footer>

    </div>
</code>```

CSS:

```<code>.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signint .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
        box-sizing: border-box;
padding: 10px;
font-size: 16px;
}

.form-signin .form-control: focus {
z-index: 2;
}
.form-signin {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-siginin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
</code>```

答:
You can achieve this straightforwardly with the help of flexbox. Before that you'll have to group the associated label and input elements in a wrapper div so that they can become flex-items. Finally, adjust the width of .form-signin and set its display to flex

.form-signin {
  padding: 15px;
  margin: 0 auto;
  display: flex;
}

.form-signin .form-signin-heading,
.form-signint .checkbox {
  margin-bottom: 10px;
}

.form-signin .checkbox {
  font-weight: normal;
}

.form-signin .form-control {
  position: relative;
  height: auto;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}

.form-signin .form-control: focus {
  z-index: 2;
}

.form-signin {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.form-siginin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="form-signin" action="/validateLogin" method="post">
  <div>
    <label for="inputEmail" class="sr-only">Email address</label>
    <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
  </div>

  <div>
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password">
  </div>

  <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form></code>```

Body:
i am trying to style form in flask python..instead of vertical i want to show form in horizontal manner..i tried display:inline in CSS but doesn't work for me..how to show form input in horizontal manner..any help would be appreciated ..thanks in advance..

    <form class="form-signin" action="/validateLogin" method="post">
    Email address
    <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
    Password
    <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password">
    <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>

CSS:

.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signint .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
        box-sizing: border-box;
padding: 10px;
font-size: 16px;
}

.form-signin .form-control: focus {
z-index: 2;
}
.form-signin {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-siginin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}

Body:
You can achieve this straightforwardly with the help of flexbox. Before that you'll have to group the associated label and input elements in a wrapper div so that they can become flex-items. Finally, adjust the width of .form-signin and set its display to flex

.form-signin {
  padding: 15px;
  margin: 0 auto;
  display: flex;
}

.form-signin .form-signin-heading,
.form-signint .checkbox {
  margin-bottom: 10px;
}

.form-signin .checkbox {
  font-weight: normal;
}

.form-signin .form-control {
  position: relative;
  height: auto;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}

.form-signin .form-control: focus {
  z-index: 2;
}

.form-signin {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.form-siginin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

<form class="form-signin" action="/validateLogin" method="post">
  <div>
    <label for="inputEmail" class="sr-only">Email address</label>
    <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
  </div>

  <div>
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password">
  </div>

  <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>


问:
Two concurrent transactions on SERIALIZABLE isolation level
Let's consider two concurrent SQL transactions:

```<code>X = 0
T1:                    |  T2:
begin                  | begin
set serializable level | set serializable level
                       |
WRITE(X,1)
                       | READ(X) : 0
COMMIT                 |
                       | COMMIT
</code>```

I've tested it with PosgreSQL.
Why does T2 commit correctly? Both transactions has serializable level. So, on my eye, after T2 was started row X was modified. So, T2:COMMIT should fail. Why it does not?

答:
In effect, a SELECT query sees a snapshot of the database as of the
  instant the query begins to run. Source

A SELECT query will just operate on that snapshot. But other kinds of queries behave like you expect.

UPDATE, DELETE, SELECT FOR UPDATE, and SELECT FOR SHARE . . . will wait for the first updating transaction to commit or roll back (if it is still in progress). Source (ibid)

You can verify this behavior by, for example, running two psql sessions. Run an UPDATE statement in one session, and a SELECT...FOR UPDATE in the other.

The documentation quoted in this answer might confuse you a little; the documentation is about a slightly different problem. But you might find the transcript of the terminal sessions useful.

Body:
Let's consider two concurrent SQL transactions:

X = 0
T1:                    |  T2:
begin                  | begin
set serializable level | set serializable level
                       |
WRITE(X,1)
                       | READ(X) : 0
COMMIT                 |
                       | COMMIT

I've tested it with PosgreSQL.
Why does T2 commit correctly? Both transactions has serializable level. So, on my eye, after T2 was started row X was modified. So, T2:COMMIT should fail. Why it does not?


问:
Is using a WorkManager appropriate for long running network calls
In my app, the user can start a background process that makes long running API calls to the backend. The user will also have the ability to pause the background thread and resume at any point.

If the app restarts, the background process should resume from where it left off. Once the background process has completed, the process should terminate.

Even when the background process is running, if the user hits the device's home button, I still want the background process to keep running. It is not necessary for any UI to be shown while it is running.

Reading up on the Android docs, it would seem that using WorkManager is probably the best choice since my minSdkVersion is 19. Is this true?

答:
The process can run for hours

WorkManager work cannot run that long. You could still use WorkManager for the scheduling aspect, but then the "work" would need to be starting a foreground service, where the service then does the actual network I/O.

It is not necessary for any UI to be shown while it is running.

On Android 8.0+, you cannot have something running for hours without UI showing, at least in the form of a Notification associated with a foreground service.


问:
Python) How to convert string to dict? (Strange type of string)
The string is..

```<code>{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api",
         "author":"안광복 (지은이)",

      }
   ]
}
</code>```

I wanna convert string to dict.

This is what I want

I want to make this whole string to dictionary, So I want to get the value of "item"

```<code>"item" : [{"title: ", " : ", ... }, {"title: ", " : ", ...  }, { "title: ", " : ", ... }]
</code>```

I want the dictionaries(looks like dictionary but string) in the list(looks like list but str) so i want to use like dictionary

```<code>print(decoding_bestseller.find("item",370))
b=decoding_bestseller.split('"item"')
want_str=b[1]
want_str1=want_str.strip(':[]{}')
want_list=want_str1.split(',')
book_dic = {}
for i in range(0,len(want_list)):
    in_colon = ":" in want_list[i]
    if in_colon:
        split_list = want_list[i].split(':')
        book_key = split_list[0].strip('""')
        book_value = split_list[1].strip('""')
        book_dic[book_key] = book_value
</code>```

I did like that but I failed.

The string is like this
    {" : ", " : ", "item : [ {"title : ", "link : ", } {"title : ", "link : ",  }, " : "}

i want to make {"title : ", "link : ", ...} to REAL dictionary!

答: If your string is well written (no json error, you can check there to correct your json), then you can use json.loads(yourString) (doc)

Body:
The string is..

{
   "version":"20131101",
   "logo":"http://image.aladin.co.kr/img/header/2011/aladin_logo_new.gif",
   "title":"알라딘 베스트셀러 리스트 - 철학사",
   "link":"http:\/\/www.aladin.co.kr\/shop\/common\/wbest.aspx?BestType=Bestseller&BranchType=1&CID=51441&Year=2019&Month=5&Week=4&partner=openAPI",
   "pubDate":"Mon, 27 May 2019 10:33:33 GMT",
   "totalResults":955,
   "startIndex":1,
   "itemsPerPage":10,
   "query":"QueryType=BESTSELLER;CategoryId=51441;Year=2019;Month=5;Week=4",
   "searchCategoryId":51441,
   "searchCategoryName":"철학사",
   "item":[
      {
         "title":"처음 읽는 서양철학사 (개정증보판) - 서양의 대표 철학자 40인과 시작하는 철학의 첫걸음",
         "link":"http:\/\/www.aladin.co.kr\/shop\/wproduct.aspx?ItemId=100442130&partner=openAPI&start=api",
         "author":"안광복 (지은이)",

      }
   ]
}

I wanna convert string to dict.

This is what I want

I want to make this whole string to dictionary, So I want to get the value of "item"

"item" : [{"title: ", " : ", ... }, {"title: ", " : ", ...  }, { "title: ", " : ", ... }]

I want the dictionaries(looks like dictionary but string) in the list(looks like list but str) so i want to use like dictionary

print(decoding_bestseller.find("item",370))
b=decoding_bestseller.split('"item"')
want_str=b[1]
want_str1=want_str.strip(':[]{}')
want_list=want_str1.split(',')
book_dic = {}
for i in range(0,len(want_list)):
    in_colon = ":" in want_list[i]
    if in_colon:
        split_list = want_list[i].split(':')
        book_key = split_list[0].strip('""')
        book_value = split_list[1].strip('""')
        book_dic[book_key] = book_value

I did like that but I failed.

The string is like this
    {" : ", " : ", "item : [ {"title : ", "link : ", } {"title : ", "link : ",  }, " : "}

i want to make {"title : ", "link : ", ...} to REAL dictionary!


问:
bash scripting: Can I get sed to output the original line, then a space, then the modified line?
I'm new to Unix in all its forms, so please go easy on me!
I have a bash script that will pipe an ls command with arbitrary filenames into sed, which will use an arbitrary replacement pattern on the files, and then this will be piped into awk for some processing. The catch is, awk needs to know both the original file name and the new one.

I've managed everything except getting the original file names into awk. For instance, let's say my files are test.* and my replacement pattern is 's:es:ar;', which would change every occurrence of "test" to "tart". For testing purposes I'm just using awk to print what it's receiving:

```<code>ls "$@" | sed "$pattern" | awk '{printf "0: %s\n1: %s\n2: %s\n", $0,$1,$2}'
</code>```

where test.* is in $@ and the pattern is stored in $pattern.
Clearly, this doesn't get me to where I want to be. The output is obviously

```<code>0: tart.c
1: tart.c
2:
</code>```

If I could get sed to output "test.c tart.c", then I'd have two parameters for awk. I've played around with the pattern to no avail, even hardcoding "test.c" into the replacement. But of course that just gave me amateur results like "ttest.c art.c". Is it possible for sed to remember the input, then work it into the beginning of the output? Do I even have the right ideas? Thanks in advance!

答:
Two ways to change the first t in a b in the duplicated field.

Duplicate (& replays the matched part), change first word and swap (remember 2 strings with a space in between):

```<code>echo test.c |  sed -r 's/.*/& &/;s/t/b/;s/([^ ]*) (.*)/\2 \1/'
</code>```

or with more magic (copy original value to buffer, make the change, insert value from buffer as the first line and replace eond of line with a space)

```<code>echo test.c |  sed 'h;s/t/b/;x;G;s/\n/ /'
</code>```

Body:
I'm new to Unix in all its forms, so please go easy on me!
I have a bash script that will pipe an ls command with arbitrary filenames into sed, which will use an arbitrary replacement pattern on the files, and then this will be piped into awk for some processing. The catch is, awk needs to know both the original file name and the new one.

I've managed everything except getting the original file names into awk. For instance, let's say my files are test.* and my replacement pattern is 's:es:ar;', which would change every occurrence of "test" to "tart". For testing purposes I'm just using awk to print what it's receiving:

ls "$@" | sed "$pattern" | awk '{printf "0: %s\n1: %s\n2: %s\n", $0,$1,$2}'

where test.* is in $@ and the pattern is stored in $pattern.
Clearly, this doesn't get me to where I want to be. The output is obviously

0: tart.c
1: tart.c
2:

If I could get sed to output "test.c tart.c", then I'd have two parameters for awk. I've played around with the pattern to no avail, even hardcoding "test.c" into the replacement. But of course that just gave me amateur results like "ttest.c art.c". Is it possible for sed to remember the input, then work it into the beginning of the output? Do I even have the right ideas? Thanks in advance!

Body:
Two ways to change the first t in a b in the duplicated field.

Duplicate (& replays the matched part), change first word and swap (remember 2 strings with a space in between):

echo test.c |  sed -r 's/.*/& &/;s/t/b/;s/([^ ]*) (.*)/\2 \1/'

or with more magic (copy original value to buffer, make the change, insert value from buffer as the first line and replace eond of line with a space)

echo test.c |  sed 'h;s/t/b/;x;G;s/\n/ /'


问:
Qt - What is meant by those lines of code
In the C++ GUI Programming with Qt 4 book, part of creating a dialog application, there was the following main.cpp file:

```<code>#include <QApplication>
#include <QDialog>
#include "ui_gotocelldialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Ui::GoToCellDialog ui;
QDialog *dialog = new QDialog;
ui.setupUi(dialog);
dialog->show();
return app.exec();
}
</code>```

Can you just describe those lines of code?

```<code>    Ui::GoToCellDialog ui;
    QDialog *dialog = new QDialog;
    ui.setupUi(dialog);
</code>```

Thanks.

答:
Lets take a look:

```<code>Ui::GoToCellDialog ui;
</code>```

This line creates an instance of GoToCellDialog. As already have been said, this class automatically generated from the gotocelldialog.ui file. The use-case is:

Open qt-designer and make the interface you want.

Save the file (in our case gotocelldialog.ui)

In your .cpp file write #include "ui_gotocelldialog.h"

Now you can use the interface you designed

PROFIT????

Next:

```<code>QDialog *dialog = new QDialog;
</code>```

This line creates new instance of the QDialog class that represents simple modal window (commonly called as dialog). But your window would be empty after this line. You need to place the controls, do you? How you can do this? Lets see:

```<code>ui.setupUi(dialog);
</code>```

This line uses the interface you designed in the qt-designer. It places this interface to the newly created dialog. So you can see all the controls in the window. Pretty easy as for me.

ContentLicense: CC BY-SA 3.0

Body:
In the C++ GUI Programming with Qt 4 book, part of creating a dialog application, there was the following main.cpp file:

#include <QApplication>
#include <QDialog>
#include "ui_gotocelldialog.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Ui::GoToCellDialog ui;
QDialog *dialog = new QDialog;
ui.setupUi(dialog);
dialog->show();
return app.exec();
}

Can you just describe those lines of code?

    Ui::GoToCellDialog ui;
    QDialog *dialog = new QDialog;
    ui.setupUi(dialog);

Thanks.

Body:
Lets take a look:

Ui::GoToCellDialog ui;

This line creates an instance of GoToCellDialog. As already have been said, this class automatically generated from the gotocelldialog.ui file. The use-case is:

Open qt-designer and make the interface you want.

Save the file (in our case gotocelldialog.ui)

In your .cpp file write #include "ui_gotocelldialog.h"

Now you can use the interface you designed

PROFIT????

Next:

QDialog *dialog = new QDialog;

This line creates new instance of the QDialog class that represents simple modal window (commonly called as dialog). But your window would be empty after this line. You need to place the controls, do you? How you can do this? Lets see:

ui.setupUi(dialog);

This line uses the interface you designed in the qt-designer. It places this interface to the newly created dialog. So you can see all the controls in the window. Pretty easy as for me.


问:
How to get single items count in a slice with go?
For example, this is a slice:

```<code>[1, 2, 3, 3, 4]
</code>```

want to get single data 1, 2, 4 's count and return count = 3.

Maybe remove duplicate items(include itself) is an idea, but didn't find suitalbe method.

What I tried:

```<code>  func removeDuplicateItems() {
      intSlice := []int{1, 2, 3, 3, 4}
      fmt.Println(intSlice)

      keys := make(map[int]bool)
      list := []int{}
      for _, entry := range intSlice {
          if _, value := keys[entry]; !value {
              keys[entry] = true
              list = append(list, entry)
          }
      }

      fmt.Println(list)
  }
</code>```

Got

```<code>[1 2 3 3 4]
[1 2 3 4]
</code>```

答:
I suppose a really easy & quick way to get the count of unique values would be to use a map:

```<code>data := map[int]bool{}
cnt := 0 // count of unique values
for _, i := range intSlice {
    if dup, ok := data[i]; !ok {
        // we haven't seen value i before, assume it's unique
        data[i] = false // add to map, mark as non-duplicate
        cnt++ // increment unique count
    } else if !dup {
        // we have seen value i before, but this is only the second time
        cnt-- // unique count goes down here
        data[i] = true // mark this value as known duplicate
    }
}
</code>```

At the end of this loop, you'll have cnt with the count of unique values, and you can iterate the map data for all keys with value false to get the unique values that you found in the slice. All keys combined basically are the values in the slice, de-duplicated.

Body:
For example, this is a slice:

[1, 2, 3, 3, 4]

want to get single data 1, 2, 4 's count and return count = 3.

Maybe remove duplicate items(include itself) is an idea, but didn't find suitalbe method.

What I tried:

  func removeDuplicateItems() {
      intSlice := []int{1, 2, 3, 3, 4}
      fmt.Println(intSlice)

      keys := make(map[int]bool)
      list := []int{}
      for _, entry := range intSlice {
          if _, value := keys[entry]; !value {
              keys[entry] = true
              list = append(list, entry)
          }
      }

      fmt.Println(list)
  }

Got

[1 2 3 3 4]
[1 2 3 4]

Body:
I suppose a really easy & quick way to get the count of unique values would be to use a map:

data := map[int]bool{}
cnt := 0 // count of unique values
for _, i := range intSlice {
    if dup, ok := data[i]; !ok {
        // we haven't seen value i before, assume it's unique
        data[i] = false // add to map, mark as non-duplicate
        cnt++ // increment unique count
    } else if !dup {
        // we have seen value i before, but this is only the second time
        cnt-- // unique count goes down here
        data[i] = true // mark this value as known duplicate
    }
}

At the end of this loop, you'll have cnt with the count of unique values, and you can iterate the map data for all keys with value false to get the unique values that you found in the slice. All keys combined basically are the values in the slice, de-duplicated.


问:
django - call a view multiple times with different parameters
I have a django view that takes as parameter a path and returns the list of objects inside that path.
I need to call this view multiple times with different paths.

This is an example like my view:

```<code>python views.py

def filelist(request, foo):
    files = os.listdir(foo)
    context = { 'files' : files, }
    return render(request,'template2.html', context)
</code>```

The urls.py is like:

```<code>python urls.py

urlpatterns = [
    path('', views.index, name='index'),
    path('filelist/<str:path>/', views.filelist, name = "filelist"),
    ]
</code>```

The template is like this one:

```<code>HTML template.html

  <div class="collapse">
       <div class="one">
       {% include 'template2.html' %}
       </div>
  </div>

  <div class="collapse">
       <div class="two">
       {% include 'template2.html' %}
       </div>
  </div>

  <script>
  $(".one").load("{% url 'filelist' 'path1' %}", function() {
  alert( "Ok1" );
  });
  $(".two").load("{% url 'filelist' 'path2' %}", function() {
  alert( "Ok2" );
  });
  </script>

</code>```

Everything works but the variable {{ files }} is always the same.
Inside template2.html there is only a for loop that shows the files' names.

Any help? There is the possibility to store the variable {{ files }} in some local variables and then use it inside a {% for f in files %} loop?
Thanks.

答:
I did it.
If someone else has this problem, my solution is the following:</p>

```<code>HTML template.html

<a class="btn btn-light btn-s" id="buttonone">1</a>
<a class="btn btn-light btn-s" id="buttontwo">2</a>

<script>
$(document).ready(function() {
    $("#buttonone").click(function(event){
        $('.one').load("{% url 'filelist' 'path1' %}");
        });
    });

$(document).ready(function() {
    $("#buttontwo").click(function(event){
        $('.two').load("{% url 'filelist' 'path2' %}");
        });
    });
</script>
</code>```

Body:
I have a django view that takes as parameter a path and returns the list of objects inside that path.
I need to call this view multiple times with different paths.

This is an example like my view:

python views.py

def filelist(request, foo):
    files = os.listdir(foo)
    context = { 'files' : files, }
    return render(request,'template2.html', context)

The urls.py is like:

python urls.py

urlpatterns = [
    path('', views.index, name='index'),
    path('filelist/<str:path>/', views.filelist, name = "filelist"),
    ]

The template is like this one:

HTML template.html

       {% include 'template2.html' %}

       {% include 'template2.html' %}

Everything works but the variable {{ files }} is always the same.
Inside template2.html there is only a for loop that shows the files' names.

Any help? There is the possibility to store the variable {{ files }} in some local variables and then use it inside a {% for f in files %} loop?
Thanks.

Body:
I did it.
If someone else has this problem, my solution is the following:

HTML template.html

<a class="btn btn-light btn-s" id="buttonone">1</a>
<a class="btn btn-light btn-s" id="buttontwo">2</a>

<script>
$(document).ready(function() {
    $("#buttonone").click(function(event){
        $('.one').load("{% url 'filelist' 'path1' %}");
        });
    });

$(document).ready(function() {
    $("#buttontwo").click(function(event){
        $('.two').load("{% url 'filelist' 'path2' %}");
        });
    });
</script>


问:
deleting line from file MQL4
I am saving all the trades done by my EA into a CSV file.  When a Trade is closed by the EA, I have to add string "Book Profit" to the end of  particular line from the file.
eg:
Below is the line that is saved in the file while trade is open
"Buy GBPJPY 146.28 145.15", I would like to add string "Book Profit" to the end of the above line and save it to the file.
After saving the line should look like
"Buy GBPJPY 146.28 145.15 Book Profit"

```<code>int file_handle_dtf=FileOpen("MyTrades.CSV",FILE_READ|FILE_WRITE|FILE_CSV);
   if(file_handle_dtf!=INVALID_HANDLE){
      while(!FileIsEnding(file_handle_dtf)){

         str_size1=FileReadInteger(file_handle_dtf,INT_VALUE);
         //--- read the string

         str1=FileReadString(file_handle_dtf,str_size1);
         strBP=StringConcatenate(str1,",Book Profit");
         FileWriteString(file_handle_dtf,strBP+"\n");
         }

      }
</code>```

This code just overwrites the file and it is not readable

答:
Seek the end of the file first before writing to it:</p>

```<code>if (FileSeek(file_handle_dtf, 0, SEEK_END))
{
   // put file writing code here
}
</code>```

Title: deleting line from file MQL4

Body:
I am saving all the trades done by my EA into a CSV file.  When a Trade is closed by the EA, I have to add string "Book Profit" to the end of  particular line from the file.
eg:
Below is the line that is saved in the file while trade is open
"Buy GBPJPY 146.28 145.15", I would like to add string "Book Profit" to the end of the above line and save it to the file.
After saving the line should look like
"Buy GBPJPY 146.28 145.15 Book Profit"

int file_handle_dtf=FileOpen("MyTrades.CSV",FILE_READ|FILE_WRITE|FILE_CSV);
   if(file_handle_dtf!=INVALID_HANDLE){
      while(!FileIsEnding(file_handle_dtf)){

         str_size1=FileReadInteger(file_handle_dtf,INT_VALUE);
         //--- read the string

         str1=FileReadString(file_handle_dtf,str_size1);
         strBP=StringConcatenate(str1,",Book Profit");
         FileWriteString(file_handle_dtf,strBP+"\n");
         }

      }

This code just overwrites the file and it is not readable

Body:
Seek the end of the file first before writing to it:

if (FileSeek(file_handle_dtf, 0, SEEK_END))
{
   // put file writing code here
}


问:
How to use routerLink with innerHTML
I am using Angular 6. I just want to create a dynamic route by using the innerHTML. I tried the following code but it is not working.
In the component file, I wrote the following code inside the constructor:

this.anchor = "Dynamic Login"
```
<p>In the template file, I wrote the following code:</p>
<pre class="lang-html prettyprint-override"><code><div [innerHtml]="anchor"></div>
</code>```

答:
I had the same issue. I just replaced the Something

to

```<code><a href="#/something">Something</a>
</code>```

And it works just fine

Title: How to use routerLink with innerHTML

Body:
I am using Angular 6. I just want to create a dynamic route by using the innerHTML. I tried the following code but it is not working.
In the component file, I wrote the following code inside the constructor:

this.anchor = "Dynamic Login"

In the template file, I wrote the following code:

Body:
I had the same issue. I just replaced the <a routerLink="/something">Something</a>

to

<a href="#/something">Something</a>

And it works just fine


问:
When are pytest fixture generators continued and does the scope affect this?
My tests directory looks like this:

```<code>tests/
    conftest.py
    some_of_tests/
        conftest.py
        test_parts.py
        test_these_parts.py
    some_other_tests/
        conftest.py
        test_these_other_parts.py
</code>```

I have a fixture in the /tests/confest.py that creates some test file, instantiates a database connection, then does some database cleanup:

```<code>@pytest.fixture(scope='session', autouse=True)
def setup_db():
    try:
        generate_test_files()
        db = connect_to_db()
        yield db
    finally:
        # cleanup
        print("Cleaning up session scoped fixture")
</code>```

Within the tests/some_tests/conftest.py, I have another fixture that creates some files, creates a database table, then deletes those files:

```<code>@pytest.fixture(scope='package')
def local_setup():
    try:
        generate_test_files()
        # do stuff with db
        yield db
    finally:
        delete_test_files()
        print("Cleaning up package scoped fixture")
</code>```

I have my tests set up in such a way that I'd like the test files generated by some_of_tests to be cleaned up before running the tests in some_other_tests. I was expecting the fixtures in some_of_tests to continue and call delete_test_files() before running the tests in the some_other_tests, but when I run pytest --capture=no tests, I see:

```<code>Cleaning up session scoped fixture
Cleaning up package scoped fixture
</code>```

after all the tests have run, and they are not in the order I expected. What am I misunderstanding and what is the best way to cleanup package scoped tests before running the next package of tests?

Also, I understand that pytest runs in alphabetical order. I am exploiting this to run the tests in the order I want them to. So pytest would run them like some_of_tests/test_parts.py -> some_of_tests/test_these_parts.py -> some_other_tests/test_these_other_parts.py

答:
I was facing the same problem. But what i concluded was you need to have __init__.py added to your tests so that they can be recognized as packages.
Else it will run the teardown for the test in the end and act like a session.

For ex:

```<code>system_test/
     - conftest.py
     - test_dir1/
          - __init__.py
          - conftest.py (here put scope as package)
          - test1.py
          - test2.py
     - test_dir2/
          - __init__.py
          - test1.py
          - test2.py
          - conftest.py (here put scope as package)
</code>```

It works as expected.

Body:
My tests directory looks like this:

tests/
    conftest.py
    some_of_tests/
        conftest.py
        test_parts.py
        test_these_parts.py
    some_other_tests/
        conftest.py
        test_these_other_parts.py

I have a fixture in the /tests/confest.py that creates some test file, instantiates a database connection, then does some database cleanup:

@pytest.fixture(scope='session', autouse=True)
def setup_db():
    try:
        generate_test_files()
        db = connect_to_db()
        yield db
    finally:
        # cleanup
        print("Cleaning up session scoped fixture")

Within the tests/some_tests/conftest.py, I have another fixture that creates some files, creates a database table, then deletes those files:

@pytest.fixture(scope='package')
def local_setup():
    try:
        generate_test_files()
        # do stuff with db
        yield db
    finally:
        delete_test_files()
        print("Cleaning up package scoped fixture")

I have my tests set up in such a way that I'd like the test files generated by some_of_tests to be cleaned up before running the tests in some_other_tests. I was expecting the fixtures in some_of_tests to continue and call delete_test_files() before running the tests in the some_other_tests, but when I run pytest --capture=no tests, I see:

Cleaning up session scoped fixture
Cleaning up package scoped fixture

after all the tests have run, and they are not in the order I expected. What am I misunderstanding and what is the best way to cleanup package scoped tests before running the next package of tests?

Also, I understand that pytest runs in alphabetical order. I am exploiting this to run the tests in the order I want them to. So pytest would run them like some_of_tests/test_parts.py -> some_of_tests/test_these_parts.py -> some_other_tests/test_these_other_parts.py

Body:
I was facing the same problem. But what i concluded was you need to have __init__.py added to your tests so that they can be recognized as packages.
Else it will run the teardown for the test in the end and act like a session.

For ex:

system_test/
     - conftest.py
     - test_dir1/
          - __init__.py
          - conftest.py (here put scope as package)
          - test1.py
          - test2.py
     - test_dir2/
          - __init__.py
          - test1.py
          - test2.py
          - conftest.py (here put scope as package)

It works as expected.


问:
Python tutorial code from RabbitMQ failing to run
Edit: I had the wrong version of the pika package installed on my device. It works fine after I updated from pip.

I just started learning the usage of RabbitMQ (using Python) by following their tutorial. The send.py code works works fine but when I try to run receive.py, I see this error:

```<code>Traceback (most recent call last):
  File "receive.py", line 15, in <module>
    no_ack=True)
TypeError: basic_consume() got multiple values for keyword argument 'queue'
</code>```

Here's the code inside receive.py:

```<code>#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
</code>```

Any idea what I am doing wrong?

答: I got the same issue on Ubuntu 18.04 with the in-stock python-pika package version 0.11.0-1, after I remove the in-stock version and installed a newer version pika (1.0.1) by pip, this issue disappeared.</p>

Body:
Edit: I had the wrong version of the pika package installed on my device. It works fine after I updated from pip.

I just started learning the usage of RabbitMQ (using Python) by following their tutorial. The send.py code works works fine but when I try to run receive.py, I see this error:

Traceback (most recent call last):
  File "receive.py", line 15, in <module>
    no_ack=True)
TypeError: basic_consume() got multiple values for keyword argument 'queue'

Here's the code inside receive.py:

#!/usr/bin/env python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

Any idea what I am doing wrong?


问:
Highcharts xrange styling
I want to display my highchart like below. I'm using an 'xrange' type highchart for this. I'm trying to display an event for each data point where there will be a start data and an end date.

So far i was able to create this chart using xrange type, but I was not able to get the exact display like the above image.
Below is my code,

Highcharts.chart('container', {
    chart: {
        type: 'xrange'
    },
    title: {
        text: ''
    },
    xAxis: {
        visible: false
    },
    yAxis: {
        visible: false
    },
    legend: {
        enabled: false
    },
    series: [{
        name: '',
        pointWidth: 20,
        data: [{
            x: Date.UTC(2014, 10, 21),
            x2: Date.UTC(2014, 11, 2),
            y: 0,
            color: 'rgba(230, 141, 11, 0.5)',
            pointWidth: 10
        }, {
            x: Date.UTC(2014, 10, 26),
            x2: Date.UTC(2014, 11, 5),
            color: 'rgba(228, 53, 70, 0.5)',
            y: 0,
            pointWidth: 10
        }, {
            x: Date.UTC(2014, 11, 8),
            x2: Date.UTC(2014, 11, 10),
            color: 'rgba(40, 167, 69, 0.5)',
            y: 0,
            pointWidth: 10
        }, {
            x: Date.UTC(2014, 11, 9),
            x2: Date.UTC(2014, 11, 19),
            color: 'rgba(40, 147, 164, 0.5)',
            y: 0,
            pointWidth: 10
        }],
        dataLabels: {
            enabled: false
        }
    }]

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import 'https://code.highcharts.com/css/highcharts.css';

#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}</code>```

```

Is there a way to change my implementation in highchart to get output like the above?

答:
You can set a transparent color for points and use border color to achieve the wanted result. Use xAxis to add the black line under the series.

```<code>xAxis: {
    visible: true,
    tickLength: 0,
    lineWidth: 6,
    lineColor: '#000',
    labels: {
        enabled: false
    }
},
series: [{
    borderWidth: 6,
    data: [{
        x: Date.UTC(2014, 10, 21),
        x2: Date.UTC(2014, 11, 2),
        y: 0,
        color: 'transparent',
        borderColor: 'rgba(230, 141, 11, 0.5)'
    }, ...],
    ...
}]
</code>```

Live demo: http://jsfiddle.net/BlackLabel/8p0weh7s/

API Reference:

https://api.highcharts.com/highcharts/series.xrange.borderColor

https://api.highcharts.com/highcharts/xAxis.labels.enabled

Title: Highcharts xrange styling

Body:
I want to display my highchart like below. I'm using an 'xrange' type highchart for this. I'm trying to display an event for each data point where there will be a start data and an end date.

So far i was able to create this chart using xrange type, but I was not able to get the exact display like the above image.
Below is my code,

Highcharts.chart('container', {
    chart: {
        type: 'xrange'
    },
    title: {
        text: ''
    },
    xAxis: {
        visible: false
    },
    yAxis: {
        visible: false
    },
    legend: {
        enabled: false
    },
    series: [{
        name: '',
        pointWidth: 20,
        data: [{
            x: Date.UTC(2014, 10, 21),
            x2: Date.UTC(2014, 11, 2),
            y: 0,
            color: 'rgba(230, 141, 11, 0.5)',
            pointWidth: 10
        }, {
            x: Date.UTC(2014, 10, 26),
            x2: Date.UTC(2014, 11, 5),
            color: 'rgba(228, 53, 70, 0.5)',
            y: 0,
            pointWidth: 10
        }, {
            x: Date.UTC(2014, 11, 8),
            x2: Date.UTC(2014, 11, 10),
            color: 'rgba(40, 167, 69, 0.5)',
            y: 0,
            pointWidth: 10
        }, {
            x: Date.UTC(2014, 11, 9),
            x2: Date.UTC(2014, 11, 19),
            color: 'rgba(40, 147, 164, 0.5)',
            y: 0,
            pointWidth: 10
        }],
        dataLabels: {
            enabled: false
        }
    }]

});

@import 'https://code.highcharts.com/css/highcharts.css';

#container {
    min-width: 300px;
    max-width: 800px;
    height: 300px;
    margin: 1em auto;
}

Is there a way to change my implementation in highchart to get output like the above?

Body:
You can set a transparent color for points and use border color to achieve the wanted result. Use xAxis to add the black line under the series.

xAxis: {
    visible: true,
    tickLength: 0,
    lineWidth: 6,
    lineColor: '#000',
    labels: {
        enabled: false
    }
},
series: [{
    borderWidth: 6,
    data: [{
        x: Date.UTC(2014, 10, 21),
        x2: Date.UTC(2014, 11, 2),
        y: 0,
        color: 'transparent',
        borderColor: 'rgba(230, 141, 11, 0.5)'
    }, ...],
    ...
}]

Live demo: http://jsfiddle.net/BlackLabel/8p0weh7s/

API Reference:

https://api.highcharts.com/highcharts/series.xrange.borderColor

https://api.highcharts.com/highcharts/xAxis.labels.enabled


问:
Add ALT attribute via jquery seems not working as expected
I'm trying to auto assign the alt attribute to images without it. This is my code:

```<code>$(document).ready(function () {
    var attr = $(this).attr('alt');
    if (typeof attr === typeof undefined || attr === false) {
        $('img').each(function () {
            var $img = $(this);
            var filename = $img.attr('src');
            $img.attr('title', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
            $img.attr('alt', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
        });
    }
});
</code>```

I have a dropdown selector with flag images for countries. Until user do not click on the dropdown selector the images are not displayed. I think that this is causing the code to do not work as expected.

If I check the output of the page, for example in Firefox view source code, I can't find any alt attribute added to the images. Meanwhile if I just analize the element in Firefox I see that the alt attribute is correctly added to the img tag.

Why? What's wrong? How should I edit it so that the page always has the alt attributes added to the code soon as it loads? This is important to me for page accessibility.

Thanks in advance.

答:
```<code>jQuery(document).ready(function () {
   jQuery("img").each(function(){
       if(!jQuery(this).attr("alt")  || jQuery(this).attr("alt") == ''){
            var filename = jQuery(this).attr('src');
            var alt = filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.'));
            jQuery(this).attr("alt", alt);
       }
   });
});
</code>```

Body:
I'm trying to auto assign the alt attribute to images without it. This is my code:

$(document).ready(function () {
    var attr = $(this).attr('alt');
    if (typeof attr === typeof undefined || attr === false) {
        $('img').each(function () {
            var $img = $(this);
            var filename = $img.attr('src');
            $img.attr('title', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
            $img.attr('alt', filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.')));
        });
    }
});

I have a dropdown selector with flag images for countries. Until user do not click on the dropdown selector the images are not displayed. I think that this is causing the code to do not work as expected.

If I check the output of the page, for example in Firefox view source code, I can't find any alt attribute added to the images. Meanwhile if I just analize the element in Firefox I see that the alt attribute is correctly added to the img tag.

Why? What's wrong? How should I edit it so that the page always has the alt attributes added to the code soon as it loads? This is important to me for page accessibility.

Thanks in advance.


问:
GoogleAnalytics API Audience > Technology > Network > Service Provider
There is a proliferation of LeadFeeder, WhoisVisiting, Leady, LeadFuse, LeadForensics type sites.

The founder of LeadFeeder wrote about it here: https://analytics.googleblog.com/2016/09/using-google-analytics-with-leadfeeder.html.

They all use the Google Analytics API to gather the Audience > Technology > Network > Service Provider field.

For the life of me I can't find this in the API documentation.

I went through every core Dimension I could find here: https://developers.google.com/analytics/devguides/reporting/core/dimsmets

The only other thing I can think of is that maybe the Network Audience is only available to Google Analytics 360 Premium?

I've scoured the API documentation and Googled it into the ground.

Not much code to show... unless you know the right API function to call... which I can't figure out!

答: It's called networkLocation in the API.</p>

Body: It's called networkLocation in the API.


问:
Placing image over view in react native
I'm trying to place my image over view that is already on other view but no success...

I had been trying to use position:'absolute' and more other options I had seen but it didn't work for me.

```<code>render() {
    let locationFlag=Platform.OS === 'ios'?true:false
    return (
      <View style={styles.container}>
        <LinearGradient
          colors={[ '#75a4e7','#7d50f6']}
          start={{x: .2, y: 1}}
          end={{x:.8,y:0}}
          locations={locationFlag?[.15,1]:[.18,2.1]}
          style={styles.gradient}>

          <View style={styles.profilePhotoContainer}>
          <TouchableOpacity onPress={this.handleEditProfileImage.bind(this)}>
          <Image
          style={styles.profileImage}
          source={this.state.profilePhoto}
        />
       </TouchableOpacity>

          </View>
        </LinearGradient>

        <View style={
            [styles.profileBox]}
          >
         </View>
        </View>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignSelf: 'stretch',
    backgroundColor: Colors.LIGHT_GRAY
  },
gradient: {
    alignSelf: 'stretch',
    alignItems: 'center',
    flexDirection: 'column',
    height: Dimensions.get('window').height * .35,
  },
profilePhotoContainer: {
    zIndex: 50,
    position: 'absolute',
    backgroundColor:'blue',
    top: Dimensions.get('window').height * .12,
    elevation: 4,
  },
  profileImage: {
    zIndex: 5,
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 4,
    borderColor: '#FFF',
    backgroundColor: 'transparent',
  },
 profileBox: {
    zIndex: 1,
    position: 'absolute',
    left: Dimensions.get('window').width * .07,
    top: Dimensions.get('window').height * .18,
    borderRadius: 8,
    shadowRadius: 8,
    elevation: 3,
    shadowOpacity: 0.3,
    backgroundColor: 'yellow',
    width: Dimensions.get('window').width * .86,
    height: Dimensions.get('window').height * .50,
    }

</code>```

In the link you can see what did I do so far and what is the issue:

https://imgur.com/a/kC4ZTUn

I want to achieve this situation:

https://imgur.com/a/KMSRVfZ

Thank you

答:
Here is a sample code to achieve similar to the design,

```<code><View style={{flex: 1}}>
   <View style={{flex:0.33,backgroundColor:"aqua",justifyContent:"center",alignItems:"center"}}>
     <View style={{position:"absolute",backgroundColor:"grey",height:200,width:100,borderRadius:5,left:0.23*width,top:0.25*height}}/> {/*Represents the box where you add user name, profession etc  */}
     <View style={{backgroundColor:"yellow",height:50,width:50,borderRadius:25}}/> {/*Image tag goes here  */}
    </View>
  </View>
</code>```

I don't feel the necessity to add position:"absolute" prop for the profilePhotoContainerthe positioning can be controlled by flex principles. You may require only one view with position:"absolute" prop.

Do comment if you require further assistance.

Title: Placing image over view in react native

Body:
I'm trying to place my image over view that is already on other view but no success...

I had been trying to use position:'absolute' and more other options I had seen but it didn't work for me.

render() {
    let locationFlag=Platform.OS === 'ios'?true:false
    return (
      <View style={styles.container}>
        <LinearGradient
          colors={[ '#75a4e7','#7d50f6']}
          start={{x: .2, y: 1}}
          end={{x:.8,y:0}}
          locations={locationFlag?[.15,1]:[.18,2.1]}
          style={styles.gradient}>

          <View style={styles.profilePhotoContainer}>
          <TouchableOpacity onPress={this.handleEditProfileImage.bind(this)}>
          <Image
          style={styles.profileImage}
          source={this.state.profilePhoto}
        />
       </TouchableOpacity>

          </View>
        </LinearGradient>

        <View style={
            [styles.profileBox]}
          >
         </View>
        </View>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'flex-start',
    alignSelf: 'stretch',
    backgroundColor: Colors.LIGHT_GRAY
  },
gradient: {
    alignSelf: 'stretch',
    alignItems: 'center',
    flexDirection: 'column',
    height: Dimensions.get('window').height * .35,
  },
profilePhotoContainer: {
    zIndex: 50,
    position: 'absolute',
    backgroundColor:'blue',
    top: Dimensions.get('window').height * .12,
    elevation: 4,
  },
  profileImage: {
    zIndex: 5,
    width: 100,
    height: 100,
    borderRadius: 50,
    borderWidth: 4,
    borderColor: '#FFF',
    backgroundColor: 'transparent',
  },
 profileBox: {
    zIndex: 1,
    position: 'absolute',
    left: Dimensions.get('window').width * .07,
    top: Dimensions.get('window').height * .18,
    borderRadius: 8,
    shadowRadius: 8,
    elevation: 3,
    shadowOpacity: 0.3,
    backgroundColor: 'yellow',
    width: Dimensions.get('window').width * .86,
    height: Dimensions.get('window').height * .50,
    }

In the link you can see what did I do so far and what is the issue:

https://imgur.com/a/kC4ZTUn

I want to achieve this situation:

https://imgur.com/a/KMSRVfZ

Thank you

Body:
Here is a sample code to achieve similar to the design,

<View style={{flex: 1}}>
   <View style={{flex:0.33,backgroundColor:"aqua",justifyContent:"center",alignItems:"center"}}>
     <View style={{position:"absolute",backgroundColor:"grey",height:200,width:100,borderRadius:5,left:0.23*width,top:0.25*height}}/> {/*Represents the box where you add user name, profession etc  */}
     <View style={{backgroundColor:"yellow",height:50,width:50,borderRadius:25}}/> {/*Image tag goes here  */}
    </View>
  </View>

I don't feel the necessity to add position:"absolute" prop for the profilePhotoContainerthe positioning can be controlled by flex principles. You may require only one view with position:"absolute" prop.

Do comment if you require further assistance.


问:
Laravel 5.7 error return response()->json(['content'=>'a
b]); then it turns into

I am having the php error of returning the json api incorrectly, it is correctly affected by the html tag
. Project 102tube.tv I am developing Laravel 5.7

I have data in api as follows:

```<code>$arr = ['contetn' => 'line 1 <br /> line 2'];
return response()->json($arr);
</code>```

And the situation I'm having:

It is suffering from the problem of being replate from
 to

Does anyone know why?

答:
It's happning because once it will be encoded using json_encode the / will be stripped.

Laravel internally used json_encode to send response in json. If you would like to skip the slashes...you'll have to manually encode with option JSON_UNESCAPED_SLASHES and send the response.

Like

```<code>$arr = ['contetn' => 'line 1 <br /> line 2'];

$res = json_encode($arr, JSON_UNESCAPED_SLASHES);

return response($res, 200)
                  ->header('Content-Type', 'application/json');
</code>```

For more details on json response check the documentation..
https://laravel.com/docs/5.8/responses#json-responses

Title: Laravel 5.7 error return response()->json(['content'=>'a<br />b]); then it turns into <br \>

Body:
I am having the php error of returning the json api incorrectly, it is correctly affected by the html tag
. Project 102tube.tv I am developing Laravel 5.7

I have data in api as follows:

$arr = ['contetn' => 'line 1
 line 2'];
return response()->json($arr);

And the situation I'm having:

It is suffering from the problem of being replate from
 to

Does anyone know why?

Body:
It's happning because once it will be encoded using json_encode the / will be stripped.

Laravel internally used json_encode to send response in json. If you would like to skip the slashes...you'll have to manually encode with option JSON_UNESCAPED_SLASHES and send the response.

Like

$arr = ['contetn' => 'line 1 <br /> line 2'];

$res = json_encode($arr, JSON_UNESCAPED_SLASHES);

return response($res, 200)
                  ->header('Content-Type', 'application/json');

For more details on json response check the documentation..
https://laravel.com/docs/5.8/responses#json-responses


问:
Moodle localized date_selector
The following snippet creates a date selector using the Moodle Forms API:

```<code>$form->addElement('date_selector', 'html_id', 'label', $options);
</code>```

As per documentation (https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#date_selector) options supports the following settings:

```<code>array(
    'startyear' => 1970,
    'stopyear'  => 2020,
    'timezone'  => 99,
    'optional'  => false
);
</code>```

I am missing an option for localization here. As the Moodle API is based on PHP QuickForm I hoped that I could pass a language option like it is supported by HTML_QuickForm_date (https://pear.php.net/manual/en/package.html.html-quickform.html-quickform-date.php). Apparently, I was wrong.

Is there a way to get a Moodle date picker with non-English month names?

答:
Also posted the question in the Moodle developer forum: https://moodle.org/mod/forum/discuss.php?d=386699#p1558991

Short answer: Normally, all widgets are localized according to the current language by default. However, we're using Docker which lacks some i18n tools or configuration. Therefore, certain features (like the date picker dialog) are not properly localized.

Title: Moodle localized date_selector

Body:
The following snippet creates a date selector using the Moodle Forms API:

$form->addElement('date_selector', 'html_id', 'label', $options);

As per documentation (https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#date_selector) options supports the following settings:

array(
    'startyear' => 1970,
    'stopyear'  => 2020,
    'timezone'  => 99,
    'optional'  => false
);

I am missing an option for localization here. As the Moodle API is based on PHP QuickForm I hoped that I could pass a language option like it is supported by HTML_QuickForm_date (https://pear.php.net/manual/en/package.html.html-quickform.html-quickform-date.php). Apparently, I was wrong.

Is there a way to get a Moodle date picker with non-English month names?


问:
Correct way to format input and output of TimeField in Django Rest Famework?
models.py

```<code>class DemoA(models.Model):
    my_time = models.TimeField()
</code>```

serializers.py

```<code>class DemoASerializer(serializer.ModelSerializer):
    class Meta:
        model = DemoA
        fields = ('my_time', )
</code>```

By default, for my_time field, it gives the format as 10:30:00, (%H:%M:%S). What is want is the serialized format as 10:30, (%H:%M).

Is there any default way to specify format for such cases, like specifying extra_kwargs in serializer Meta?

答:
Setting the format on the serializer works, but it can be antipattern on scale, since you will need to add it to all your serializers across your entire application. DRF allows you to set it on your settings as the default format for your application. You show set it, and override the format on serializer only when needed.</p>

```<code>REST_FRAMEWORK = {
   ... # your other stuff
   'TIME_INPUT_FORMATS': ('%H:%M', )
}
</code>```

Body:
models.py

class DemoA(models.Model):
    my_time = models.TimeField()

serializers.py

class DemoASerializer(serializer.ModelSerializer):
    class Meta:
        model = DemoA
        fields = ('my_time', )

By default, for my_time field, it gives the format as 10:30:00, (%H:%M:%S). What is want is the serialized format as 10:30, (%H:%M).

Is there any default way to specify format for such cases, like specifying extra_kwargs in serializer Meta?

Body:
Setting the format on the serializer works, but it can be antipattern on scale, since you will need to add it to all your serializers across your entire application. DRF allows you to set it on your settings as the default format for your application. You show set it, and override the format on serializer only when needed.

REST_FRAMEWORK = {
   ... # your other stuff
   'TIME_INPUT_FORMATS': ('%H:%M', )
}


问:
Weird object issue when trying to render partial from mailer view
Using Rails 3. Per first snippet of code below, it's hard to google search what this error means when trying to render a partial from my mailer view.

This is the error:

```<code>ActionView::Template::Error (undefined method `long_date' for #<#<Class:0x00000102452ab0>:0x00000102440b30>):
</code>```

Here's my mailer view (email_note.html.erb)

```<code><div style="width:500px;">
  <%= render :partial => "shared/note", :object => @note %>
</div>
</code>```

This is the call i'm making in my partial that is throwing the error
    <%= long_date(note.created_at) %>

long_date has always worked when I have given the partial @note objects from other actions (e.g. 'show' in my notes_controller). this is the method

```<code>def long_date(date)
  date.strftime('%A %b %e, %G')
end
</code>```

Here is my ActionMailer class (address and note_id are sent from an 'email' action in my notes_controller)

```<code>class UserMailer < ActionMailer::Base
 default :from => "gminett@gmail.com"

  def email_note(address,note_id)
    @note = Note.find(note_id)
    mail(:to => "#{address}", :subject => "Note from repository: #{@note.subject}")
  end
end
</code>```

Seems to me rails (very most likely due to some oversight on my part) is not interpreting my @note object as a Note class, but i don't know how to fix it. Help is much appreciated.

答:
This is because by default ActionMailer templates don't share the same helpers that ActionView ones do. If you need to use helpers in your mailer templates then try including the module in your ActionMailer class:</p>

```<code>include DateTimeHelper
</code>```

Body:
Using Rails 3. Per first snippet of code below, it's hard to google search what this error means when trying to render a partial from my mailer view.

This is the error:

ActionView::Template::Error (undefined method `long_date' for #<#<Class:0x00000102452ab0>:0x00000102440b30>):

Here's my mailer view (email_note.html.erb)

  <%= render :partial => "shared/note", :object => @note %>

This is the call i'm making in my partial that is throwing the error
    <%= long_date(note.created_at) %>

long_date has always worked when I have given the partial @note objects from other actions (e.g. 'show' in my notes_controller). this is the method

def long_date(date)
  date.strftime('%A %b %e, %G')
end

Here is my ActionMailer class (address and note_id are sent from an 'email' action in my notes_controller)

class UserMailer < ActionMailer::Base
 default :from => "gminett@gmail.com"

  def email_note(address,note_id)
    @note = Note.find(note_id)
    mail(:to => "#{address}", :subject => "Note from repository: #{@note.subject}")
  end
end

Seems to me rails (very most likely due to some oversight on my part) is not interpreting my @note object as a Note class, but i don't know how to fix it. Help is much appreciated.

Body:
This is because by default ActionMailer templates don't share the same helpers that ActionView ones do. If you need to use helpers in your mailer templates then try including the module in your ActionMailer class:

include DateTimeHelper