问:
Export a specific data in an app in the django admin to a pdf
I've already set everything that is need to export a data to pdf format. Now, my problem is how can I do this use case to the django admin. Can I accomplish this by action whilst providing the class view then add that specific class view in the action to the modeladmin? Is that possible? How can I do this?

This is my class view

```<code>class PdfCarrier(View):

    def get(self, request, carrier_id):
        carrier = Carrier.objects.filter(id=carrier_id).first()
        params = {
        'today': timezone.now(),
        'carrier': carrier,
        'request': request
        }

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = "inline; filename=Carrier-Report.pdf"

        html = render_to_string('carrier/carrier_pdf.html', params)
        css = [
            base.BASE_DIR + '/src/css/bootstrap3/css/bootstrap.min.css'
        ]

        HTML(string=html).write_pdf(response, stylesheets=css)
        return response
        # return Render.render('carrier/carrier_print.html', params)
</code>```

my url providing it.

```<code>    path('<uuid:carrier_id>/carrier-report.pdf', views.PdfCarrier.as_view(), name="print_carrier"),

</code>```

答:
That is possible. In your model admin class prepend the pdf path to the list of built-in urls.

```<code>class YourModelAdmin(admin.ModelAdmin):
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('<uuid:carrier_id>/carrier-report.pdf', self.pdf_view),
        ]
        return custom_urls + urls
</code>```

Then define the method pdf_view like below.

```<code>class YourModelAdmin(admin.ModelAdmin):
    ...
    def pdf_view(self, request, carrier_id):
        # do whatever you want
        # and return the response
</code>```

That's it.

Body:
I've already set everything that is need to export a data to pdf format. Now, my problem is how can I do this use case to the django admin. Can I accomplish this by action whilst providing the class view then add that specific class view in the action to the modeladmin? Is that possible? How can I do this?

This is my class view

class PdfCarrier(View):

    def get(self, request, carrier_id):
        carrier = Carrier.objects.filter(id=carrier_id).first()
        params = {
        'today': timezone.now(),
        'carrier': carrier,
        'request': request
        }

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = "inline; filename=Carrier-Report.pdf"

        html = render_to_string('carrier/carrier_pdf.html', params)
        css = [
            base.BASE_DIR + '/src/css/bootstrap3/css/bootstrap.min.css'
        ]

        HTML(string=html).write_pdf(response, stylesheets=css)
        return response
        # return Render.render('carrier/carrier_print.html', params)

my url providing it.

    path('<uuid:carrier_id>/carrier-report.pdf', views.PdfCarrier.as_view(), name="print_carrier"),

Body:
That is possible. In your model admin class prepend the pdf path to the list of built-in urls.

class YourModelAdmin(admin.ModelAdmin):
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('<uuid:carrier_id>/carrier-report.pdf', self.pdf_view),
        ]
        return custom_urls + urls

Then define the method pdf_view like below.

class YourModelAdmin(admin.ModelAdmin):
    ...
    def pdf_view(self, request, carrier_id):
        # do whatever you want
        # and return the response

That's it.


来源: stackexchange

问:
ViewPager2 default position
I'm creating a slideshow with ViewPager2. For example, the slideshow has 3 items and I want to show the second item when the activity opens. I use setCurrentItem(int item, boolean smoothScroll) method but it doesn't work and nothing happens. How can I achieve it?

```<code>viewPager.adapter = adapter
viewPager.setCurrentItem(1, true)
</code>```

答:
First You need to Initilaze the Main activity under any listener or button You want then After that You need to put this Line..
here MainActvity is the Viewpager Main Class You are using and and 2 is the position where you want to move</p>

```<code> MainActivity main = (MainActivity ) mContext;
    main.selectTab(2, true);
</code>```

ContentLicense: CC BY-SA 4.0

Title: ViewPager2 default position

Body:
I'm creating a slideshow with ViewPager2. For example, the slideshow has 3 items and I want to show the second item when the activity opens. I use setCurrentItem(int item, boolean smoothScroll) method but it doesn't work and nothing happens. How can I achieve it?

viewPager.adapter = adapter
viewPager.setCurrentItem(1, true)

Body:
First You need to Initilaze the Main activity under any listener or button You want then After that You need to put this Line..
here MainActvity is the Viewpager Main Class You are using and and 2 is the position where you want to move

 MainActivity main = (MainActivity ) mContext;
    main.selectTab(2, true);


问:
Making request(s) after getting an object from first request
I am new to Rx and need help with understanding it. I am using TMDB to get data. Now it returns me a Json Object which contains a List of movie ids. I want to be able to send request(s) for ids in this list.

Lets say my first request is searchFor(String query), which gives me a Object which contains a response field which has a List of movies.
My second request is getDetails(String id), which is the final data I wish to show.

I have a made a Single<MovieResponse> searchFor(String query), and Single<MovieDetail> getDetails(String id).

The problem is I want to keep it reactive and make the 2nd request(getDetails) immediately as I receive data from the 1st request.

I was thinking of something like FlatMap.

答:
I figured out that I could chain the operators to achieve what I wanted.
I did,</p>

```<code>Single.subscribeOn(...)
    .observeOn(...)
    .map(...)      // return the arraylist in the object
    .flatmap(...)  // return observable for that arraylist
    .flatmap(...)  // return (n) observables for the elements of arraylist
</code>```

Body:
I figured out that I could chain the operators to achieve what I wanted.
I did,

Single.subscribeOn(...)
    .observeOn(...)
    .map(...)      // return the arraylist in the object
    .flatmap(...)  // return observable for that arraylist
    .flatmap(...)  // return (n) observables for the elements of arraylist


问:
react-textfit not fitting text correctly in multi mode
I am trying to use the react-textfit module with multi-line support. However, my text is overflowing the parent div rather than fitting neatly inside.

An excerpt of my code:

```<code>return(
    <div style={{margin: '10px', border: 'solid black 2px', width: '200px', height: '80px'}}>
        <Textfit mode="multi">
            The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.
        </Textfit>
    </div>
)
</code>```

What I am seeing:

The text does auto-fit for single mode and shows correctly on a single line. However, when I switch it to multi mode, it is behaving as if I am not even using the <Textfit> module.

Additional note: while the above text is hard-coded, the actual text will be dynamically pulled from a database.

Question:

What am I doing wrong? How can I fix this so that the text fits inside of the div container?

答:
You can either make the Textfit know the height of the parent div with:  <Textfit mode="multi" style={{height: '100%'}}> or you can make the parent div a display: flex.

I'm not exactly sure of how Textfit works under the hood but this works fine in almost every scenarios.

Here's a small Stackblitz to illustrate.

Let me know if this doesn't do exactly what you want! :)

Body:
I am trying to use the react-textfit module with multi-line support. However, my text is overflowing the parent div rather than fitting neatly inside.

An excerpt of my code:

return(

        <Textfit mode="multi">
            The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.
        </Textfit>

)

What I am seeing:

The text does auto-fit for single mode and shows correctly on a single line. However, when I switch it to multi mode, it is behaving as if I am not even using the <Textfit> module.

Additional note: while the above text is hard-coded, the actual text will be dynamically pulled from a database.

Question:

What am I doing wrong? How can I fix this so that the text fits inside of the div container?


问:
How Can I replace value if IS NOT IN a list?
I have a list with all values distinct in a column and I need to replace all values that IS NOT IN this list with 1

I've tried this

```<code>uniq = X_train3.select('street').distinct().collect()
X_test3 = X_test3.withColumn('street', F.when(array_contains('street', uniq), 1))
</code>```

and i also tried this:

```<code>uniq = X_train3.select('street').distinct().collect()
X_test3 = X_test3.withColumn('street', F.when(~col('street').isin(uniq), 1))
</code>```

both result in this error:
java.lang.RuntimeException: Unsupported literal type class java.util.ArrayList [[1.0]]

This is what I did in python and works:

uniq = X_train3[cl].unique()
uniq = uniq.tolist()
X_test3['street'] = X_test3['street'].map(lambda x: 1 if x not in uniq else x)]
```

答:
You can do this (in Scala, write the equivalent pyspark):

```<code>val new_X_test3 = X_test3
.join(X_train3
    .select("street")
    .distinct()
    .withColumnRenamed("street","street_train"),
    col("street") === col("street_train"),
    "leftouter")
.withColumn("street_test",
    when(col("street_train").isNull, lit("1"))
    .otherwise(col("street")))
.drop("street","street_train")
.withColumnRenamed("street_test","street")
</code>```

Also if you're convinced that the list of unique streets is very small (since you tried collecting it on the driver in your code) you can provide the broadcasthint around X_train3. So code becomes:

```<code>val new_X_test3 = X_test3
.join(broadcast(X_train3
    .select("street")
    .distinct()
    .withColumnRenamed("street","street_train")),
    col("street") === col("street_train"),
    "leftouter")
.withColumn("street_test",
    when(col("street_train").isNull, lit("1"))
    .otherwise(col("street")))
.drop("street","street_train")
.withColumnRenamed("street_test","street")
</code>```

Body:
I have a list with all values distinct in a column and I need to replace all values that IS NOT IN this list with 1

I've tried this

uniq = X_train3.select('street').distinct().collect()
X_test3 = X_test3.withColumn('street', F.when(array_contains('street', uniq), 1))

and i also tried this:

uniq = X_train3.select('street').distinct().collect()
X_test3 = X_test3.withColumn('street', F.when(~col('street').isin(uniq), 1))

both result in this error:
java.lang.RuntimeException: Unsupported literal type class java.util.ArrayList [[1.0]]

This is what I did in python and works:

uniq = X_train3[cl].unique()
uniq = uniq.tolist()
X_test3['street'] = X_test3['street'].map(lambda x: 1 if x not in uniq else x)]

Body:
You can do this (in Scala, write the equivalent pyspark):

val new_X_test3 = X_test3
.join(X_train3
    .select("street")
    .distinct()
    .withColumnRenamed("street","street_train"),
    col("street") === col("street_train"),
    "leftouter")
.withColumn("street_test",
    when(col("street_train").isNull, lit("1"))
    .otherwise(col("street")))
.drop("street","street_train")
.withColumnRenamed("street_test","street")

Also if you're convinced that the list of unique streets is very small (since you tried collecting it on the driver in your code) you can provide the broadcasthint around X_train3. So code becomes:

val new_X_test3 = X_test3
.join(broadcast(X_train3
    .select("street")
    .distinct()
    .withColumnRenamed("street","street_train")),
    col("street") === col("street_train"),
    "leftouter")
.withColumn("street_test",
    when(col("street_train").isNull, lit("1"))
    .otherwise(col("street")))
.drop("street","street_train")
.withColumnRenamed("street_test","street")


问:
Volley request JSONArray should be recognized if it was empty
I am using Volley to get JSON from remote PHP script.
Sometimes, the JSON array is empty.

This my code:

```<code>StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray array=jsonObject.getJSONArray("data");

                    for (int i=0; i<array.length(); i++ ){
                        JSONObject ob=array.getJSONObject(i);
                        Notificacion listData=new Notificacion(ob.getString("id_notificacion")
                                ,ob.getString("texto"),
                                ob.getString("fecha"),
                                ob.getString("nombre"),
                                ob.getString("nombre")+" "+ob.getString("apellidos"),
                                ob.getString("profesor"),
                                ob.getString("tutor"),
                                ob.getString("estado"),
                                ob.getString("envia_tutor"),
                                ob.getString("envia_profesor")

                                );
                        list_data.add(listData);
                        spinner.setVisibility(View.GONE);
                    }
                    rv.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("arry","array lengt error:"+error);
                Toast.makeText(getActivity(),
                        "No tienes notificaciones.", Toast.LENGTH_LONG)
                        .show();
                spinner.setVisibility(View.GONE);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
</code>```

If the JSON array is empty, then I am getting the response listener message saying that data[] is empty, but the Toast is not showing and also the spinner visibility is not gone as expected.

How should I change in my code to launch a Toast and to set the spinner visibility to GONE when the received JSON array is empty?

答:
You should some changes in your code  like this:</p>

```<code>StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray array=jsonObject.getJSONArray("data");

                         if (array.length()==0){
                        Toast.makeText(getActivity(),
                    "No tienes notificaciones.", Toast.LENGTH_LONG)
                    .show();
                     spinner.setVisibility(View.GONE);
                           }else{
                        for (int i=0; i<array.length(); i++ ){
                        JSONObject ob=array.getJSONObject(i);
                        Notificacion listData=new Notificacion(ob.getString("id_notificacion")
                                ,ob.getString("texto"),
                                ob.getString("fecha"),
                                ob.getString("nombre"),
                                ob.getString("nombre")+" "+ob.getString("apellidos"),
                                ob.getString("profesor"),
                                ob.getString("tutor"),
                                ob.getString("estado"),
                                ob.getString("envia_tutor"),
                                ob.getString("envia_profesor")

                                  );
                        list_data.add(listData);
                        spinner.setVisibility(View.VISIBLE);
                    }
                    rv.setAdapter(adapter);
                   }

                } catch (JSONException e) {
                    e.printStackTrace();
              spinner.setVisibility(View.GONE);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("arry","array lengt error:"+error);

                spinner.setVisibility(View.GONE);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
</code>```

Body:
I am using Volley to get JSON from remote PHP script.
Sometimes, the JSON array is empty.

This my code:

StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray array=jsonObject.getJSONArray("data");

                    for (int i=0; i<array.length(); i++ ){
                        JSONObject ob=array.getJSONObject(i);
                        Notificacion listData=new Notificacion(ob.getString("id_notificacion")
                                ,ob.getString("texto"),
                                ob.getString("fecha"),
                                ob.getString("nombre"),
                                ob.getString("nombre")+" "+ob.getString("apellidos"),
                                ob.getString("profesor"),
                                ob.getString("tutor"),
                                ob.getString("estado"),
                                ob.getString("envia_tutor"),
                                ob.getString("envia_profesor")

                                );
                        list_data.add(listData);
                        spinner.setVisibility(View.GONE);
                    }
                    rv.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("arry","array lengt error:"+error);
                Toast.makeText(getActivity(),
                        "No tienes notificaciones.", Toast.LENGTH_LONG)
                        .show();
                spinner.setVisibility(View.GONE);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);

If the JSON array is empty, then I am getting the response listener message saying that data[] is empty, but the Toast is not showing and also the spinner visibility is not gone as expected.

How should I change in my code to launch a Toast and to set the spinner visibility to GONE when the received JSON array is empty?

Body:
You should some changes in your code  like this:

StringRequest stringRequest=new StringRequest(Request.Method.GET, HI, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject=new JSONObject(response);
                    JSONArray array=jsonObject.getJSONArray("data");

                         if (array.length()==0){
                        Toast.makeText(getActivity(),
                    "No tienes notificaciones.", Toast.LENGTH_LONG)
                    .show();
                     spinner.setVisibility(View.GONE);
                           }else{
                        for (int i=0; i<array.length(); i++ ){
                        JSONObject ob=array.getJSONObject(i);
                        Notificacion listData=new Notificacion(ob.getString("id_notificacion")
                                ,ob.getString("texto"),
                                ob.getString("fecha"),
                                ob.getString("nombre"),
                                ob.getString("nombre")+" "+ob.getString("apellidos"),
                                ob.getString("profesor"),
                                ob.getString("tutor"),
                                ob.getString("estado"),
                                ob.getString("envia_tutor"),
                                ob.getString("envia_profesor")

                                  );
                        list_data.add(listData);
                        spinner.setVisibility(View.VISIBLE);
                    }
                    rv.setAdapter(adapter);
                   }

                } catch (JSONException e) {
                    e.printStackTrace();
              spinner.setVisibility(View.GONE);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("arry","array lengt error:"+error);

                spinner.setVisibility(View.GONE);
            }
        });
        RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);


问:
How do I check if a particular app is installed on the user's device on iOS?
Is there a function which I can use to check if the user has a particular app installed on their device. Ie, instagram</p>

答:
```<code>class func isAppInstalled(_ appName:String) -> Bool{

    let appScheme = "\(appName)://app"
    let appUrl = URL(string: appScheme)

    if UIApplication.shared.canOpenURL(appUrl! as URL){
        return true
    } else {
        return false
    }

}
</code>```

Add the name of the app you are checking to LSApplicationQueriesSchemes in your info.plist file

Body:
class func isAppInstalled(_ appName:String) -> Bool{

    let appScheme = "\(appName)://app"
    let appUrl = URL(string: appScheme)

    if UIApplication.shared.canOpenURL(appUrl! as URL){
        return true
    } else {
        return false
    }

}

Add the name of the app you are checking to LSApplicationQueriesSchemes in your info.plist file


问:
Create provisioning profile in iphone application
How can i build provisioning profile for deploying an iPhone application?</p>

答: Ensure that your iPhone is not jailbroken. The process described is a bit of a pain but it's a one-time thing.</p>

OwnerDisplayName: Khushi

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
adding bed raw html form to room raw html as a pop up to add a lot of beds
I have a raw html which i get the room details in which i need to add in a button pop up for a raw html form that can show up
○ You should be able to add multiple beds for a Room
           § Each Bed entity will have following fields:
               □ Width
               □ Length
               □ Quantity
               □ Mattress Type
                   ® None
                   ® Innerspring
                   ® Pillow top
                   ® Hybrid
                   ® Specialty foam
                   ® Gel
                   ® Memory foam
                   ® Latex
                   ® Matress airbed
Matress waterbed

with each click on the +add beds it should show up the html form to add in details and then save all this while saving the Room form.

didnt find a better way to approach

NA

it must be a raw html with some js or jquery to pop up a html form on click fill in the details and when clicked on add bed it should open another html form and need to add in details and same must show in edit view too.must be able to remove the beds html form if not needed and in the end must save with the room html form.

答: Okay, so for that you definatelly need Javascript, or jQuery. On your button add event listener on click. In your html prepare form witch display attribute is set to None. If user clicks to button, this attribute is set to Block. If you want to do things asynchronously think about AJAX calls using jQuery. Let me know if that helped a bit ;)</p>


问:
What is Python equivalent of for(i=1;i<10000000;i=1*10)?
In python how can we create a for-loop that does not have a constant step-size? I want to create a for-loop with step-function i=i*10, How can I do that?

For example: I want to create a python equivalent for: for(i=1;i<10000000;i=i*10){...}
How do I do this in python2 and python3?

I know that I can just use while-loop But I want to know if there is a way using for-loop?

答:
this is a variant:</p>

```<code>from math import log

for i in (10 ** e for e in range(round(log(10000000, 10)))):
    print(i)
</code>```

Body:
this is a variant:

from math import log

for i in (10 ** e for e in range(round(log(10000000, 10)))):
    print(i)


问:
Typescript removes (tree-shaking) my file/class
Suppose a class adds itself to an other class as follows

bar.ts:

```<code>import { Foo } from './foo';

export class Bar {}

Foo.prop = Bar;
</code>```

And file foo.ts

```<code>export class Foo {
    public static prop: any;
}
</code>```

Now, if would like to use this in index.ts

```<code>import { Foo } from './foo';

console.log(Foo.prop); // -> undefined
</code>```

It is undefined. It looks like that bar.ts is not used at all (probably tree shaking). So I can fix that as follows:

```<code>import { Foo } from './foo';
import { Bar } from './bar';

new Bar(); // trick!
console.log(Foo.prop); // -> Bar
</code>```

Is there a way to tell typescript to include Bar anyway, because the solution I showed is ugly.

For completeness, here is my tsconfig.json

```<code>{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "sourceMap": true,
    "noImplicitAny": false,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "outDir": "./dist",
    "baseUrl": "./",
    "lib": ["es2017", "dom", "dom.iterable"]
  },
  "exclude": ["node_modules", "**/*.spec.ts", "dist"]
}
</code>```

答:
Foo.prop = Bar;

is what is causing the issue, you're doing this in Bar.ts, do this in Foo.ts, now when you create a new object of Foo in index.ts, tree shaking won't remove Bar.ts.

As a general rule, if you need to add a dependency to a class,always do that in the file where the class is defined (Foo.ts in this case)

Body:
Suppose a class adds itself to an other class as follows

bar.ts:

import { Foo } from './foo';

export class Bar {}

Foo.prop = Bar;

And file foo.ts

export class Foo {
    public static prop: any;
}

Now, if would like to use this in index.ts

import { Foo } from './foo';

console.log(Foo.prop); // -> undefined

It is undefined. It looks like that bar.ts is not used at all (probably tree shaking). So I can fix that as follows:

import { Foo } from './foo';
import { Bar } from './bar';

new Bar(); // trick!
console.log(Foo.prop); // -> Bar

Is there a way to tell typescript to include Bar anyway, because the solution I showed is ugly.

For completeness, here is my tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "sourceMap": true,
    "noImplicitAny": false,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "outDir": "./dist",
    "baseUrl": "./",
    "lib": ["es2017", "dom", "dom.iterable"]
  },
  "exclude": ["node_modules", "**/*.spec.ts", "dist"]
}


问:
TypeError: console.log(...) is not a function
I'm really confused how I can get console.log is not a function on line 1091. If I remove the closure below, line 1091 doesn't complain such error. Chrome Version 43.0.2357.130 (64-bit).

Here is the code:

```<code>$scope.columnNameChanged = function (tableColumn) {
    setDirtyColumn(tableColumn);
    //propagate changes to the key fields
    for (var i = 0; i < $scope.tableIndexes.length; ++i) {
        for (var j = 0; j < $scope.tableIndexes[i].columnName.length; ++j) {
            if ($scope.tableIndexes[i].columnName[j] === tableColumn.previousName) {
                console.log('xxx', $scope.tableIndexes[i].columnName[j])
                (function (i, j) {
                    $timeout(function () {
                        console.log($scope.tableIndexes[i].columnName[j])
                        $scope.tableIndexes[i].columnName[j] = tableColumn.name.toUpperCase();
                        console.log($scope.tableIndexes[i].columnName[j])
                    });
                })(i, j);
            }
        }
    }
};
</code>```

答: In react-native at least, the console seems to work without any import, so, removing import console = require('console'); or import console from 'console'; from the begin of my file fixed it for me. (the VS Code IDE seems to add that automatically sometimes )

Body:
I'm really confused how I can get console.log is not a function on line 1091. If I remove the closure below, line 1091 doesn't complain such error. Chrome Version 43.0.2357.130 (64-bit).

Here is the code:

$scope.columnNameChanged = function (tableColumn) {
    setDirtyColumn(tableColumn);
    //propagate changes to the key fields
    for (var i = 0; i < $scope.tableIndexes.length; ++i) {
        for (var j = 0; j < $scope.tableIndexes[i].columnName.length; ++j) {
            if ($scope.tableIndexes[i].columnName[j] === tableColumn.previousName) {
                console.log('xxx', $scope.tableIndexes[i].columnName[j])
                (function (i, j) {
                    $timeout(function () {
                        console.log($scope.tableIndexes[i].columnName[j])
                        $scope.tableIndexes[i].columnName[j] = tableColumn.name.toUpperCase();
                        console.log($scope.tableIndexes[i].columnName[j])
                    });
                })(i, j);
            }
        }
    }
};


问:
How to save information in cookies using  element
I am building 'Cart' page, I have list of items and  buttons, which should save that specific item in Cookie object.

Here is the code I have which prints items to webpage

```<code>    Cookie c;
                while(rs.next())
                {
                    out.println("<div id=\"aaa\">");
                    out.println("<div id=\"bbb\" style=\"background-image:url("+rs.getString("poster")+"); background-repeat: no-repeat; background-size:cover;\">"+"</div>");
                        out.println("<div id=\"ccc\">");
                        out.println("<h2>"+rs.getString("name")+"</h2>");
                        out.println("<p>Category: <em>" + rs.getString("Category")+"</em></p>");
                        out.println("<p>Size: "+rs.getDouble("size")+"</p>");
                        out.println("<p>Publisher: "+rs.getString("publisher")+"</p>");
                        out.println("<p>Price:"+rs.getDouble("price")+"</p>");

                        c = new Cookie(rs.getString("name"), Double.toString(rs.getDouble("price")));
                        out.println("<footer class=\"align-center\">");
                        out.println("<a href=\"Cart\" target=\"_blank\" class=\"button alt\">Open</a>");
                        out.println("</footer>");
                    out.println("</div>");

                        out.println("<div id=\"ddd\"></div>");
                    out.println("</div>");
                    out.println("<hr />");
                }
</code>```

what I want exactly is cookie object to be filled with item name and price after this button is pressed.

```<code>   out.println("<footer class=\"align-center\">");
                    out.println("<a href=\"Cart\" target=\"_blank\" class=\"button alt\">Open</a>");
                    out.println("</footer>");
</code>```

答:
You can passed the value of specific product i.e name,price etc by passing that value in  and get that value in your cart page and use request.getParameter("something") to get value of that item passed and save in cookies like below :

```<code> String name=rs.getString("name");
 String price=Double.toString(rs.getDouble("price"));
     out.println("<footer class=\"align-center\">");
   //passing value in url
     out.println("<a href=\"Cart?name="+name+"&price="+price\" target=\"_blank\" class=\"button alt\">Open</a>");
      out.println("</footer>");
</code>```

And then in your cart page do like below :

```<code> String name=request.getParameter("name");//getting value from url
 String price=request.getParameter("price");
Cookie ck=new Cookie("name",name);//creating cookie object name
response.addCookie(ck);//adding cookie in the response
</code>```

Also ,don't use htmlin your href="https://stackoverflow.com/questions/101579/when-do-you-use-a-jsp-and-when-a-servlet">servlet instead put this in jsp

Title: How to save information in cookies using <a> element

Body:
I am building 'Cart' page, I have list of items and  buttons, which should save that specific item in Cookie object.

Here is the code I have which prints items to webpage

    Cookie c;
                while(rs.next())
                {
                    out.println("
");
                    out.println("
"+"
");
                        out.println("
");
                        out.println("
"+rs.getString("name")+"
");
                        out.println("
Category: " + rs.getString("Category")+"
");
                        out.println("
Size: "+rs.getDouble("size")+"
");
                        out.println("
Publisher: "+rs.getString("publisher")+"
");
                        out.println("
Price:"+rs.getDouble("price")+"
");

                        c = new Cookie(rs.getString("name"), Double.toString(rs.getDouble("price")));
                        out.println("");
                        out.println("Open");
                        out.println("");
                    out.println("
");

                        out.println("

");
                    out.println("
");
                    out.println("
");
                }

what I want exactly is cookie object to be filled with item name and price after this button is pressed.

   out.println("");
                    out.println("Open");
                    out.println("");

Body:
You can passed the value of specific product i.e name,price etc by passing that value in <a href=""> and get that value in your cart page and use request.getParameter("something") to get value of that item passed and save in cookies like below :

 String name=rs.getString("name");
 String price=Double.toString(rs.getDouble("price"));
     out.println("<footer class=\"align-center\">");
   //passing value in url
     out.println("<a href=\"Cart?name="+name+"&price="+price\" target=\"_blank\" class=\"button alt\">Open</a>");
      out.println("</footer>");

And then in your cart page do like below :

 String name=request.getParameter("name");//getting value from url
 String price=request.getParameter("price");
Cookie ck=new Cookie("name",name);//creating cookie object name
response.addCookie(ck);//adding cookie in the response

Also ,don't use htmlin your servlet instead put this in jsp


问:
Angular Material mat-spinner custom color
Does anyone know how can I change mat-spinner color in Angular Material?
Overriding css doesn't work. I tried changing color in material files but they can only be imported, I can't change anything there.
I want it to be my custom color, not color from prebiult-themes.</p>

答:
To your .css/.scss component file style add (it will works locally - in component only)</p>

```<code>:host ::ng-deep .mat-progress-spinner circle, .mat-spinner circle {
    stroke: #bada55;
}
</code>```

Body:
To your .css/.scss component file style add (it will works locally - in component only)

:host ::ng-deep .mat-progress-spinner circle, .mat-spinner circle {
    stroke: #bada55;
}


问:
spell check in Rstudio
How to configure and use spell check in Rstudio? In the tools>Global option>spelling I have set the main dictionary language as English(US) and custom dictionary as en_us from "/usr/lib/rstudio/resources/dictionaries/en_US.dic".

Still I do not see any indication (such as red make) on wrong spellings!!

答: I recently spotted live, on-the-fly spell checking in OSX v.1.3.118 and later, which can be downloaded from https://dailies.rstudio.com/

Title: spell check in Rstudio


问:
Sphinxsearch: 1064 can not use HAVING with attribute not related to GROUP BY
I am using the example sphinxsearch config and the 'test' database that comes with the download for version 3.1.1

```<code>source src1
{
type            = mysql

sql_host        = localhost
sql_user        = root
sql_pass        =
sql_db          = test
sql_port        = 3306  # optional, default is 3306

sql_query       = \
    SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS date_added, title, content \
    FROM documents

sql_attr_uint       = group_id
sql_attr_timestamp  = date_added
}
</code>```

When running this:

```<code>$array = $sphinx->prepare("SELECT date_added,group_id FROM test1 GROUP BY group_id HAVING group_id > 1");
$array->execute();
</code>```

I get this error:

```<code>SQLSTATE[42000]: Syntax error or access violation: 1064 can not use HAVING with attribute not related to GROUP BY
</code>```

答:
Use where condition instead of having since you didn't use any aggregation also group by is not necessary in this case

```<code>SELECT date_added,group_id
FROM test1
where group_id>1
</code>```

Body:
I am using the example sphinxsearch config and the 'test' database that comes with the download for version 3.1.1

source src1
{
type            = mysql

sql_host        = localhost
sql_user        = root
sql_pass        =
sql_db          = test
sql_port        = 3306  # optional, default is 3306

sql_query       = \
    SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS date_added, title, content \
    FROM documents

sql_attr_uint       = group_id
sql_attr_timestamp  = date_added
}

When running this:

$array = $sphinx->prepare("SELECT date_added,group_id FROM test1 GROUP BY group_id HAVING group_id > 1");
$array->execute();

I get this error:

SQLSTATE[42000]: Syntax error or access violation: 1064 can not use HAVING with attribute not related to GROUP BY

Body:
Use where condition instead of having since you didn't use any aggregation also group by is not necessary in this case

SELECT date_added,group_id
FROM test1
where group_id>1


问:
Not able overriding variable value from end file using Nunjucks
I am using Nunjucks as the template engine for my project, where I have the following scenario.

The base file can use the layout and page level variable and generate final HTML.

Base file: base.html

```<code><html class="{{htmlClass}}"> .. </html>
</code>```

Layout file: layout.html

```<code>...
{% extends "html/_layouts/base.html" %}
{% set htmlClass = "class-1" %}
...
</code>```

Page file: page.html

```<code>...
{% extends "html/_layouts/layout.html" %}
{% set htmlClass = "class-2" %}
...
</code>```

The actual generated HTML file has:

```<code><html class="class-1"> .. </html>
</code>```

Expected generated HTML file should have (it should append the page level variable value) :

```<code><html class="class-2"> .. </html>
</code>```

Please consider that I do not want to use two separate variables.

Previously I was using the PUG and I was using block htmlClass and to override value append htmlClass with a variable.

I have tried to find a similar way for Nunjucks, unfortunately, I can't find  append.

Thanks in advance

答:
try

```<code>{% set htmlClass = "class-2" %}
{% extends "html/_layouts/layout.html" %}
</code>```

instead of:

```<code>{% extends "html/_layouts/layout.html" %}
{% set htmlClass = "class-2" %}
</code>```

set before extends

Body:
I am using Nunjucks as the template engine for my project, where I have the following scenario.

The base file can use the layout and page level variable and generate final HTML.

Base file: base.html

 ..

Layout file: layout.html

...
{% extends "html/_layouts/base.html" %}
{% set htmlClass = "class-1" %}
...

Page file: page.html

...
{% extends "html/_layouts/layout.html" %}
{% set htmlClass = "class-2" %}
...

The actual generated HTML file has:

 ..

Expected generated HTML file should have (it should append the page level variable value) :

 ..

Please consider that I do not want to use two separate variables.

Previously I was using the PUG and I was using block htmlClass and to override value append htmlClass with a variable.

I have tried to find a similar way for Nunjucks, unfortunately, I can't find  append.

Thanks in advance

Body:
try

{% set htmlClass = "class-2" %}
{% extends "html/_layouts/layout.html" %}

instead of:

{% extends "html/_layouts/layout.html" %}
{% set htmlClass = "class-2" %}

set before extends


问:
How to return a nested list of frequency from a Python list?
From a list of cards - return a nested list of the cards with the same numbers and then the rest in a separate list.

```<code>EXAMPLE: ['6C', '7C', '7D', '8S', '6D']
</code>```

returning [['7C', '7D'], ['6C','6D'], ['8S']]

I have attempted using a while loop, but cant figure it out.

Thank you!

答:
I know it's not an optimal solution but...</p>

```<code>a = ['6C', '7C', '7D', '8S', '6D']
item = []
ls = []
for i in range(len(a)):
  if a[i][0] in ls:
    continue
  else:
    ls.append(a[i][0])
    temp = []
    temp.append(a[i])
    for j in range((i+1), len(a)):
      if a[i][0] == a[j][0]:
        temp.append(a[j])
      else:
        continue
    item.append(temp)
print(item)
</code>```

Body:
From a list of cards - return a nested list of the cards with the same numbers and then the rest in a separate list.

EXAMPLE: ['6C', '7C', '7D', '8S', '6D']

returning [['7C', '7D'], ['6C','6D'], ['8S']]

I have attempted using a while loop, but cant figure it out.

Thank you!

Body:
I know it's not an optimal solution but...

a = ['6C', '7C', '7D', '8S', '6D']
item = []
ls = []
for i in range(len(a)):
  if a[i][0] in ls:
    continue
  else:
    ls.append(a[i][0])
    temp = []
    temp.append(a[i])
    for j in range((i+1), len(a)):
      if a[i][0] == a[j][0]:
        temp.append(a[j])
      else:
        continue
    item.append(temp)
print(item)


问:
Bootstrap 4 dropdown width
I know how to change bootstrap 4 dropdown menu width whit:

```<code>.dropdown-menu{ min-width: ??px;}
</code>```

But how to change the width of only 1 specific dropdown menu if I have multiple dropdown on my navbar?

I had try whit an id like

```<code>#loginDropdown { min-width: ??px;}
</code>```

addign the id to the specific dropdown menu but this doesn't work.

How to solve?

答:
try this:</p>

```<code>#loginDropdown { min-width: ??px !important;}
</code>```

Title: Bootstrap 4 dropdown width

Body:
I know how to change bootstrap 4 dropdown menu width whit:

.dropdown-menu{ min-width: ??px;}

But how to change the width of only 1 specific dropdown menu if I have multiple dropdown on my navbar?

I had try whit an id like

#loginDropdown { min-width: ??px;}

addign the id to the specific dropdown menu but this doesn't work.

How to solve?

Body:
try this:

#loginDropdown { min-width: ??px !important;}


问:
Assigning a variable name as an object property while using Array.prototype.map
I'm iterating through an array of arrays using .map() in an attempt to assign the inner arrays to an object as a key:value pair. It is not successful. Can this even work? Do I need to break it out into more steps/functions/variables?

I've tried every syntax I can think of for the element in the assignment of the property.

I also tried using arr.map(function() {}) syntax with all of these, and there was no difference.

const smallArr = [1, 23, 25, 46, 52, 789, 64];

const thisArr = [5, 4, 65, 24, 35];

const thatArr = [{key: 1, anotherKey: 2}];

let parentObj = {};

const bigArr = [smallArr, thisArr, thatArr];

const newSomething = bigArr.map(arr => parentObj["arr"] = arr);

// parentObj returns: { arr: [ { key: 1, anotherKey: 2 } ] }
```

<p>I understand both of these. It's assigning the string of my element
every iteration and overwriting the value so that the final object is
one key:value pair with value being the last inner array in the outer
array.</p>

<pre class="lang-js prettyprint-override"><code>const newSomething = bigArr.map(arr => parentObj.arr = arr);
  //returns { arr: [ { key: 1, anotherKey: 2 } ] }

const newSomething = bigArr.map(arr => parentObj['arr'] = arr);
  //returns { arr: [ { key: 1, anotherKey: 2 } ] }
</code>```

This one I don't understand what's going on in the last pair.

const newSomething = bigArr.map(arr => parentObj[`${arr}`] = arr);
  // returns {
        '1,23,25,46,52,789,64': [ 1, 23, 25, 46, 52, 789, 64 ],
        '5,4,65,24,35': [ 5, 4, 65, 24, 35 ],
        '[object Object]': [ { key: 1, anotherKey: 2 } ],
         arr: [ { key: 1, anotherKey: 2 } ]
        }
```

<p>This one I don't understand at all.</p>

<pre class="lang-js prettyprint-override"><code>const newSomething = bigArr.map(arr => parentObj["`${arr}`"] = arr);
  // returns {
        '`${arr}`': [ { key: 1, anotherKey: 2 } ],
         arr: [ { key: 1, anotherKey: 2 } ]
         }
</code>```

I'm trying to get to:

parentObj = {
    smallArr: [1, 23, 25, 46, 52, 789, 64],
    thisArr: [5, 4, 65, 24, 35],
    thatArr: [{key: 1, anotherKey: 2}],
}
```

答:
You can simply use object literal shorthand property

let smallArr = [1, 23, 25, 46, 52, 789, 64];
let thisArr =  [5, 4, 65, 24, 35];
let thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr, thisArr, thatArr,}

console.log(parentObj)```

Body:
I'm iterating through an array of arrays using .map() in an attempt to assign the inner arrays to an object as a key:value pair. It is not successful. Can this even work? Do I need to break it out into more steps/functions/variables?

I've tried every syntax I can think of for the element in the assignment of the property.

I also tried using arr.map(function() {}) syntax with all of these, and there was no difference.

const smallArr = [1, 23, 25, 46, 52, 789, 64];

const thisArr = [5, 4, 65, 24, 35];

const thatArr = [{key: 1, anotherKey: 2}];

let parentObj = {};

const bigArr = [smallArr, thisArr, thatArr];

const newSomething = bigArr.map(arr => parentObj["arr"] = arr);

// parentObj returns: { arr: [ { key: 1, anotherKey: 2 } ] }

I understand both of these. It's assigning the string of my element
every iteration and overwriting the value so that the final object is
one key:value pair with value being the last inner array in the outer
array.

const newSomething = bigArr.map(arr => parentObj.arr = arr);
  //returns { arr: [ { key: 1, anotherKey: 2 } ] }

const newSomething = bigArr.map(arr => parentObj['arr'] = arr);
  //returns { arr: [ { key: 1, anotherKey: 2 } ] }

This one I don't understand what's going on in the last pair.

const newSomething = bigArr.map(arr => parentObj[`${arr}`] = arr);
  // returns {
        '1,23,25,46,52,789,64': [ 1, 23, 25, 46, 52, 789, 64 ],
        '5,4,65,24,35': [ 5, 4, 65, 24, 35 ],
        '[object Object]': [ { key: 1, anotherKey: 2 } ],
         arr: [ { key: 1, anotherKey: 2 } ]
        }

This one I don't understand at all.

const newSomething = bigArr.map(arr => parentObj["`${arr}`"] = arr);
  // returns {
        '`${arr}`': [ { key: 1, anotherKey: 2 } ],
         arr: [ { key: 1, anotherKey: 2 } ]
         }

I'm trying to get to:

parentObj = {
    smallArr: [1, 23, 25, 46, 52, 789, 64],
    thisArr: [5, 4, 65, 24, 35],
    thatArr: [{key: 1, anotherKey: 2}],
}


问:
What is the proper way to test SpringBoot Database with H2?
I am trying to run Springboot test with H2 in-memory db with Mybatis.
So far I have done

configuring h2 DB in application-test.properties

adding annotation

```<code>@SpringBootTest, @TestPropertySource (locations = "TEST_APPLICATION_PROPERTIES_LOCATION")
</code>```

autowiring dao and serviceImpl beans

adding seed.sql and purge.sql to the test class with

```<code>@SqlGroup({
        @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:/database/seed.sql"),
        @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:/database/purge.sql") })
</code>```

Despite the above measures, I still have two problems

I can't retrieve user that I input with the seed.sql. I made a user with id="admin", pw="admin", and was trying to retrieve with findById("admin"). But it always returns null.

I can't open h2 DB while debugging with the @test. I simply can't access h2 with localhost:8080/h2-console (the path was written explicitly in application-test.properties)

Is there any extra measure that I should take to test SpringBoot with h2?

答: Add    spring.h2.console.enabled=true    in your properties file.

Body:
I am trying to run Springboot test with H2 in-memory db with Mybatis.
So far I have done

configuring h2 DB in application-test.properties

adding annotation

@SpringBootTest, @TestPropertySource (locations = "TEST_APPLICATION_PROPERTIES_LOCATION")

autowiring dao and serviceImpl beans

adding seed.sql and purge.sql to the test class with

@SqlGroup({
        @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:/database/seed.sql"),
        @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = "classpath:/database/purge.sql") })

Despite the above measures, I still have two problems

I can't retrieve user that I input with the seed.sql. I made a user with id="admin", pw="admin", and was trying to retrieve with findById("admin"). But it always returns null.

I can't open h2 DB while debugging with the @test. I simply can't access h2 with localhost:8080/h2-console (the path was written explicitly in application-test.properties)

Is there any extra measure that I should take to test SpringBoot with h2?


问:
Is there any FaceTime API for iPhone developers?
I am developing an application having FaceTime feature. How do I know when both are connected/disconnected using FaceTime? I need to restrict the call duration and also I don't want to show others FaceTime ID when it is getting connected because of security reasons. Is there any delegate to know those details? Could anyone give some idea to get it?</p>

答:
There is no FaceTime api in the offical API.

You can use the the facetime url scheme:

facetime://


问:
Cannot read property 'touched' of undefined in angular6 reactive forms
i have written code to validate page,but am getting error like ' Cannot read property 'touched' of undefined'.please any one help me this code.please any one correct if am wrong.

html:

```<code><div class="container pt-4">
    <form [formGroup]="goalForm" (submit)="submit()">
        <div class="card">
            <div class="card-header">Sub Goals</div>
            <div class="card-body" formArrayName="subgoals">
                <div *ngFor="let goal of goalForm.controls.subgoals.controls; let i=index">
                    <div [formGroupName]="i" class="row">
                        <div class="form-group col-sm-3">
                            <label for="name">Criteria Name *</label>
                            <input class="form-control" formControlName="criteria_name" type="text"
                                    id="criteria_name" name="criteria_name"
                                    placeholder="Criteria Name">
                            <span class="text-danger" *ngIf="goalForm.controls['criteria_name'].touched
                                    && goalForm.controls['criteria_name'].hasError('required')">
                                    Criteria Name is required! </span>
                        </div>
                        <div class="form-group col-sm-3">
                            <label for="weightage">Criteria Weightage *</label>
                            <input class="form-control" formControlName="criteria_weightage" type="number"
                                    id="criteria_weightage" name="criteria_weightage"
                                    placeholder="Criteria Weightage">
                            <span class="text-danger" *ngIf="goalForm.controls['criteria_weightage'].touched
                                    && goalForm.controls['criteria_weightage'].hasError('required')">
                                    Criteria Weightage is required! </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
</code>```

kpa-goal.component.ts:

```<code> ngOnInit(){
        this.goalForm = this.fb.group({
            subgoals :this.fb.array([
              this.initgoal(),
            ])
          });
    }
    initgoal(){
        return this.fb.group({
          criteria_name: [null,Validators.compose([Validators.required])],
          criteria_weightage: [null,Validators.compose([Validators.required])]
          });
    }
</code>```

答:
You actually had a FormArray (subgoals) inside your FormGroup and the 2 fields (criteria_name & criteria_weightage) were inside the FormArray... so you had to access the 2 fields by traversing the subgoals before you could get to your 2 fields (criteria_name & criteria_weightage).

relevant HTML:

```<code><div class="container pt-4">
        <form [formGroup]="goalForm" (submit)="submit()">
            <div class="card">
                <div class="card-header">Sub Goals</div>
                <div class="card-body" formArrayName="subgoals">
                    <div *ngFor="let goal of goalForm.controls.subgoals.controls; let i=index">
                        <div [formGroupName]="i" class="row">
                            <div class="form-group col-sm-3">
                                <label for="name">Criteria Name *</label>
                  <input class="form-control" formControlName="criteria_name" type="text"
                          id="criteria_name" name="criteria_name"
                          placeholder="Criteria Name">
                          <span class="text-danger" *ngIf="goalForm.controls.subgoals.controls[0].controls.criteria_name.touched && goalForm.controls.subgoals.controls[0].controls.criteria_name.errors?.required" >
                          Criteria Name is required!
                          </span>
              </div>
              <div class="form-group col-sm-3">
                  <label for="weightage">Criteria Weightage *</label>
                  <input class="form-control" formControlName="criteria_weightage" type="number"
                          id="criteria_weightage" name="criteria_weightage"
                          placeholder="Criteria Weightage">
                          <span class="text-danger" *ngIf="goalForm.controls.subgoals.controls[0].controls.criteria_weightage.touched && goalForm.controls.subgoals.controls[0].controls.criteria_weightage.errors?.required" >
                          Criteria Weightage is required!
                          </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
</code>```

complete working demo on stackblitz here

Body:
i have written code to validate page,but am getting error like ' Cannot read property 'touched' of undefined'.please any one help me this code.please any one correct if am wrong.

html:

    <form [formGroup]="goalForm" (submit)="submit()">

Sub Goals

                            Criteria Name *
                            <input class="form-control" formControlName="criteria_name" type="text"
                                    id="criteria_name" name="criteria_name"
                                    placeholder="Criteria Name">

                                    Criteria Name is required!

                            Criteria Weightage *
                            <input class="form-control" formControlName="criteria_weightage" type="number"
                                    id="criteria_weightage" name="criteria_weightage"
                                    placeholder="Criteria Weightage">

                                    Criteria Weightage is required!

    </form>

kpa-goal.component.ts:

 ngOnInit(){
        this.goalForm = this.fb.group({
            subgoals :this.fb.array([
              this.initgoal(),
            ])
          });
    }
    initgoal(){
        return this.fb.group({
          criteria_name: [null,Validators.compose([Validators.required])],
          criteria_weightage: [null,Validators.compose([Validators.required])]
          });
    }

Body:
You actually had a FormArray (subgoals) inside your FormGroup and the 2 fields (criteria_name & criteria_weightage) were inside the FormArray... so you had to access the 2 fields by traversing the subgoals before you could get to your 2 fields (criteria_name & criteria_weightage).

relevant HTML:

<div class="container pt-4">
        <form [formGroup]="goalForm" (submit)="submit()">
            <div class="card">
                <div class="card-header">Sub Goals</div>
                <div class="card-body" formArrayName="subgoals">
                    <div *ngFor="let goal of goalForm.controls.subgoals.controls; let i=index">
                        <div [formGroupName]="i" class="row">
                            <div class="form-group col-sm-3">
                                <label for="name">Criteria Name *</label>
                  <input class="form-control" formControlName="criteria_name" type="text"
                          id="criteria_name" name="criteria_name"
                          placeholder="Criteria Name">
                          <span class="text-danger" *ngIf="goalForm.controls.subgoals.controls[0].controls.criteria_name.touched && goalForm.controls.subgoals.controls[0].controls.criteria_name.errors?.required" >
                          Criteria Name is required!
                          </span>
              </div>
              <div class="form-group col-sm-3">
                  <label for="weightage">Criteria Weightage *</label>
                  <input class="form-control" formControlName="criteria_weightage" type="number"
                          id="criteria_weightage" name="criteria_weightage"
                          placeholder="Criteria Weightage">
                          <span class="text-danger" *ngIf="goalForm.controls.subgoals.controls[0].controls.criteria_weightage.touched && goalForm.controls.subgoals.controls[0].controls.criteria_weightage.errors?.required" >
                          Criteria Weightage is required!
                          </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

complete working demo on stackblitz here


问:
filter by key in javascript
I would like to filter by key in javascript.

I have a ajax function , on passing id, will result obj1 in success one after other.
I would like to combine all results by key and push to single object.
How to do the following in javascript.

```<code>var id =["trans", "fund"]
setTimeout(()=>{
      id.map((e)=>this.static(e))
    }, 2000)

static(id){
var li = $.ajax({
           url: "/en",
          method: 'get',
          global: false,
          async: false,
          data: {
            providers: id
          },
          success: function (data) {
            return data;
          }
        }).responseText;
  var obj1=data; //I need to combine and store data in expected output format
}

//on first call
var obj1={
  country: "SG",
  trans: [{
    rate: 20,
    members: 100
  }]
}
//on second call
var obj1={
  country: "TH",
  fund: [{
    rate: 20,
    members: 100
  }]
}

</code>```

Expected Output:

```<code>var result ={
  trans: [{
    rate: 20,
    members: 100
  }],
  fund: [{
    rate: 20,
    members: 100
  }]
}
</code>```

答:
try to do something like this. I assume your keys are fixed. click on the link for demo.</p>

```<code>  var output = {};
  var id = ["trans", "fund"]

  //on first call
  var obj1 = {
    country: "SG",
    trans: [{
      rate: 20,
      members: 100
    }]
  }
  //on second call
  var obj2 = {
    country: "TH",
    fund: [{
      rate: 20,
      members: 100
    }]
  }

  function getObj(selectedId) {
    console.log(id); // global variable.
    if(!id) return;

    id.forEach(x => {
      let obj1Key = obj1[x];
      if (obj1Key) output[x] = obj1Key;

      let obj2Key = obj2[x];
      if (obj2Key) output[x] = obj2Key;
    })
   console.log('output object', output);
   console.log('JSON:', JSON.stringify(output));
  }
</code>```

Title: filter by key in javascript

Body:
I would like to filter by key in javascript.

I have a ajax function , on passing id, will result obj1 in success one after other.
I would like to combine all results by key and push to single object.
How to do the following in javascript.

var id =["trans", "fund"]
setTimeout(()=>{
      id.map((e)=>this.static(e))
    }, 2000)

static(id){
var li = $.ajax({
           url: "/en",
          method: 'get',
          global: false,
          async: false,
          data: {
            providers: id
          },
          success: function (data) {
            return data;
          }
        }).responseText;
  var obj1=data; //I need to combine and store data in expected output format
}

//on first call
var obj1={
  country: "SG",
  trans: [{
    rate: 20,
    members: 100
  }]
}
//on second call
var obj1={
  country: "TH",
  fund: [{
    rate: 20,
    members: 100
  }]
}

Expected Output:

var result ={
  trans: [{
    rate: 20,
    members: 100
  }],
  fund: [{
    rate: 20,
    members: 100
  }]
}

Body:
try to do something like this. I assume your keys are fixed. click on the link for demo.

  var output = {};
  var id = ["trans", "fund"]

  //on first call
  var obj1 = {
    country: "SG",
    trans: [{
      rate: 20,
      members: 100
    }]
  }
  //on second call
  var obj2 = {
    country: "TH",
    fund: [{
      rate: 20,
      members: 100
    }]
  }

  function getObj(selectedId) {
    console.log(id); // global variable.
    if(!id) return;

    id.forEach(x => {
      let obj1Key = obj1[x];
      if (obj1Key) output[x] = obj1Key;

      let obj2Key = obj2[x];
      if (obj2Key) output[x] = obj2Key;
    })
   console.log('output object', output);
   console.log('JSON:', JSON.stringify(output));
  }


问:
Select child of element if exists, else take parent
I want to catch the error message text from within a  tag, or if it does not exist, from its parent, a div tag. For this I need a valid xpath expression that can handle both cases as one if possible.

Here is the html code.
It's either version 1:

  some error message

```

<p>or version 2:</p>

<pre class="lang-html prettyprint-override"><code><div class='error-message'>
  <span>
    some other error message
  </span>
</div>
</code>```

So the xpaths would be:

v1: //div[@class='error-message']

v2: //div[@class='error-message']/span

Now I need to combine (with some 'or' expression maybe?) v1 and v2 somehow.

If have tried:

//div[@class='error-message']/descendant-or-self::* but it finds both elements when the span exists (would prefer the span!)

//div[@class='error-message']/descendant-or-self::span but finds nothing when the span does not exist

I also tried, what was given in this answer: XPath select child if child exists, else select parent but using the code .../(span, .[not(span)]) seems to be invalid, at least in Ranorex.

答:
You could try following approach:

```<code>//div[@class='error-message']/descendant-or-self::*[@innertext!='']
</code>```

Note: there is a limitation that if the text content is empty, it will not work :(

Body:
I want to catch the error message text from within a  tag, or if it does not exist, from its parent, a div tag. For this I need a valid xpath expression that can handle both cases as one if possible.

Here is the html code.
It's either version 1:

  some error message

or version 2:

    some other error message

So the xpaths would be:

v1: //div[@class='error-message']

v2: //div[@class='error-message']/span

Now I need to combine (with some 'or' expression maybe?) v1 and v2 somehow.

If have tried:

//div[@class='error-message']/descendant-or-self::* but it finds both elements when the span exists (would prefer the span!)

//div[@class='error-message']/descendant-or-self::span but finds nothing when the span does not exist

I also tried, what was given in this answer: XPath select child if child exists, else select parent but using the code .../(span, .[not(span)]) seems to be invalid, at least in Ranorex.

Body:
You could try following approach:

//div[@class='error-message']/descendant-or-self::*[@innertext!='']

Note: there is a limitation that if the text content is empty, it will not work :(


问:
tag <c:forEach/> si not doing anything
I am trying to show through JSP code the value of some variables stored in in ArrayList money.
I am using Java for this project.
The thing is that when I try to do:

```<code><c:forEach var="pos" items="${yourGame.money}">
    <c:out value="${pos.nombre}"/>
     ${pos.nombre}: <a href="${pos.url}"><b>${pos.precio}</b></a>
<br/>
</c:forEach>
</code>```

It shows nothing, and I have made sure that yourGame.money isn't empty so I don't know what's going on. I am new to JSP and have run out of ideas; could anyone please help me?

This are the structures I am using:

```<code>public class Juego{
    String nombre;
    String plataforma;
    String edicion;
    ArrayList<Precios> money = new ArrayList();
}

public class Precios{
    String precio;
    String url;
    String nombre;
}
</code>```

The JSP class recieves a "Juego" object, and I am trying to print the values of the "money" atribute. I know the class JSP is recieving the "Juego" object fine since I have already printed some other variables of this class such as :

```<code><h3>The ultimate edition: ${yourGame.edicion}</h3>
</code>```

And it works just fine ...enter code here

答:
Can you cross check your controller/Action classes and ensure you are setting money attribute in this yourGame bean and this bean is stored in request or session properly.

This is the only place where I suspect, you might have missed something. Apart from this you jsp looks fine to me.

One more point to check, can you try to print like this
<c:out value="${yourGame.edicion}"/>
just wanted to make sure the core tag is working fine in your jsp.

Title: tag <c:forEach/> si not doing anything

Body:
I am trying to show through JSP code the value of some variables stored in in ArrayList money.
I am using Java for this project.
The thing is that when I try to do:

<c:forEach var="pos" items="${yourGame.money}">
    <c:out value="${pos.nombre}"/>
     ${pos.nombre}: ${pos.precio}

</c:forEach>

It shows nothing, and I have made sure that yourGame.money isn't empty so I don't know what's going on. I am new to JSP and have run out of ideas; could anyone please help me?

This are the structures I am using:

public class Juego{
    String nombre;
    String plataforma;
    String edicion;
    ArrayList<Precios> money = new ArrayList();
}

public class Precios{
    String precio;
    String url;
    String nombre;
}

The JSP class recieves a "Juego" object, and I am trying to print the values of the "money" atribute. I know the class JSP is recieving the "Juego" object fine since I have already printed some other variables of this class such as :

The ultimate edition: ${yourGame.edicion}

And it works just fine ...enter code here


问:
How to register FUSE filesystem type with mount(8) and fstab?
I've written a small FUSE-based filesystem and now the only part's missing is that I want to register it with fstab(5) to auto-mount it on system startup and/or manually mount it with just mount /srv/virtual-db. How can I achieve this?

I know, I can just run /usr/bin/vdbfs.py /srv/virtual-db from some init script, but that's not exactly pretty.

I'm sorry because this may be not exactly a programming question, but it's highly related, as the packaging and deployment is still the programmer's job.

答:
After researching a lot found this solution to mount fuse filesystem suing fstab entry. I was using fuse for s3bucket to mount on local linux machine.

.passwd-s3fs : Is containing credentials to access your aws account 1] Secret key and 2] Access Key .

uid : User Id. You can type linux command id and you can get uid

Syntax:

```<code>s3fs#<Bucket_Name> <Mounted_Direcotry_Path> fuse _netdev,allow_other,passwd_file=/home/ubuntu/.passwd-s3fs,use_cache=/tmp,umask=002,uid=<User_Id> 0 0
</code>```

Example:

```<code>s3fs#myawsbucket /home/ubuntu/s3bucket/mys3bucket fuse _netdev,allow_other,passwd_file=/home/ubuntu/.passwd-s3fs,use_cache=/tmp,umask=002,uid=1000 0 0
</code>```

To mount you need run following command.

```<code>mount -a
</code>```

To check your bucket is mounted properly or not use following command to check which shows all mounted points.

```<code>df -h
</code>```

Body:
After researching a lot found this solution to mount fuse filesystem suing fstab entry. I was using fuse for s3bucket to mount on local linux machine.

.passwd-s3fs : Is containing credentials to access your aws account 1] Secret key and 2] Access Key .

uid : User Id. You can type linux command id and you can get uid

Syntax:

s3fs#<Bucket_Name> <Mounted_Direcotry_Path> fuse _netdev,allow_other,passwd_file=/home/ubuntu/.passwd-s3fs,use_cache=/tmp,umask=002,uid=<User_Id> 0 0

Example:

s3fs#myawsbucket /home/ubuntu/s3bucket/mys3bucket fuse _netdev,allow_other,passwd_file=/home/ubuntu/.passwd-s3fs,use_cache=/tmp,umask=002,uid=1000 0 0

To mount you need run following command.

mount -a

To check your bucket is mounted properly or not use following command to check which shows all mounted points.

df -h


问:
How can we generate a conformation prompt before deleting a comment in Django?
I am trying to link java script and Django views, I have a comments delete view, where its functionality is good but, i need some conformation using javascript before deleting them.

I don't have knowledge regarding the Mapping Javascript and Django views. Can any one help me in writing the code?

```<code>@login_required
def delete_my_comment(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    if comment.user == request.user.username:
        comment.delete()
        messages.success(request, f' Your comment is deleted')
    return redirect('post-detail', pk=comment.post.id)

 <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete Post</a>
</code>```

Can some help me in writing javascript logic for the delete conformation based on above code?
Thank you all

答: The answer with generic view is great, but if you need more controll of your UI you can do this using JavaScript. Just add event listener on deleting button. If user clicks this button - some hidden html form will be displayed, by changing its display attribute to block. If you're using bootstrap it's even simpler. Read about Bootstrap Modals </p>

Body:
I am trying to link java script and Django views, I have a comments delete view, where its functionality is good but, i need some conformation using javascript before deleting them.

I don't have knowledge regarding the Mapping Javascript and Django views. Can any one help me in writing the code?

@login_required
def delete_my_comment(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    if comment.user == request.user.username:
        comment.delete()
        messages.success(request, f' Your comment is deleted')
    return redirect('post-detail', pk=comment.post.id)

 Delete Post

Can some help me in writing javascript logic for the delete conformation based on above code?
Thank you all


问:
Unable to write json data to file in c++
I have a json data which I want to write to a json file in c++. I am using nlohmann json and below is the code:

```<code>using nlohmann::json;

std::ofstream output_file("C:\\Program Files (x86)\\output.json");

json outJson;

std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string created(30, '\0');
std::strftime(&created[0], created.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now));

outJson["Created"] = created;
outJson["DataId"] = "T-452";
outJson["Type"] = "UserData";

output_file << outJson;
</code>```

But nothing is getting saved in output.json.

答:
Explicit serialisation and calling close() before exiting should do the trick here.

```<code>output_file << outJson.dump(4);
output_file.close();
</code>```

Body:
I have a json data which I want to write to a json file in c++. I am using nlohmann json and below is the code:

using nlohmann::json;

std::ofstream output_file("C:\\Program Files (x86)\\output.json");

json outJson;

std::time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::string created(30, '\0');
std::strftime(&created[0], created.size(), "%Y-%m-%d %H:%M:%S", std::localtime(&now));

outJson["Created"] = created;
outJson["DataId"] = "T-452";
outJson["Type"] = "UserData";

output_file << outJson;

But nothing is getting saved in output.json.

Body:
Explicit serialisation and calling close() before exiting should do the trick here.

output_file << outJson.dump(4);
output_file.close();


问:
Set HTML img attribute to Angular binding
Inside the HTML class for my Angular component, I have an image displaying with:

```<code><div class="row" id="work">
  <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12" id="">
      <img class="img-fluid" width="100%" [height]="height" src="assets/images/logo.png" alt="">
      <img class="img-fluid" width="100%" height="100" src="assets/images/logo.png" alt="">
      <img class="img-fluid" width="100%" height="100" src="assets/images/logo.png" alt="">
  </div>
</div>
</code>```

In my typescript file for the component, I have a height variable being set to "100" on init.

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  height = "500";

  constructor() { }

  ngOnInit() {
    this.height = "500";
  }
}
</code>```

On page load, the image height is equal to the default images height, it it not reading/using my height variable. Probably something silly, but not sure what.

EDIT:

"img-fluid" was the problem. It ignores the height attribute, sets height to auto, so I couldnt set it myself from Typescript.

答:
Just use

```<code>[ngStyle]='{height:height}'
</code>```

edit

Or use like this: here 'x' is the condition (if any) and "200px" is the default height.
     [ngStyle]='{height : x ? "200px" :height}'

Body:
Inside the HTML class for my Angular component, I have an image displaying with:

In my typescript file for the component, I have a height variable being set to "100" on init.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  height = "500";

  constructor() { }

  ngOnInit() {
    this.height = "500";
  }
}

On page load, the image height is equal to the default images height, it it not reading/using my height variable. Probably something silly, but not sure what.

EDIT:

"img-fluid" was the problem. It ignores the height attribute, sets height to auto, so I couldnt set it myself from Typescript.

Body:
Just use

[ngStyle]='{height:height}'

edit

Or use like this: here 'x' is the condition (if any) and "200px" is the default height.
     [ngStyle]='{height : x ? "200px" :height}'


问:
Regex not to allow to consecutive dot characters and more
I am trying to make a JavaScript Regex which satisfies the following conditions

a-z are possible

0-9 are possible

dash, underscore, apostrophe, period are possible

ampersand, bracket, comma, plus are not possible

consecutive periods are not possible

period cannot be located in the start and the end

max 64 characters

Till now, I have come to following regex

```<code>^[^.][a-zA-Z0-9-_\.']+[^.]$
</code>```

However, this allows consecutive dot characters in the middle and does not check for length.
Could anyone guide me how to add these 2 conditions?

答:
Here is a pattern which seems to work:

```<code>^(?!.*\.\.)[a-zA-Z0-9_'-](?:[a-zA-Z0-9_'.-]{0,62}[a-zA-Z0-9_'-])?$
</code>```

Demo

Here is an explanation of the regex pattern:

```<code>^                          from the start of the string
    (?!.*\.\.)             assert that two consecutive dots do not appear anywhere
    [a-zA-Z0-9_'-]         match an initial character (not dot)
    (?:                    do not capture
    [a-zA-Z0-9_'.-]{0,62}  match to 62 characters, including dot
    [a-zA-Z0-9_'-]         ending with a character, excluding dot
     )?                    zero or one time
$                          end of the string
</code>```

Body:
I am trying to make a JavaScript Regex which satisfies the following conditions

a-z are possible

0-9 are possible

dash, underscore, apostrophe, period are possible

ampersand, bracket, comma, plus are not possible

consecutive periods are not possible

period cannot be located in the start and the end

max 64 characters

Till now, I have come to following regex

^[^.][a-zA-Z0-9-_\.']+[^.]$

However, this allows consecutive dot characters in the middle and does not check for length.
Could anyone guide me how to add these 2 conditions?

Body:
Here is a pattern which seems to work:

^(?!.*\.\.)[a-zA-Z0-9_'-](?:[a-zA-Z0-9_'.-]{0,62}[a-zA-Z0-9_'-])?$

Demo

Here is an explanation of the regex pattern:

^                          from the start of the string
    (?!.*\.\.)             assert that two consecutive dots do not appear anywhere
    [a-zA-Z0-9_'-]         match an initial character (not dot)
    (?:                    do not capture
    [a-zA-Z0-9_'.-]{0,62}  match to 62 characters, including dot
    [a-zA-Z0-9_'-]         ending with a character, excluding dot
     )?                    zero or one time
$                          end of the string


问:
Find X number exist inside array of n sum or not
I want to find x number exist inside given below array or not. For finding x number inside, any element of the array can make given x number. This is based on the element's have an inside array and check it exist or not. It's not like promotion and combination.

```<code>let arrr = [
    4,
    7,
    6,
    2,
    7,
    6
];
</code>```

Example : If X=16 then result should be [4,6,6] = 16 (true)

Example :
If X=11 then result should be [4,7] = 11 (true)

Example : If X=18
then result should be [4,6,6,2] = 18 (true)

答:
It's not optimized but it works:      </p>

```<code>    function Contains(array, value) {
        const str = array.reduce((p, c) => p + c.toString(), "");
        const fn = function (active, rest, a) {
            const sum = rest.split("").reduce((p, c) => p + Number(c), 0);
            if (sum === value) return true;
            if (!active && !rest) return;
            if (!rest) {
                a.push(active);
            } else {
                if (fn(active + rest[0], rest.slice(1), a) === true) return true;
                if (fn(active, rest.slice(1), a) === true) return true;
            }
            return a;
        }
        const result = fn("", str, []) === true;
        return result === true;
    }
    Contains(array, value)
</code>```

Body:
I want to find x number exist inside given below array or not. For finding x number inside, any element of the array can make given x number. This is based on the element's have an inside array and check it exist or not. It's not like promotion and combination.

let arrr = [
    4,
    7,
    6,
    2,
    7,
    6
];

Example : If X=16 then result should be [4,6,6] = 16 (true)

Example :
If X=11 then result should be [4,7] = 11 (true)

Example : If X=18
then result should be [4,6,6,2] = 18 (true)

Body:
It's not optimized but it works:

    function Contains(array, value) {
        const str = array.reduce((p, c) => p + c.toString(), "");
        const fn = function (active, rest, a) {
            const sum = rest.split("").reduce((p, c) => p + Number(c), 0);
            if (sum === value) return true;
            if (!active && !rest) return;
            if (!rest) {
                a.push(active);
            } else {
                if (fn(active + rest[0], rest.slice(1), a) === true) return true;
                if (fn(active, rest.slice(1), a) === true) return true;
            }
            return a;
        }
        const result = fn("", str, []) === true;
        return result === true;
    }
    Contains(array, value)


问:
How to zoom a sheet in revit api?
I wrote an external command that creates detail views for doors, windows, etc and puts each object in a separate sheet.

Sometimes the new sheets are zoomed-out by default (the yellow circle shows the actual sheet).
I guess it has to do with the witness lines (in the blue circle).

Sheet zoomed out

I tried activating the views and then found their uiView and used the zoom methods but they don't seem to make a difference (possibly because they work in model coordinates and not in sheet outline coordinates).

uv.ZoomToFit();

Manual zoom-to-fit works fine.
Also, the sheet's outline property is correct (not too large).

Any ideas?

Thanks!

答:
You can use the ShowElements method to zoom to an element. That does the same as zoom-to-fit to a specific set of elements. The element may possibly also be the sheet itself.

The Building Coder discusses how that can also be used to Switch View or Document.

Also, look at displaying a text file from a TaskDialog command link.

Title: How to zoom a sheet in revit api?


问:
Homestead.yaml file not adding project folder in vagrant | Mac os
I am using mac os and just install vagrant and configured homestead.yaml file but after vagrant up command also tried vagrant reload --provision

Also database not created in mysql.

Here is my homestead.yaml file

```<code>ip: "192.168.10.10"
memory: 3048
cpus: 2
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: /Users/myname/mytest
      to: /home/vagrant/mytest

sites:
      - map: mytest.local
      to : /home/vagrant/mytest/public

databases:
    -  mytest
</code>```

can someone help me ?

答:
Finally, I found the solution.

to add path we need to add ~(tilde) sign it refers as a home directory in mac.

updated yaml file.

```<code>ip: "192.168.10.10"
memory: 3048
cpus: 2
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/myname/mytest
      to: /home/vagrant/mytest

sites:
      - map: mytest.local
      to : /home/vagrant/mytest/public

databases:
    -  mytest
</code>```

Body:
I am using mac os and just install vagrant and configured homestead.yaml file but after vagrant up command also tried vagrant reload --provision

Also database not created in mysql.

Here is my homestead.yaml file

ip: "192.168.10.10"
memory: 3048
cpus: 2
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: /Users/myname/mytest
      to: /home/vagrant/mytest

sites:
      - map: mytest.local
      to : /home/vagrant/mytest/public

databases:
    -  mytest

can someone help me ?

Body:
Finally, I found the solution.

to add path we need to add ~(tilde) sign it refers as a home directory in mac.

updated yaml file.

ip: "192.168.10.10"
memory: 3048
cpus: 2
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: ~/myname/mytest
      to: /home/vagrant/mytest

sites:
      - map: mytest.local
      to : /home/vagrant/mytest/public

databases:
    -  mytest


问:
Syncing profile pictures from Azure Active Directory to Azure DevOps
I have created an Azure DevOps organization and it has been successfully linked with my Azure AD tenant, group search in the organization correctly shows Azure Active Directory (security) groups.

My user however does not have the correct profile picture in Azure DevOps. In Office 365 and in Azure AD my profile picture shows up correctly, but in Azure DevOps only my initials show up in a colored circle.

Is there a missing setting to make user profile pictures show up in Azure DevOps?

答:
You can click the circular image showing the user's initials in the upper right corner of the organization page, and then you will see my profile options and click it. Then you can set up your own profile picture by clicking Edit Profile.

After completing all the above steps, please wait a moment, because the server may need some time to synchronize settings and display user profile images in the organization.

Please note that in some pages, users will still display their initials, such as commit history, build author, etc. But in Azure Boards, user's profile pictures can display normally.


问:
UIView setting constraints
I am having trouble creating a UIView instance programmatically. I have a function that returns the view so that I can use it in an NSAttachment inside a UITextView.

This is what I am trying to achieve:

This is what I am getting in the simulator:

Code Below:

```<code>let fullView = UIView()
    let firstButton = UIButton()
    let secondButton = UIButton()
    let thirdTextView = UITextView()

    fullView.frame = CGRect(x: 0, y: 0, width: textView.frame.width, height: 90)
    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

    firstButton.setTitle(text1, for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    thirdTextView.text = text2

    let descriptionBarStackView = UIStackView()
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill
    descriptionBarStackView.distribution = .fillProportionally

    descriptionBarStackView.addArrangedSubview(firstButton)
    descriptionBarStackView.addArrangedSubview(secondButton)

    let viewWithStackViews = UIStackView()
    viewWithStackViews.axis = .vertical
    viewWithStackViews.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
    viewWithStackViews.distribution = .fillEqually
    viewWithStackViews.addArrangedSubview(descriptionBarStackView)
    viewWithStackViews.addArrangedSubview(thirdTextView)

    fullView.addSubview(viewWithStackViews)

    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    thirdTextView.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
    viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 5),
    viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 5),
    viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 5),
    viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 5),
    ])
</code>```

Edit:

答:
You are setting
viewWithStackViews.distribution = .fillEqually

Because of .fillEqually the StackView will allocate equal height to the subviews. Thats why you are seeing buttons in half of viewWithStackViews and thirdTextView in remaining half.
So change it to:
viewWithStackViews.distribution = .fillProportionally

One more thing: your thirdTextView is not getting its height according to its content.
Try this to allow you thirdTextView to get height automatically. In case the text might be too long, set scrolledEnabled to true and set height contraint for the textView.

thirdTextView.translatesAutoresizingMaskIntoConstraints = true
  thirdTextView.sizeToFit()
  thirdTextView.scrollEnabled = false

Title: UIView setting constraints

Body:
I am having trouble creating a UIView instance programmatically. I have a function that returns the view so that I can use it in an NSAttachment inside a UITextView.

This is what I am trying to achieve:

This is what I am getting in the simulator:

Code Below:

let fullView = UIView()
    let firstButton = UIButton()
    let secondButton = UIButton()
    let thirdTextView = UITextView()

    fullView.frame = CGRect(x: 0, y: 0, width: textView.frame.width, height: 90)
    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

    firstButton.setTitle(text1, for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    thirdTextView.text = text2

    let descriptionBarStackView = UIStackView()
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill
    descriptionBarStackView.distribution = .fillProportionally

    descriptionBarStackView.addArrangedSubview(firstButton)
    descriptionBarStackView.addArrangedSubview(secondButton)

    let viewWithStackViews = UIStackView()
    viewWithStackViews.axis = .vertical
    viewWithStackViews.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
    viewWithStackViews.distribution = .fillEqually
    viewWithStackViews.addArrangedSubview(descriptionBarStackView)
    viewWithStackViews.addArrangedSubview(thirdTextView)

    fullView.addSubview(viewWithStackViews)

    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    thirdTextView.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
    viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 5),
    viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 5),
    viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 5),
    viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 5),
    ])

Edit:


问:
ffmpeg encoding error
I have just finished installing ffmpeg on my centOS server using the below link:
http://www.ultratechhost.com/forums/thread-122.html -> Method 1\

phpinfo() reports that ffmpeg has been successfully installed and i also see the ffmpeg section in phpinfo.

But when I try to encode I get an error. Please try and shed some light what the problem is and what the solution could be.

The command and the error is as follows:

ffmpeg -i greenlantern.mov green1.flv

  FFmpeg version 0.6.1, Copyright (c) 2000-2010 the FFmpeg developers

    built on Dec  4 2010 15:35:31 with gcc 4.1.2 20080704 (Red Hat 4.1.2-48)

    configuration: --prefix=/usr --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --incdir=/usr/include --disable-avisynth --extra-cflags='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fPIC' --enable-avfilter --enable-avfilter-lavf --enable-libdirac --enable-libfaac --enable-libfaad --enable-libfaadbin --enable-libgsm --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libx264 --enable-gpl --enable-nonfree --enable-postproc --enable-pthreads --enable-shared --enable-swscale --enable-vdpau --enable-version3 --enable-x11grab

    libavutil     50.15. 1 / 50.15. 1

    libavcodec    52.72. 2 / 52.72. 2

    libavformat   52.64. 2 / 52.64. 2

    libavdevice   52. 2. 0 / 52. 2. 0

    libavfilter    1.19. 0 /  1.19. 0

    libswscale     0.11. 0 /  0.11. 0

    libpostproc   51. 2. 0 / 51. 2. 0

  [mov,mp4,m4a,3gp,3g2,mj2 @ 0x1ea4e8b0]Estimating duration from bitrate, this may be inaccurate

  Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'greenlantern.mov':

    Duration: N/A, bitrate: N/A

  Output #0, flv, to 'green1.flv':

  Output file #0 does not contain any stream

答:
Is this file DRM protected by any chance? If so, converting probably won't work.

It looks like this is a problem with the file, rather than a problem with ffmpeg.

Title: ffmpeg encoding error


答:
You can use this regex

```<code>^(?!^[.])(?!.*[.]$)(?!.*[.]{2})[\w.'-]{1,64}$
</code>```

Regex Breakdown

```<code>^ #Start of string
(?!^[.]) #Dot should not be in start
(?!.*[.]$) #Dot should not be in start
(?!.*[.]{2}) #No consecutive two dots
[\w.'-]{1,64} #Match with the character set at least one times and at most 64 times.
$ #End of string
</code>```

Correction in your regex

- shouldn't be in between of character class. It denotes range. Avoid using it in between

[a-zA-Z0-9_] is equivalent to \w

Title: Regex not to allow to consecutive dot characters and more

Body:
You can use this regex

^(?!^[.])(?!.*[.]$)(?!.*[.]{2})[\w.'-]{1,64}$

Regex Breakdown

^ #Start of string
(?!^[.]) #Dot should not be in start
(?!.*[.]$) #Dot should not be in start
(?!.*[.]{2}) #No consecutive two dots
[\w.'-]{1,64} #Match with the character set at least one times and at most 64 times.
$ #End of string

Correction in your regex

- shouldn't be in between of character class. It denotes range. Avoid using it in between

[a-zA-Z0-9_] is equivalent to \w


问:
Assigning a variable name as an object property while using Array.prototype.map
I'm iterating through an array of arrays using .map() in an attempt to assign the inner arrays to an object as a key:value pair. It is not successful. Can this even work? Do I need to break it out into more steps/functions/variables?

I've tried every syntax I can think of for the element in the assignment of the property.

I also tried using arr.map(function() {}) syntax with all of these, and there was no difference.

const smallArr = [1, 23, 25, 46, 52, 789, 64];

const thisArr = [5, 4, 65, 24, 35];

const thatArr = [{key: 1, anotherKey: 2}];

let parentObj = {};

const bigArr = [smallArr, thisArr, thatArr];

const newSomething = bigArr.map(arr => parentObj["arr"] = arr);

// parentObj returns: { arr: [ { key: 1, anotherKey: 2 } ] }
```

<p>I understand both of these. It's assigning the string of my element
every iteration and overwriting the value so that the final object is
one key:value pair with value being the last inner array in the outer
array.</p>

<pre class="lang-js prettyprint-override"><code>const newSomething = bigArr.map(arr => parentObj.arr = arr);
  //returns { arr: [ { key: 1, anotherKey: 2 } ] }

const newSomething = bigArr.map(arr => parentObj['arr'] = arr);
  //returns { arr: [ { key: 1, anotherKey: 2 } ] }
</code>```

This one I don't understand what's going on in the last pair.

const newSomething = bigArr.map(arr => parentObj[`${arr}`] = arr);
  // returns {
        '1,23,25,46,52,789,64': [ 1, 23, 25, 46, 52, 789, 64 ],
        '5,4,65,24,35': [ 5, 4, 65, 24, 35 ],
        '[object Object]': [ { key: 1, anotherKey: 2 } ],
         arr: [ { key: 1, anotherKey: 2 } ]
        }
```

<p>This one I don't understand at all.</p>

<pre class="lang-js prettyprint-override"><code>const newSomething = bigArr.map(arr => parentObj["`${arr}`"] = arr);
  // returns {
        '`${arr}`': [ { key: 1, anotherKey: 2 } ],
         arr: [ { key: 1, anotherKey: 2 } ]
         }
</code>```

I'm trying to get to:

parentObj = {
    smallArr: [1, 23, 25, 46, 52, 789, 64],
    thisArr: [5, 4, 65, 24, 35],
    thatArr: [{key: 1, anotherKey: 2}],
}
```

答:
Just explicitly assign each variable:

const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr, thisArr, thatArr };

console.log(parentObj);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

The above is shorthand for:

const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr: smallArr, thisArr: thisArr, thatArr: thatArr };

console.log(parentObj);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Body:
I'm iterating through an array of arrays using .map() in an attempt to assign the inner arrays to an object as a key:value pair. It is not successful. Can this even work? Do I need to break it out into more steps/functions/variables?

I've tried every syntax I can think of for the element in the assignment of the property.

I also tried using arr.map(function() {}) syntax with all of these, and there was no difference.

const smallArr = [1, 23, 25, 46, 52, 789, 64];

const thisArr = [5, 4, 65, 24, 35];

const thatArr = [{key: 1, anotherKey: 2}];

let parentObj = {};

const bigArr = [smallArr, thisArr, thatArr];

const newSomething = bigArr.map(arr => parentObj["arr"] = arr);

// parentObj returns: { arr: [ { key: 1, anotherKey: 2 } ] }

I understand both of these. It's assigning the string of my element
every iteration and overwriting the value so that the final object is
one key:value pair with value being the last inner array in the outer
array.

const newSomething = bigArr.map(arr => parentObj.arr = arr);
  //returns { arr: [ { key: 1, anotherKey: 2 } ] }

const newSomething = bigArr.map(arr => parentObj['arr'] = arr);
  //returns { arr: [ { key: 1, anotherKey: 2 } ] }

This one I don't understand what's going on in the last pair.

const newSomething = bigArr.map(arr => parentObj[`${arr}`] = arr);
  // returns {
        '1,23,25,46,52,789,64': [ 1, 23, 25, 46, 52, 789, 64 ],
        '5,4,65,24,35': [ 5, 4, 65, 24, 35 ],
        '[object Object]': [ { key: 1, anotherKey: 2 } ],
         arr: [ { key: 1, anotherKey: 2 } ]
        }

This one I don't understand at all.

const newSomething = bigArr.map(arr => parentObj["`${arr}`"] = arr);
  // returns {
        '`${arr}`': [ { key: 1, anotherKey: 2 } ],
         arr: [ { key: 1, anotherKey: 2 } ]
         }

I'm trying to get to:

parentObj = {
    smallArr: [1, 23, 25, 46, 52, 789, 64],
    thisArr: [5, 4, 65, 24, 35],
    thatArr: [{key: 1, anotherKey: 2}],
}

Body:
Just explicitly assign each variable:

const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr, thisArr, thatArr };

console.log(parentObj);

.as-console-wrapper { max-height: 100% !important; top: auto; }

The above is shorthand for:

const smallArr = [1, 23, 25, 46, 52, 789, 64];
const thisArr = [5, 4, 65, 24, 35];
const thatArr = [{key: 1, anotherKey: 2}];
let parentObj = { smallArr: smallArr, thisArr: thisArr, thatArr: thatArr };

console.log(parentObj);

.as-console-wrapper { max-height: 100% !important; top: auto; }