问:
When to register a method that will call Form.Invoke to an event?
I get the following exception in a Windows Form application

System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

The method where the exception occurs calls this.Invoke (System.Windows.Forms.Form.Invoke). This method is registered to the event of another class in the constructor, which seems to lead to a race condition and this exception.

```<code>public Form1()
{
    InitializeComponent();
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}

private void MyMethod()
{
    this.Invoke((MethodInvoker)delegate
    {
        // ... some code ...
    }
}
</code>```

At which stage of the form lifecycle is the Handle created? In which event of the form would it be safe to register the method to the foreign event?

答:
Put the InitializeComponent() call back before you register the handler, as suggested by bitxwise

You'll get the same problem when the form is disposed so unregsiter the handler then.

You could do somthing like if(this.IsHandleCreated) in your handler to be safe.

Body:
I get the following exception in a Windows Form application

System.InvalidOperationException: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

The method where the exception occurs calls this.Invoke (System.Windows.Forms.Form.Invoke). This method is registered to the event of another class in the constructor, which seems to lead to a race condition and this exception.

public Form1()
{
    InitializeComponent();
    SomeOtherClass.Instance.MyEvent += new SomeDelegate(MyMethod);
}

private void MyMethod()
{
    this.Invoke((MethodInvoker)delegate
    {
        // ... some code ...
    }
}

At which stage of the form lifecycle is the Handle created? In which event of the form would it be safe to register the method to the foreign event?


来源: stackexchange

问:
Selecting and changing the attribute of a class using jQuery?
I've highlighted the class which I want to change one of its attributes...

How to select and change the opacity attribute and change it to 0.1 using jQuery?

I've tried this with no success...

```<code>var item = $('.slide-object slide-object-stategroup shown')

$(item).attr( 'opacity' ): 0.1;
</code>```

答:
Your selector is wrong.

The way you are changing opacity is wrong.

See the code below:

```<code>var item = $('.slide-object.slide-object-stategroup.shown')
$(item).css( 'opacity', 0.1);
</code>```

Use .css method to change any css property. Also classes needs to have a . before their name. Spaces in selector means you are accessing the child. So remove the spaces and add a dot in the selector.

ContentLicense: CC BY-SA 4.0

Body:
I've highlighted the class which I want to change one of its attributes...

How to select and change the opacity attribute and change it to 0.1 using jQuery?

I've tried this with no success...

var item = $('.slide-object slide-object-stategroup shown')

$(item).attr( 'opacity' ): 0.1;

Body:
Your selector is wrong.

The way you are changing opacity is wrong.

See the code below:

var item = $('.slide-object.slide-object-stategroup.shown')
$(item).css( 'opacity', 0.1);

Use .css method to change any css property. Also classes needs to have a . before their name. Spaces in selector means you are accessing the child. So remove the spaces and add a dot in the selector.


问:
LDAP: error code 49 - 80090308: LdapErr: DSID-0C09042F, comment: AcceptSecurityContext error, data 52e, v2580
```<code>LDAP: error code 49 - 80090308: LdapErr: DSID-0C09042F, comment: AcceptSecurityContext error, data 52e, v2580
</code>```

I know "52e" code is when username is valid, but password is invalid. I am using the same user name and password for validating user against Active directory and its working fine.

Here is my java code:

```<code>        String userName = "user_test";
        String password =  "*******";
        String base ="DC=test,DC=local";
        String dn = "cn="+ userName + "," + "CN=Users," + base;

        try {
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.SECURITY_AUTHENTICATION, "simple");

            env.put(Context.SECURITY_PRINCIPAL, dn);

            env.put(Context.SECURITY_CREDENTIALS, password);

            env.put(Context.PROVIDER_URL, "ldap://*****.test.local:389");

            System.out.println("Attempting to Connect...");

            ctx = new InitialLdapContext(env, null);
            System.out.println("Connection Successful.");
        } catch (NamingException nex) {
            System.out.println("LDAP Connection: FAILED");
            nex.printStackTrace();
        }
        return ctx;
    }

</code>```

I do not know exactly why getting this error. Can anyone please help on this?

答:
The error is pretty definitive.

49 52e 1326    ERROR_LOGON_FAILURE Returns when username is valid but password/credential is invalid.

Often the Hard Part is properly determining the DN.

Body:
LDAP: error code 49 - 80090308: LdapErr: DSID-0C09042F, comment: AcceptSecurityContext error, data 52e, v2580

I know "52e" code is when username is valid, but password is invalid. I am using the same user name and password for validating user against Active directory and its working fine.

Here is my java code:

        String userName = "user_test";
        String password =  "*******";
        String base ="DC=test,DC=local";
        String dn = "cn="+ userName + "," + "CN=Users," + base;

        try {
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.SECURITY_AUTHENTICATION, "simple");

            env.put(Context.SECURITY_PRINCIPAL, dn);

            env.put(Context.SECURITY_CREDENTIALS, password);

            env.put(Context.PROVIDER_URL, "ldap://*****.test.local:389");

            System.out.println("Attempting to Connect...");

            ctx = new InitialLdapContext(env, null);
            System.out.println("Connection Successful.");
        } catch (NamingException nex) {
            System.out.println("LDAP Connection: FAILED");
            nex.printStackTrace();
        }
        return ctx;
    }

I do not know exactly why getting this error. Can anyone please help on this?


问:
What is doing __str__ function in Django?
I'm reading and trying to understand django documentation so I have a logical question.

There is my models.py file:

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=255)
    tagline = models.TextField()

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Post(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline
```

What is doing here each __str__ function in each class?
What is the reason I need those functions in it?

答:
You created a Blog model. Once you migrate this, Django will create a table with "name" and "tagline" columns in your database.

If you want to interact with the database with the model, for example create an instance of the model and save it or retrieve the model from db,

```<code>def __str__(self):
    return self.name
</code>```

will come handy. Open the python interactive shell in your project's root folder via:

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

Then

```<code>from projectName.models import Blog
Blog.objects.all() # will get you all the objects in "Blog" table
</code>```

Also, when you look at the models in your admin panel, you will see your objects listed, with the name property.

The problem is, the return will look like this if you did not add that function:

```<code><QuerySet [<Blog:>,<Blog:>,<Blog:>....]
</code>```

So you will not know what those objects are. A better way to recognize those objects is retrieving them by one of its properties which you set it as name. This way you will get the result as follow:

```<code> <QuerySet [<Blog:itsName>,<Blog:itsName>,<Blog:itsName>....]
</code>```

If you want to test this out, run python manage.py shell and run:

```<code>from projectName.models import Blog

# The below will create and save an instance.
# It is a single step. Copy-paste multiple times.
Blog.objects.create(name="first",tagline="anything")
Blog.objects.all() # check out the result
</code>```

Body:
I'm reading and trying to understand django documentation so I have a logical question.

There is my models.py file:

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=255)
    tagline = models.TextField()

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Post(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):
        return self.headline

What is doing here each __str__ function in each class?
What is the reason I need those functions in it?

Body:
You created a Blog model. Once you migrate this, Django will create a table with "name" and "tagline" columns in your database.

If you want to interact with the database with the model, for example create an instance of the model and save it or retrieve the model from db,

def __str__(self):
    return self.name

will come handy. Open the python interactive shell in your project's root folder via:

python manage.py shell

Then

from projectName.models import Blog
Blog.objects.all() # will get you all the objects in "Blog" table

Also, when you look at the models in your admin panel, you will see your objects listed, with the name property.

The problem is, the return will look like this if you did not add that function:

<QuerySet [<Blog:>,<Blog:>,<Blog:>....]

So you will not know what those objects are. A better way to recognize those objects is retrieving them by one of its properties which you set it as name. This way you will get the result as follow:

 <QuerySet [<Blog:itsName>,<Blog:itsName>,<Blog:itsName>....]

If you want to test this out, run python manage.py shell and run:

from projectName.models import Blog

# The below will create and save an instance.
# It is a single step. Copy-paste multiple times.
Blog.objects.create(name="first",tagline="anything")
Blog.objects.all() # check out the result


问:
DynamoDB and ElasticSearch - table design approaches
I'am currently thinking about my DynamoDB database. The goal is to get the best speed with a really large amount of data possible. For me, DynamoDB seems as a good option. Furthermore, it is necessary for me to connect the table to ElasticSearch because I need geopoint-querys (like show me all posts that are within a specific area).
Would the following approach make sense to you regarding the best practices of DynamoDB? It is possible, that the sort key for example 'posts' is a hot spot, but if I query only with ElasticSearch, there should be no problem - right? What would be the best solution?

My tables look like this:

So my thoughts are:

To query all users just select every row with the sort_key 'user'

To get a post with the creator, query the post_id and the sort_key 'post'

In a relational database, the two tables would look like this:

答:
I don't think dynamo DB is a good option for that.
Limitation for DynamoDB listed below.

You can't get more than 1 MB data per API call

wildcard search will give you a poor performance

Aggregation will be a nightmare since you plan for the huge data


问:
Get values from 'composed Annotations' in Spring
With Spring, you can have some kind of composed annotations. A prominent example is the @SpringBootApplication-annotation, which is a composite of an  @Configuration, @EnableAutoConfiguration and @ComponentScan.

I am trying to get all Beans that are affected by a certain annotation, i.e. ComponentScan.

Following this answer, I am using the following code:

```<code>for (T o : applicationContext.getBeansWithAnnotation(ComponentScan.class).values()) {
    ComponentScan ann = (ComponentScan) o.getClass().getAnnotation(ComponentScan.class);
    ...
}
</code>```

which does not work, since not all beans, returned by getBeansWithAnnotation(ComponentScan.class) are indeed annotated with that annotation, since those that are e.g. annotated with @SpringBootApplication are (usually) not.

Now I am looking for some kind of generic way, to retrieve the value of an annotation, even when it is only added as piece of another annotation.
How can I do this?

答:
It turns out, there is a utility set AnnotatedElementUtils which allows you to handle those merged annotations.

```<code>for (Object annotated : context.getBeansWithAnnotation(ComponentScan.class).values()) {
    Class clazz = ClassUtils.getUserClass(annotated) // thank you jin!
    ComponentScan mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(clazz, ComponentScan.class);
    if (mergedAnnotation != null) { // For some reasons, this might still be null.
        // TODO: useful stuff.
    }
}
</code>```

Body:
With Spring, you can have some kind of composed annotations. A prominent example is the @SpringBootApplication-annotation, which is a composite of an  @Configuration, @EnableAutoConfiguration and @ComponentScan.

I am trying to get all Beans that are affected by a certain annotation, i.e. ComponentScan.

Following this answer, I am using the following code:

for (T o : applicationContext.getBeansWithAnnotation(ComponentScan.class).values()) {
    ComponentScan ann = (ComponentScan) o.getClass().getAnnotation(ComponentScan.class);
    ...
}

which does not work, since not all beans, returned by getBeansWithAnnotation(ComponentScan.class) are indeed annotated with that annotation, since those that are e.g. annotated with @SpringBootApplication are (usually) not.

Now I am looking for some kind of generic way, to retrieve the value of an annotation, even when it is only added as piece of another annotation.
How can I do this?

Body:
It turns out, there is a utility set AnnotatedElementUtils which allows you to handle those merged annotations.

for (Object annotated : context.getBeansWithAnnotation(ComponentScan.class).values()) {
    Class clazz = ClassUtils.getUserClass(annotated) // thank you jin!
    ComponentScan mergedAnnotation = AnnotatedElementUtils.getMergedAnnotation(clazz, ComponentScan.class);
    if (mergedAnnotation != null) { // For some reasons, this might still be null.
        // TODO: useful stuff.
    }
}


问:
Android textview text get cut off on the sides with custom font
This is what happens in the preview and on device:

TextView is nothing special, it just loads the custom font:

```<code>public class TestTextView extends AppCompatTextView {

    public TestTextView(Context context) {
        super(context);

        init(context);
    }

    public TestTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init(context);
    }

    public TestTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init(context);
    }

    void init(Context context) {

        Typeface t = Typeface.createFromAsset(context.getAssets(), "fonts/daisy.ttf");

        setTypeface(t);
    }
}
</code>```

Layout is also very basic, but just in case:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/material_red200"
    android:orientation="vertical">

    <*custompackage* .TestTextView
        android:gravity="left"
        android:padding="0dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="just some text for testing"
        android:textColor="@color/material_black"
        android:textSize="100dp" />

</LinearLayout>
</code>```

As you can see, the left parts, like 'j' and 'f' are cut off.

Setting the padding or margin did not work.

This font fits into it's frame when using from other programs.

Thanks in advance.

Edit:
What @play_err_ mentioned is not a solution in my case.

I am using in the final version a textview that resizes automatically, so adding spaces would be terribly difficult.

I need an explanation why other programs (eg photoshop, after effects...) can calculate a proper bounding box and android cannot

I am also loading different fonts dynamically and I do not want to create an

```<code>if(badfont)
     addSpaces()
</code>```

答:
Reworked @Dmitry Kopytov solution:

in Kotlin

recycle the old bitmap

added documentation

fall back on default TextView rendering if the bitmap cannot be created (not enough memory)

Code:

```<code>/**
 * This TextView is able to draw text on the padding area.
 * It's mainly used to support italic texts in custom fonts that can go out of bounds.
 * In this case, you've to set an horizontal padding (or just end padding).
 *
 * This implementation is doing a render-to-texture procedure, as such it consumes more RAM than a standard TextView,
 * it uses an additional bitmap of the size of the view.
 */
class TextViewNoClipping(context: Context, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {
    private class NonClippableCanvas(@NonNull val bitmap: Bitmap) : Canvas(bitmap) {
        override fun clipRect(left: Float, top: Float, right: Float, bottom: Float): Boolean {
            return true
        }
    }

    private var rttCanvas: NonClippableCanvas? = null

    override fun onSizeChanged(width: Int, height: Int,
                               oldwidth: Int, oldheight: Int) {
        if ((width != oldwidth || height != oldheight) && width > 0 && height > 0) {
            rttCanvas?.bitmap?.recycle()
            try {
                Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)?.let {
                    rttCanvas = NonClippableCanvas(it)
                }
            } catch (t: Throwable) {
                // If for some reasons the bitmap cannot be created, we fall back on default rendering (potentially cropping the text).
                rttCanvas?.bitmap?.recycle()
                rttCanvas = null
            }
        }

        super.onSizeChanged(width, height, oldwidth, oldheight)
    }

    override fun onDraw(canvas: Canvas) {
        rttCanvas?.let {
            // Clear the RTT canvas from the previous font.
            it.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

            // Draw on the RTT canvas (-> bitmap) that will use clipping on the NonClippableCanvas, resulting in no-clipping
            super.onDraw(it)

            // Finally draw the bitmap that contains the rendered text (no clipping used here, will display on top of padding)
            canvas.drawBitmap(it.bitmap, 0f, 0f, null)

        } ?: super.onDraw(canvas) // If rtt is not available, use default rendering process
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is what happens in the preview and on device:

TextView is nothing special, it just loads the custom font:

public class TestTextView extends AppCompatTextView {

    public TestTextView(Context context) {
        super(context);

        init(context);
    }

    public TestTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        init(context);
    }

    public TestTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init(context);
    }

    void init(Context context) {

        Typeface t = Typeface.createFromAsset(context.getAssets(), "fonts/daisy.ttf");

        setTypeface(t);
    }
}

Layout is also very basic, but just in case:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/material_red200"
    android:orientation="vertical">

    <*custompackage* .TestTextView
        android:gravity="left"
        android:padding="0dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="just some text for testing"
        android:textColor="@color/material_black"
        android:textSize="100dp" />

</LinearLayout>

As you can see, the left parts, like 'j' and 'f' are cut off.

Setting the padding or margin did not work.

This font fits into it's frame when using from other programs.

Thanks in advance.

Edit:
What @play_err_ mentioned is not a solution in my case.

I am using in the final version a textview that resizes automatically, so adding spaces would be terribly difficult.

I need an explanation why other programs (eg photoshop, after effects...) can calculate a proper bounding box and android cannot

I am also loading different fonts dynamically and I do not want to create an

if(badfont)
     addSpaces()

Body:
Reworked @Dmitry Kopytov solution:

in Kotlin

recycle the old bitmap

added documentation

fall back on default TextView rendering if the bitmap cannot be created (not enough memory)

Code:

/**
 * This TextView is able to draw text on the padding area.
 * It's mainly used to support italic texts in custom fonts that can go out of bounds.
 * In this case, you've to set an horizontal padding (or just end padding).
 *
 * This implementation is doing a render-to-texture procedure, as such it consumes more RAM than a standard TextView,
 * it uses an additional bitmap of the size of the view.
 */
class TextViewNoClipping(context: Context, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {
    private class NonClippableCanvas(@NonNull val bitmap: Bitmap) : Canvas(bitmap) {
        override fun clipRect(left: Float, top: Float, right: Float, bottom: Float): Boolean {
            return true
        }
    }

    private var rttCanvas: NonClippableCanvas? = null

    override fun onSizeChanged(width: Int, height: Int,
                               oldwidth: Int, oldheight: Int) {
        if ((width != oldwidth || height != oldheight) && width > 0 && height > 0) {
            rttCanvas?.bitmap?.recycle()
            try {
                Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)?.let {
                    rttCanvas = NonClippableCanvas(it)
                }
            } catch (t: Throwable) {
                // If for some reasons the bitmap cannot be created, we fall back on default rendering (potentially cropping the text).
                rttCanvas?.bitmap?.recycle()
                rttCanvas = null
            }
        }

        super.onSizeChanged(width, height, oldwidth, oldheight)
    }

    override fun onDraw(canvas: Canvas) {
        rttCanvas?.let {
            // Clear the RTT canvas from the previous font.
            it.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

            // Draw on the RTT canvas (-> bitmap) that will use clipping on the NonClippableCanvas, resulting in no-clipping
            super.onDraw(it)

            // Finally draw the bitmap that contains the rendered text (no clipping used here, will display on top of padding)
            canvas.drawBitmap(it.bitmap, 0f, 0f, null)

        } ?: super.onDraw(canvas) // If rtt is not available, use default rendering process
    }
}


问:
Show the post tags with a description in Single.php (not all tags, only the tags of that post with description)
I want to show single post tags with description in single.php.

I searched about this, the closest solution is below. But this code lists all tags of the blog with a description.

```<code>$tags = get_tags( array( 'hide_empty' => false ) );
if ($tags) {
    foreach ($tags as $tag) {
        if ($tag->description) {
            echo '<dt><a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . '>' . $tag->name.'</a></dt><dd>' . $tag->description . '</dd>';
        }
    }
}
</code>```

I need to list only the post tags with description. (It should exclude the post tags without a description.)

For example:

We have 4500+ tags in database.

200+ tags have description.

There are 7 tags on an example single post.

Only 4 of them are have a description.

Result:

I need to show only 4 tags in single.php.

答:
You can try below code it will work in single.php</p>

```<code><?php

$tags = wp_get_post_tags(get_the_ID());
if ($tags) {
    foreach ($tags as $tag) {
        if ($tag->description) {
            echo '<dt><a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . '>' . $tag->name.'</a></dt><dd>' . $tag->description . '</dd>';
        }
    }
}

?>
</code>```

Body:
I want to show single post tags with description in single.php.

I searched about this, the closest solution is below. But this code lists all tags of the blog with a description.

$tags = get_tags( array( 'hide_empty' => false ) );
if ($tags) {
    foreach ($tags as $tag) {
        if ($tag->description) {
            echo '
term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . '>' . $tag->name.'

' . $tag->description . '
';
        }
    }
}

I need to list only the post tags with description. (It should exclude the post tags without a description.)

For example:

We have 4500+ tags in database.

200+ tags have description.

There are 7 tags on an example single post.

Only 4 of them are have a description.

Result:

I need to show only 4 tags in single.php.

Body:
You can try below code it will work in single.php

<?php

$tags = wp_get_post_tags(get_the_ID());
if ($tags) {
    foreach ($tags as $tag) {
        if ($tag->description) {
            echo '<dt><a href="' . get_tag_link( $tag->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $tag->name ) . '" ' . '>' . $tag->name.'</a></dt><dd>' . $tag->description . '</dd>';
        }
    }
}

?>


问:
How to use a variable/Parameter with an IN clause in ORACLE SQL
I have a simple select query:

```<code>SELECT A
FROM B
WHERE A IN :conditions
</code>```

where A is a char.

If i do the full query as:

```<code>SELECT A
FROM B
WHERE A IN ('A','E','I','O','U')
</code>```

it works

but if i use the parameter, when i try to execute with ORACLE SQL Developer i cannot get it to work.

I've already tried to submit the parameter as:

```<code>1* ('A','E','I','O','U')
2* 'A','E','I','O','U'
3* A,E,I,O,U
</code>```

and query returns no results

What's the correct syntax to do so?

Thank U all

答:
You may use a substitution variable in SQL Developer (or in SQL* Plus). Use double quotes while defining.

Test data

```<code>create table b as select 'A' as a from dual union all
select 'I' as a from dual union all
select 'U' as a from dual
</code>```

Execution

```<code>define params = "'A','E','I','O','U'"
select A from B where A in (&params);
</code>```

Result

```<code>old:select A from B where A in (&params)
new:select A from B where A in ('A','E','I','O','U')

A
-
A
I
U
</code>```

Body:
I have a simple select query:

SELECT A
FROM B
WHERE A IN :conditions

where A is a char.

If i do the full query as:

SELECT A
FROM B
WHERE A IN ('A','E','I','O','U')

it works

but if i use the parameter, when i try to execute with ORACLE SQL Developer i cannot get it to work.

I've already tried to submit the parameter as:

1* ('A','E','I','O','U')
2* 'A','E','I','O','U'
3* A,E,I,O,U

and query returns no results

What's the correct syntax to do so?

Thank U all

Body:
You may use a substitution variable in SQL Developer (or in SQL* Plus). Use double quotes while defining.

Test data

create table b as select 'A' as a from dual union all
select 'I' as a from dual union all
select 'U' as a from dual

Execution

define params = "'A','E','I','O','U'"
select A from B where A in (&params);

Result

old:select A from B where A in (&params)
new:select A from B where A in ('A','E','I','O','U')

A
-
A
I
U


问:
How to stop flickering of Markers on mouseover and onmouseout events in react-google-maps?
I'm using React.js and react-google-maps to implement this. I'm trying to display the InfoWindow on Hovering any Marker and hiding when mouse leaves the Marker.
 Here's the link for code. (https://codesandbox.io/s/loving-microservice-88oop)</p>

答:
It's quite simple actually.
Let's go through this together.

You are hovering the element

The element gets visible, you are now with your mouse cursor over the element

Because you are now no longer hovering the marker (you are now actually hovering the popup) the popup get's hidden.

Now that the popup is hidden you are basically starting from 1) again

How to prevent this:

Option 1: Change your hover so that it's also applied to the popup and not just for the marker

Option 2: Change the markers position. You can do this by changing this line (line 36 in your example):

```<code>position={{
            lat: selectedPark.geometry.coordinates[1] + 0.0500,
            lng: selectedPark.geometry.coordinates[0]
          }}
</code>```

Body:
It's quite simple actually.
Let's go through this together.

You are hovering the element

The element gets visible, you are now with your mouse cursor over the element

Because you are now no longer hovering the marker (you are now actually hovering the popup) the popup get's hidden.

Now that the popup is hidden you are basically starting from 1) again

How to prevent this:

Option 1: Change your hover so that it's also applied to the popup and not just for the marker

Option 2: Change the markers position. You can do this by changing this line (line 36 in your example):

position={{
            lat: selectedPark.geometry.coordinates[1] + 0.0500,
            lng: selectedPark.geometry.coordinates[0]
          }}


问:
How to stop code once a set time has been reached
I have asked this question previously but have gotten no valid responses. I would like players to complete my quiz but they only have a set time to do it and once it reaches the set time it ends the game and stops asking all the questions.

I have tried multiple different codes but displayed below is the latest one i am trying.

```<code>import time

max_time = int(input('Enter the amount of seconds you want to run this: '))
start_time = time.time()
while (time.time() - start_time) > max_time:
    sys.exit()

question_1 = ("Question?")
option_1 =(" a. 54 \n b. 50 \n c. 47 \n d. 38")
print(question_1)
print(option_1)
answer_1 = input(">")
if answer_1.lower() == "a":
    print("Correct")
else:
    print("Incorrect")

question_a2 = ("Question 2?")
option_a2 = (" a. 4 \n b. 6 \n c. 8 \n d. 10")
print(question_a2)
print(option_a2)
answer_a2 = input(">")
if answer_a2.lower() == "a":
    print("Correct")
else:
    print("Incorrect")
end_time = time.time()

</code>```

This code just keeps going through the questions like normal and nothing happens. I am fairly new and any help would be appreciated.

答:
First off all, you should start using functions to minimize code duplication (copy&paste). An easy, but not really interactive solution is to check the time after a question is answered. Replace

```<code>if answer_a2.lower() == "a":
    print("Correct")
else:
    print("Incorrect")
</code>```

with

```<code>if (time.time() - start_time) > max_time:
    print("Sorry, you didn't answer in time")
    stop_quiz = True
elif answer_1.lower() == "a":
    print("Correct")
    total_points += 1
else:
    print("Incorrect")
</code>```

Before you ask the next question, check if stop_quiz is True and only continue if it is False. I hope you get the idea. I also introduced a variable for counting correct answered questions.

UPDATE: Rewritten quiz by using a class for storage of points and time

```<code>import time

class Quiz:
  def __init__(self):
      self.total_points = 0
      self.stop_quiz = False
      self.start_time = time.time()
      self.max_time = int(input('Enter the amount of seconds you want to run this: '))

  def ask_question(self, question, options, correct_answer):
      if self.stop_quiz:
          return
      print(question)
      print(options)
      answer = input(">")
      if (time.time() - self.start_time) > self.max_time:
          print("Sorry, you didn't answer in time. The quiz is over")
          self.stop_quiz = True
      elif answer.lower() == correct_answer:
          print("Correct")
          self.total_points += 1
      else:
          print("Incorrect")

  def get_result(self):
      print("You got {} Points!".format(self.total_points))

quiz = Quiz()
quiz.ask_question("Question 1?", "a. 54 \nb. 50 \nc. 47 \nd. 38", "a")
quiz.ask_question("Question 2?", "a. 54 \nb. 20 \nc. 47 \nd. 38", "b")
quiz.get_result()
</code>```

Body:
I have asked this question previously but have gotten no valid responses. I would like players to complete my quiz but they only have a set time to do it and once it reaches the set time it ends the game and stops asking all the questions.

I have tried multiple different codes but displayed below is the latest one i am trying.

import time

max_time = int(input('Enter the amount of seconds you want to run this: '))
start_time = time.time()
while (time.time() - start_time) > max_time:
    sys.exit()

question_1 = ("Question?")
option_1 =(" a. 54 \n b. 50 \n c. 47 \n d. 38")
print(question_1)
print(option_1)
answer_1 = input(">")
if answer_1.lower() == "a":
    print("Correct")
else:
    print("Incorrect")

question_a2 = ("Question 2?")
option_a2 = (" a. 4 \n b. 6 \n c. 8 \n d. 10")
print(question_a2)
print(option_a2)
answer_a2 = input(">")
if answer_a2.lower() == "a":
    print("Correct")
else:
    print("Incorrect")
end_time = time.time()

This code just keeps going through the questions like normal and nothing happens. I am fairly new and any help would be appreciated.

Body:
First off all, you should start using functions to minimize code duplication (copy&paste). An easy, but not really interactive solution is to check the time after a question is answered. Replace

if answer_a2.lower() == "a":
    print("Correct")
else:
    print("Incorrect")

with

if (time.time() - start_time) > max_time:
    print("Sorry, you didn't answer in time")
    stop_quiz = True
elif answer_1.lower() == "a":
    print("Correct")
    total_points += 1
else:
    print("Incorrect")

Before you ask the next question, check if stop_quiz is True and only continue if it is False. I hope you get the idea. I also introduced a variable for counting correct answered questions.

UPDATE: Rewritten quiz by using a class for storage of points and time

import time

class Quiz:
  def __init__(self):
      self.total_points = 0
      self.stop_quiz = False
      self.start_time = time.time()
      self.max_time = int(input('Enter the amount of seconds you want to run this: '))

  def ask_question(self, question, options, correct_answer):
      if self.stop_quiz:
          return
      print(question)
      print(options)
      answer = input(">")
      if (time.time() - self.start_time) > self.max_time:
          print("Sorry, you didn't answer in time. The quiz is over")
          self.stop_quiz = True
      elif answer.lower() == correct_answer:
          print("Correct")
          self.total_points += 1
      else:
          print("Incorrect")

  def get_result(self):
      print("You got {} Points!".format(self.total_points))

quiz = Quiz()
quiz.ask_question("Question 1?", "a. 54 \nb. 50 \nc. 47 \nd. 38", "a")
quiz.ask_question("Question 2?", "a. 54 \nb. 20 \nc. 47 \nd. 38", "b")
quiz.get_result()


问:
Copying a column in excel and doubling every entry/cell. How to?
Let's say we have a row of elements, 1 per cell: 1,2,3,4.
I want to copy this row(or column) and double every entry: 1,1,2,2,3,3,4,4.

Is there any formula, function, etc that does this? Thanks a lot.

I have about 20k entries so doing it manually is not an option.

答:
For example:

Formula in F1:

```<code>=INDEX($A1:$D1,1,ROUNDUP((COLUMN()-5)/2,0))
</code>```

Drag right and down...

Body:
For example:

Formula in F1:

=INDEX($A1:$D1,1,ROUNDUP((COLUMN()-5)/2,0))

Drag right and down...


问:
Where can I find source code of ldconfig?
I want to peek into its implementation,where is it available?</p>

答:
Here is how I found out where the source code is, on my system which runs the Fedora distribution of Linux. (For Debian, Ubuntu and similar distributions the command(s) to use would be different.)

```<code>rpm -qfi `which ldconfig`
</code>```

(those `s are backticks, not apostrophes.)

This outputs the following

```<code>Name        : glibc                        Relocations: (not relocatable)
Version     : 2.13                              Vendor: Fedora Project
Release     : 1                             Build Date: Thu 20 Jan 2011 10:52:15 AM GMT
Install Date: Sun 13 Mar 2011 11:42:50 AM GMT      Build Host: x86-04.phx2.fedoraproject.org
Group       : System Environment/Libraries   Source RPM: glibc-2.13-1.src.rpm
Size        : 13616282                         License: LGPLv2+ and LGPLv2+ with exceptions and GPLv2+
Signature   : RSA/SHA256, Thu 20 Jan 2011 04:42:22 PM GMT, Key ID 421caddb97a1071f
Packager    : Fedora Project
URL         : http://www.gnu.org/software/glibc/
Summary     : The GNU libc libraries
Description :
The glibc package contains standard libraries which are used by
multiple programs on the system. In order to save disk space and
memory, as well as to make upgrading easier, common system code is
kept in one place and shared between programs. This particular package
contains the most important sets of shared libraries: the standard C
library and the standard math library. Without these two libraries, a
Linux system will not function.
</code>```

The important part of this output is the Source RPM field. This shows that ldconfig is part of the glibc project (at least, according to Fedora - very occassionally some distros package two closely-related source projects in one package, but that's rare).

So hopefully you should find the source of ldconfig in this tarball: http://ftp.gnu.org/gnu/glibc/glibc-2.9.tar.gz

In the unlikely event that it isn't there, you should be able to find it in the source rpm for glibc for the Fedora distribution (or the equivalent source package for your distribution).

Body:
Here is how I found out where the source code is, on my system which runs the Fedora distribution of Linux. (For Debian, Ubuntu and similar distributions the command(s) to use would be different.)

rpm -qfi `which ldconfig`

(those `s are backticks, not apostrophes.)

This outputs the following

Name        : glibc                        Relocations: (not relocatable)
Version     : 2.13                              Vendor: Fedora Project
Release     : 1                             Build Date: Thu 20 Jan 2011 10:52:15 AM GMT
Install Date: Sun 13 Mar 2011 11:42:50 AM GMT      Build Host: x86-04.phx2.fedoraproject.org
Group       : System Environment/Libraries   Source RPM: glibc-2.13-1.src.rpm
Size        : 13616282                         License: LGPLv2+ and LGPLv2+ with exceptions and GPLv2+
Signature   : RSA/SHA256, Thu 20 Jan 2011 04:42:22 PM GMT, Key ID 421caddb97a1071f
Packager    : Fedora Project
URL         : http://www.gnu.org/software/glibc/
Summary     : The GNU libc libraries
Description :
The glibc package contains standard libraries which are used by
multiple programs on the system. In order to save disk space and
memory, as well as to make upgrading easier, common system code is
kept in one place and shared between programs. This particular package
contains the most important sets of shared libraries: the standard C
library and the standard math library. Without these two libraries, a
Linux system will not function.

The important part of this output is the Source RPM field. This shows that ldconfig is part of the glibc project (at least, according to Fedora - very occassionally some distros package two closely-related source projects in one package, but that's rare).

So hopefully you should find the source of ldconfig in this tarball: http://ftp.gnu.org/gnu/glibc/glibc-2.9.tar.gz

In the unlikely event that it isn't there, you should be able to find it in the source rpm for glibc for the Fedora distribution (or the equivalent source package for your distribution).


问:
Create Access Database in Visual C++
Currently I need to find a method to create an Access database in Visual C++ 2008, so that:

I can create the Access database in different formats, including Access 95/97 format, 2000 format, and 2007 accdb format.

I can create not only tables, but also other objects, including queries, reports, forms and macros in the Access database.

When adding a large volume of records into the tables, the method has a better performance.

I have searched online, and have found resourced such as this which lists some methods, however, as far as I know, DAO seems to be deprecated.

How about the other methods?

Thanks

答:
As I have understood, you want to create database, objects in it, via calling some function and procedures. Best approach to my mind is to use DAO Library. Here is VBScript example:</p>

```<code>Sub CreateDatabaseFile(ByVal strDbPath)
    Dim wspDefault 'As Workspace
    Dim dbs      ' As Database
    Dim dbEngine ' DAO DB Engine
    Dim dbLangGeneral
    dbLangGeneral = ";LANGID=0x0409;CP=1252;COUNTRY=0"
    Set dbEngine = CreateObject("DAO.DBEngine.120")
    Set wspDefault = DBEngine.Workspaces(0)
    Set dbs = wspDefault.CreateDatabase(strDbPath, dbLangGeneral)
    Dim s
    s="CREATE TABLE tblCustomers (CustomerID INTEGER CONSTRAINT PK_tblCustomers PRIMARY KEY, " _
    & " [Last Name] TEXT(50) NOT NULL, [First Name] TEXT(50) NOT NULL, Phone TEXT(10), Email TEXT(50), " _
    & " Address TEXT(40)) "
    dbs.execute s
    dbs.Close

    Dim AccessApp
    Set AccessApp = CreateObject("Access.Application")
    AccessApp.OpenCurrentDatabase strDbPath
    Dim frm 'As Form
    Dim ctlLabel 'As Control
    Dim  ctlText 'As Control
    Dim intDataX 'As Integer, intDataY As Integer
    Dim intDataY
    Dim intLabelX 'As Integer, intLabelY As Integer
    Dim intLabelY

    ' Create new form with tblCustomers table as its record source.
    Set frm = AccessApp.CreateForm
    'frm.Name = "MyForm"
    frm.RecordSource = "tblCustomers"

    ' Set positioning values for new controls.
    intLabelX = 100
    intLabelY = 100
    intDataX = 1000
    intDataY = 100

    ' Create unbound default-size text box in detail section.
    Dim acTextBox
    acTextBox = 109
    Set ctlText = AccessApp.CreateControl(frm.Name, acTextBox, , "", "", _
        intDataX, intDataY)
    ctlText.ControlSource = "Last Name"
    Dim acLabel
    acLabel = 100
    ' Create child label control for text box.
    Set ctlLabel = AccessApp.CreateControl(frm.Name, acLabel, , _
         ctlText.Name, "NewLabel", intLabelX, intLabelY)
    Dim acButton

    AccessApp.DoCmd.Save, frm.Name
    ' Restore form.
    AccessApp.DoCmd.Restore
    AccessApp.DoCmd.Quit
End Sub
Call CreateDatabaseFile("c:\test\a test database file.mdb")
</code>```

Title: Create Access Database in Visual C++

Body:
As I have understood, you want to create database, objects in it, via calling some function and procedures. Best approach to my mind is to use DAO Library. Here is VBScript example:

Sub CreateDatabaseFile(ByVal strDbPath)
    Dim wspDefault 'As Workspace
    Dim dbs      ' As Database
    Dim dbEngine ' DAO DB Engine
    Dim dbLangGeneral
    dbLangGeneral = ";LANGID=0x0409;CP=1252;COUNTRY=0"
    Set dbEngine = CreateObject("DAO.DBEngine.120")
    Set wspDefault = DBEngine.Workspaces(0)
    Set dbs = wspDefault.CreateDatabase(strDbPath, dbLangGeneral)
    Dim s
    s="CREATE TABLE tblCustomers (CustomerID INTEGER CONSTRAINT PK_tblCustomers PRIMARY KEY, " _
    & " [Last Name] TEXT(50) NOT NULL, [First Name] TEXT(50) NOT NULL, Phone TEXT(10), Email TEXT(50), " _
    & " Address TEXT(40)) "
    dbs.execute s
    dbs.Close

    Dim AccessApp
    Set AccessApp = CreateObject("Access.Application")
    AccessApp.OpenCurrentDatabase strDbPath
    Dim frm 'As Form
    Dim ctlLabel 'As Control
    Dim  ctlText 'As Control
    Dim intDataX 'As Integer, intDataY As Integer
    Dim intDataY
    Dim intLabelX 'As Integer, intLabelY As Integer
    Dim intLabelY

    ' Create new form with tblCustomers table as its record source.
    Set frm = AccessApp.CreateForm
    'frm.Name = "MyForm"
    frm.RecordSource = "tblCustomers"

    ' Set positioning values for new controls.
    intLabelX = 100
    intLabelY = 100
    intDataX = 1000
    intDataY = 100

    ' Create unbound default-size text box in detail section.
    Dim acTextBox
    acTextBox = 109
    Set ctlText = AccessApp.CreateControl(frm.Name, acTextBox, , "", "", _
        intDataX, intDataY)
    ctlText.ControlSource = "Last Name"
    Dim acLabel
    acLabel = 100
    ' Create child label control for text box.
    Set ctlLabel = AccessApp.CreateControl(frm.Name, acLabel, , _
         ctlText.Name, "NewLabel", intLabelX, intLabelY)
    Dim acButton

    AccessApp.DoCmd.Save, frm.Name
    ' Restore form.
    AccessApp.DoCmd.Restore
    AccessApp.DoCmd.Quit
End Sub
Call CreateDatabaseFile("c:\test\a test database file.mdb")


问:
Boolean Value cannot be stored in database (laravel)
so, i want to store a boolean value to database, but it always stored its default value (false). what i am doing is using Function Store as default

This is my UserController:

```<code> public function store(Request $request)
{
     $request->validate([
        'name'      =>'required',
        'email'     =>'required',
        'is_active'     =>'required',
        'password'  => 'required|string|min:6|max:191|confirmed',
        'password_confirmation' => 'required|same:password',
    ]);
      $user = new User;
      $user->name     = $request->name;
      $user->email    = $request->email;
      $user->password = Hash::make($request->password);
    $user->save();

    return redirect()->route('users.index')->with('success','Users created successfully');
}
</code>```

And this is my create form to submit:

```<code> <form action="{{ route('users.store') }}" method="POST">
              @csrf
              <div class="col-sm-9 form-left">
                <div class="form-group form-box">
                  <label for="name">Name</label>
                  <input type="text" class="form-control" id="name" name="name" placeholder="Name">
                </div>

                <div class="form-group form-box">
                  <label for="email">Email</label>
                  <input type="text" class="form-control" id="email" name="email" placeholder="Email">
                </div>

                <div class="form-group form-box">
                  <label for="password">Password</label>
                  <input type="password" class="form-control" id="password" name="password" placeholder="Password">
                </div>

                <div class="form-group form-box">
                  <label for="password_confirmation">Password Confirmation</label>
                  <input type="password" class="form-control" id="password_confirmation" name="password_confirmation" placeholder="Password Confirmation">
                </div>

              </div>

              <div class="col-sm-3 form-right">
               <div class="form-group form-box">
                  <label for="is_active">Status</label>
                  <div class="radio">
                    <label><input type="radio" name="is_active" id="is_active" value="0" checked> Not Verified</label>
                  </div>
                  <div class="radio">
                    <label><input type="radio" name="is_active" id="is_active" value="1" > Verified</label>
                  </div>
                </div>

                <button type="submit" class="btn btn-default">Save</button>
              </div>

          </form>
</code>```

Did i Miss something?

答:
You have missed is_active column while saving</p>

```<code> $user->is_active    = $request->is_active;
</code>```

Body:
so, i want to store a boolean value to database, but it always stored its default value (false). what i am doing is using Function Store as default

This is my UserController:

 public function store(Request $request)
{
     $request->validate([
        'name'      =>'required',
        'email'     =>'required',
        'is_active'     =>'required',
        'password'  => 'required|string|min:6|max:191|confirmed',
        'password_confirmation' => 'required|same:password',
    ]);
      $user = new User;
      $user->name     = $request->name;
      $user->email    = $request->email;
      $user->password = Hash::make($request->password);
    $user->save();

    return redirect()->route('users.index')->with('success','Users created successfully');
}

And this is my create form to submit:

 <form action="{{ route('users.store') }}" method="POST">
              @csrf

                  Name
                  <input type="text" class="form-control" id="name" name="name" placeholder="Name">

                  Email
                  <input type="text" class="form-control" id="email" name="email" placeholder="Email">

                  Password
                  <input type="password" class="form-control" id="password" name="password" placeholder="Password">

                  Password Confirmation
                  <input type="password" class="form-control" id="password_confirmation" name="password_confirmation" placeholder="Password Confirmation">

                  Status

                    <input type="radio" name="is_active" id="is_active" value="0" checked> Not Verified

                    <input type="radio" name="is_active" id="is_active" value="1" > Verified

                <button type="submit" class="btn btn-default">Save</button>

          </form>

Did i Miss something?

Body:
You have missed is_active column while saving

 $user->is_active    = $request->is_active;


答:
you forgot ?</p>

```<code>$user->is_active = $request->is_active;
</code>```

Title: Boolean Value cannot be stored in database (laravel)

Body:
you forgot ?

$user->is_active = $request->is_active;


问:
Nodejs expressjs make npm package available throughout the project
I've this folder structure.

```<code>/app.js
/src
 /routes
 /controllers
</code>```

In routes folder, I've bunch of js files. All of these files need to require passport js package like this

```<code>const passport = require('passport');
</code>```

Instead of doing this, can I require the package in one place (Most probably in app.js) and somehow pass that to each and every file in the routes folder instead of requiring it on every file.

答:
If the files in the routes folder are not using the express router you can rather or else export the function which accepts passport and app objects like

```<code>module.exports = function(app, passport) {
  app.get('/', (req, res) => {
      res.json('some route');
  });
}
</code>```

Then you will be requiring the passport only once in the app.js/server.js and passing the same object to every route

Body:
I've this folder structure.

/app.js
/src
 /routes
 /controllers

In routes folder, I've bunch of js files. All of these files need to require passport js package like this

const passport = require('passport');

Instead of doing this, can I require the package in one place (Most probably in app.js) and somehow pass that to each and every file in the routes folder instead of requiring it on every file.

Body:
If the files in the routes folder are not using the express router you can rather or else export the function which accepts passport and app objects like

module.exports = function(app, passport) {
  app.get('/', (req, res) => {
      res.json('some route');
  });
}

Then you will be requiring the passport only once in the app.js/server.js and passing the same object to every route


问:
How to make play and pause the video in react-native?
i am uploading the video from my gallery , in this case video is automatically playing but i want to control the video using play and pause button and also how to delete the uploaded file. here i am using image picker from expo.

This is my code which plays automatically

```<code>  selectVideo = async () => {
            let result = await ImagePicker.launchImageLibraryAsync({
               mediaTypes:"Videos"
            });
              if (!result.cancelled) {
                this.setState({ video: result.uri });
              }
          };
    render(){
return(
<Avatar xlarge rounded source={require('../../../assets/arrows.png')} onPress={this.selectVideo.bind(this)}/>
    {video &&
         <Video
                  source={{ uri: video }}
                  rate={1.0}
                  volume={1.0}
                  isMuted={false}
                  resizeMode="cover"
                  shouldPlay
                  isLooping
                  style={{ width:100, height:100 }}
                />
    }
</code>```

答:
use pause prop to control video play and pause      </p>

```<code> handleClick=()=>{
  cosnt {isPause} =this.state;
  this.setState({isPause:!isPause})
  }
  render(){
 return{
  const {isPause}=this.state;
   <VideoPlayer
    source={source}
    ref={(ref) => {
      this.player = ref;
    }}
    paused={isPause}
    onBuffer={this.onBuffer}
    onEnd={this.onEnd}
    allowsExternalPlayback={true}
    onError={this.videoError}
    width={width}
    height={height}
  />
  {isPause && <IconWrapper onPress={this.handleClick}/>}
   }}
</code>```

Body:
i am uploading the video from my gallery , in this case video is automatically playing but i want to control the video using play and pause button and also how to delete the uploaded file. here i am using image picker from expo.

This is my code which plays automatically

  selectVideo = async () => {
            let result = await ImagePicker.launchImageLibraryAsync({
               mediaTypes:"Videos"
            });
              if (!result.cancelled) {
                this.setState({ video: result.uri });
              }
          };
    render(){
return(
<Avatar xlarge rounded source={require('../../../assets/arrows.png')} onPress={this.selectVideo.bind(this)}/>
    {video &&
         <Video
                  source={{ uri: video }}
                  rate={1.0}
                  volume={1.0}
                  isMuted={false}
                  resizeMode="cover"
                  shouldPlay
                  isLooping
                  style={{ width:100, height:100 }}
                />
    }

Body:
use pause prop to control video play and pause

 handleClick=()=>{
  cosnt {isPause} =this.state;
  this.setState({isPause:!isPause})
  }
  render(){
 return{
  const {isPause}=this.state;
   <VideoPlayer
    source={source}
    ref={(ref) => {
      this.player = ref;
    }}
    paused={isPause}
    onBuffer={this.onBuffer}
    onEnd={this.onEnd}
    allowsExternalPlayback={true}
    onError={this.videoError}
    width={width}
    height={height}
  />
  {isPause && <IconWrapper onPress={this.handleClick}/>}
   }}


问:
Replace particular file content in nodejs
I want to replace a particular line using javascript with new content.
This is the file content,

```<code>SERVER=1055@localhost

GROUP_SERVERS=2325@localhost

LINE_IAM_INTERESTED=KTYUIERVW:2800

FILE_PATH="C:\Program Files\somefile\Shared Files\"
</code>```

In this line, LINE_IAM_INTERESTED=KTYUIERVW:2800 .I want to replace KTYUIERVW with KJHTERDY and 2800 with 78945

I have shown what I tried using fs appendfilesync

```<code>
fs.appendFileSync('file_name').toString().split('\n').forEach(function(line){
    app.console.log("called append");
    var sEntry = line.split("=");
    if (sEntry.length == 2) {
      if (sEntry[0] == "LINE_IAM_INTERESTED") {
      app.console.log("found one!!!!");
      }
    }
  });
</code>```

答:
appendFile and appendFileSync are used for adding to the end of the file. Although you can do it as a one liner as shown in the other answer, I've kept the structure of your code the same. Here you want to read the data, modify it then re-write it. Using the block of code you have, you can modify it to use readFileSync and writeFileSync.

```<code>let newData = fs.readFileSync('file_name', 'utf-8').split('\n').map(line => {
  let sEntry = line.split('=')
  if (sEntry.length == 2) {
    if (sEntry[0] == "LINE_IAM_INTERESTED") {
      console.log("found one!!!!");
      return sEntry[0] + '=' + 'KJHTERDY:78945'
    }
  }
  return line
}).join('\n')

fs.writeFileSync('file_name', newData)
</code>```

I've swapped the forEach for map which lets us change the array data by returning the desired value. The new array is then joined back together and written back to the file.

Body:
I want to replace a particular line using javascript with new content.
This is the file content,

SERVER=1055@localhost

GROUP_SERVERS=2325@localhost

LINE_IAM_INTERESTED=KTYUIERVW:2800

FILE_PATH="C:\Program Files\somefile\Shared Files\"

In this line, LINE_IAM_INTERESTED=KTYUIERVW:2800 .I want to replace KTYUIERVW with KJHTERDY and 2800 with 78945

I have shown what I tried using fs appendfilesync

fs.appendFileSync('file_name').toString().split('\n').forEach(function(line){
    app.console.log("called append");
    var sEntry = line.split("=");
    if (sEntry.length == 2) {
      if (sEntry[0] == "LINE_IAM_INTERESTED") {
      app.console.log("found one!!!!");
      }
    }
  });

Body:
appendFile and appendFileSync are used for adding to the end of the file. Although you can do it as a one liner as shown in the other answer, I've kept the structure of your code the same. Here you want to read the data, modify it then re-write it. Using the block of code you have, you can modify it to use readFileSync and writeFileSync.

let newData = fs.readFileSync('file_name', 'utf-8').split('\n').map(line => {
  let sEntry = line.split('=')
  if (sEntry.length == 2) {
    if (sEntry[0] == "LINE_IAM_INTERESTED") {
      console.log("found one!!!!");
      return sEntry[0] + '=' + 'KJHTERDY:78945'
    }
  }
  return line
}).join('\n')

fs.writeFileSync('file_name', newData)

I've swapped the forEach for map which lets us change the array data by returning the desired value. The new array is then joined back together and written back to the file.


问:
Ranges in Kotlin
How do I write code to return a range of 10 numbers from a given number.

i.e if I am given 5, code should return 0..9

358 should return 350..359

33 should return 30..39  etc

答:
Do you mean something like this?</p>

```<code>fun range10(contained: Int): IntRange {
    val start = contained - contained % 10
    val end = start + 9
    return start..end
}
</code>```

Title: Ranges in Kotlin

Body:
Do you mean something like this?

fun range10(contained: Int): IntRange {
    val start = contained - contained % 10
    val end = start + 9
    return start..end
}


问:
How to make the items in the last row consume remaining space in CSS Grid?
Is there a way to force all the items in the last row, of a grid, to fill the row, no matter how many they are?

I do not know the number of items that will be in the grid so I cannot target them directly. I tried to use grid-auto-flow: dense, but it is not really helping.

This is my question visualized:
:

div {
  margin:20px auto;
  width: 400px;
  background: #d8d8d8;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(3, 1fr);
}
span {
  height: 50px;
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>
 </code>```

答:
This is totally possible with CSS grid by combining the CSS rules nth-child and nth-last-of-type. The only caveat is that the number of columns needs to be known in advance.

.grid {
    display: grid;
    grid-template-columns: auto auto auto;
    justify-items: start;
    grid-gap: 10px;
}

.grid div {
  border: 1px solid #ccc;
  width: 100%;
}

.grid > *:nth-child(3n-1) {
  justify-self: center;
  text-align: center;
}

.grid > *:nth-child(3n) {
  justify-self: end;
  text-align: right;
}

.grid > *:nth-child(3n-1):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 2;
}

.grid > *:nth-child(3n-2):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
</div></code>```

Body:
This is totally possible with CSS grid by combining the CSS rules nth-child and nth-last-of-type. The only caveat is that the number of columns needs to be known in advance.

.grid {
    display: grid;
    grid-template-columns: auto auto auto;
    justify-items: start;
    grid-gap: 10px;
}

.grid div {
  border: 1px solid #ccc;
  width: 100%;
}

.grid > *:nth-child(3n-1) {
  justify-self: center;
  text-align: center;
}

.grid > *:nth-child(3n) {
  justify-self: end;
  text-align: right;
}

.grid > *:nth-child(3n-1):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 2;
}

.grid > *:nth-child(3n-2):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 3;
}

<div class="grid">
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
</div>


问:
how can I access a class from a subclass of type list
I have the following code in C# and I am trying to find out why I am not able to access from a subclass that is from type list the elements of a class address. This is the code

```<code>MemberList list = MemberDB.GetMembers("sql", m_page,
    m_RecordPerPage, out count, _state);

/*******************************/

public static MemberList GetMembers(string sql, int page,
    int pageSize, out int count, string parState)
{
    MemberList retval = new MemberList();

    SqlParameter pOut = new SqlParameter("@Count", SqlDbType.Int, 4);
    pOut.Direction = ParameterDirection.Output;

    SqlParameter[] param = new SqlParameter[]{
    new SqlParameter("@Sql", sql),
    new SqlParameter("@parState", parState),
    new SqlParameter("@Page", page),
    new SqlParameter("@PageSize", pageSize),
    pOut };

    using (SqlDataReader reader = SqlHelper.ExecuteReader(
        Helper.ConnectionString, CommandType.StoredProcedure,
        "[app_Member_Search]", param))
    {
        while (reader.Read())
        //if (reader.Read())
        {
            retval.Add(Read(reader));
            //retval = Read(reader);
        }
    }

    count = Helper.ToInt32(pOut.Value);

    return retval;
}
</code>```

```<code>public class Member
{
    private Address m_address;

    public Address Address
    {
        get { return m_address; }
        set { m_address = value; }
    }

    public Member()
    {
        m_address = new Address();
    }
}

public class MemberList : List<Member>
{
    public MemberList() { }
}
</code>```

```<code>case "Address":
    retval.Address.Address1 = Helper.ToString(reader[i]);
    //throw new Exception(Helper.ToString(reader[i]));
    //retval.Address1 = Helper.ToString(reader[i]);
    break;

case "Address2":
    retval.Address.Address2 = Helper.ToString(reader[i]);
    //retval.Address2 = Helper.ToString(reader[i]);
    break;

case "City":
    retval.Address.City = Helper.ToString(reader[i]);
    //retval.City = Helper.ToString(reader[i]);
    break;

case "State":
    retval.Address.State = Helper.ToString(reader[i]);
    //retval.State = Helper.ToString(reader[i]);
    break;
</code>```

答:
I think your problem may be coming from being confused about the inheritance hierarchy of your MemberList class.  It isn't actually a subclass of member at all, it is a subclass of List(Of T).  When you replace the T with some class name all you are saying is that the list should be a list of that type, but the list is still a list not a subclass of that type. This is using a .net feature called generics.  You can read more about generics here.

If the switch statement in your example is referring to the same retval that can be seen in your fist code snippet you will need to specify an index in the list for it to work.  Such as:

```<code>//index should be set to the correct index for the Member you are modifying
retval[index].Address.Address1 = "Some Value";
</code>```

However this will require you to add a new Member to the list before this can work.  I would probably make a new Member instance, set is properties in the switch statement and then add it to the MemberList at the end.  That way you avoid having to index into the list each time you want to set a property so it is a cleaner and slightly faster solution (in both execution time and writing it time).

ContentLicense: CC BY-SA 2.5

Body:
I have the following code in C# and I am trying to find out why I am not able to access from a subclass that is from type list the elements of a class address. This is the code

MemberList list = MemberDB.GetMembers("sql", m_page,
    m_RecordPerPage, out count, _state);

/*******************************/

public static MemberList GetMembers(string sql, int page,
    int pageSize, out int count, string parState)
{
    MemberList retval = new MemberList();

    SqlParameter pOut = new SqlParameter("@Count", SqlDbType.Int, 4);
    pOut.Direction = ParameterDirection.Output;

    SqlParameter[] param = new SqlParameter[]{
    new SqlParameter("@Sql", sql),
    new SqlParameter("@parState", parState),
    new SqlParameter("@Page", page),
    new SqlParameter("@PageSize", pageSize),
    pOut };

    using (SqlDataReader reader = SqlHelper.ExecuteReader(
        Helper.ConnectionString, CommandType.StoredProcedure,
        "[app_Member_Search]", param))
    {
        while (reader.Read())
        //if (reader.Read())
        {
            retval.Add(Read(reader));
            //retval = Read(reader);
        }
    }

    count = Helper.ToInt32(pOut.Value);

    return retval;
}

public class Member
{
    private Address m_address;

    public Address Address
    {
        get { return m_address; }
        set { m_address = value; }
    }

    public Member()
    {
        m_address = new Address();
    }
}

public class MemberList : List<Member>
{
    public MemberList() { }
}

case "Address":
    retval.Address.Address1 = Helper.ToString(reader[i]);
    //throw new Exception(Helper.ToString(reader[i]));
    //retval.Address1 = Helper.ToString(reader[i]);
    break;

case "Address2":
    retval.Address.Address2 = Helper.ToString(reader[i]);
    //retval.Address2 = Helper.ToString(reader[i]);
    break;

case "City":
    retval.Address.City = Helper.ToString(reader[i]);
    //retval.City = Helper.ToString(reader[i]);
    break;

case "State":
    retval.Address.State = Helper.ToString(reader[i]);
    //retval.State = Helper.ToString(reader[i]);
    break;

LastEditorDisplayName: casperOne

Body:
I think your problem may be coming from being confused about the inheritance hierarchy of your MemberList class.  It isn't actually a subclass of member at all, it is a subclass of List(Of T).  When you replace the T with some class name all you are saying is that the list should be a list of that type, but the list is still a list not a subclass of that type. This is using a .net feature called generics.  You can read more about generics here.

If the switch statement in your example is referring to the same retval that can be seen in your fist code snippet you will need to specify an index in the list for it to work.  Such as:

//index should be set to the correct index for the Member you are modifying
retval[index].Address.Address1 = "Some Value";

However this will require you to add a new Member to the list before this can work.  I would probably make a new Member instance, set is properties in the switch statement and then add it to the MemberList at the end.  That way you avoid having to index into the list each time you want to set a property so it is a cleaner and slightly faster solution (in both execution time and writing it time).

OwnerDisplayName: Caleb Vear


问:
Is there away to change previous domain address to newly assigned elastic ip address
Is there a way to reconfigure the previous instance's IP address to the newly assigned IP address.

After I configured all my instance and I tried to assign the elastic IP. I found that the IP is changed. therefore the website under apache2 /var/www/html was no longer valid / unreachable.

is there any way that I can change old IP to new IP address?

NEW: ec2-13-237-246-127.ap-southeast-2.compute.amazonaws.com

will redirect to

OLD:http://ec2-54-206-98-171.ap-southeast-2.compute.amazonaws.com/

since I changed to associate a new IP into this instance.

答:
Unfortunately, you can not reuse that public IP address.

A public IP address is assigned to your instance from Amazon's pool of public IPv4 addresses, and is not associated with your AWS account. When a public IP address is disassociated from your instance, it is released back into the public IPv4 address pool, and you cannot reuse it.

If you require a persistent public IP address that can be associated to and from instances as you require, use an Elastic IP address instead


问:
How to mock an observable value from a service Angular 7?
I have been trying to write unit tests for my Angular component. Currently in my service call to get the data for my component I have an observable that is given true once the call has finished. This observable to subscribed to in my component so the component knows when the call has bee completed. I have managed to mock the call for data in my component but I am struggling to find a way to mock the single observable value.

All the questions on SO that I can find are all about mocking a function call from the service in the component but none that I can find are about mocking a single observable.

Here is my function call in the service. As you can see the observable is given a new value once the finalize function runs:

  public getSmallInfoPanel(key: string): BehaviorSubject<InfoPanelResponse> {

    if (key) {
      this.infoPanel = new BehaviorSubject<InfoPanelResponse>(null);

      this.http.get(`${this.apiUrl}api/Panels/GetInfoPanel/${key}`).pipe(
          retry(3),
          finalize(() => {
            this.hasLoadedSubject.next(true);
          }))
        .subscribe((x: InfoPanelResponse) => this.infoPanel.next(x));
    }
    return this.infoPanel;
  }
```

<p>Here is how I created the <code>Observable</code> in the service:</p>

<pre class="lang-js prettyprint-override"><code> private hasLoadedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
 public hasLoadedObs: Observable<boolean> = this.hasLoadedSubject.asObservable();
</code>```

Then in my component I subscribe to the Observable created from the BehaviourSubject:

public hasLoaded: boolean;

  ngOnInit() {

    this.infoPanelSmallService.hasLoadedObs.subscribe(z => this.hasLoaded = z);

  }
```

<p>When I run <code>ng test</code> the component test fails because it does not know what <code>hasLoadedObs</code> is so it cannot subscribe to it.</p>

<p>Let me know if I can provide more info. Thank you.</p>

<p><strong>UPDATE 1</strong></p>

<pre class="lang-js prettyprint-override"><code>describe('InformationPanelSmallComponent', () => {
  let component: InformationPanelSmallComponent;
  let fixture: ComponentFixture<InformationPanelSmallComponent>;

  let mockInfoPanelService;
  let mockInfoPanel: InfoPanel;
  let mockInfoPanelResponse: InfoPanelResponse;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FontAwesomeModule,
        HttpClientTestingModule
      ],
      declarations: [InformationPanelSmallComponent, CmsInfoDirective],
      providers: [
        { provide: InfoPanelSmallService, useValue: mockInfoPanelService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {

    mockInfoPanel = {
      Title: 'some title',
      Heading: 'some heading',
      Description: 'some description',
      ButtonText: 'some button text',
      ButtonUrl: 'some button url',
      ImageUrl: 'some image url',
      Key: 'test-key',
      SearchUrl: '',
      VideoUrl: ''
    }

    mockInfoPanelResponse = {
      InfoPanel: mockInfoPanel
    }

    fixture = TestBed.createComponent(InformationPanelSmallComponent);
    component = fixture.componentInstance;

    mockInfoPanelService = jasmine.createSpyObj(['getSmallInfoPanel']);

    component = new InformationPanelSmallComponent(mockInfoPanelService);

    component.key = "test-key"

  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
  //TO DO
  it('should get info panel from info panel service', () => {
    mockInfoPanelService.getSmallInfoPanel.and.returnValue(of(mockInfoPanelResponse));
    component.ngOnInit();

    expect(mockInfoPanelService.getSmallInfoPanel).toHaveBeenCalled();
    expect(component.infoPanel).toEqual(mockInfoPanel);
  });
});

</code>```

答:
I found that it had to do with the order I was mocking the service and creating the component. I also used TestBed.overrideProvider which is something different to what I was using above. This is the end resulting test file:

describe('InformationPanelSmallComponent', () => {
  let component: InformationPanelSmallComponent;
  let fixture: ComponentFixture<InformationPanelSmallComponent>;

  let mockInfoPanelService;
  let mockInfoPanel: InfoPanel;
  let mockInfoPanelResponse: InfoPanelResponse;

  beforeEach(async(() => {
    mockInfoPanelService = jasmine.createSpyObj(['getSmallInfoPanel', 'hasLoadedObs']);

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FontAwesomeModule,
        HttpClientTestingModule
      ],
      declarations: [InformationPanelSmallComponent, CmsInfoDirective, UrlRedirectDirective],
      providers: [
        { provide: 'BASE_URL', useValue: '/' },
        { provide: 'API_URL', useValue: '/' }
      ]
    })

    TestBed.overrideProvider(InfoPanelSmallService, { useValue: mockInfoPanelService });

    TestBed.compileComponents();
  }));

  beforeEach(() => {

    mockInfoPanel = {
      Title: 'some title',
      Heading: 'some heading',
      Description: 'some description',
      ButtonText: 'some button text',
      ButtonUrl: 'some button url',
      ImageUrl: 'some image url',
      Key: 'test-key',
      SearchUrl: '',
      VideoUrl: ''
    }

    mockInfoPanelResponse = {
      InfoPanel: mockInfoPanel
    }

    fixture = TestBed.createComponent(InformationPanelSmallComponent);
    component = fixture.componentInstance;

    mockInfoPanelService.getSmallInfoPanel.and.returnValue(of(mockInfoPanelResponse));
    mockInfoPanelService.hasLoadedObs = of(true);

    component.key = "test-key"

    fixture.detectChanges();

  });

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

  describe('ngOnInit', () => {
    it('should get info panel from info panel service', () => {
      expect(component.hasLoaded).toEqual(true);
      expect(mockInfoPanelService.getSmallInfoPanel).toHaveBeenCalled();
      expect(component.infoPanel).toEqual(mockInfoPanel);
    });

    it('should get loaded is true from service', () => {
      expect(component.hasLoaded).toEqual(true);
    });
  });
});

```

I then got no more errors and the tests actually functioned correctly. Thanks @RuiMarques and others for all the input.

Body:
I have been trying to write unit tests for my Angular component. Currently in my service call to get the data for my component I have an observable that is given true once the call has finished. This observable to subscribed to in my component so the component knows when the call has bee completed. I have managed to mock the call for data in my component but I am struggling to find a way to mock the single observable value.

All the questions on SO that I can find are all about mocking a function call from the service in the component but none that I can find are about mocking a single observable.

Here is my function call in the service. As you can see the observable is given a new value once the finalize function runs:

  public getSmallInfoPanel(key: string): BehaviorSubject<InfoPanelResponse> {

    if (key) {
      this.infoPanel = new BehaviorSubject<InfoPanelResponse>(null);

      this.http.get(`${this.apiUrl}api/Panels/GetInfoPanel/${key}`).pipe(
          retry(3),
          finalize(() => {
            this.hasLoadedSubject.next(true);
          }))
        .subscribe((x: InfoPanelResponse) => this.infoPanel.next(x));
    }
    return this.infoPanel;
  }

Here is how I created the Observable in the service:

 private hasLoadedSubject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
 public hasLoadedObs: Observable<boolean> = this.hasLoadedSubject.asObservable();

Then in my component I subscribe to the Observable created from the BehaviourSubject:

public hasLoaded: boolean;

  ngOnInit() {

    this.infoPanelSmallService.hasLoadedObs.subscribe(z => this.hasLoaded = z);

  }

When I run ng test the component test fails because it does not know what hasLoadedObs is so it cannot subscribe to it.

Let me know if I can provide more info. Thank you.

UPDATE 1

describe('InformationPanelSmallComponent', () => {
  let component: InformationPanelSmallComponent;
  let fixture: ComponentFixture<InformationPanelSmallComponent>;

  let mockInfoPanelService;
  let mockInfoPanel: InfoPanel;
  let mockInfoPanelResponse: InfoPanelResponse;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FontAwesomeModule,
        HttpClientTestingModule
      ],
      declarations: [InformationPanelSmallComponent, CmsInfoDirective],
      providers: [
        { provide: InfoPanelSmallService, useValue: mockInfoPanelService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {

    mockInfoPanel = {
      Title: 'some title',
      Heading: 'some heading',
      Description: 'some description',
      ButtonText: 'some button text',
      ButtonUrl: 'some button url',
      ImageUrl: 'some image url',
      Key: 'test-key',
      SearchUrl: '',
      VideoUrl: ''
    }

    mockInfoPanelResponse = {
      InfoPanel: mockInfoPanel
    }

    fixture = TestBed.createComponent(InformationPanelSmallComponent);
    component = fixture.componentInstance;

    mockInfoPanelService = jasmine.createSpyObj(['getSmallInfoPanel']);

    component = new InformationPanelSmallComponent(mockInfoPanelService);

    component.key = "test-key"

  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
  //TO DO
  it('should get info panel from info panel service', () => {
    mockInfoPanelService.getSmallInfoPanel.and.returnValue(of(mockInfoPanelResponse));
    component.ngOnInit();

    expect(mockInfoPanelService.getSmallInfoPanel).toHaveBeenCalled();
    expect(component.infoPanel).toEqual(mockInfoPanel);
  });
});

Body:
I found that it had to do with the order I was mocking the service and creating the component. I also used TestBed.overrideProvider which is something different to what I was using above. This is the end resulting test file:

describe('InformationPanelSmallComponent', () => {
  let component: InformationPanelSmallComponent;
  let fixture: ComponentFixture<InformationPanelSmallComponent>;

  let mockInfoPanelService;
  let mockInfoPanel: InfoPanel;
  let mockInfoPanelResponse: InfoPanelResponse;

  beforeEach(async(() => {
    mockInfoPanelService = jasmine.createSpyObj(['getSmallInfoPanel', 'hasLoadedObs']);

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FontAwesomeModule,
        HttpClientTestingModule
      ],
      declarations: [InformationPanelSmallComponent, CmsInfoDirective, UrlRedirectDirective],
      providers: [
        { provide: 'BASE_URL', useValue: '/' },
        { provide: 'API_URL', useValue: '/' }
      ]
    })

    TestBed.overrideProvider(InfoPanelSmallService, { useValue: mockInfoPanelService });

    TestBed.compileComponents();
  }));

  beforeEach(() => {

    mockInfoPanel = {
      Title: 'some title',
      Heading: 'some heading',
      Description: 'some description',
      ButtonText: 'some button text',
      ButtonUrl: 'some button url',
      ImageUrl: 'some image url',
      Key: 'test-key',
      SearchUrl: '',
      VideoUrl: ''
    }

    mockInfoPanelResponse = {
      InfoPanel: mockInfoPanel
    }

    fixture = TestBed.createComponent(InformationPanelSmallComponent);
    component = fixture.componentInstance;

    mockInfoPanelService.getSmallInfoPanel.and.returnValue(of(mockInfoPanelResponse));
    mockInfoPanelService.hasLoadedObs = of(true);

    component.key = "test-key"

    fixture.detectChanges();

  });

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

  describe('ngOnInit', () => {
    it('should get info panel from info panel service', () => {
      expect(component.hasLoaded).toEqual(true);
      expect(mockInfoPanelService.getSmallInfoPanel).toHaveBeenCalled();
      expect(component.infoPanel).toEqual(mockInfoPanel);
    });

    it('should get loaded is true from service', () => {
      expect(component.hasLoaded).toEqual(true);
    });
  });
});

I then got no more errors and the tests actually functioned correctly. Thanks @RuiMarques and others for all the input.


问:
How do I remove duplicates from a list, while preserving order?
How do I remove duplicates from a list, while preserving order? Using a set to remove duplicates destroys the original order.
Is there a built-in or a Pythonic idiom?</p>

答:
Eliminating the duplicate values in a sequence, but preserve the order of the remaining items. Use of general purpose generator function.</p>

```<code># for hashable sequence
def remove_duplicates(items):
    seen = set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)

a = [1, 5, 2, 1, 9, 1, 5, 10]
list(remove_duplicates(a))
# [1, 5, 2, 9, 10]

# for unhashable sequence
def remove_duplicates(items, key=None):
    seen = set()
    for item in items:
        val = item if key is None else key(item)
        if val not in seen:
            yield item
            seen.add(val)

a = [ {'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, {'x': 2, 'y': 4}]
list(remove_duplicates(a, key=lambda d: (d['x'],d['y'])))
# [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}]
</code>```

OwnerDisplayName: jmglov

LastEditorDisplayName: J.F. Sebastian

Body:
Eliminating the duplicate values in a sequence, but preserve the order of the remaining items. Use of general purpose generator function.

# for hashable sequence
def remove_duplicates(items):
    seen = set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)

a = [1, 5, 2, 1, 9, 1, 5, 10]
list(remove_duplicates(a))
# [1, 5, 2, 9, 10]

# for unhashable sequence
def remove_duplicates(items, key=None):
    seen = set()
    for item in items:
        val = item if key is None else key(item)
        if val not in seen:
            yield item
            seen.add(val)

a = [ {'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, {'x': 2, 'y': 4}]
list(remove_duplicates(a, key=lambda d: (d['x'],d['y'])))
# [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}]


问:
Terraform on Azure DevOps with azurerm Backend
So I want to use terraform v0.12.0 for defining my azure infrastructure. Our company is heavy on placing restrictions on things to use, so I am a bit reluctant to use off the shelf build/release tasks from Azure DevOps Marketplace. So I downloaded the exe, added it to the code, I can also download it directly on the build/release agent.

So I used Azure DevOps Release pipelines built-in task Azure Cli (v1.151.1) with the following code

```<code>call az login --service-principal -u $(clientid) -p $(clientsecret) --tenant $(tenantid)
call cd $(System.DefaultWorkingDirectory)/_DevOps/drop/Terraform/
call set ARM_ACCESS_KEY=$(az keyvault secret show --name mybackendkey --vault-name mykeyvault --query value -o tsv)
call set ARM_CLIENT_ID="$(clientid)"
call set ARM_CLIENT_SECRET="$(clientsecret)"
call set ARM_SUBSCRIPTION_ID="$(subscriptionid)"
call set ARM_TENANT_ID="$(tenantid)"
call terraform init -backend-config="storage_account_name=mystorageaccount" -backend-config="container_name=terraform-state" -backend-config="key=terraform.tfstate"
call terraform plan -input=false
call terraform apply -input=false
</code>```

with the following terraform.tf file

```<code>terraform {
  backend "azurerm" {
    storage_account_name = "mystorageaccount"
    container_name = "terraform-state"
    key = "terraform.tfstate"
    resource_group_name  = "myresourcegroup"
    subscription_id = "00000000-0000-0000-0000-000000000000"
    client_id = "00000000-0000-0000-0000-000000000000"
    client_secret = "mysecret"
    tenant_id = "00000000-0000-0000-0000-000000000000"
  }
}
</code>```

Now it is giving the the following error

```<code>2019-05-27T14:45:53.7470711Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_ACCESS_KEY=$(az keyvault secret show --name mybackendkey --vault-name mykeyvault --query value -o tsv)
2019-05-27T14:45:53.7491727Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_CLIENT_ID="***"
2019-05-27T14:45:53.7511373Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_CLIENT_SECRET="***"
2019-05-27T14:45:53.7532794Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_SUBSCRIPTION_ID="***"
2019-05-27T14:45:53.7554859Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_TENANT_ID="***"
2019-05-27T14:45:53.7574875Z D:\a\r1\a\_DevOps\drop\Terraform>call terraform init -backend-config="storage_account_name=mystorageaccount" -backend-config="container_name=terraform-state" -backend-config="key=terraform.tfstate"
2019-05-27T14:45:53.9641074Z Initializing the backend...
2019-05-27T14:45:53.9721551Z Successfully configured the backend "azurerm"! Terraform will automatically
2019-05-27T14:45:53.9721831Z use this backend unless the backend configuration changes.
2019-05-27T14:45:53.9737291Z Error: Failed to get migrated workspaces: Error creating storage client for storage account "mystorageaccount": azure: malformed storage account key: illegal base64 data at input byte 0
2019-05-27T14:45:53.9856719Z D:\a\r1\a\_DevOps\drop\Terraform>call terraform plan -out=tfplan -input=false
2019-05-27T14:45:54.1177547Z Error: Error loading state: Error creating storage client for storage account "mystorageaccount": azure: malformed storage account key: illegal base64 data at input byte 0
2019-05-27T14:45:54.1302709Z D:\a\r1\a\_DevOps\drop\Terraform>call terraform apply -input=false tfplan
2019-05-27T14:45:54.2539375Z CreateFile tfplan: The system cannot find the file specified.
2019-05-27T14:45:54.2782991Z ##[error]Script failed with error: Error: D:\a\_temp\azureclitaskscript1558968322690.bat failed with return code: 1
2019-05-27T14:45:54.2899205Z [command]C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" account clear"
</code>```

It works if I move my backend to local, is there anyway I can make it work with Azure Backend? BTW I am getting the secrets and Ids from Azure Key Vault directly injected into the DevOps peipline

答:
For your issue, just as the error shows that the storage account access key that you set through the environment variable is wrong. As your comment, it's a wrong way to set the environment variable ARM_ACCESS_KEY.

I think there are two ways to solve the issue. One is that use the DevOps way to set the environment variables. And it seems it's a windows host. So another way is to set the environment variables in windows way.

Add the windows way below:

In PowerShell:

```<code>$env:ARM_ACCESS_KEY=$(az keyvault secret show --name mybackendkey --vault-name mykeyvault --query value -o tsv)
</code>```

In CMD it seems you cannot directly set the environment variables through the output of the command, just can set it with a string.

```<code>set ARM_ACCESS_KEY="xxxxx"
</code>```

Body:
So I want to use terraform v0.12.0 for defining my azure infrastructure. Our company is heavy on placing restrictions on things to use, so I am a bit reluctant to use off the shelf build/release tasks from Azure DevOps Marketplace. So I downloaded the exe, added it to the code, I can also download it directly on the build/release agent.

So I used Azure DevOps Release pipelines built-in task Azure Cli (v1.151.1) with the following code

call az login --service-principal -u $(clientid) -p $(clientsecret) --tenant $(tenantid)
call cd $(System.DefaultWorkingDirectory)/_DevOps/drop/Terraform/
call set ARM_ACCESS_KEY=$(az keyvault secret show --name mybackendkey --vault-name mykeyvault --query value -o tsv)
call set ARM_CLIENT_ID="$(clientid)"
call set ARM_CLIENT_SECRET="$(clientsecret)"
call set ARM_SUBSCRIPTION_ID="$(subscriptionid)"
call set ARM_TENANT_ID="$(tenantid)"
call terraform init -backend-config="storage_account_name=mystorageaccount" -backend-config="container_name=terraform-state" -backend-config="key=terraform.tfstate"
call terraform plan -input=false
call terraform apply -input=false

with the following terraform.tf file

terraform {
  backend "azurerm" {
    storage_account_name = "mystorageaccount"
    container_name = "terraform-state"
    key = "terraform.tfstate"
    resource_group_name  = "myresourcegroup"
    subscription_id = "00000000-0000-0000-0000-000000000000"
    client_id = "00000000-0000-0000-0000-000000000000"
    client_secret = "mysecret"
    tenant_id = "00000000-0000-0000-0000-000000000000"
  }
}

Now it is giving the the following error

2019-05-27T14:45:53.7470711Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_ACCESS_KEY=$(az keyvault secret show --name mybackendkey --vault-name mykeyvault --query value -o tsv)
2019-05-27T14:45:53.7491727Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_CLIENT_ID="***"
2019-05-27T14:45:53.7511373Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_CLIENT_SECRET="***"
2019-05-27T14:45:53.7532794Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_SUBSCRIPTION_ID="***"
2019-05-27T14:45:53.7554859Z D:\a\r1\a\_DevOps\drop\Terraform>call set ARM_TENANT_ID="***"
2019-05-27T14:45:53.7574875Z D:\a\r1\a\_DevOps\drop\Terraform>call terraform init -backend-config="storage_account_name=mystorageaccount" -backend-config="container_name=terraform-state" -backend-config="key=terraform.tfstate"
2019-05-27T14:45:53.9641074Z Initializing the backend...
2019-05-27T14:45:53.9721551Z Successfully configured the backend "azurerm"! Terraform will automatically
2019-05-27T14:45:53.9721831Z use this backend unless the backend configuration changes.
2019-05-27T14:45:53.9737291Z Error: Failed to get migrated workspaces: Error creating storage client for storage account "mystorageaccount": azure: malformed storage account key: illegal base64 data at input byte 0
2019-05-27T14:45:53.9856719Z D:\a\r1\a\_DevOps\drop\Terraform>call terraform plan -out=tfplan -input=false
2019-05-27T14:45:54.1177547Z Error: Error loading state: Error creating storage client for storage account "mystorageaccount": azure: malformed storage account key: illegal base64 data at input byte 0
2019-05-27T14:45:54.1302709Z D:\a\r1\a\_DevOps\drop\Terraform>call terraform apply -input=false tfplan
2019-05-27T14:45:54.2539375Z CreateFile tfplan: The system cannot find the file specified.
2019-05-27T14:45:54.2782991Z ##[error]Script failed with error: Error: D:\a\_temp\azureclitaskscript1558968322690.bat failed with return code: 1
2019-05-27T14:45:54.2899205Z [command]C:\windows\system32\cmd.exe /D /S /C ""C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" account clear"

It works if I move my backend to local, is there anyway I can make it work with Azure Backend? BTW I am getting the secrets and Ids from Azure Key Vault directly injected into the DevOps peipline

Body:
For your issue, just as the error shows that the storage account access key that you set through the environment variable is wrong. As your comment, it's a wrong way to set the environment variable ARM_ACCESS_KEY.

I think there are two ways to solve the issue. One is that use the DevOps way to set the environment variables. And it seems it's a windows host. So another way is to set the environment variables in windows way.

Add the windows way below:

In PowerShell:

$env:ARM_ACCESS_KEY=$(az keyvault secret show --name mybackendkey --vault-name mykeyvault --query value -o tsv)

In CMD it seems you cannot directly set the environment variables through the output of the command, just can set it with a string.

set ARM_ACCESS_KEY="xxxxx"


问:
QUASAR - Justify-center and screen breakpoints
I’m having this issue, I searched in the forum but didn’t find anything related.

I am trying to use justify-center for small screens and justify-end for large screens. Reading the docs I found this:

So I tried to use it as justify-sm-center and justify-lg-end but haven’t been able to make it work. I made this fiddle to demonstrate it:

https://jsfiddle.net/leoprada/3b40vn6g/

Class: justify-center applied when BP lg (justify-lg-center) and justify-end on BP sm (justify-sm-end)

            col-4

            Col-4

```

I don’t really know if I am doing something wrong.

(I know how to make it work by my own using CSS but I’d rather use the predefined quasar class, of course)

答:
I don’t think the breakpoints work on rows (only items within rows), so I think to do what you want, you would have to use the Vue Class Bindings with breakpoints or platform detection. Something like:</p>

```<code><div class="row">
  <div :class="$q.platform.is.mobile ? 'justify-end' : 'justify-center'"  class="row col-12 bg-black">
    <div class="col-sm-4 col-lg-6 bg-blue q-py-md text-center">
      col-4
    </div>
  </div>
</div>
</code>```

Body:
I’m having this issue, I searched in the forum but didn’t find anything related.

I am trying to use justify-center for small screens and justify-end for large screens. Reading the docs I found this:

So I tried to use it as justify-sm-center and justify-lg-end but haven’t been able to make it work. I made this fiddle to demonstrate it:

https://jsfiddle.net/leoprada/3b40vn6g/

Class: justify-center applied when BP lg (justify-lg-center) and justify-end on BP sm (justify-sm-end)

            col-4

            Col-4

I don’t really know if I am doing something wrong.

(I know how to make it work by my own using CSS but I’d rather use the predefined quasar class, of course)

Body:
I don’t think the breakpoints work on rows (only items within rows), so I think to do what you want, you would have to use the Vue Class Bindings with breakpoints or platform detection. Something like:

<div class="row">
  <div :class="$q.platform.is.mobile ? 'justify-end' : 'justify-center'"  class="row col-12 bg-black">
    <div class="col-sm-4 col-lg-6 bg-blue q-py-md text-center">
      col-4
    </div>
  </div>
</div>