问:
Place imageview next to textview
I'm trying to place an imageview next to a textview. However they keep ending up on different "lines".

```<code>    <ImageView
      android:layout_width="10dp"
      android:layout_height="wrap_content"
      android:id="@+id/medication_administration_time_row_fmk_icon" />

    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_toLeftOf="@id/medication_administration_time_row_fmk_icon"
      android:id="@+id/medication_administration_time_row_drug" />
</code>```

Placing the image as a compound drawable isn't an option as that is used for another image.

Any clues about how I can get the image on the same line as the text?

答:
You can do it like this</p>

```<code>        <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="4dp"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/imageViewTipoProduto"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="16dp"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="8dp"
                    app:srcCompat="@drawable/ic_kit_produtos_white_12dp" />

                <TextView
                    android:id="@+id/textViewTipoProduto"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="22dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginStart="8dp"
                    android:layout_marginTop="4dp"
                    android:fontFamily="sans-serif-light"
                    android:letterSpacing="0.04"
                    android:text="@string/kit_de_produtos"
                    android:textColor="#ffffff"
                    android:textSize="14sp"
                    android:textStyle="normal" />

            </LinearLayout>
</code>```

Title: Place imageview next to textview

Body:
I'm trying to place an imageview next to a textview. However they keep ending up on different "lines".

    <ImageView
      android:layout_width="10dp"
      android:layout_height="wrap_content"
      android:id="@+id/medication_administration_time_row_fmk_icon" />

    <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_toLeftOf="@id/medication_administration_time_row_fmk_icon"
      android:id="@+id/medication_administration_time_row_drug" />

Placing the image as a compound drawable isn't an option as that is used for another image.

Any clues about how I can get the image on the same line as the text?

Body:
You can do it like this

        <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="4dp"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/imageViewTipoProduto"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="16dp"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="8dp"
                    app:srcCompat="@drawable/ic_kit_produtos_white_12dp" />

                <TextView
                    android:id="@+id/textViewTipoProduto"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="22dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginStart="8dp"
                    android:layout_marginTop="4dp"
                    android:fontFamily="sans-serif-light"
                    android:letterSpacing="0.04"
                    android:text="@string/kit_de_produtos"
                    android:textColor="#ffffff"
                    android:textSize="14sp"
                    android:textStyle="normal" />

            </LinearLayout>


来源: stackexchange

问:
Run Proguard on multi-module project as "one piece"
TLDR: How to pass proguard mapping to javac to compile against obfuscated library ?

That's long, but I don't see how to make it shorter:

Background:
I have the following product setup:

Android Studio project
 - Library module
    - (sub)module Core
    - (sub)module A
    - (sub)module B
    - (sub)module C
- Sample App module
- ... Other modules

Each of library submodules A, B, C reference classes in Core, but A, B, C independent among themselves. Conceptually similar to Play Services where user can only have code and required sub-module.
Each of the library submodules has external APIs but also many internal classes
The goal is to be able to distribute Core, A, B, C as independent aar-s.

Goal:
obfuscate all sub-modules together leaving only public APIs exposed but package and distribute them separately in obfuscated/optimized form.

Issue:
I do not see how to use it with straightforward gradle configuration. Custom build system is needed here, Unless there is a any known solution?

What is needed here is:

Java-Compile all sub-modules together

Proguard-obfuscate them together

Run all the rest of the build process separately

Where is normal build process is for each module is:
- Compile -> do everything incl. obfuscation -> package

Straight forward setup fails at the compilation of the first submodule after Core. If it only would be possible to pass Proguard mapping.txt as an input to Java compiler... But I could not find such an option. Any ideas?

Thanks!!!

答:
I've had the same problem, and I've written this post on my personal website.

In essence, what you are looking for is the maven-publish Gradle plugin, that will allow you to package your library modules to AAR and conveniently manage and distribute them, while retaining the information on their dependencies.

You can configure this plugin to package a specific buildType for which you will enable proguard obfuscation.

ContentLicense: CC BY-SA 3.0


问:
How to save mxworkflow editor as Xml using javascript
Iam using mxWorkflow -Editor to draw workflow process

then i tried to save the  workflow as xml but it is not working

i tried this

```<code>  function GetXML(container)
{
    var graph = new mxGraph(container);
    var enc = new mxCodec();
    var node = enc.encode(graph.getModel());

    var model = graph.getModel();
    try
    {
       // var graph = new mxGraph(container);
        graph.model.addListener(mxEvent.CHANGE, function (sender, evt) {

            var changes = evt.getProperty('edit').changes;

            for (var i = 0; i < changes.length; i++) {
                var change = changes[i];

                if (change instanceof mxChildChange &&
                  change.change.previous == null) {
                    graph.startEditingAtCell(change.child);
                    break;
                }
            }
        });
    }
    finally
    {
        // Updates the display

        model.endUpdate();
       // graph.getModel().endUpdate();
    }

// Adds an option to view the XML of the graph
document.body.appendChild(mxUtils.button('View XML', function()
{
    var encoder = new mxCodec();
    var node = encoder.encode(graph.getModel());
    mxUtils.popup(mxUtils.getXml(node), true);
}));
</code>```

I've looked at few posts & documentation , but didn't find anything

答:
use function mxUtils.getPrettyXml

var button = mxUtils.button('View XML', function() {
    var encoder = new mxCodec();
    var node = encoder.encode(graph.getModel());
    mxUtils.popup(mxUtils.getPrettyXml(node), true);
});
document.appendChild(button);```

Body:
Iam using mxWorkflow -Editor to draw workflow process

then i tried to save the  workflow as xml but it is not working

i tried this

  function GetXML(container)
{
    var graph = new mxGraph(container);
    var enc = new mxCodec();
    var node = enc.encode(graph.getModel());

    var model = graph.getModel();
    try
    {
       // var graph = new mxGraph(container);
        graph.model.addListener(mxEvent.CHANGE, function (sender, evt) {

            var changes = evt.getProperty('edit').changes;

            for (var i = 0; i < changes.length; i++) {
                var change = changes[i];

                if (change instanceof mxChildChange &&
                  change.change.previous == null) {
                    graph.startEditingAtCell(change.child);
                    break;
                }
            }
        });
    }
    finally
    {
        // Updates the display

        model.endUpdate();
       // graph.getModel().endUpdate();
    }

// Adds an option to view the XML of the graph
document.body.appendChild(mxUtils.button('View XML', function()
{
    var encoder = new mxCodec();
    var node = encoder.encode(graph.getModel());
    mxUtils.popup(mxUtils.getXml(node), true);
}));

I've looked at few posts & documentation , but didn't find anything


问:
iPhone app update while still in background
I was wondering what happens if a user updates an app (through the app store/update) while the app is still in the background on iOS 4.x

I am planning a big update for my next release and I wanted to know if it is a special case I have to handle to avoid a crash.

Or can I trust the OS to restart the application on the next launch (or to kill the background process during the update), detecting that the application has changed instead of just doing a "applicationWillEnterForeground"?

答: iOS / Apple take care of that use-case for you, you don't need to worry about it. Your app will get terminated, so when the user next taps its icon you will have a relaunch. </p>

ContentLicense: CC BY-SA 2.5


问:
Weird Value When Calculating Date Difference
I have been using the following code to calculate the difference between two dates and I have been getting an unusual error:

if I pass the following dates:

d1 = 08/12/2017
d2 = 31/07/2022

it returns: 24055..

isn't the result supposed to be return as the number of months?

```<code> public static int CalcDateDiff( java.util.Date  date1,  java.util.Date  date2) {
    if(date1 == null || date2 ==null )
    {
        if(date2 == null)
        {
              Calendar d1 = Calendar.getInstance();
                d1.setTime(date1);
                final Calendar d2 = Calendar.getInstance();
                int diff = (d2.get(Calendar.YEAR) - d1.get(Calendar.YEAR)) * 12 + d2.get(Calendar.MONTH) - d1.get(Calendar.MONTH);

                return diff;
        }
        else
            return -1;
    }
    else
    {

            Calendar d1 = Calendar.getInstance();
            d1.setTime(date1);
            final Calendar d2 = Calendar.getInstance();
            d2.setTime(date2);
            int diff = (d2.get(Calendar.YEAR) - d1.get(Calendar.YEAR)) * 12 + d2.get(Calendar.MONTH) - d1.get(Calendar.MONTH);

            return diff;
        }
}
</code>```

Thanks in advance!

答:
Best Solution:

If you already have java.sql.Date instances then

```<code>final Date d1 = new java.sql.Date(2017 - 1900, 12, 8);
final Date d2 = new java.sql.Date(2022 - 1900, 07, 31);
</code>```

I know that I am using a deprecated constructor in java.sql.Date, that is just for convenience to get what I need in the least amount of lines of code.
  Never use this constructor in production code!

The simplest most straightforward self documenting way to get what you want:

```<code>final long monthsBetween ChronoUnit.MONTHS.between(d1.toLocalDate(),d2.toLocalDate()) + 1;
</code>```

Because with this method you do not have to twiddle with TimeZone information because it is all guaranteed to be correct for instances of LocalDate created this way.

For some reason only java.sql.Date only has .toLocalDate() which is good for you because that is what you get back from the database.

public LocalDate toLocalDate()
  Converts this Date object to a
  LocalDate The conversion creates a LocalDate that represents the same
  date value as this Date in local time zone

Returns: a LocalDate object representing the same date value
  Since:
  1.8

Comments on corrections to your code:

The correct formula is:

```<code>(y2 - y1) * 12 + (m2 - m1) + 1
</code>```

Also, your code is overly complex and using very old classes.

Java 8 Solution and your Java 7 compatible corrected solution:

```<code>public class Q47717075
{
    /*
    https://stackoverflow.com/questions/1086396/java-date-month-difference
     */
    public static void main(@Nonnull final String[] args)
    {
        final Date d1 = new java.sql.Date(2017 - 1900, 12, 8);
        final Date d2 = new java.sql.Date(2022 - 1900, 07, 31);
        System.out.println(CalcDateDiff(d1, d2));
        /* Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z. */
        System.out.println(intervalInMonths(LocalDate.of(2017,12,8), LocalDate.of(2022,7,31)));
        System.out.println(ChronoUnit.MONTHS.between(d1.toLocalDate(),d2.toLocalDate()) + 1);
    }

    /*
       Alternate Java 8 version
     */
    public static int intervalInMonths(@Nonnull final LocalDate i1, @Nonnull final LocalDate i2)
    {
        final Period p = Period.between(i1, i2);
        return (p.getYears() * 12) + p.getMonths() + 1;
    }

    /**
     * Your versin corrected
     */
    public static int CalcDateDiff(@Nonnull final Date date1, @Nonnull final Date date2)
    {
        final Calendar d1 = Calendar.getInstance();
        d1.setTime(date1);
        final Calendar d2 = Calendar.getInstance();
        d2.setTime(date2);

        return ((d2.get(YEAR) - d1.get(YEAR)) * 12 + (d2.get(MONTH) - d1.get(MONTH)) + 1);
    }
}
</code>```

The Correct Output is:

```<code>56
56
56
</code>```

Body:
I have been using the following code to calculate the difference between two dates and I have been getting an unusual error:

if I pass the following dates:

d1 = 08/12/2017
d2 = 31/07/2022

it returns: 24055..

isn't the result supposed to be return as the number of months?

 public static int CalcDateDiff( java.util.Date  date1,  java.util.Date  date2) {
    if(date1 == null || date2 ==null )
    {
        if(date2 == null)
        {
              Calendar d1 = Calendar.getInstance();
                d1.setTime(date1);
                final Calendar d2 = Calendar.getInstance();
                int diff = (d2.get(Calendar.YEAR) - d1.get(Calendar.YEAR)) * 12 + d2.get(Calendar.MONTH) - d1.get(Calendar.MONTH);

                return diff;
        }
        else
            return -1;
    }
    else
    {

            Calendar d1 = Calendar.getInstance();
            d1.setTime(date1);
            final Calendar d2 = Calendar.getInstance();
            d2.setTime(date2);
            int diff = (d2.get(Calendar.YEAR) - d1.get(Calendar.YEAR)) * 12 + d2.get(Calendar.MONTH) - d1.get(Calendar.MONTH);

            return diff;
        }
}

Thanks in advance!

Body:
Best Solution:

If you already have java.sql.Date instances then

final Date d1 = new java.sql.Date(2017 - 1900, 12, 8);
final Date d2 = new java.sql.Date(2022 - 1900, 07, 31);

I know that I am using a deprecated constructor in java.sql.Date, that is just for convenience to get what I need in the least amount of lines of code.
  Never use this constructor in production code!

The simplest most straightforward self documenting way to get what you want:

final long monthsBetween ChronoUnit.MONTHS.between(d1.toLocalDate(),d2.toLocalDate()) + 1;

Because with this method you do not have to twiddle with TimeZone information because it is all guaranteed to be correct for instances of LocalDate created this way.

For some reason only java.sql.Date only has .toLocalDate() which is good for you because that is what you get back from the database.

public LocalDate toLocalDate()
  Converts this Date object to a
  LocalDate The conversion creates a LocalDate that represents the same
  date value as this Date in local time zone

Returns: a LocalDate object representing the same date value
  Since:
  1.8

Comments on corrections to your code:

The correct formula is:

(y2 - y1) * 12 + (m2 - m1) + 1

Also, your code is overly complex and using very old classes.

Java 8 Solution and your Java 7 compatible corrected solution:

public class Q47717075
{
    /*
    https://stackoverflow.com/questions/1086396/java-date-month-difference
     */
    public static void main(@Nonnull final String[] args)
    {
        final Date d1 = new java.sql.Date(2017 - 1900, 12, 8);
        final Date d2 = new java.sql.Date(2022 - 1900, 07, 31);
        System.out.println(CalcDateDiff(d1, d2));
        /* Obtains an instance of Instant from a text string such as 2007-12-03T10:15:30.00Z. */
        System.out.println(intervalInMonths(LocalDate.of(2017,12,8), LocalDate.of(2022,7,31)));
        System.out.println(ChronoUnit.MONTHS.between(d1.toLocalDate(),d2.toLocalDate()) + 1);
    }

    /*
       Alternate Java 8 version
     */
    public static int intervalInMonths(@Nonnull final LocalDate i1, @Nonnull final LocalDate i2)
    {
        final Period p = Period.between(i1, i2);
        return (p.getYears() * 12) + p.getMonths() + 1;
    }

    /**
     * Your versin corrected
     */
    public static int CalcDateDiff(@Nonnull final Date date1, @Nonnull final Date date2)
    {
        final Calendar d1 = Calendar.getInstance();
        d1.setTime(date1);
        final Calendar d2 = Calendar.getInstance();
        d2.setTime(date2);

        return ((d2.get(YEAR) - d1.get(YEAR)) * 12 + (d2.get(MONTH) - d1.get(MONTH)) + 1);
    }
}

The Correct Output is:

56
56
56


问:
Pointer to a class method in c++
A have a lot of B classes, a class A has one object b. This object b has a function (calc) that needs a pointer to a method in an object of A. This method (fun) acess private variables in class (in my example just return 3).

```<code>class A;

class B {
public:
  virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
};

class A {
  B* b;

public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run(){ return b->calc(&A::fun); };
};

int main() {
  B* b = new B();
  A a(b);
  a.run();
  return 0;
}
</code>```

How can I use a pointer to a method correctly in definition of calc method in class B?

I am getting this error message:

```<code>teste.cpp:10:58: error: must use ‘.*’ or ‘->*’ to call pointer-to-member     function in ‘fun (...)’, e.g. ‘(... ->* fun) (...)’
   virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
                                                      ^
</code>```

答:
I recommend the std::function approach if it's feasible for you. However, for the sake of completeness, here's how you would correctly use pointer-to-member functions.

The pointer-to-member itself doesn't store the "current" instance of A, so you need to pass that explicitly. Then you use the special ->* (or .*) syntax to call it.

```<code>virtual int calc (A* value, int (A::*fun)())  {
  return 2 * (value->*fun)();
};
</code>```

Then you would call it as b->calc(this, &A::fun);.

Title: Pointer to a class method in c++

Body:
A have a lot of B classes, a class A has one object b. This object b has a function (calc) that needs a pointer to a method in an object of A. This method (fun) acess private variables in class (in my example just return 3).

class A;

class B {
public:
  virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
};

class A {
  B* b;

public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run(){ return b->calc(&A::fun); };
};

int main() {
  B* b = new B();
  A a(b);
  a.run();
  return 0;
}

How can I use a pointer to a method correctly in definition of calc method in class B?

I am getting this error message:

teste.cpp:10:58: error: must use ‘.*’ or ‘->*’ to call pointer-to-member     function in ‘fun (...)’, e.g. ‘(... ->* fun) (...)’
   virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
                                                      ^

Body:
I recommend the std::function approach if it's feasible for you. However, for the sake of completeness, here's how you would correctly use pointer-to-member functions.

The pointer-to-member itself doesn't store the "current" instance of A, so you need to pass that explicitly. Then you use the special ->* (or .*) syntax to call it.

virtual int calc (A* value, int (A::*fun)())  {
  return 2 * (value->*fun)();
};

Then you would call it as b->calc(this, &A::fun);.


问:
Convert Sparse Matrix from Eigen::SparseMatrix to Cusp::hyb_matrix
I am looking for a way to convert

Eigen::SparseMatrix< float> <-> cusp::hyb_matrix< int, float, cusp::host_memory>

back and forth.

The Eigen matrix is a result of a previous computation and I need a cusp::hyb_matrix to use the GPU for conjugate gradient computation later.

Thanks.

答:
Well, I have found a workaround that does what needed but a more direct way is still missing.

Based on this example, i just needed to extract the rows/cols/coeffs vectors of values from the Eigen::SparseMatrix to construct a cusp::hyb_matrix. This can be done as follows :

```<code>void SparseMatrix2Coo(Eigen::SparseMatrix<float> Matrix, std::vector<int>& rows, std::vector<int>& cols, std::vector<float>& coeffs)
{
rows.clear();
cols.clear();
coeffs.clear();
for (int k=0; k < Matrix.outerSize(); ++k)
{
    for (Eigen::SparseMatrix<float>::InnerIterator it(Matrix,k); it; ++it)
    {
        rows.push_back(it.row());
        cols.push_back(it.col());
        coeffs.push_back(Matrix.coeff(it.row(), it.col()));
    }
}
assert(cols.size() == coeffs.size());
assert(rows.size() == cols.size());
}
</code>```

Now, once we have rows/cols/coeffs, we just need to use those in the example above as inputs :

```<code>void computeConjugateGradientGPU(std::vector<int>& rows, std::vector<int>& cols, std::vector<float>& coeffs, std::vector<float>& b, Eigen::VectorXf& x)
{
int arrays_size = rows.size();
/// allocate device memory for CSR format
int   * device_I;
cudaMalloc(&device_I, arrays_size * sizeof(int));
int   * device_J;
cudaMalloc(&device_J, arrays_size * sizeof(int));
float * device_V;
cudaMalloc(&device_V, arrays_size * sizeof(float));

float * device_b;
cudaMalloc(&device_b, b.size() * sizeof(float));

/// copy raw data from host to device
cudaMemcpy(device_I, &cols[0], arrays_size * sizeof(int),   cudaMemcpyHostToDevice);
cudaMemcpy(device_J, &rows[0], arrays_size * sizeof(int),   cudaMemcpyHostToDevice);
cudaMemcpy(device_V, &coeffs[0], arrays_size * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(device_b, &b[0],  b.size() * sizeof(float), cudaMemcpyHostToDevice);

/// and the rest is the same...
}
</code>```

The other way around is pretty obvious with the same logic.

Hope this helps someone.

Cheers.

Body:
Well, I have found a workaround that does what needed but a more direct way is still missing.

Based on this example, i just needed to extract the rows/cols/coeffs vectors of values from the Eigen::SparseMatrix to construct a cusp::hyb_matrix. This can be done as follows :

void SparseMatrix2Coo(Eigen::SparseMatrix<float> Matrix, std::vector<int>& rows, std::vector<int>& cols, std::vector<float>& coeffs)
{
rows.clear();
cols.clear();
coeffs.clear();
for (int k=0; k < Matrix.outerSize(); ++k)
{
    for (Eigen::SparseMatrix<float>::InnerIterator it(Matrix,k); it; ++it)
    {
        rows.push_back(it.row());
        cols.push_back(it.col());
        coeffs.push_back(Matrix.coeff(it.row(), it.col()));
    }
}
assert(cols.size() == coeffs.size());
assert(rows.size() == cols.size());
}

Now, once we have rows/cols/coeffs, we just need to use those in the example above as inputs :

void computeConjugateGradientGPU(std::vector<int>& rows, std::vector<int>& cols, std::vector<float>& coeffs, std::vector<float>& b, Eigen::VectorXf& x)
{
int arrays_size = rows.size();
/// allocate device memory for CSR format
int   * device_I;
cudaMalloc(&device_I, arrays_size * sizeof(int));
int   * device_J;
cudaMalloc(&device_J, arrays_size * sizeof(int));
float * device_V;
cudaMalloc(&device_V, arrays_size * sizeof(float));

float * device_b;
cudaMalloc(&device_b, b.size() * sizeof(float));

/// copy raw data from host to device
cudaMemcpy(device_I, &cols[0], arrays_size * sizeof(int),   cudaMemcpyHostToDevice);
cudaMemcpy(device_J, &rows[0], arrays_size * sizeof(int),   cudaMemcpyHostToDevice);
cudaMemcpy(device_V, &coeffs[0], arrays_size * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(device_b, &b[0],  b.size() * sizeof(float), cudaMemcpyHostToDevice);

/// and the rest is the same...
}

The other way around is pretty obvious with the same logic.

Hope this helps someone.

Cheers.


问:
Template parse errors: 'md-form-field' is not a known element
I am using Angular 4 and Angular Material 2. For the following code :

```<code><form>
  <md-form-field>
    <input mdInput [ngModel]="userName" placeholder="User" [formControl]="usernameFormControl">
    <md-error *ngIf="usernameFormControl.hasError('required')">
      This is <strong>required</strong>
    </md-error>
    <input mdInput [ngModel]="password" placeholder="Password" [formControl]="passwordFormControl">
    <md-error *ngIf="passwordFormControl.hasError('required')">
      This is <strong>required</strong>
    </md-error>
    <button md-raised-button color="primary" [disabled]="!usernameFormControl.valid || !passwordFormControl.valid">Login</button>
  </md-form-field>
</form>
</code>```

I am getting an error:

Template parse errors: 'md-form-field' is not a known element:
  1. If 'md-form-field' is an Angular component, then verify that it is part of this module.
  2. If 'md-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component
  to suppress this message. ("   [ERROR ->]

Could you please help me where I am missing?

Following is my app.module.ts code where I have imported material modules:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { LoginComponent } from './login.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import {
  MdAutocompleteModule,
  MdButtonModule,
  MdButtonToggleModule,
  MdCardModule,
  MdCheckboxModule,
  MdChipsModule,
  MdCoreModule,
  MdDatepickerModule,
  MdDialogModule,
  MdExpansionModule,
  MdGridListModule,
  MdIconModule,
  MdInputModule,
  MdListModule,
  MdMenuModule,
  MdNativeDateModule,
  MdPaginatorModule,
  MdProgressBarModule,
  MdProgressSpinnerModule,
  MdRadioModule,
  MdRippleModule,
  MdSelectModule,
  MdSidenavModule,
  MdSliderModule,
  MdSlideToggleModule,
  MdSnackBarModule,
  MdSortModule,
  MdTableModule,
  MdTabsModule,
  MdToolbarModule,
  MdTooltipModule
} from '@angular/material';

import {CdkTableModule} from '@angular/cdk';

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpModule,
    FormsModule,
    ReactiveFormsModule,
    MdAutocompleteModule,
    MdButtonModule,
    MdButtonToggleModule,
    MdCardModule,
    MdCheckboxModule,
    MdChipsModule,
    MdCoreModule,
    MdDatepickerModule,
    MdDialogModule,
    MdExpansionModule,
    MdGridListModule,
    MdIconModule,
    MdInputModule,
    MdListModule,
    MdMenuModule,
    MdNativeDateModule,
    MdPaginatorModule,
    MdProgressBarModule,
    MdProgressSpinnerModule,
    MdRadioModule,
    MdRippleModule,
    MdSelectModule,
    MdSidenavModule,
    MdSliderModule,
    MdSlideToggleModule,
    MdSnackBarModule,
    MdSortModule,
    MdTableModule,
    MdTabsModule,
    MdToolbarModule,
    MdTooltipModule,
    CdkTableModule
  ],
  declarations: [
    AppComponent,
    LoginComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
If you are finding difficulties importing files then just you can have one methodology to import.

First import any required components in your .component.ts

And import the specific module in your module .module.ts

And then add it in imports in @NgModule ({
imports : [ <Example>Module ]
})

Example you want to import formcontrols just in you angular application

1). app.component.ts

```<code>`import { FormGroup, FormControl } from '@angular/forms'`
</code>```

2). app.module.ts

import { FormsModule } from '@angular/forms'

below in app.module.ts in

@NgModule ({
imports : [ FormsModule ]
})

Body:
I am using Angular 4 and Angular Material 2. For the following code :

<form>
  <md-form-field>
    <input mdInput [ngModel]="userName" placeholder="User" [formControl]="usernameFormControl">
    <md-error *ngIf="usernameFormControl.hasError('required')">
      This is required
    </md-error>
    <input mdInput [ngModel]="password" placeholder="Password" [formControl]="passwordFormControl">
    <md-error *ngIf="passwordFormControl.hasError('required')">
      This is required
    </md-error>
    <button md-raised-button color="primary" [disabled]="!usernameFormControl.valid || !passwordFormControl.valid">Login</button>
  </md-form-field>
</form>

I am getting an error:

Template parse errors: 'md-form-field' is not a known element:
  1. If 'md-form-field' is an Angular component, then verify that it is part of this module.
  2. If 'md-form-field' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component
  to suppress this message. ("   [ERROR ->]

Could you please help me where I am missing?

Following is my app.module.ts code where I have imported material modules:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { LoginComponent } from './login.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import {
  MdAutocompleteModule,
  MdButtonModule,
  MdButtonToggleModule,
  MdCardModule,
  MdCheckboxModule,
  MdChipsModule,
  MdCoreModule,
  MdDatepickerModule,
  MdDialogModule,
  MdExpansionModule,
  MdGridListModule,
  MdIconModule,
  MdInputModule,
  MdListModule,
  MdMenuModule,
  MdNativeDateModule,
  MdPaginatorModule,
  MdProgressBarModule,
  MdProgressSpinnerModule,
  MdRadioModule,
  MdRippleModule,
  MdSelectModule,
  MdSidenavModule,
  MdSliderModule,
  MdSlideToggleModule,
  MdSnackBarModule,
  MdSortModule,
  MdTableModule,
  MdTabsModule,
  MdToolbarModule,
  MdTooltipModule
} from '@angular/material';

import {CdkTableModule} from '@angular/cdk';

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpModule,
    FormsModule,
    ReactiveFormsModule,
    MdAutocompleteModule,
    MdButtonModule,
    MdButtonToggleModule,
    MdCardModule,
    MdCheckboxModule,
    MdChipsModule,
    MdCoreModule,
    MdDatepickerModule,
    MdDialogModule,
    MdExpansionModule,
    MdGridListModule,
    MdIconModule,
    MdInputModule,
    MdListModule,
    MdMenuModule,
    MdNativeDateModule,
    MdPaginatorModule,
    MdProgressBarModule,
    MdProgressSpinnerModule,
    MdRadioModule,
    MdRippleModule,
    MdSelectModule,
    MdSidenavModule,
    MdSliderModule,
    MdSlideToggleModule,
    MdSnackBarModule,
    MdSortModule,
    MdTableModule,
    MdTabsModule,
    MdToolbarModule,
    MdTooltipModule,
    CdkTableModule
  ],
  declarations: [
    AppComponent,
    LoginComponent
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
If you are finding difficulties importing files then just you can have one methodology to import.

First import any required components in your .component.ts

And import the specific module in your module .module.ts

And then add it in imports in @NgModule ({
imports : [ <Example>Module ]
})

Example you want to import formcontrols just in you angular application

1). app.component.ts

`import { FormGroup, FormControl } from '@angular/forms'`

2). app.module.ts

import { FormsModule } from '@angular/forms'

below in app.module.ts in

@NgModule ({
imports : [ FormsModule ]
})


问:
Function that returns the closest number to B that's in an UNSORTED multidimensional array, A?
As the title states, I want to create a function that'll take a multidimensional array A, and a number B, that ultimately returns the number in A that is the closest to B. If the number B is in A, then return it. If there's 2 numbers in A that are equally distant from B, choose the first one by counting from row to row.

This is the code I have so far:

```<code>import numpy as np
def g_C(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2 # to assert that A is a multidimensional array.
  get = (np.abs(A-B)).argmin()
  return (A[get])
</code>```

However from my understanding, I think (np.abs(M-N)).argmin() really only effectively works for sorted arrays? I'm not allowed to sort the array in this problem; I have to work on it for face value, examining row by row, and grabbing the first instance of the closest number to B.

So for example, g_C([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9) should return 8

Also, I was given the hint that numpy.argmin would help, and I see that it's purpose is to extract the first occurrence something occurs, which makes sense in this problem, but I'm not sure how exactly to fit that into the code I have at the moment.

EDIT
The flat suggestion works perfectly fine. Thank you everyone.

I'm trying RagingRoosevelt's second suggestion, and I'm stuck.

```<code>def g_C(A,B):
  A = np.asanyarray(A)
  D = np.full_like(A, B) # created an array D with same qualities as array A, but just filled with values of B
  diffs = abs(D-A) # finding absolute value differences between D and A
  close = diffs.argmin(axis=1) # find argmin of 'diffs', row by row
  close = np.asanyarray(close) # converted the argmins of 'diff' into an array
  closer = close.argmin() # the final argmin ??
  return closer
</code>```

I'm trying out this suggestion because I have another problem related to this where I have to extract the row who's sum is the closest number to B. And I figure this is good practice anyway.

答:
Your existing code is fine except, by default, argmin returns an index to the flattened array. So you could do

```<code>return A.flat[abs(A - B).argmin()]
</code>```

to get the right value from A.

EDIT: For your other problem - finding the row in a 2-dimensional array A whose sum is closest to B - you can do:

```<code>return A[abs(A.sum(axis=1) - B).argmin()]
</code>```

In either case I don't see any need to create an array of B.

Body:
As the title states, I want to create a function that'll take a multidimensional array A, and a number B, that ultimately returns the number in A that is the closest to B. If the number B is in A, then return it. If there's 2 numbers in A that are equally distant from B, choose the first one by counting from row to row.

This is the code I have so far:

import numpy as np
def g_C(A,B):
  A = np.asanyarray(A)
  assert A.ndim == 2 # to assert that A is a multidimensional array.
  get = (np.abs(A-B)).argmin()
  return (A[get])

However from my understanding, I think (np.abs(M-N)).argmin() really only effectively works for sorted arrays? I'm not allowed to sort the array in this problem; I have to work on it for face value, examining row by row, and grabbing the first instance of the closest number to B.

So for example, g_C([[1,3,6,-8],[2,7,1,0],[4,5,2,8],[2,3,7,10]],9) should return 8

Also, I was given the hint that numpy.argmin would help, and I see that it's purpose is to extract the first occurrence something occurs, which makes sense in this problem, but I'm not sure how exactly to fit that into the code I have at the moment.

EDIT
The flat suggestion works perfectly fine. Thank you everyone.

I'm trying RagingRoosevelt's second suggestion, and I'm stuck.

def g_C(A,B):
  A = np.asanyarray(A)
  D = np.full_like(A, B) # created an array D with same qualities as array A, but just filled with values of B
  diffs = abs(D-A) # finding absolute value differences between D and A
  close = diffs.argmin(axis=1) # find argmin of 'diffs', row by row
  close = np.asanyarray(close) # converted the argmins of 'diff' into an array
  closer = close.argmin() # the final argmin ??
  return closer

I'm trying out this suggestion because I have another problem related to this where I have to extract the row who's sum is the closest number to B. And I figure this is good practice anyway.

Body:
Your existing code is fine except, by default, argmin returns an index to the flattened array. So you could do

return A.flat[abs(A - B).argmin()]

to get the right value from A.

EDIT: For your other problem - finding the row in a 2-dimensional array A whose sum is closest to B - you can do:

return A[abs(A.sum(axis=1) - B).argmin()]

In either case I don't see any need to create an array of B.


问:
How can i make a the text bold which is stored in a string variable?
I want to make the text stored inside a string variable to bold.

String buttonText = t.getText().toString();
                String val = map.get(buttonText);

```<code>          new MaterialDialog.Builder(LearningMode.this)
                    .iconRes(BalloonColor.get(2))
                    .limitIconToDefaultSize()
                    .title("Meaning")

                    .content(buttonText+"\n"+val)

                    .positiveText("Continue")
                    .cancelable(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            mover.resume();
                        }
                    })

                    .show();
</code>```

at .content(buttonText+"\n"+val)
i want the string stored inside this to become bold.
i have tried html.fromhtml it is not working

like this Html.fromHtml("  "+buttonText+" ")

added space in the above  as it is converting to bold

and other methods like declaring in strings.xml with  wont work here as i'm dealing it programmatically here!

ultimately when the string button text is displayed in the output sholud be bold.

i have already referred this Set TextView text from html-formatted string resource in XML

Update:

There is no textview used.

Someone please help!

答:
try this: </p>

```<code> buttonText.setTypeface(null, Typeface.BOLD);
</code>```

Body:
I want to make the text stored inside a string variable to bold.

String buttonText = t.getText().toString();
                String val = map.get(buttonText);

          new MaterialDialog.Builder(LearningMode.this)
                    .iconRes(BalloonColor.get(2))
                    .limitIconToDefaultSize()
                    .title("Meaning")

                    .content(buttonText+"\n"+val)

                    .positiveText("Continue")
                    .cancelable(false)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            mover.resume();
                        }
                    })

                    .show();

at .content(buttonText+"\n"+val)
i want the string stored inside this to become bold.
i have tried html.fromhtml it is not working

like this Html.fromHtml("  "+buttonText+" ")

added space in the above  as it is converting to bold

and other methods like declaring in strings.xml with  wont work here as i'm dealing it programmatically here!

ultimately when the string button text is displayed in the output sholud be bold.

i have already referred this Set TextView text from html-formatted string resource in XML

Update:

There is no textview used.

Someone please help!

Body:
try this:

 buttonText.setTypeface(null, Typeface.BOLD);


问:
extracting lines if the first field matches another list saved in a different file -- shell command
I have two files. One contains a list of items, e.g.,

Allie
Bob
John
Laurie
```

<p>Another file (file2) contains a different list of items in a different order, but some items might overlap with the items in file 1, e.g, </p>

<pre class="lang-none prettyprint-override"><code>Laurie 45 56 6 75
Moxipen 10 45 56 56
Allie 45 56 67 23
</code>```

I want to intersect these two files and extract only those lines from file 2 whose first field matches an item in field 1.

i.e., my output should be

Allie 45 56 67 23
Laurie 45 56 6 75
```

<p>(preferably in this order, but it's OK if not)</p>

<p><code>grep -f file1 file2</code> doesn't do what I want. </p>

<p>I also need something efficient because the second file is HUGE.</p>

<p>I also tried this:</p>

```awk -F, 'FNR==NR {a[$1]=$0; next}; $1 in a {print a[$1]}' file2 file1
```

答:
If order doesn't matter then

```<code>awk 'FNR==NR{ arr[$1]; next }$1 in arr' file1 file2
</code>```

Explanation

FNR==NR{ arr[$1]; next } Here we read first file (file1), arr is array, whose index key being first field $1.

$1 in arr we read second file ( file2), if array arr which was created while reading first file, has index key which is second file's first column ($1 in arr gives true, if index key exists), then print current record/row/line from file2

Test Results:

```<code>akshay@db-3325:/tmp$ cat file1
Allie
Bob
John
Laurie

akshay@db-3325:/tmp$ cat file2
Laurie 45 56 6 75
Moxipen 10 45 56 56
Allie 45 56 67 23

akshay@db-3325:/tmp$ awk 'FNR==NR{ arr[$1]; next }$1 in arr' file1 file2
Laurie 45 56 6 75
Allie 45 56 67 23
</code>```

Body:
I have two files. One contains a list of items, e.g.,

Allie
Bob
John
Laurie

Another file (file2) contains a different list of items in a different order, but some items might overlap with the items in file 1, e.g,

Laurie 45 56 6 75
Moxipen 10 45 56 56
Allie 45 56 67 23

I want to intersect these two files and extract only those lines from file 2 whose first field matches an item in field 1.

i.e., my output should be

Allie 45 56 67 23
Laurie 45 56 6 75

(preferably in this order, but it's OK if not)

grep -f file1 file2 doesn't do what I want.

I also need something efficient because the second file is HUGE.

I also tried this:

awk -F, 'FNR==NR {a[$1]=$0; next}; $1 in a {print a[$1]}' file2 file1

Body:
If order doesn't matter then

awk 'FNR==NR{ arr[$1]; next }$1 in arr' file1 file2

Explanation

FNR==NR{ arr[$1]; next } Here we read first file (file1), arr is array, whose index key being first field $1.

$1 in arr we read second file ( file2), if array arr which was created while reading first file, has index key which is second file's first column ($1 in arr gives true, if index key exists), then print current record/row/line from file2

Test Results:

akshay@db-3325:/tmp$ cat file1
Allie
Bob
John
Laurie

akshay@db-3325:/tmp$ cat file2
Laurie 45 56 6 75
Moxipen 10 45 56 56
Allie 45 56 67 23

akshay@db-3325:/tmp$ awk 'FNR==NR{ arr[$1]; next }$1 in arr' file1 file2
Laurie 45 56 6 75
Allie 45 56 67 23


问:
jquery function unexpected token error
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

```<code><div class="primary-colors">
    <h3>Primary Colors</h3>
    <div class="primary-range-container">
        <input type="range" min="1" max="15" value ="5" class="primary-slider"><span class="value">0</span>
    </div>
    <hr>
    <div class="color-container">
        <div class="color primary-color-1"></div>
        <div class="color primary-color-2"></div>
        <div class="color primary-color-3"></div>
        <div class="color primary-color-4"></div>
        <div class="color primary-color-5"></div>
        <div class="color primary-color-6"></div>
        <div class="color primary-color-7"></div>
        <div class="color primary-color-8"></div>
        <div class="color primary-color-9"></div>
        <div class="color primary-color-10"></div>
        <div class="color primary-color-11"></div>
    </div>
</div>
</code>```

And the javascript code looks like this

```<code>var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);
</code>```

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

答:
To create a prototype with jQuery you assign to a function</p>

```<code>$.fn.colorBlocks = function (colorContainer, rangeSlider) {
   //code here
}
</code>```

Title: jquery function unexpected token error

Body:
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

Primary Colors

        <input type="range" min="1" max="15" value ="5" class="primary-slider">0

And the javascript code looks like this

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

Body:
To create a prototype with jQuery you assign to a function

$.fn.colorBlocks = function (colorContainer, rangeSlider) {
   //code here
}


问:
Locks at C# to use prevent multiple threads or events to use same variable value
I want to free my application from sql, because I do not have a large db. I want to hold my data on memory, so my application will run faster.

My question here is that I've a key pool, and a key can be used by only 4 clients, I want to lock each key when it is registered to a client so I will use:

```<code>lock(key)
{
  assignKeyToClient(clientId);
}
</code>```

If I use that, will lock use the copy of the key or lock the original "key" on ram and does free it after finishing assignment?

Thanks!

答:
I think you are confused on what the lock statement means - it is only for concurrency management - it ensures that the section of code it is protecting (the "critical section") is only entered by one thread at a time.

This has nothing to do with user data, i.e. client id's or keys. To manage unique client id's you could use something like a Dictionary. When you do assign your keys you should use a lock only if there is more than one thread executing this section of code. If that's the case use a private readonly object variable to lock on within your class instance to make sure the same key is only assigned once:

```<code>private readonly object myLock = new object();
private Dictionary<int> assignedKeys = new Dictionary<int>();
...

lock(myLock)
{
  int key = PickAKeyHere();
  AssignKeyToClient(key, clientId);
  assignedKeys[key] = clientId; //keep track of which client is assigned what key
}
</code>```

Body:
I want to free my application from sql, because I do not have a large db. I want to hold my data on memory, so my application will run faster.

My question here is that I've a key pool, and a key can be used by only 4 clients, I want to lock each key when it is registered to a client so I will use:

lock(key)
{
  assignKeyToClient(clientId);
}

If I use that, will lock use the copy of the key or lock the original "key" on ram and does free it after finishing assignment?

Thanks!

Body:
I think you are confused on what the lock statement means - it is only for concurrency management - it ensures that the section of code it is protecting (the "critical section") is only entered by one thread at a time.

This has nothing to do with user data, i.e. client id's or keys. To manage unique client id's you could use something like a Dictionary. When you do assign your keys you should use a lock only if there is more than one thread executing this section of code. If that's the case use a private readonly object variable to lock on within your class instance to make sure the same key is only assigned once:

private readonly object myLock = new object();
private Dictionary<int> assignedKeys = new Dictionary<int>();
...

lock(myLock)
{
  int key = PickAKeyHere();
  AssignKeyToClient(key, clientId);
  assignedKeys[key] = clientId; //keep track of which client is assigned what key
}


问:
How to remove MySQL Workbench 5.2 in ubuntu unity?
I have just download the .deb and installed it. It works. Now i want to uninstall it.

I have tried:

sudo apt-get remove mysql-workbench, but it says "E: Unable to locate package mysql-workbench".

Go to the Software manager, but it's not between the installed apps.

Execute again the .deb, but it doesn't give the option to uninstall it.

I reboot my pc after installing it.

Any idea?

Javier.

答:
You have to specify the edition that you want to uninstall..

```<code>sudo apt-get remove mysql-workbench-community
</code>```

Body:
You have to specify the edition that you want to uninstall..

sudo apt-get remove mysql-workbench-community


问:
Why can I not call upon the property of this object? (Angular, MongoDB)
I am making an angular application which uses a MongoDB database and NodeJS server.

The idea is that I make an application which for now only has a list of posts and beside that the detailed-post. The components are nicely standing next to eachother and working but I have one problem. When I try to retrieve a single post I can see via console.dir(post) that all is good and the object has been transmitted to the angular app. The problem is that when I try to use post.content I get an undefined message.

I have searched for hours but can not seem to find the cause of this. I would greatly appreciate any help you can give me. Beneath here is all the information, if you need to see something else, please tell me.

Thanks in advance.

This is the post-detail.component.html where I want to display the data.

```<code><div class="row">
<div class="col-xs-12">
<p>Content:</p>
<h1>{{ post.content }}</h1>
</div>
</div>
</code>```

The detail.ts file (I left out the imports)

```<code>    @Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.component.html',
  styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
  post: Post = new Post();
  id: string;

constructor(private postService: PostService,
            private route: ActivatedRoute,
            private router: Router) {
}

ngOnInit() {
  this.route.params
    .subscribe(
      (params: Params) => {
        this.id = params['id'];
        this.postService.getPost(this.id).then(res => {
          console.dir(res);
          console.dir(res.content);
          this.post = res;
        });
      }
    );
  }
}
</code>```

The post.service.ts which I am using to retrieve the actual data:

```<code>@Injectable()
export class PostService {
  postChanged = new Subject<Post[]>();

  private headers = new Headers({'Content-Type': 'application/json'});
  private serverUrl = environment.serverUrl + '/blogPosts/'; // URL to web api
  private posts: Post[];

  constructor(private http: Http) {
  }

  //this one DOES work
  getPosts() {
    console.log('Fetching BlogPosts from database.')
    return this.http.get(this.serverUrl, {headers: this.headers})
      .toPromise()
      .then(response => {
        this.posts = response.json() as Post[];
        return response.json() as Post[];
      })
      .catch(error => {
        return error;
      });
  }

  getPost(index: string) {
    console.log('Fetching individual BlogPost from database.');
    console.log('index' + index);
    if (index == null) {
      console.log('null');
      return null;
    }
    return this.http.get(this.serverUrl + index, {headers: this.headers})
      .toPromise()
      .then(response => {
        console.dir(response.json().content);
        console.dir(response.json());
        return response.json() as Post;
      })
      .catch(error => {

        return this.handleError(error);
      });
  }
}
</code>```

The Post model:

```<code>export class Post {

  private id: string;
  private _content: string;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
  public get _id(): string {
    return this.id;
  }

  public set _id(n: string) {
    this.id = n;
  }

  public get content(): string {
    return this._content;
  }

  public set content(n: string) {
    this._content = n;
  }
}
</code>```

And I added in the Postman GET /blogPost/id and the console log as images.
Thanks!

Console log

Postman GET route

答:
I might be wrong but can you please change the _content to content everywhere in the service ?

Edit: are you sure the this.id is correct when you call the service method ? cause if it is null or undefined then return null will be executed.

Another note is that in Postman i see the response is an array of objects (one object) at this example. Can you try this.post = res[0]; in the component ?

Body:
I am making an angular application which uses a MongoDB database and NodeJS server.

The idea is that I make an application which for now only has a list of posts and beside that the detailed-post. The components are nicely standing next to eachother and working but I have one problem. When I try to retrieve a single post I can see via console.dir(post) that all is good and the object has been transmitted to the angular app. The problem is that when I try to use post.content I get an undefined message.

I have searched for hours but can not seem to find the cause of this. I would greatly appreciate any help you can give me. Beneath here is all the information, if you need to see something else, please tell me.

Thanks in advance.

This is the post-detail.component.html where I want to display the data.

Content:

{{ post.content }}

The detail.ts file (I left out the imports)

    @Component({
  selector: 'app-post-detail',
  templateUrl: './post-detail.component.html',
  styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
  post: Post = new Post();
  id: string;

constructor(private postService: PostService,
            private route: ActivatedRoute,
            private router: Router) {
}

ngOnInit() {
  this.route.params
    .subscribe(
      (params: Params) => {
        this.id = params['id'];
        this.postService.getPost(this.id).then(res => {
          console.dir(res);
          console.dir(res.content);
          this.post = res;
        });
      }
    );
  }
}

The post.service.ts which I am using to retrieve the actual data:

@Injectable()
export class PostService {
  postChanged = new Subject<Post[]>();

  private headers = new Headers({'Content-Type': 'application/json'});
  private serverUrl = environment.serverUrl + '/blogPosts/'; // URL to web api
  private posts: Post[];

  constructor(private http: Http) {
  }

  //this one DOES work
  getPosts() {
    console.log('Fetching BlogPosts from database.')
    return this.http.get(this.serverUrl, {headers: this.headers})
      .toPromise()
      .then(response => {
        this.posts = response.json() as Post[];
        return response.json() as Post[];
      })
      .catch(error => {
        return error;
      });
  }

  getPost(index: string) {
    console.log('Fetching individual BlogPost from database.');
    console.log('index' + index);
    if (index == null) {
      console.log('null');
      return null;
    }
    return this.http.get(this.serverUrl + index, {headers: this.headers})
      .toPromise()
      .then(response => {
        console.dir(response.json().content);
        console.dir(response.json());
        return response.json() as Post;
      })
      .catch(error => {

        return this.handleError(error);
      });
  }
}

The Post model:

export class Post {

  private id: string;
  private _content: string;

  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
  public get _id(): string {
    return this.id;
  }

  public set _id(n: string) {
    this.id = n;
  }

  public get content(): string {
    return this._content;
  }

  public set content(n: string) {
    this._content = n;
  }
}

And I added in the Postman GET /blogPost/id and the console log as images.
Thanks!

Console log

Postman GET route


问:
Is there a way to remove magic numbers from a XML Schema?
I have a WSDL with some types defined. Some elements accept lists of elements and on the service return I also have elements with list of values (or other elements).

As a result I have some magic numbers in the XSD (e.g. minOccurs="10", maxOccurs="250" etc). These values 10, 250 etc are repeated throughout the XSD types.

Is there a way to declare them as some sort of constants? and then reuse them by name for the minOccurs and maxOccurs attributes?

答:
XSD is XML so you could use entities defined in a DTD:</p>

```<code>minOccurs="&minOccurs;"
</code>```

Body:
XSD is XML so you could use entities defined in a DTD:

minOccurs="&minOccurs;"


答:
You can do it your way, but the member function must be called on a particular instance:

```<code>class A;

class B {
public:
    virtual int calc(A* a, int (A::*fun)()) { return 2 * (a->*fun)(); };
};

class A {
    B* b;

public:
    A(B* b_) : b(b_) {};
    int fun() { return 3; };
    int run() { return b->calc(this, &A::fun); }; // now also passing this pointer
};

int main() {
    B* b = new B();
    A a(b);
    a.run();
    return 0;
}
</code>```

If you can live without calc() being virtual then a lambda is also an option:

```<code>class A;

class B {
public:
    template<typename T>
    int calc(T fun) { return 2 * fun(); };
};

class A {
    B* b;

public:
    A(B* b_) : b(b_) {};
    int fun() { return 3; };
    int run() {
        return b->calc([this]() {return fun(); } );
    };
};

int main() {
    B* b = new B();
    A a(b);
    a.run();
    return 0;
}
</code>```

Title: Pointer to a class method in c++

Body:
A have a lot of B classes, a class A has one object b. This object b has a function (calc) that needs a pointer to a method in an object of A. This method (fun) acess private variables in class (in my example just return 3).

class A;

class B {
public:
  virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
};

class A {
  B* b;

public:
  A (B* b_) : b (b_) {};
  int fun() { return 3; };
  int run(){ return b->calc(&A::fun); };
};

int main() {
  B* b = new B();
  A a(b);
  a.run();
  return 0;
}

How can I use a pointer to a method correctly in definition of calc method in class B?

I am getting this error message:

teste.cpp:10:58: error: must use ‘.*’ or ‘->*’ to call pointer-to-member     function in ‘fun (...)’, e.g. ‘(... ->* fun) (...)’
   virtual int calc ( int (A::*fun)())  {    return 2*fun();  };
                                                      ^

Body:
You can do it your way, but the member function must be called on a particular instance:

class A;

class B {
public:
    virtual int calc(A* a, int (A::*fun)()) { return 2 * (a->*fun)(); };
};

class A {
    B* b;

public:
    A(B* b_) : b(b_) {};
    int fun() { return 3; };
    int run() { return b->calc(this, &A::fun); }; // now also passing this pointer
};

int main() {
    B* b = new B();
    A a(b);
    a.run();
    return 0;
}

If you can live without calc() being virtual then a lambda is also an option:

class A;

class B {
public:
    template<typename T>
    int calc(T fun) { return 2 * fun(); };
};

class A {
    B* b;

public:
    A(B* b_) : b(b_) {};
    int fun() { return 3; };
    int run() {
        return b->calc([this]() {return fun(); } );
    };
};

int main() {
    B* b = new B();
    A a(b);
    a.run();
    return 0;
}


问:
AWS ECS tasks keep starting and stopping
I am trying to use ECS for deployment with travis.
At one point everything was working but now it stopped.

I am following this tutorial https://testdriven.io/part-five-ec2-container-service/

There are 2 tasks that keep stopping and starting.

These are the messages I see in tasks:

```<code>STOPPED (CannotStartContainerError: API error (500): oci ru)

STOPPED (Essential container in task exited)
</code>```

These are the messages I see in the logs:

```<code>FATAL: could not write to file "pg_wal/xlogtemp.28": No space left on device

container_linux.go:262: starting container process caused "exec: \"./entrypoint.sh\": permission denied"
</code>```

Why is ECS stopping and starting so many new tasks? This was not happening before.

This is my docker_deploy.sh from my main microservice which I am calling via travis.

```<code>#!/bin/sh

if [ -z "$TRAVIS_PULL_REQUEST" ] || [ "$TRAVIS_PULL_REQUEST" == "false" ];
then

    if [ "$TRAVIS_BRANCH" == "staging" ];
    then
        JQ="jq --raw-output --exit-status"

        configure_aws_cli() {
            aws --version
            aws configure set default.region us-east-1
            aws configure set default.output json
            echo "AWS Configured!"
        }

        make_task_def() {
            task_template=$(cat ecs_taskdefinition.json)
            task_def=$(printf "$task_template" $AWS_ACCOUNT_ID $AWS_ACCOUNT_ID)
            echo "$task_def"
        }

        register_definition() {
            if revision=$(aws ecs register-task-definition --cli-input-json "$task_def" --family $family | $JQ '.taskDefinition.taskDefinitionArn');
            then
                echo "Revision: $revision"
            else
                echo "Failed to register task definition"
                return 1
            fi
        }

        deploy_cluster() {

            family="testdriven-staging"
            cluster="ezasdf-staging"
            service="ezasdf-staging"

            make_task_def
            register_definition

            if [[ $(aws ecs update-service --cluster $cluster --service $service --task-definition $revision | $JQ '.service.taskDefinition') != $revision ]];
            then
                echo "Error updating service."
                return 1
            fi

        }

        configure_aws_cli
        deploy_cluster

    fi
fi
</code>```

This is my Dockerfile from my users microservice:

```<code>FROM python:3.6.2

# install environment dependencies
RUN apt-get update -yqq \
    && apt-get install -yqq --no-install-recommends \
        netcat \
    && apt-get -q clean

# set working directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# add requirements (to leverage Docker cache)
ADD ./requirements.txt /usr/src/app/requirements.txt

# install requirements
RUN pip install -r requirements.txt

# add entrypoint.sh
ADD ./entrypoint.sh /usr/src/app/entrypoint.sh
RUN chmod +x /usr/src/app/entrypoint.sh

# add app
ADD . /usr/src/app

# run server
CMD ["./entrypoint.sh"]
</code>```

entrypoint.sh:

```<code>#!/bin/sh

echo "Waiting for postgres..."

while ! nc -z users-db 5432;
do
    sleep 0.1
done

echo "PostgreSQL started"

python manage.py recreate_db
python manage.py seed_db
gunicorn -b 0.0.0.0:5000 manage:app
</code>```

I tried deleting my cluster and deregistering my tasks and restarting but ECS still continuously stops and starts new tasks now.

When it was working fine: the difference was that instead of the CMD ["./entrypoint.sh"] in my Dockerfile, I had

```<code>RUN python manage.py recreate_db
RUN python manage.py seed_db
CMD gunicorn -b 0.0.0.0:5000 manage:app
</code>```

travis is passing.

答:
Do docker ps -a

Which results in all the stopped containers which are excited, these also consumes disk space.use below command to remove those zoombie

docker rm $(docker ps -a | grep Exited | awk '{print $1}')

And also remove older images or unused images these takes more DiskStation size than containers

docker rmi -f image_name

Body:
I am trying to use ECS for deployment with travis.
At one point everything was working but now it stopped.

I am following this tutorial https://testdriven.io/part-five-ec2-container-service/

There are 2 tasks that keep stopping and starting.

These are the messages I see in tasks:

STOPPED (CannotStartContainerError: API error (500): oci ru)

STOPPED (Essential container in task exited)

These are the messages I see in the logs:

FATAL: could not write to file "pg_wal/xlogtemp.28": No space left on device

container_linux.go:262: starting container process caused "exec: \"./entrypoint.sh\": permission denied"

Why is ECS stopping and starting so many new tasks? This was not happening before.

This is my docker_deploy.sh from my main microservice which I am calling via travis.

#!/bin/sh

if [ -z "$TRAVIS_PULL_REQUEST" ] || [ "$TRAVIS_PULL_REQUEST" == "false" ];
then

    if [ "$TRAVIS_BRANCH" == "staging" ];
    then
        JQ="jq --raw-output --exit-status"

        configure_aws_cli() {
            aws --version
            aws configure set default.region us-east-1
            aws configure set default.output json
            echo "AWS Configured!"
        }

        make_task_def() {
            task_template=$(cat ecs_taskdefinition.json)
            task_def=$(printf "$task_template" $AWS_ACCOUNT_ID $AWS_ACCOUNT_ID)
            echo "$task_def"
        }

        register_definition() {
            if revision=$(aws ecs register-task-definition --cli-input-json "$task_def" --family $family | $JQ '.taskDefinition.taskDefinitionArn');
            then
                echo "Revision: $revision"
            else
                echo "Failed to register task definition"
                return 1
            fi
        }

        deploy_cluster() {

            family="testdriven-staging"
            cluster="ezasdf-staging"
            service="ezasdf-staging"

            make_task_def
            register_definition

            if [[ $(aws ecs update-service --cluster $cluster --service $service --task-definition $revision | $JQ '.service.taskDefinition') != $revision ]];
            then
                echo "Error updating service."
                return 1
            fi

        }

        configure_aws_cli
        deploy_cluster

    fi
fi

This is my Dockerfile from my users microservice:

FROM python:3.6.2

# install environment dependencies
RUN apt-get update -yqq \
    && apt-get install -yqq --no-install-recommends \
        netcat \
    && apt-get -q clean

# set working directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# add requirements (to leverage Docker cache)
ADD ./requirements.txt /usr/src/app/requirements.txt

# install requirements
RUN pip install -r requirements.txt

# add entrypoint.sh
ADD ./entrypoint.sh /usr/src/app/entrypoint.sh
RUN chmod +x /usr/src/app/entrypoint.sh

# add app
ADD . /usr/src/app

# run server
CMD ["./entrypoint.sh"]

entrypoint.sh:

#!/bin/sh

echo "Waiting for postgres..."

while ! nc -z users-db 5432;
do
    sleep 0.1
done

echo "PostgreSQL started"

python manage.py recreate_db
python manage.py seed_db
gunicorn -b 0.0.0.0:5000 manage:app

I tried deleting my cluster and deregistering my tasks and restarting but ECS still continuously stops and starts new tasks now.

When it was working fine: the difference was that instead of the CMD ["./entrypoint.sh"] in my Dockerfile, I had

RUN python manage.py recreate_db
RUN python manage.py seed_db
CMD gunicorn -b 0.0.0.0:5000 manage:app

travis is passing.


问:
Number of items purchased per invoice using seaborn and pandas
I'm using online retail dataset and I want to plot the distribution of number of items per invoice number.

InvoiceNo of type: non-null object

Quantity  of type: non-null int64

How to do that? Also, I didn't know how to filter using pandas operations to get that without visualizations.
like for example if I want to know the quantity per invoice I can do:

```<code>retail_uk.groupby('InvoiceNo').sum().sort_values(by='Quantity', ascending=False)['Quantity']
</code>```

I need an answer for both:

How to plot that with Seaborn (more important because it allows me to get a better idea of the distribution) what are the different data transformations needed to achieve that?

How to do it using groupby of Pandas.

答:
I think you need aggregate sum and for plot seaborn.barplot:

```<code>url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00352/Online%20Retail.xlsx'
retail_uk = pd.read_excel(url)

df = retail_uk.groupby('InvoiceNo', as_index=False)['Quantity'].sum()
#if want sorting
df = df.sort_values(by='Quantity', ascending=False)
print (df.head())

ax = sns.barplot(x="InvoiceNo", y="Quantity", data=df)
</code>```

Body:
I'm using online retail dataset and I want to plot the distribution of number of items per invoice number.

InvoiceNo of type: non-null object

Quantity  of type: non-null int64

How to do that? Also, I didn't know how to filter using pandas operations to get that without visualizations.
like for example if I want to know the quantity per invoice I can do:

retail_uk.groupby('InvoiceNo').sum().sort_values(by='Quantity', ascending=False)['Quantity']

I need an answer for both:

How to plot that with Seaborn (more important because it allows me to get a better idea of the distribution) what are the different data transformations needed to achieve that?

How to do it using groupby of Pandas.

Body:
I think you need aggregate sum and for plot seaborn.barplot:

url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00352/Online%20Retail.xlsx'
retail_uk = pd.read_excel(url)

df = retail_uk.groupby('InvoiceNo', as_index=False)['Quantity'].sum()
#if want sorting
df = df.sort_values(by='Quantity', ascending=False)
print (df.head())

ax = sns.barplot(x="InvoiceNo", y="Quantity", data=df)


问:
Sequelize: Bulk update or insert into MSSQL DB
I have spent the last 24 hours combing the internet for a solution and have yet to find one. I am trying to do a bulk upsert (update or insert) of a single model into a mssql db. bulkCreate with updateOnDuplicate:true does not work with mssql. Is there any other solution? This is dataset is anywhere between 1-50k rows. Any help would be greatly appreciated!</p>

答:
For SQL 2016+ you can simply pass your bulk data as JSON using a NVarchar(max) parameter, and parse and load it on the server.  Your query would look something like this:

```<code>Insert into TargetTable(Number,Date,Customer,Quantity,[Order])
SELECT Number,Date,Customer,Quantity,[Order]
FROM OPENJSON ( @json )
WITH (
              Number   varchar(200)   '$.Order.Number',
              Date     datetime       '$.Order.Date',
              Customer varchar(200)   '$.AccountNumber',
              Quantity int            '$.Item.Quantity',
              [Order]  nvarchar(MAX)  AS JSON
 );
</code>```

And you would bind the @json parameter with a NVarchar(max) (string) value like:

```<code>[
  {
    "Order": {
      "Number":"SO43659",
      "Date":"2011-05-31T00:00:00"
    },
    "AccountNumber":"AW29825",
    "Item": {
      "Price":2024.9940,
      "Quantity":1
    }
  },
  {
    "Order": {
      "Number":"SO43661",
      "Date":"2011-06-01T00:00:00"
    },
    "AccountNumber":"AW73565",
    "Item": {
      "Price":2024.9940,
      "Quantity":3
    }
  }
]
</code>```

An update would look something like:

```<code> with q as
 (
    select t.Number, t.Quantity oldQuantity, j.Quantity newQuantity
    from OPENJSON ( @json )
    WITH (
                  Number   varchar(200)   '$.Order.Number',
                  Date     datetime       '$.Order.Date',
                  Customer varchar(200)   '$.AccountNumber',
                  Quantity int            '$.Item.Quantity',
                  [Order]  nvarchar(MAX)  AS JSON
          ) j
    join TargetTable t
      on j.Number = t.Number
 )
 update q set oldQuantity = newQuantity
</code>```

See: https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql

If you can't bind a parameter, then in a pinch you an include the JSON document as a literal string in your TSQL batch.

Body:
For SQL 2016+ you can simply pass your bulk data as JSON using a NVarchar(max) parameter, and parse and load it on the server.  Your query would look something like this:

Insert into TargetTable(Number,Date,Customer,Quantity,[Order])
SELECT Number,Date,Customer,Quantity,[Order]
FROM OPENJSON ( @json )
WITH (
              Number   varchar(200)   '$.Order.Number',
              Date     datetime       '$.Order.Date',
              Customer varchar(200)   '$.AccountNumber',
              Quantity int            '$.Item.Quantity',
              [Order]  nvarchar(MAX)  AS JSON
 );

And you would bind the @json parameter with a NVarchar(max) (string) value like:

[
  {
    "Order": {
      "Number":"SO43659",
      "Date":"2011-05-31T00:00:00"
    },
    "AccountNumber":"AW29825",
    "Item": {
      "Price":2024.9940,
      "Quantity":1
    }
  },
  {
    "Order": {
      "Number":"SO43661",
      "Date":"2011-06-01T00:00:00"
    },
    "AccountNumber":"AW73565",
    "Item": {
      "Price":2024.9940,
      "Quantity":3
    }
  }
]

An update would look something like:

 with q as
 (
    select t.Number, t.Quantity oldQuantity, j.Quantity newQuantity
    from OPENJSON ( @json )
    WITH (
                  Number   varchar(200)   '$.Order.Number',
                  Date     datetime       '$.Order.Date',
                  Customer varchar(200)   '$.AccountNumber',
                  Quantity int            '$.Item.Quantity',
                  [Order]  nvarchar(MAX)  AS JSON
          ) j
    join TargetTable t
      on j.Number = t.Number
 )
 update q set oldQuantity = newQuantity

See: https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql

If you can't bind a parameter, then in a pinch you an include the JSON document as a literal string in your TSQL batch.


问:
rgl package - cube within a cube
I'm trying to create a rectangular prism within a cube.  I need the cube to have dimensions of 1x1x1 units, with an origin at 0,0,0. The rectangle within the cube would ideally start at the origin and then pull from a vector variable to get its XYZ dimensions.  The rectangular prism can only have positive values that range from 0 to 1, which is why I only want to show positive values instead of what seems to be the default for cube3d of showing -1 to 1 in all dimensions around the origin.

Can someone point me in the right direction as to how to make this work?

Data example:

```<code>Augusta = c(0.4, 0.2, 0.8)
</code>```

The code I currently have (pulled from stackoverflow) -

```<code>c3d <- cube3d(color="red", alpha=0.5)
c3d
shade3d(c3d)
axes3d()
rgl.viewpoint(theta = 45, phi = 25, fov = 60, zoom = 1)
</code>```

Can I adapt this function to suit my needs? If so, what would the method  look like?  If this isn't the right function, what would you suggest?

Another potential method I found, but which would require a different input and would therefore not be preferred, is described here

答:
I'm not sure if I can understand your problem, but perhaps scale3d() and translate3d() would give what you want (see: ?scale3d).

```<code>library(rgl)

c3d <- cube3d(color="red", alpha=0.5)
c3d2 <- c3d %>%
  translate3d(1, 1, 1) %>%
  scale3d(0.5, 0.5, 0.5)

c3d3 <- cube3d(color = "blue") %>%
  translate3d(1, 1, 1) %>%
  scale3d(0.5, 0.5, 0.5) %>%
  scale3d(0.4, 0.2, 0.8)

shade3d(c3d2)
shade3d(c3d3)
axes3d()
# title3d(xlab = "x", ylab = "y", zlab = "z")
</code>```

Title: rgl package - cube within a cube

Body:
I'm trying to create a rectangular prism within a cube.  I need the cube to have dimensions of 1x1x1 units, with an origin at 0,0,0. The rectangle within the cube would ideally start at the origin and then pull from a vector variable to get its XYZ dimensions.  The rectangular prism can only have positive values that range from 0 to 1, which is why I only want to show positive values instead of what seems to be the default for cube3d of showing -1 to 1 in all dimensions around the origin.

Can someone point me in the right direction as to how to make this work?

Data example:

Augusta = c(0.4, 0.2, 0.8)

The code I currently have (pulled from stackoverflow) -

c3d <- cube3d(color="red", alpha=0.5)
c3d
shade3d(c3d)
axes3d()
rgl.viewpoint(theta = 45, phi = 25, fov = 60, zoom = 1)

Can I adapt this function to suit my needs? If so, what would the method  look like?  If this isn't the right function, what would you suggest?

Another potential method I found, but which would require a different input and would therefore not be preferred, is described here

Body:
I'm not sure if I can understand your problem, but perhaps scale3d() and translate3d() would give what you want (see: ?scale3d).

library(rgl)

c3d <- cube3d(color="red", alpha=0.5)
c3d2 <- c3d %>%
  translate3d(1, 1, 1) %>%
  scale3d(0.5, 0.5, 0.5)

c3d3 <- cube3d(color = "blue") %>%
  translate3d(1, 1, 1) %>%
  scale3d(0.5, 0.5, 0.5) %>%
  scale3d(0.4, 0.2, 0.8)

shade3d(c3d2)
shade3d(c3d3)
axes3d()
# title3d(xlab = "x", ylab = "y", zlab = "z")


问:
cannot get the correct date and time in php
I dont know why I'm not getting the correct date and time in my region.
Here's the code

```<code><?php
//date_default_timezone_set('Asia/Manila');
echo date('YYYY-mm-dd H:i:s'); ?>
</code>```

Even if I comment out or change the time zone the date and time that I'm getting is still the same.
The date today is 23. But its outputting 22. And the time doesn't change even if I change the time zones.
Does it have something to do with my computer?
Because I sometimes notice that the clock on the lower right corner of the screen is not displaying the correct time.

Heres the current time, but its displaying this:

```<code>01-22-2011 05:38:31-PM
</code>```

答:
Are you sure that's the script producing the output shown?

```<code>echo date('YYYY-mm-dd H:i:s'); ?>
</code>```

Doesn't seem to match the format of

```<code>01-22-2011 05:38:31-PM
</code>```

Other than that, the timezone setting looks right.

Body:
I dont know why I'm not getting the correct date and time in my region.
Here's the code

<?php
//date_default_timezone_set('Asia/Manila');
echo date('YYYY-mm-dd H:i:s'); ?>

Even if I comment out or change the time zone the date and time that I'm getting is still the same.
The date today is 23. But its outputting 22. And the time doesn't change even if I change the time zones.
Does it have something to do with my computer?
Because I sometimes notice that the clock on the lower right corner of the screen is not displaying the correct time.

Heres the current time, but its displaying this:

01-22-2011 05:38:31-PM

Body:
Are you sure that's the script producing the output shown?

echo date('YYYY-mm-dd H:i:s'); ?>

Doesn't seem to match the format of

01-22-2011 05:38:31-PM

Other than that, the timezone setting looks right.


问:
WIX: Duplicate symbol 'Property:WixUI_Mode' found, Custom Dialog creation
I have version 3.14 of Wix toolset and VS2017 and the following problem...
when i'm trying get my own dialog order using predefined  WixUI_Minimal. Same problem was in 3.11 toolset

Step Create Wix project in VS2017

Copy WixUI_Minimal.wxs from  .\wix3-develop\wix3-develop\src\ext\UIExtension\wixlib

Rename file WixUI_Minimal.wxs to Custom_Minimal.wxs and include into project

Change in Custom_Minimal.wxs:

<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <UI Id="Custom_Minimal">

Add Custom_Minimal ref to Product.wxs:

<Product Id="398c09df-6b61-4b0b-bf18-075a0bb98300" Name="SetupProject2" Language="1033" Version="1.0.0.0" Manufacturer="STH" UpgradeCode="524cff23-7bce-4078-9fb9-51b2eb7a844c">
    <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />
    <UIRef Id="Custom_Minimal" />

Trying to build but lot of errors:

Severity   Code    Description Project File    Line    Suppression State
Error       Duplicate symbol 'Property:WixUI_Mode' found. This typically means that an Id is duplicated. Check to make sure all your identifiers of a given type (File, Component, Feature) are unique. SetupProject3   C:\Users\...\source\repos\MtPubSubExample-mt3\SetupProject3\Custom_Minimal.wxs  28

and much more similar...

Anyone know why this is happening??

答:
I know this is old but I was just running into the same issue and it was very frustrating.

Seems that including the same <InstallUISequence> in your custom UI and using a Wix defined Dialog will somehow bring in one of the UI's that also has the <InstallUISequence> with that same dialog.

In the case of WixUI_Minimal you probably had

```<code><InstallUISequence>
     <Show Dialog="WelcomeDlg" Before="WelcomeEulaDlg">Installed AND PATCH</Show>
     <Show Dialog="WelcomeEulaDlg" Before="ProgressDlg">NOT Installed</Show>
</InstallUISequence>
</code>```

Included in your custom UI wxs. You can get around this by either defining your own WelcomeDlg and WelcomeEulaDlg (with modified names) and use them instead of the wix versions.

Or you can remove the <InstallUISequence> from the UI. I thought I might have to add an order but it seems to already use the "WelcomeDlg" first so just removing the <InstallUISequence> was enough. I just had to update the publish Event for the new window so it would properly move on to the next dialog when clicking next/back.

Body:
I know this is old but I was just running into the same issue and it was very frustrating.

Seems that including the same <InstallUISequence> in your custom UI and using a Wix defined Dialog will somehow bring in one of the UI's that also has the <InstallUISequence> with that same dialog.

In the case of WixUI_Minimal you probably had

<InstallUISequence>
     <Show Dialog="WelcomeDlg" Before="WelcomeEulaDlg">Installed AND PATCH</Show>
     <Show Dialog="WelcomeEulaDlg" Before="ProgressDlg">NOT Installed</Show>
</InstallUISequence>

Included in your custom UI wxs. You can get around this by either defining your own WelcomeDlg and WelcomeEulaDlg (with modified names) and use them instead of the wix versions.

Or you can remove the <InstallUISequence> from the UI. I thought I might have to add an order but it seems to already use the "WelcomeDlg" first so just removing the <InstallUISequence> was enough. I just had to update the publish Event for the new window so it would properly move on to the next dialog when clicking next/back.


问:
How do you sort a table with datetime by time with Ecto?
I am hitting a wall at the moment. I am working with Elixir and Ecto and I have a table with data and a column with Datetime.

The Datetime column is as follows:

```<code>2017-11-16 16:02:01
2017-11-23 09:00:07
2017-11-27 13:19:58
2017-12-05 07:48:42
</code>```

What I want to do is sort this table based on time, instead of date. So the result(ASC) would be:

```<code>2017-12-05 07:48:42
2017-11-23 09:00:07
2017-11-27 13:19:58
2017-11-16 16:02:01
</code>```

Do you guys have any ideas in ecto? A postgres query might also help!

答:
So I think something like this should work:

```<code>Post
|> order_by([p], fragment("?::time", p.inserted_at))
|> Repo.all()
</code>```

Here you use a fragment to in order to leverage the PostgreSQL casting mechanism which extracts the time part from the datetime. I have not tested it but I guess it should work.

Body:
I am hitting a wall at the moment. I am working with Elixir and Ecto and I have a table with data and a column with Datetime.

The Datetime column is as follows:

2017-11-16 16:02:01
2017-11-23 09:00:07
2017-11-27 13:19:58
2017-12-05 07:48:42

What I want to do is sort this table based on time, instead of date. So the result(ASC) would be:

2017-12-05 07:48:42
2017-11-23 09:00:07
2017-11-27 13:19:58
2017-11-16 16:02:01

Do you guys have any ideas in ecto? A postgres query might also help!

Body:
So I think something like this should work:

Post
|> order_by([p], fragment("?::time", p.inserted_at))
|> Repo.all()

Here you use a fragment to in order to leverage the PostgreSQL casting mechanism which extracts the time part from the datetime. I have not tested it but I guess it should work.


问:
A* (a-star) issues finding shortest path - specific example

In this example (please see picture), the Manhattan heuristic delays the path because of the unwalkable block west of the destination block.

My question is how can I fix this? Do I need to keep checking the blocks on the open list (the gray blocks) even after I found the destination? I might as well use dijkstra if I have to do that. Do I have to live with an imperfection like this if I go with a-star or is there a solution?

I have done my research on it and implemented my own algorithm that works exactly as the tutorials / articles on the web have explained, but I keep running into specific instances like this where a* fails to find the shortest path.

答: Your heuristic needs to be admissible but is not.  Use Diagonal or Euclidean distance instead.</p>


问:
Parsing table using nested FindElement with xpath (in JAVA)
I'm a bit new to selenium and xpath and am curious if I'm doing something right and how findElement will behave. I've looked and looked for an example but I can't find one.

Given this Table (simplified but relevant)

          R1C1
          R1C2

          R2C1
          R2C2

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

<p>If I use the following, will I have the info I'm expecting?</p>

```WebElement r1 = driver.findElement(By.xpath("//table/tbody/tr[1]"));
String r1c1 = r1.findElement(By.xpath("//td[1]")).getText();
String r1c2 = r1.findElement(By.xpath("//td[2]")).getText();

WebElement r2 = driver.findElement(By.xpath("//table/tbody/tr[2]"));
String r2c1 = r1.findElement(By.xpath("//td[1]")).getText();
String r2c2 = r1.findElement(By.xpath("//td[2]")).getText();
```

<p>Alt:</p>

```String r2c1 = driver.findElement(By.xpath("//table/tbody/tr[2]")).findElement(By.xpath("//td[1]")).getText();
```

Please keep in mind this is HIGHLY simplified in comparison to what I'm actually doing, but I'm confident the rest will work. My question revolves specifically around finding an element off of another element. And, no, there are no unique Class/ID tags I can utilize to specifically identify a given cell of the table.

Will this work as I expect it to? (I realize I could just try it, but then the answer wouldn't be available online for the next person to search for)

答:
I would rather suggest to Keep It Short and Simple for a better Execution Performance.

If you want to getText() from the following four WebElements keep it as simple as :

```<code>String r1c1 = driver.findElement(By.xpath("//table//tbody/tr/td")).getAttribute("innerHTML");
String r1c2 = driver.findElement(By.xpath("//table//tbody/tr//following::td[2]")).getAttribute("innerHTML");

String r2c1 = driver.findElement(By.xpath("//table//tbody//following::tr[2]/td")).getAttribute("innerHTML");
String r2c2 = driver.findElement(By.xpath("//table//tbody//following::tr[2]//following::td[2]")).getAttribute("innerHTML");
</code>```

Body:
I'm a bit new to selenium and xpath and am curious if I'm doing something right and how findElement will behave. I've looked and looked for an example but I can't find one.

Given this Table (simplified but relevant)

          R1C1
          R1C2

          R2C1
          R2C2

If I use the following, will I have the info I'm expecting?

WebElement r1 = driver.findElement(By.xpath("//table/tbody/tr[1]"));
String r1c1 = r1.findElement(By.xpath("//td[1]")).getText();
String r1c2 = r1.findElement(By.xpath("//td[2]")).getText();

WebElement r2 = driver.findElement(By.xpath("//table/tbody/tr[2]"));
String r2c1 = r1.findElement(By.xpath("//td[1]")).getText();
String r2c2 = r1.findElement(By.xpath("//td[2]")).getText();

Alt:

String r2c1 = driver.findElement(By.xpath("//table/tbody/tr[2]")).findElement(By.xpath("//td[1]")).getText();

Please keep in mind this is HIGHLY simplified in comparison to what I'm actually doing, but I'm confident the rest will work. My question revolves specifically around finding an element off of another element. And, no, there are no unique Class/ID tags I can utilize to specifically identify a given cell of the table.

Will this work as I expect it to? (I realize I could just try it, but then the answer wouldn't be available online for the next person to search for)

Body:
I would rather suggest to Keep It Short and Simple for a better Execution Performance.

If you want to getText() from the following four WebElements keep it as simple as :

String r1c1 = driver.findElement(By.xpath("//table//tbody/tr/td")).getAttribute("innerHTML");
String r1c2 = driver.findElement(By.xpath("//table//tbody/tr//following::td[2]")).getAttribute("innerHTML");

String r2c1 = driver.findElement(By.xpath("//table//tbody//following::tr[2]/td")).getAttribute("innerHTML");
String r2c2 = driver.findElement(By.xpath("//table//tbody//following::tr[2]//following::td[2]")).getAttribute("innerHTML");


问:
Why has my git commit changed all lines to CRLF?
The project I'm working on has a text file called pom.xml. Looking at the history this file has always had every line ending with LF... until recently.

I'm running on Windows and when I installed git bash I took the option to automatically convert to CRLF on checkout and back to LF on commit. I have just checked this as follows:

```<code>git config core.autocrlf
true
</code>```

The problem is my most recent commit has included the CR characters in the commit and the history tells me that every single line changed.

I just committed some changes to a different text file and I can see correctly that my working copy has CRLF but if I view the history it shows up as just LF. So for this commit the conversion from CRLF to LF has worked. This file is a .drl drools rule file if that makes a difference. I don't understand why it would work on one occasion but not on another. Both files were consistently using LF with previous revisions.

I've had a look at a few other files and noticed I'm not the only one who has had this problem. Some of the other .xml files have at some point switched from LF to CRLF. This messes up the history so I would like to sort this out.

Edit

If I look at the commit that contained this pom.xml change, I also created two new Java classes. Both of these were committed with CRLF, so each file in the commit has the incorrect line endings. If I check a different commit from around the same time I can see all files (including a mix of new and existing Java classes and .drl text files) have been converted to just LF on the commit.

答:
I found the problem. The setting core.autocrlf is not properly set when installing git bash. So git config core.autocrlf returns true, but git config --global core.autocrlf returns blank.

This is fine if you only use git bash as the setting is picked up. However, I had made a commit using EGit within Eclipse and this found the --global setting not set and used the default of false. This is why the behaviour was inconsistent, commits via git bash worked but not via Eclipse.

I fixed it by setting the global setting as follows:

```<code>git config --global core.autocrlf true
</code>```

This has made commits behave whichever tool I use and also Eclipse is behaving when I compare two revisions of a file.

Body:
The project I'm working on has a text file called pom.xml. Looking at the history this file has always had every line ending with LF... until recently.

I'm running on Windows and when I installed git bash I took the option to automatically convert to CRLF on checkout and back to LF on commit. I have just checked this as follows:

git config core.autocrlf
true

The problem is my most recent commit has included the CR characters in the commit and the history tells me that every single line changed.

I just committed some changes to a different text file and I can see correctly that my working copy has CRLF but if I view the history it shows up as just LF. So for this commit the conversion from CRLF to LF has worked. This file is a .drl drools rule file if that makes a difference. I don't understand why it would work on one occasion but not on another. Both files were consistently using LF with previous revisions.

I've had a look at a few other files and noticed I'm not the only one who has had this problem. Some of the other .xml files have at some point switched from LF to CRLF. This messes up the history so I would like to sort this out.

Edit

If I look at the commit that contained this pom.xml change, I also created two new Java classes. Both of these were committed with CRLF, so each file in the commit has the incorrect line endings. If I check a different commit from around the same time I can see all files (including a mix of new and existing Java classes and .drl text files) have been converted to just LF on the commit.

Body:
I found the problem. The setting core.autocrlf is not properly set when installing git bash. So git config core.autocrlf returns true, but git config --global core.autocrlf returns blank.

This is fine if you only use git bash as the setting is picked up. However, I had made a commit using EGit within Eclipse and this found the --global setting not set and used the default of false. This is why the behaviour was inconsistent, commits via git bash worked but not via Eclipse.

I fixed it by setting the global setting as follows:

git config --global core.autocrlf true

This has made commits behave whichever tool I use and also Eclipse is behaving when I compare two revisions of a file.


问:
MySQL String to Time Format
Could you please help.

In the database time represent in string format like 5.5 (hours) how to convert to 5:30 min

I tried

```<code>select CAST('5.50' AS DATETIME)

select STR_TO_DATE('5.50', '%h:%i %p') ;
</code>```

but this is not working.

Thank you

答:
You can add the 5.5 hours interval to time 00:00:00 to get a time of 05:30:00.

This however:

```<code>select time '00:00:00' + interval '5.5' hour
</code>```

does not work. MySQL truncates the 5.5 to 5 for some reason. So use

```<code>select time '00:00:00' + interval '5.5' * 60 * 60 second
</code>```

instead.

UPDATE: Just looked it up. That interval 5.5 hour does not work was filed as a bug in 2007 here: https://bugs.mysql.com/bug.php?id=31013.

Title: MySQL String to Time Format

Body:
Could you please help.

In the database time represent in string format like 5.5 (hours) how to convert to 5:30 min

I tried

select CAST('5.50' AS DATETIME)

select STR_TO_DATE('5.50', '%h:%i %p') ;

but this is not working.

Thank you

Body:
You can add the 5.5 hours interval to time 00:00:00 to get a time of 05:30:00.

This however:

select time '00:00:00' + interval '5.5' hour

does not work. MySQL truncates the 5.5 to 5 for some reason. So use

select time '00:00:00' + interval '5.5' * 60 * 60 second

instead.

UPDATE: Just looked it up. That interval 5.5 hour does not work was filed as a bug in 2007 here: https://bugs.mysql.com/bug.php?id=31013.


问:
iPhone GPS Coordinate uploading
I am looking for a way for the iPhone to push out GPS coordinates every hour and display them on a public website.

I have a friend biking across the country for charity and he wants everyone to be able to view his progress.  Any creative ideas besides the iPhone?  Any ideas with minimal programming would be appreciated.

Thanks for the help!
Dylan

答:
What about using gpsnerd.com? Signup for an account. Can track live position. Mark your account as public to share with others.

I created thi site. Let me know if you have questions.

Bob

Title: iPhone GPS Coordinate uploading


问:
How to disable and enable jetty request log dynamically?
How to disable and enable jetty request log dynamically in a web project?I want to disable the request log when the system resource is pretty low which may save the world.</p>

答:
Use the Slf4jRequestLog implementation for Request Logging and simply enable/disable the selected Slf4j implementation using the techniques that the implementation provides.

You cannot rely on the behaviors of the default implementation in your use case.