问:
MoPub initialization with SdkInitializationListener
I like to initialize MoPub SDK in Android and continue loading banners and interstitials only if SDK init is complete and successful.

What can be a good way to accomplish this?

答:
Very easy to accomplish with Android's new Livedata objects. There objects are observable and you can receive their changes wherever you want in your app.

Technology and patterns used:

Livedata

Singleton pattern

MoPub SDK 5.11.1

I will show you how by code snippets

Singleton pattern

```<code>public class MoPubSdk {

    private static MoPubSdk INSTANCE;

    public static MoPubSdk getInstance(Activity activity) {
        if(MoPubSdk.INSTANCE == null) {
            MoPubSdk.INSTANCE = new MoPubSdk(activity);
        }
        return MoPubSdk.INSTANCE;
    }

}
</code>```

Constructor with SdkInitializationListener function

Note the MutableLiveData object that changes it's value to true (isInitialized) when the listener is called and the MoPub SDK is ready to call ads. Also see the showConsentIfNeeded function which you can see in the next code block. Just comment the function if not needed.

```<code>public class MoPubSdk {

    private final MutableLiveData<Boolean> isMoPubSdkInitialized = new MutableLiveData<>();
    private Activity mActivity;

    private MoPubSdk(Activity activity) {
        this.mActivity = activity;

        SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder("ANYadunitID")
                .withLogLevel(BuildConfig.DEBUG ? MoPubLog.LogLevel.DEBUG : MoPubLog.LogLevel.NONE)
                .build();

        MoPub.initializeSdk(activity, sdkConfiguration, initSdkListener());
    }

    private SdkInitializationListener initSdkListener() {
        return new SdkInitializationListener() {
           @Override
           public void onInitializationFinished() {
           /* MoPub SDK initialized.
           Check if you should show the consent dialog here, and make your ad requests. */
                Log.d("MoPub", "SDK initialized");
                isMoPubSdkInitialized.setValue(true);
                showConsentIfNeeded();
            }
        };
    }

    public LiveData<Boolean> isMoPubSdkInitialized() {
        return isMoPubSdkInitialized;
    }
}
</code>```

Optional consent Dialog

```<code>private void showConsentIfNeeded() {
    PersonalInfoManager mPersonalInfoManager = MoPub.getPersonalInformationManager();

    Log.d("customeee", "Can collect pers information? "+MoPub.canCollectPersonalInformation()
            + ".\nShould show consent dialog? "+mPersonalInfoManager.shouldShowConsentDialog());

    if(!MoPub.canCollectPersonalInformation()) {
            if(mPersonalInfoManager.shouldShowConsentDialog()) {
            mPersonalInfoManager.loadConsentDialog(new ConsentDialogListener() {
                @Override
                public void onConsentDialogLoaded() {
                    mPersonalInfoManager.showConsentDialog();
                }

                @Override
                public void onConsentDialogLoadFailed(@NonNull MoPubErrorCode moPubErrorCode) {
                    MoPubLog.i("Consent dialog failed to load.");
                }
            });
        }
    }
}
</code>```

So much for initialization. Now let's call the MoPub SDK from an activity and continue with banner loading.

```<code>public class MyActivity extends Activity {

private MoPubSdk moPubSdk;

    protected void onCreate(final Bundle savedInstanceState) {
    moPubSdk = MoPubSdk.getInstance(this);
    moPubSdk.isMoPubSdkInitialized().observe(this, new Observer<Boolean>() {
        @Override
        public void onChanged(Boolean aBoolean) {
            if (aBoolean)
                //Init your banner here.
        }
    });
    }
}
</code>```

The LiveData is easy to explain. First time the MoPub SDK initialization begins the Livedata object is false. It takes some time to init, on success the value switches to true and the observer gets called, you can begin banner loading.

On switching activities during init or call MoPubSdk#getInstance another time, the value is already true and gets passed directly on #observe call and you init your banner straight away.

Body:
Very easy to accomplish with Android's new Livedata objects. There objects are observable and you can receive their changes wherever you want in your app.

Technology and patterns used:

Livedata

Singleton pattern

MoPub SDK 5.11.1

I will show you how by code snippets

Singleton pattern

public class MoPubSdk {

    private static MoPubSdk INSTANCE;

    public static MoPubSdk getInstance(Activity activity) {
        if(MoPubSdk.INSTANCE == null) {
            MoPubSdk.INSTANCE = new MoPubSdk(activity);
        }
        return MoPubSdk.INSTANCE;
    }

}

Constructor with SdkInitializationListener function

Note the MutableLiveData object that changes it's value to true (isInitialized) when the listener is called and the MoPub SDK is ready to call ads. Also see the showConsentIfNeeded function which you can see in the next code block. Just comment the function if not needed.

public class MoPubSdk {

    private final MutableLiveData<Boolean> isMoPubSdkInitialized = new MutableLiveData<>();
    private Activity mActivity;

    private MoPubSdk(Activity activity) {
        this.mActivity = activity;

        SdkConfiguration sdkConfiguration = new SdkConfiguration.Builder("ANYadunitID")
                .withLogLevel(BuildConfig.DEBUG ? MoPubLog.LogLevel.DEBUG : MoPubLog.LogLevel.NONE)
                .build();

        MoPub.initializeSdk(activity, sdkConfiguration, initSdkListener());
    }

    private SdkInitializationListener initSdkListener() {
        return new SdkInitializationListener() {
           @Override
           public void onInitializationFinished() {
           /* MoPub SDK initialized.
           Check if you should show the consent dialog here, and make your ad requests. */
                Log.d("MoPub", "SDK initialized");
                isMoPubSdkInitialized.setValue(true);
                showConsentIfNeeded();
            }
        };
    }

    public LiveData<Boolean> isMoPubSdkInitialized() {
        return isMoPubSdkInitialized;
    }
}

Optional consent Dialog

private void showConsentIfNeeded() {
    PersonalInfoManager mPersonalInfoManager = MoPub.getPersonalInformationManager();

    Log.d("customeee", "Can collect pers information? "+MoPub.canCollectPersonalInformation()
            + ".\nShould show consent dialog? "+mPersonalInfoManager.shouldShowConsentDialog());

    if(!MoPub.canCollectPersonalInformation()) {
            if(mPersonalInfoManager.shouldShowConsentDialog()) {
            mPersonalInfoManager.loadConsentDialog(new ConsentDialogListener() {
                @Override
                public void onConsentDialogLoaded() {
                    mPersonalInfoManager.showConsentDialog();
                }

                @Override
                public void onConsentDialogLoadFailed(@NonNull MoPubErrorCode moPubErrorCode) {
                    MoPubLog.i("Consent dialog failed to load.");
                }
            });
        }
    }
}

So much for initialization. Now let's call the MoPub SDK from an activity and continue with banner loading.

public class MyActivity extends Activity {

private MoPubSdk moPubSdk;

    protected void onCreate(final Bundle savedInstanceState) {
    moPubSdk = MoPubSdk.getInstance(this);
    moPubSdk.isMoPubSdkInitialized().observe(this, new Observer<Boolean>() {
        @Override
        public void onChanged(Boolean aBoolean) {
            if (aBoolean)
                //Init your banner here.
        }
    });
    }
}

The LiveData is easy to explain. First time the MoPub SDK initialization begins the Livedata object is false. It takes some time to init, on success the value switches to true and the observer gets called, you can begin banner loading.

On switching activities during init or call MoPubSdk#getInstance another time, the value is already true and gets passed directly on #observe call and you init your banner straight away.


来源: stackexchange

问:
change url zend
class ContactusController extends Zend_Controller_Action it result url/contactus.I like to change url/contact-us . How can i add "-" in url. Please help me to find-out the solution

答:
You can do by adding a route with Zend_Router .

```<code>$router = $this->_front->getRouter();

$router->addRoute('contactus',
    new Zend_Controller_Router_Route('contact-us',
        array(
            'controller' => 'contactus',
            'action'     => 'index',
            'category'   => null
        )
    );
);
</code>```

Can read more about it from http://framework.zend.com/manual/en/zend.controller.router.html

ContentLicense: CC BY-SA 3.0

Title: change url zend

Body:
You can do by adding a route with Zend_Router .

$router = $this->_front->getRouter();

$router->addRoute('contactus',
    new Zend_Controller_Router_Route('contact-us',
        array(
            'controller' => 'contactus',
            'action'     => 'index',
            'category'   => null
        )
    );
);

Can read more about it from http://framework.zend.com/manual/en/zend.controller.router.html


问:
How to get Collection Data from firestore
I am using firestore

I have health name collection

```<code>collection health
doc customername
collection customerinfo  // multiple
doc customerwardinfo
</code>```

Code:

```<code>firebase.firestore()
        .collection("health")
        .doc('customername')
        .get()
        .then((data)=>{
            console.log("customer data",data);
        })
</code>```

i am using the above code but not getting data. i want to use for each for some sub collections. but i am not able to implement it. how i will get all data. suppose a collection has 10 docs. then use foreach for each doc and get data from each doc.

答:
.doc().get() does NOT return a promise of the Document; it returns a promise of a DocumentSnapshot, which contains a great deal MORE than just the document.
https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentSnapshot

As you can see, DocumentSnapshot has properties "exists", "metadata", "id" and "ref", and methods "data()" [which returns an object with the document fields - the data], "get()" [which can return specified fields from the document], and "isEqual()", which can compare DocumentSnapshots.

on .doc().get().get() - while the final result would be only the requested fields, the entire document is fetched from the database/store.

As  Frank van Puffelen mentions, there is no way to retrieve a list of sub-collections - Firestore does NOT enforce or document your schema; that's your job as a developer.

Tracy Hall

ContentLicense: CC BY-SA 4.0

Body:
I am using firestore

I have health name collection

collection health
doc customername
collection customerinfo  // multiple
doc customerwardinfo

Code:

firebase.firestore()
        .collection("health")
        .doc('customername')
        .get()
        .then((data)=>{
            console.log("customer data",data);
        })

i am using the above code but not getting data. i want to use for each for some sub collections. but i am not able to implement it. how i will get all data. suppose a collection has 10 docs. then use foreach for each doc and get data from each doc.


问:
CORS error working only for one controller
I am working on a dotnet core web api.

My API is hosted on localhost:44366
and My client side application is hosted at http://127.0.0.1:5501/ (using vs code live server)

I am making two POST request using a submit button
Previously I faced the following issue when I was making one POST request:

```<code>Access to XMLHttpRequest at 'https://localhost:44366/api/surveycreatoroptions' from origin
'http://127.0.0.1:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.
</code>```

I have tried the [EnableCors("AllowMyOrigin")] method on both the controllers.

It works the for the first request but not for the second request (giving the same error)

This is what I have used for Enabling CORS

```<code> services.AddCors(options =>
            {
            options.AddPolicy("AllowMyOrigin",
             builder => builder.WithOrigins("http://127.0.0.1:5501").AllowAnyMethod().AllowAnyHeader())
             ;
            });

        }
</code>```

How can I make it work for both the requests.

答:
I encountered your problem. For solve this firstly add this code to startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
     services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
     {
      builder.AllowAnyMethod()
             .AllowAnyHeader()
             .AllowAnyOrigin()
             .AllowCredentials();
        }));
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });
  }}

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DiagnosticListener diagnosticListenerSource, DiagnosticObserver diagnosticObserver)
 {
        app.UseCors("MyPolicy");
 }
</code>```

Then "Access-Control-Allow-Origin" should be added to the api send request header.

Typescript example:

```<code>fetch(window.appSettings.API_URL + path, {
        redirect: 'follow',
        method,
        body: data === null ? null : JSON.stringify(data),
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            Authorization: 'Bearer ' + bToken,
        },
    });
</code>```

You can change origin if you want for security

Body:
I am working on a dotnet core web api.

My API is hosted on localhost:44366
and My client side application is hosted at http://127.0.0.1:5501/ (using vs code live server)

I am making two POST request using a submit button
Previously I faced the following issue when I was making one POST request:

Access to XMLHttpRequest at 'https://localhost:44366/api/surveycreatoroptions' from origin
'http://127.0.0.1:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.

I have tried the [EnableCors("AllowMyOrigin")] method on both the controllers.

It works the for the first request but not for the second request (giving the same error)

This is what I have used for Enabling CORS

 services.AddCors(options =>
            {
            options.AddPolicy("AllowMyOrigin",
             builder => builder.WithOrigins("http://127.0.0.1:5501").AllowAnyMethod().AllowAnyHeader())
             ;
            });

        }

How can I make it work for both the requests.

Body:
I encountered your problem. For solve this firstly add this code to startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
     {
      builder.AllowAnyMethod()
             .AllowAnyHeader()
             .AllowAnyOrigin()
             .AllowCredentials();
        }));
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });
  }}

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DiagnosticListener diagnosticListenerSource, DiagnosticObserver diagnosticObserver)
 {
        app.UseCors("MyPolicy");
 }

Then "Access-Control-Allow-Origin" should be added to the api send request header.

Typescript example:

fetch(window.appSettings.API_URL + path, {
        redirect: 'follow',
        method,
        body: data === null ? null : JSON.stringify(data),
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            Authorization: 'Bearer ' + bToken,
        },
    });

You can change origin if you want for security


问:
How would it be possible to use variadic function without passing number of arguments and only with 3 dots?
Considering the code below, is it possible to define a variadic function without getting number of arguments?</p>

```<code>void printFunction(...)
{
    int noOfArgs = "Any way to get number of arguments?";
    va_list args;
    va_start(args, noOfArgs);
    cout << va_arg(args, int) << endl;
    for (int i = 2; i <= noOfArgs; i++)
    {
        cout << va_arg(args, int) << endl;
    }
    va_end(args);
}

int main()
{

    printFunction(1, 2, 3, 4, 5);

    return 0;
}
</code>```

答:
Getting the amount of arguments is not possible in C va_args. The best you can do is to use a magic value that ends the sequence and a macro to hide it from your user:

```<code>#define printFunction(...) actualPrintFunction(__VA_ARGS__, 42)
void actualPrintFunction(int first, ...)
{
    va_list args;
    va_start(args, first);
    int arg;
    std::cout << first << endl;
    while((arg = va_arg(args, int)) != 42)
    {
        cout << arg << endl;
    }
    va_end(args);
}
</code>```

As mentioned in the comments, you could alternatively use C++ fold expressions. The above has the advantage of being compatible with C and compiling faster, while the C++ approach gives you type safety.

Body:
Considering the code below, is it possible to define a variadic function without getting number of arguments?

void printFunction(...)
{
    int noOfArgs = "Any way to get number of arguments?";
    va_list args;
    va_start(args, noOfArgs);
    cout << va_arg(args, int) << endl;
    for (int i = 2; i <= noOfArgs; i++)
    {
        cout << va_arg(args, int) << endl;
    }
    va_end(args);
}

int main()
{

    printFunction(1, 2, 3, 4, 5);

    return 0;
}

Body:
Getting the amount of arguments is not possible in C va_args. The best you can do is to use a magic value that ends the sequence and a macro to hide it from your user:

#define printFunction(...) actualPrintFunction(__VA_ARGS__, 42)
void actualPrintFunction(int first, ...)
{
    va_list args;
    va_start(args, first);
    int arg;
    std::cout << first << endl;
    while((arg = va_arg(args, int)) != 42)
    {
        cout << arg << endl;
    }
    va_end(args);
}

As mentioned in the comments, you could alternatively use C++ fold expressions. The above has the advantage of being compatible with C and compiling faster, while the C++ approach gives you type safety.


问:
Generators Firebird - Entity Framework Code First .Net
I used Code First to create 2 tables (Master and Details), the problem is that Entity Framework inserted the same Generator for both tables, so when I insert a new record the trigger skips the ID numbering (1,3,5... for Master and 2,4,6... for Details) What I want is: Master ID equals 1,2,3... and Details ID equals 1,2,3... I know how to correct it in the database is just to add a new genarator and correct both triggers with the respective Generators, but how to avoid it when using Code First, is there a way to use Data Annotations in the classes? or are there another way to do it?

答: You can customize the behavior using IFbMigrationSqlGeneratorBehavior. You can also get a head start by using DefaultFbMigrationSqlGeneratorBehavior.


问:
Transform multi-row string to csv in Python
What is the best way to take this string:

```<code>1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d
</code>```

and transform to a CSV containing 6 columns?

Desired output

Is a CSV which will be imported into Pandas:

```<code>1,a,1,a,1,a
2,b,2,b,2,b
</code>```

etc..

Updated desired output as per comments to 6 rows.

Updated.  I can get the first row like this if I assign the string to l variable:

```<code>l.split()[0::4]

['1', 'a', '1', 'a', '1', 'a']
</code>```

答:
Even though Art's answer is accepted, here is another way using pandas.  You wouldn't need to export the data prior to importing with pandas if you use something like this.</p>

```<code>import pandas as pd

myFile="lines_to_read2.txt"
myData = pd.DataFrame (columns=['col1', 'col2', 'col3','col4'])
mycolumns = 4
thisItem = list()

with open(myFile, 'r') as linesToRead:
    for thisLine in linesToRead:
        thisItem.append(thisLine.strip('\n, " "'))
        if len(thisItem) == mycolumns:
            myData = myData.append({'col1':thisItem[0],'col2':thisItem[1],'col3':thisItem[2],'col4':thisItem[3]}, ignore_index=True)
            thisItem = list()

myData.to_csv('lines_as_csv_file.csv', index=False)
print(myData)   # Full Table
</code>```

Body:
What is the best way to take this string:

1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d
1
2
3
4
a
b
c
d

and transform to a CSV containing 6 columns?

Desired output

Is a CSV which will be imported into Pandas:

1,a,1,a,1,a
2,b,2,b,2,b

etc..

Updated desired output as per comments to 6 rows.

Updated.  I can get the first row like this if I assign the string to l variable:

l.split()[0::4]

['1', 'a', '1', 'a', '1', 'a']

Body:
Even though Art's answer is accepted, here is another way using pandas.  You wouldn't need to export the data prior to importing with pandas if you use something like this.

import pandas as pd

myFile="lines_to_read2.txt"
myData = pd.DataFrame (columns=['col1', 'col2', 'col3','col4'])
mycolumns = 4
thisItem = list()

with open(myFile, 'r') as linesToRead:
    for thisLine in linesToRead:
        thisItem.append(thisLine.strip('\n, " "'))
        if len(thisItem) == mycolumns:
            myData = myData.append({'col1':thisItem[0],'col2':thisItem[1],'col3':thisItem[2],'col4':thisItem[3]}, ignore_index=True)
            thisItem = list()

myData.to_csv('lines_as_csv_file.csv', index=False)
print(myData)   # Full Table


问:
Cannot have plivo send sms working
I'm using Plivo PHP library to send sms via plivo.

I'm setting the correct auth credentials in the library and it is base64 encoded as per the library in curl_request method.

I think the headers are correct and My integration with my platform works fine but when trying the send a simple message with send_message method, I cannot have it working and always get a response status 401 which is, as per the documentation, an error of authentication.

What Am I doing wrong ?

Many Thanks

My code:

```<code>//Load library messages
                $this->load->library( 'Plivo' );
                $p = new RestAPI( 'MANXXXXXXXXXXXXXZIWOD', 'MmXXXXXXXXXXXXXXXXXXXXXXXXXXXX' );

                // //for each phone Numbers generate password associated to event
                foreach ( $nums as $key => $num ) {
                    //For each combo send Message
                    $params = array(
                            'src' => '13307782635', // Sender's phone number with country code (US)
                            'dst' => '447598XXXXXX', // Receiver's phone number with country code (UK)
                            'text' => 'Hi, Message from your fired', // Your SMS text message
                            'url' => site_url( 'eventPromotion/report' ), // The URL to which with the status of the message is sent
                            'method' => 'POST' // The method used to call the url
                        );
                    // Send message
                    $response = $p->send_message($params);

                    // Print the response
                    echo "Response : ";
                    var_dump( $response );
</code>```

答:
For sending sms in Plivo using curl, you will get return proper JSON from plivo api</p>

```<code>$auth_id = 'auth_id';
$auth_token = 'auth_token';
$src = '+1XXXXXXXXXXX';
$dst = '+1XXXXXXXXXXX';

$text = 'Hello, this is testing message';

    $api = curl_init("https://api.plivo.com/v1/Account/$auth_id/Message/");
    curl_setopt_array($api, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => array("Authorization: Basic ".base64_encode($auth_id.':'.$auth_token)),
        CURLOPT_POSTFIELDS => array(
            'src' =>$src,
            'dst' => $dst,
            'text' => $text
        )
    ));

    $resp = curl_exec($api);

    $resp = curl_exec($api);
    curl_close($api);

    var_dump($resp);
</code>```

Title: Cannot have plivo send sms working

Body:
I'm using Plivo PHP library to send sms via plivo.

I'm setting the correct auth credentials in the library and it is base64 encoded as per the library in curl_request method.

I think the headers are correct and My integration with my platform works fine but when trying the send a simple message with send_message method, I cannot have it working and always get a response status 401 which is, as per the documentation, an error of authentication.

What Am I doing wrong ?

Many Thanks

My code:

//Load library messages
                $this->load->library( 'Plivo' );
                $p = new RestAPI( 'MANXXXXXXXXXXXXXZIWOD', 'MmXXXXXXXXXXXXXXXXXXXXXXXXXXXX' );

                // //for each phone Numbers generate password associated to event
                foreach ( $nums as $key => $num ) {
                    //For each combo send Message
                    $params = array(
                            'src' => '13307782635', // Sender's phone number with country code (US)
                            'dst' => '447598XXXXXX', // Receiver's phone number with country code (UK)
                            'text' => 'Hi, Message from your fired', // Your SMS text message
                            'url' => site_url( 'eventPromotion/report' ), // The URL to which with the status of the message is sent
                            'method' => 'POST' // The method used to call the url
                        );
                    // Send message
                    $response = $p->send_message($params);

                    // Print the response
                    echo "Response : ";
                    var_dump( $response );

Body:
For sending sms in Plivo using curl, you will get return proper JSON from plivo api

$auth_id = 'auth_id';
$auth_token = 'auth_token';
$src = '+1XXXXXXXXXXX';
$dst = '+1XXXXXXXXXXX';

$text = 'Hello, this is testing message';

    $api = curl_init("https://api.plivo.com/v1/Account/$auth_id/Message/");
    curl_setopt_array($api, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => array("Authorization: Basic ".base64_encode($auth_id.':'.$auth_token)),
        CURLOPT_POSTFIELDS => array(
            'src' =>$src,
            'dst' => $dst,
            'text' => $text
        )
    ));

    $resp = curl_exec($api);

    $resp = curl_exec($api);
    curl_close($api);

    var_dump($resp);


问:
R tmap sf Error: arguments imply differing number of rows when viewing map
I am trying to create a map of all school districts in each state.  The code below works for all states, except in Florida I get this error:
Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 67, 121

```<code>require(dplyr)
require(sf)
library(tmap)
require(lwgeom)

  temp <- tempfile()  ### create a temporary file to download zip file to
  temp2 <- tempfile() ### create a temporary file to put unzipped files in
  download.file("https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/SD+shapes/2018/shapefile_1718.zip", temp) # downloading the data into the tempfile

  unzip(zipfile = temp, exdir = temp2) # unzipping the temp file and putting unzipped data in temp2

  filename <- list.files(temp2, full.names = TRUE) # getting the filename of the downloaded data

  shp_file <- filename %>%
    subset(grepl("*.shp$", filename)) ## selecting only the .shp file to read in

  state_shape <- sf::st_read(shp_file) %>% ## reading in the downloaded data
    dplyr::mutate(GEOID = as.character(GEOID),
                  GEOID = stringr::str_pad(GEOID, width = 7, pad = "0")) %>%
    filter(State == "Florida")

  url = "https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/Master/2017/full_data_17_geo_exc.csv"
  master <- read.csv(file = url, stringsAsFactors = FALSE) %>%
    dplyr::mutate(NCESID = as.character(NCESID),
                  NCESID = stringr::str_pad(NCESID, width = 7, pad = "0"),
                  year = "2017") %>%
    dplyr::select(-NAME, -State, -STATE_FIPS) ## removing variables that duplicate with shapes

  state_shape <- state_shape %>%
    dplyr::left_join(master, by = c("GEOID" = "NCESID")) %>%
    select(GEOID, NAME, State, StPovRate)

  shape.clean <- lwgeom::st_make_valid(state_shape) # making all geometries valid

  povertyBlues <-  c('#dff3fe', '#92DCF0', '#49B4D6', '#2586a5', '#19596d')

  map <- tm_shape(shape.clean) +
    tm_fill("StPovRate", breaks=c(0, .1, .2, .3, .4, 1), title = "Student Poverty",
            palette = povertyBlues,
            legend.format=list(fun=function(x) paste0(formatC(x*100, digits=0, format="f"), " %"))) +
    tm_shape(shape.clean) +
    tm_borders(lwd=.25, col = "#e9e9e9", alpha = 1) +
    tm_layout(inner.margins = c(.05,.25,.1,.05))

  map  ### view the map
</code>```

The length of the tm_shape$shp and state_shape are both 67.  Does anyone know what could be causing the "arguments imply differing number of rows: 67, 121"?

Thanks!!

答:
I was not able to get these shapes to print using tmap, but I was able to manually remove the problems points and lines so that they don't trigger errors in tmap.  Both Florida and Nebraska had geometry collections in them, so I used the following script to remove any line or points and change the geometry collections to multipolygons.  I am sure there is a better way, and would be happy to hear them if others have a more elegant solution.  This, at least, allows me to move on!</p>

```<code>### Create an st_is function that works for many types
st_is = function(x, type) UseMethod("st_is")

st_is.sf = function(x, type)
  st_is(st_geometry(x), type)

st_is.sfc = function(x, type)
  vapply(x, sf:::st_is.sfg, type, FUN.VALUE = logical(1))

st_is.sfg = function(x, type)
  class(x)[2L] %in% type

####### Correct Florida #########

#### import my florida file
  temp <- tempfile()  ### create a temporary file to download zip file to
  temp2 <- tempfile() ### create a temporary file to put unzipped files in
  download.file("https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/SD+shapes/2018/shapefile_1718.zip", temp) # downloading the data into the tempfile

  unzip(zipfile = temp, exdir = temp2) # unzipping the temp file and putting unzipped data in temp2

  filename <- list.files(temp2, full.names = TRUE) # getting the filename of the downloaded data

  shp_file <- filename %>%
    subset(grepl("*.shp$", filename)) ## selecting only the .shp file to read in

  florida <- sf::st_read(shp_file) %>% ## reading in the downloaded data
    filter(State == "Florida")

#### extract polygon shapes from any geometry collection
solution <- for (i in florida) {
  for(j in seq_along(i)) {
    if (class(i[[j]]) != "character" & class(i[[j]]) != "double" & class(i[[j]]) != "numeric") {
      if (st_is.sf(i[[j]], c("GEOMETRYCOLLECTION"))) {
        i[[j]] <- st_collection_extract(i[[j]], type = c("POLYGON"))
      }
      else {
        next
      }
    }
    else {
      next
    }
  }
}

florida_clean <- florida
st_geometry(florida_clean) <- NULL #### remove geometry from original florida
sfc_geo <- sf::st_sfc(i)  #### define i as an sfc
florida_clean$geometry <- sfc_geo  #### attach i to florida
florida_clean <- sf::st_set_geometry( florida_clean, sfc_geo )  ### set florida's geometry as i, with the points and lines removed
</code>```

Body:
I am trying to create a map of all school districts in each state.  The code below works for all states, except in Florida I get this error:
Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 67, 121

require(dplyr)
require(sf)
library(tmap)
require(lwgeom)

  temp <- tempfile()  ### create a temporary file to download zip file to
  temp2 <- tempfile() ### create a temporary file to put unzipped files in
  download.file("https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/SD+shapes/2018/shapefile_1718.zip", temp) # downloading the data into the tempfile

  unzip(zipfile = temp, exdir = temp2) # unzipping the temp file and putting unzipped data in temp2

  filename <- list.files(temp2, full.names = TRUE) # getting the filename of the downloaded data

  shp_file <- filename %>%
    subset(grepl("*.shp$", filename)) ## selecting only the .shp file to read in

  state_shape <- sf::st_read(shp_file) %>% ## reading in the downloaded data
    dplyr::mutate(GEOID = as.character(GEOID),
                  GEOID = stringr::str_pad(GEOID, width = 7, pad = "0")) %>%
    filter(State == "Florida")

  url = "https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/Master/2017/full_data_17_geo_exc.csv"
  master <- read.csv(file = url, stringsAsFactors = FALSE) %>%
    dplyr::mutate(NCESID = as.character(NCESID),
                  NCESID = stringr::str_pad(NCESID, width = 7, pad = "0"),
                  year = "2017") %>%
    dplyr::select(-NAME, -State, -STATE_FIPS) ## removing variables that duplicate with shapes

  state_shape <- state_shape %>%
    dplyr::left_join(master, by = c("GEOID" = "NCESID")) %>%
    select(GEOID, NAME, State, StPovRate)

  shape.clean <- lwgeom::st_make_valid(state_shape) # making all geometries valid

  povertyBlues <-  c('#dff3fe', '#92DCF0', '#49B4D6', '#2586a5', '#19596d')

  map <- tm_shape(shape.clean) +
    tm_fill("StPovRate", breaks=c(0, .1, .2, .3, .4, 1), title = "Student Poverty",
            palette = povertyBlues,
            legend.format=list(fun=function(x) paste0(formatC(x*100, digits=0, format="f"), " %"))) +
    tm_shape(shape.clean) +
    tm_borders(lwd=.25, col = "#e9e9e9", alpha = 1) +
    tm_layout(inner.margins = c(.05,.25,.1,.05))

  map  ### view the map

The length of the tm_shape$shp and state_shape are both 67.  Does anyone know what could be causing the "arguments imply differing number of rows: 67, 121"?

Thanks!!

Body:
I was not able to get these shapes to print using tmap, but I was able to manually remove the problems points and lines so that they don't trigger errors in tmap.  Both Florida and Nebraska had geometry collections in them, so I used the following script to remove any line or points and change the geometry collections to multipolygons.  I am sure there is a better way, and would be happy to hear them if others have a more elegant solution.  This, at least, allows me to move on!

### Create an st_is function that works for many types
st_is = function(x, type) UseMethod("st_is")

st_is.sf = function(x, type)
  st_is(st_geometry(x), type)

st_is.sfc = function(x, type)
  vapply(x, sf:::st_is.sfg, type, FUN.VALUE = logical(1))

st_is.sfg = function(x, type)
  class(x)[2L] %in% type

####### Correct Florida #########

#### import my florida file
  temp <- tempfile()  ### create a temporary file to download zip file to
  temp2 <- tempfile() ### create a temporary file to put unzipped files in
  download.file("https://s3.amazonaws.com/data.edbuild.org/public/Processed+Data/SD+shapes/2018/shapefile_1718.zip", temp) # downloading the data into the tempfile

  unzip(zipfile = temp, exdir = temp2) # unzipping the temp file and putting unzipped data in temp2

  filename <- list.files(temp2, full.names = TRUE) # getting the filename of the downloaded data

  shp_file <- filename %>%
    subset(grepl("*.shp$", filename)) ## selecting only the .shp file to read in

  florida <- sf::st_read(shp_file) %>% ## reading in the downloaded data
    filter(State == "Florida")

#### extract polygon shapes from any geometry collection
solution <- for (i in florida) {
  for(j in seq_along(i)) {
    if (class(i[[j]]) != "character" & class(i[[j]]) != "double" & class(i[[j]]) != "numeric") {
      if (st_is.sf(i[[j]], c("GEOMETRYCOLLECTION"))) {
        i[[j]] <- st_collection_extract(i[[j]], type = c("POLYGON"))
      }
      else {
        next
      }
    }
    else {
      next
    }
  }
}

florida_clean <- florida
st_geometry(florida_clean) <- NULL #### remove geometry from original florida
sfc_geo <- sf::st_sfc(i)  #### define i as an sfc
florida_clean$geometry <- sfc_geo  #### attach i to florida
florida_clean <- sf::st_set_geometry( florida_clean, sfc_geo )  ### set florida's geometry as i, with the points and lines removed


问:
How do I get some data from a website which requires authentication with Ansbile?
I have been trying to login a web page and get/download some specific data from there, but couldn't make it. Is it possible? </p>

答:
If you need to download a specific file, and you can get it via http://username:password@example.com/path/file.conf then you can use the get_url module:

```<code>- name: < Fetch file that requires authentication.
  get_url:
    url: http://example.com/path/file.conf
    dest: /etc/foo.conf
    url_username: bar
    url_password: '{{ mysecret }}'
</code>```

https://docs.ansible.com/ansible/latest/modules/get_url_module.html

Body:
If you need to download a specific file, and you can get it via http://username:password@example.com/path/file.conf then you can use the get_url module:

- name: < Fetch file that requires authentication.
  get_url:
    url: http://example.com/path/file.conf
    dest: /etc/foo.conf
    url_username: bar
    url_password: '{{ mysecret }}'

https://docs.ansible.com/ansible/latest/modules/get_url_module.html


问:
How can I add two Vector3's together in unity
I am making a 2d shooter game. I have a Gameobject that is "Gun" when the Player Gameobject touches the gun it goes to the position of the player. However, I then would like to move the gun from that position on the player sprite to the sprits hand. I thought that the easiest method to do this would be to add a Vector on to the starting vector, to change the coordinates of the gun. However I am not sure how to add the vectors, this is what I have tried but it comes up with the error: 'Vector3' cannot be used as a method.  </p>

```<code>Vector3 coords = GameObject.FindGameObjectWithTag("Gun").transform.position = GameObject.FindGameObjectWithTag("Player").transform.position;
Vector3 newcoords = coords + Vector3(1, 1, 0)
</code>```

答:
You have to create instance of the Vector3:

Vector3 newcoords = coords + new Vector3(1, 1, 0)
```

Body:
I am making a 2d shooter game. I have a Gameobject that is "Gun" when the Player Gameobject touches the gun it goes to the position of the player. However, I then would like to move the gun from that position on the player sprite to the sprits hand. I thought that the easiest method to do this would be to add a Vector on to the starting vector, to change the coordinates of the gun. However I am not sure how to add the vectors, this is what I have tried but it comes up with the error: 'Vector3' cannot be used as a method.

Vector3 coords = GameObject.FindGameObjectWithTag("Gun").transform.position = GameObject.FindGameObjectWithTag("Player").transform.position;
Vector3 newcoords = coords + Vector3(1, 1, 0)


问:
Kotlin Mockk Error: Missing calls inside verify { ... } block
I already read some issues with this or a similar error message (it is also ocurring for every {}), but none of them took me to a success result.

Any hints or suggestions on how to get this to work?

Here is my setup and the Unit Test itself:

```<code>compileSdkVersion 29
defaultConfig {
   minSdkVersion 19
   targetSdkVersion 29
   testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

MockK version: 1.9.3.kotlin12
OS: Android
Kotlin version: 1.3.61
JDK version: jdk1.8.0_212
JUnit version: 4.12
Type of test: unit test
</code>```

The stacktrace of the error:

```<code>io.mockk.MockKException: Missing calls inside verify { ... } block.

    at io.mockk.impl.recording.states.VerifyingState.checkMissingCalls(VerifyingState.kt:52)
    at io.mockk.impl.recording.states.VerifyingState.recordingDone(VerifyingState.kt:21)
    at io.mockk.impl.recording.CommonCallRecorder.done(CommonCallRecorder.kt:47)
    at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:60)
    at io.mockk.impl.eval.VerifyBlockEvaluator.verify(VerifyBlockEvaluator.kt:30)
    at io.mockk.MockKDsl.internalVerify(API.kt:118)
    at io.mockk.MockKKt.verify(MockK.kt:139)
    at io.mockk.MockKKt.verify$default(MockK.kt:136)
</code>```

My Unit Test:

```<code>@Test
fun logout_clearsDatabase() {
    coroutineTestRule.testDispatcher.runBlockingTest {

        // ARRANGE
        database.dataDao().insert(listOf(DataDummies()))

        // ACT
        sut.logout()

        // ASSERT
        verify { database.clearAllTables() }
    }
}
</code>```

I have no clue what I did wrong here. database.clearAllTables() is a method provided by Room. The testDispatcher is a TestCoroutineDispatcher() provided by the androidx testing library.

UPDATE / ANSWER

Thanks to the input of @Juan Cruy Soler I changed the way of injecting the database. I did not return the real room database, instead I return a spy of it. That way the spy is injected into the SUT as well as into my test class. After that change the test runs as excpected. I this a feasible solution to my problem? Does it make sense to let the (Testing-)DependencyInjection create a spy?

答:
database should be mock or a spy to call verify on it.

I assume that it's not a mock because you are calling the method dataDao() in a previous line.

If you don't want to mock it you can use a real database instead, check that database.dataDao().getData() returns an empty list and remove the verify line.

If you mock it, then you can remove this line database.dataDao().insert(listOf(DataDummies()))

Body:
I already read some issues with this or a similar error message (it is also ocurring for every {}), but none of them took me to a success result.

Any hints or suggestions on how to get this to work?

Here is my setup and the Unit Test itself:

compileSdkVersion 29
defaultConfig {
   minSdkVersion 19
   targetSdkVersion 29
   testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

MockK version: 1.9.3.kotlin12
OS: Android
Kotlin version: 1.3.61
JDK version: jdk1.8.0_212
JUnit version: 4.12
Type of test: unit test

The stacktrace of the error:

io.mockk.MockKException: Missing calls inside verify { ... } block.

    at io.mockk.impl.recording.states.VerifyingState.checkMissingCalls(VerifyingState.kt:52)
    at io.mockk.impl.recording.states.VerifyingState.recordingDone(VerifyingState.kt:21)
    at io.mockk.impl.recording.CommonCallRecorder.done(CommonCallRecorder.kt:47)
    at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:60)
    at io.mockk.impl.eval.VerifyBlockEvaluator.verify(VerifyBlockEvaluator.kt:30)
    at io.mockk.MockKDsl.internalVerify(API.kt:118)
    at io.mockk.MockKKt.verify(MockK.kt:139)
    at io.mockk.MockKKt.verify$default(MockK.kt:136)

My Unit Test:

@Test
fun logout_clearsDatabase() {
    coroutineTestRule.testDispatcher.runBlockingTest {

        // ARRANGE
        database.dataDao().insert(listOf(DataDummies()))

        // ACT
        sut.logout()

        // ASSERT
        verify { database.clearAllTables() }
    }
}

I have no clue what I did wrong here. database.clearAllTables() is a method provided by Room. The testDispatcher is a TestCoroutineDispatcher() provided by the androidx testing library.

UPDATE / ANSWER

Thanks to the input of @Juan Cruy Soler I changed the way of injecting the database. I did not return the real room database, instead I return a spy of it. That way the spy is injected into the SUT as well as into my test class. After that change the test runs as excpected. I this a feasible solution to my problem? Does it make sense to let the (Testing-)DependencyInjection create a spy?


问:
pandas count ranges in on two data frame
assuming I have two dataframes:
(1) list of ranges
(2) actual values

```<code>import pandas as pd
import numpy as np
from datetime import datetime, timedelta

SLA = {'Wertebereich': [5, 10, 15, 20, 25]}
SLA = pd.DataFrame(data=SLA)

messwerte = pd.DataFrame(np.random.randint(0,30,size=10),
                  columns=["Messwerte"],
                  index=pd.date_range("20180101", periods=10))

       Wertebereich
0             5
1            10
2            15
3            20
4            25

            Messwerte
2018-01-01         22
2018-01-02         13
2018-01-03         14
2018-01-04         17
2018-01-05          1
2018-01-06         11
2018-01-07         17
2018-01-08          6
2018-01-09          4
2018-01-10         10
</code>```

I now want to add a new column to SLA ("Count") where I sum up all occurrences within each range.

I've created an iterating solution but was wondering if there is a more pandas way which can also handle 10000x3000 rows faster than my solution.

```<code>import pandas as pd
import numpy as np
from datetime import datetime, timedelta

SLA = {'Wertebereich': [5, 10, 15, 20, 25]}
SLA = pd.DataFrame(data=SLA)

messwerte = pd.DataFrame(np.random.randint(0,30,size=10),
                  columns=["Messwerte"],
                  index=pd.date_range("20180101", periods=10))

#print(SLA.to_string())
#print(messwerte.to_string())

###############
SLA["Count"] = 0

for i in range(0, len(SLA)-1):
    counter = 0
    treshold_min = SLA.iloc[i].get('Wertebereich')
    treshold_max = SLA.iloc[i+1].get('Wertebereich')
    for x in range(0, len(messwerte)):
        val = messwerte.iloc[x].get('Messwerte')
        print('---- ' + str(val) )
        if ((val >= treshold_min) & (val < treshold_max)):
            counter = counter +1

    SLA.ix[i,'Count'] = counter

print(SLA.to_string())
print(messwerte.to_string())
</code>```

any idea is appreciated.

thanks!

答:
Try this:

```<code>messwerte['Messwerte'].value_counts(bins=SLA['Wertebereich'])
</code>```

Output:

```<code>(20.0, 25.0]     5
(4.999, 10.0]    2
(10.0, 15.0]     1
(15.0, 20.0]     0
Name: Messwerte, dtype: int64
</code>```

Body:
assuming I have two dataframes:
(1) list of ranges
(2) actual values

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

SLA = {'Wertebereich': [5, 10, 15, 20, 25]}
SLA = pd.DataFrame(data=SLA)

messwerte = pd.DataFrame(np.random.randint(0,30,size=10),
                  columns=["Messwerte"],
                  index=pd.date_range("20180101", periods=10))

       Wertebereich
0             5
1            10
2            15
3            20
4            25

            Messwerte
2018-01-01         22
2018-01-02         13
2018-01-03         14
2018-01-04         17
2018-01-05          1
2018-01-06         11
2018-01-07         17
2018-01-08          6
2018-01-09          4
2018-01-10         10

I now want to add a new column to SLA ("Count") where I sum up all occurrences within each range.

I've created an iterating solution but was wondering if there is a more pandas way which can also handle 10000x3000 rows faster than my solution.

import pandas as pd
import numpy as np
from datetime import datetime, timedelta

SLA = {'Wertebereich': [5, 10, 15, 20, 25]}
SLA = pd.DataFrame(data=SLA)

messwerte = pd.DataFrame(np.random.randint(0,30,size=10),
                  columns=["Messwerte"],
                  index=pd.date_range("20180101", periods=10))

#print(SLA.to_string())
#print(messwerte.to_string())

###############
SLA["Count"] = 0

for i in range(0, len(SLA)-1):
    counter = 0
    treshold_min = SLA.iloc[i].get('Wertebereich')
    treshold_max = SLA.iloc[i+1].get('Wertebereich')
    for x in range(0, len(messwerte)):
        val = messwerte.iloc[x].get('Messwerte')
        print('---- ' + str(val) )
        if ((val >= treshold_min) & (val < treshold_max)):
            counter = counter +1

    SLA.ix[i,'Count'] = counter

print(SLA.to_string())
print(messwerte.to_string())

any idea is appreciated.

thanks!

Body:
Try this:

messwerte['Messwerte'].value_counts(bins=SLA['Wertebereich'])

Output:

(20.0, 25.0]     5
(4.999, 10.0]    2
(10.0, 15.0]     1
(15.0, 20.0]     0
Name: Messwerte, dtype: int64


问:
Vue computed function to match elements from 2 different arrays
Currently, I'm working with Vue v2.x.x. I have an array:

sectionTitles = ['Technology', 'Data', 'Poverty and Research', ...]
```
<p>and I have <code>jobsData</code> that looks like this:</p>
<pre class="lang-js prettyprint-override"><code>[{'title': 'Software Engineer', mainTag: 'Data', ...}...]
</code>```

I want to display
 in an
 when the sectionTitle matches the job.mainTag.

I was reading in the Vue docs that you shouldn't combine v-if with v-for, so I created a computed method to be able to filter the jobs. Here is what I did so far:

window.onload = function () {
    var app = new Vue({
    delimiters: ['${', '}'],
    el: '#app',
    data: {
      jobs: jobsData,
      sectionTitles: ['Data','Poverty Research Unit', 'Technology']
    },
    computed: {
      matchingTitles: function (sectionTitle) {
        return this.jobs.filter(function (job, sectionTitle) {
          job.mainTag === sectionTitle;
        })
      }
    }
  })
}
```
<pre class="lang-html prettyprint-override"><code><div id="app">
  <template v-for="title in sectionTitles">
    <h4 class="h3">{{ title }}</h4>
    <ul class="list-none p-0 color-mid-background" id="jobs-list">
      <li class="py-1 px-2" v-for="job in matchingTitles(title)">

          ${job.title}

      </li>
    </ul>
  </template>
</div>
</code>```

So basically I want to only display
 when the sectionTitle (for example Data) matches the job.mainTag. How can I go about achieving this in Vue?

答:
@depperm's answer works well (+1), but I'll offer a more render-efficient alternative. Computed properties are cached, so you could avoid the work of matchingTitles() on re-render. In addition, it might be easier to comprehend the template alone without having to jump to the implementation of matchingTitles().

I recommend computing the entire list to be iterated, mapping sectionTitles to the appropriate iterator object:

computed: {
  items() {
    return this.sectionTitles.map(title => ({
      title,
      jobs: this.jobs.filter(job => job.mainTag === title)
    }))
  }
}
```
<p>Then, you'd update the references in your template to use this new computed prop:</p>
<pre class="lang-html prettyprint-override"><code><template v-for="item in items">
  <h4>{{ item.title }}</h4>
  <ul>
    <li v-for="job in item.jobs">

        {{ job.title }}

    </li>
  </ul>
</template>
</code>```

new Vue({
  el: '#app',
    data: {
      jobs: [{'title': 'Software Engineer', mainTag: 'Data'}],
      sectionTitles: ['Data','Poverty Research Unit', 'Technology']
    },
    computed: {
      items() {
        return this.sectionTitles.map(title => ({
          title,
          jobs: this.jobs.filter(job => job.mainTag === title)
        }))
      }
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></script>
<div id="app">
  <template v-for="item in items">
    <h4 class="h3">{{ item.title }}</h4>
    <ul class="list-none p-0 color-mid-background" id="jobs-list">
      <li class="py-1 px-2" v-for="job in item.jobs">

          {{ job.title }}

      </li>
    </ul>
  </template>
</div></code>```

Body:
Currently, I'm working with Vue v2.x.x. I have an array:

sectionTitles = ['Technology', 'Data', 'Poverty and Research', ...]

and I have jobsData that looks like this:

[{'title': 'Software Engineer', mainTag: 'Data', ...}...]

I want to display
 in an
 when the sectionTitle matches the job.mainTag.

I was reading in the Vue docs that you shouldn't combine v-if with v-for, so I created a computed method to be able to filter the jobs. Here is what I did so far:

window.onload = function () {
    var app = new Vue({
    delimiters: ['${', '}'],
    el: '#app',
    data: {
      jobs: jobsData,
      sectionTitles: ['Data','Poverty Research Unit', 'Technology']
    },
    computed: {
      matchingTitles: function (sectionTitle) {
        return this.jobs.filter(function (job, sectionTitle) {
          job.mainTag === sectionTitle;
        })
      }
    }
  })
}

  <template v-for="title in sectionTitles">

{{ title }}

        <a :href="`${job.url}`">
          ${job.title}

  </template>

So basically I want to only display
 when the sectionTitle (for example Data) matches the job.mainTag. How can I go about achieving this in Vue?

Body:
@depperm's answer works well (+1), but I'll offer a more render-efficient alternative. Computed properties are cached, so you could avoid the work of matchingTitles() on re-render. In addition, it might be easier to comprehend the template alone without having to jump to the implementation of matchingTitles().

I recommend computing the entire list to be iterated, mapping sectionTitles to the appropriate iterator object:

computed: {
  items() {
    return this.sectionTitles.map(title => ({
      title,
      jobs: this.jobs.filter(job => job.mainTag === title)
    }))
  }
}

Then, you'd update the references in your template to use this new computed prop:

<template v-for="item in items">
  <h4>{{ item.title }}</h4>
  <ul>
    <li v-for="job in item.jobs">
      <a :href="job.url">
        {{ job.title }}
      </a>
    </li>
  </ul>
</template>

new Vue({
  el: '#app',
    data: {
      jobs: [{'title': 'Software Engineer', mainTag: 'Data'}],
      sectionTitles: ['Data','Poverty Research Unit', 'Technology']
    },
    computed: {
      items() {
        return this.sectionTitles.map(title => ({
          title,
          jobs: this.jobs.filter(job => job.mainTag === title)
        }))
      }
    }
})

<script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></script>
<div id="app">
  <template v-for="item in items">
    <h4 class="h3">{{ item.title }}</h4>
    <ul class="list-none p-0 color-mid-background" id="jobs-list">
      <li class="py-1 px-2" v-for="job in item.jobs">
        <a :href="job.url">
          {{ job.title }}
        </a>
      </li>
    </ul>
  </template>
</div>


问:
C# Trying to get XML inner text for nested node
I can succesfully load the XMl document and traverse the nodes. Once I get the node that I want, I start setting values. How do I deal with nested nodes?

Here is the xml:

```<code><incident>
<id>1234</id>
<number>5678</number>
<name>This is a name</name>
<state>Awaiting Input</state>
<priority>Medium</priority>
<category>
    <id>99999</id>
    <name>Applications</name>
    <default_tags>applications</default_tags>
    <parent_id nil="true" />
    <default_assignee_id nil="true" />
</category>
</code>```

Here is some C#:

```<code>   id = node.SelectSingleNode("id").InnerText;  //works fine
   number = node.SelectSingleNode("number").InnerText;  //works fine

   name = node.SelectSingleNode("name").InnerText;  //works fine
   descHTML = node.SelectSingleNode("description").InnerText;  //works fine
   desc = node.SelectSingleNode("description_no_html").InnerText;  //works fine
   state = node.SelectSingleNode("state").InnerText;  //works fine
   priority = node.SelectSingleNode("priority").InnerText;  //works fine

   catagoryID = node.SelectSingleNode("category/id").InnerText; // null reference error
   catagoryName = node.SelectSingleNode("category/name").InnerText; // null reference error
   catagoryTags = node.SelectSingleNode("category/default_tags").InnerText; // null reference error
</code>```

答:
If you are reading different elements that may or may not exist, use ?. after the SelectSingleNode method. This will ensure you dont get the error Object Reference Not Set to an Instance of an object.

?. in essence checks if there is a value before proceeding to evaluate the next method or proprety.

```<code>string xml = @"<incident>
<id>1234</id>
<number>5678</number>
<name>This is a name</name>
<state>Awaiting Input</state>
<priority>Medium</priority>
<category>
    <id>99999</id>
    <name>Applications</name>
    <default_tags>applications</default_tags>
    <parent_id nil=""true"" />
    <default_assignee_id nil=""true"" />
</category>
</incident>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        var node = doc.DocumentElement;

        var id = node.SelectSingleNode("id")?.InnerText;  //works fine
       var number = node.SelectSingleNode("number")?.InnerText;  //works fine

       var name = node.SelectSingleNode("name")?.InnerText;  //works fine
       var descHTML = node.SelectSingleNode("description")?.InnerText;  //ERRORS because there is no description.
       var desc = node.SelectSingleNode("description_no_html")?.InnerText;  //works fine
       var state = node.SelectSingleNode("state")?.InnerText;  //works fine
       var priority = node.SelectSingleNode("priority")?.InnerText;  //works fine

       var catagoryID = node.SelectSingleNode("//category/id")?.InnerText; // null reference error
       var catagoryName = node.SelectSingleNode("//category/name")?.InnerText; // null reference error
       var catagoryTags = node.SelectSingleNode("//category/default_tags")?.InnerText; // null reference error

        Console.WriteLine($"name: {name}");
        Console.WriteLine($"descHTML: {descHTML}");
        Console.WriteLine($"desc: {desc}");
        Console.WriteLine($"state: {state}");
        Console.WriteLine($"priority: {priority}");
        Console.WriteLine($"catagoryID: {catagoryID}");
        Console.WriteLine($"catagoryName: {catagoryName}");
        Console.WriteLine($"catagoryTags: {catagoryTags}");
</code>```

Output it prints out

```<code>name: This is a name
descHTML:
desc:
state: Awaiting Input
priority: Medium
catagoryID: 99999
catagoryName: Applications
catagoryTags: applications
</code>```

Code on #dotnetfiddle

Body:
I can succesfully load the XMl document and traverse the nodes. Once I get the node that I want, I start setting values. How do I deal with nested nodes?

Here is the xml:

<incident>
<id>1234</id>
<number>5678</number>
<name>This is a name</name>
<state>Awaiting Input</state>
<priority>Medium</priority>
<category>
    <id>99999</id>
    <name>Applications</name>
    <default_tags>applications</default_tags>
    <parent_id nil="true" />
    <default_assignee_id nil="true" />
</category>

Here is some C#:

   id = node.SelectSingleNode("id").InnerText;  //works fine
   number = node.SelectSingleNode("number").InnerText;  //works fine

   name = node.SelectSingleNode("name").InnerText;  //works fine
   descHTML = node.SelectSingleNode("description").InnerText;  //works fine
   desc = node.SelectSingleNode("description_no_html").InnerText;  //works fine
   state = node.SelectSingleNode("state").InnerText;  //works fine
   priority = node.SelectSingleNode("priority").InnerText;  //works fine

   catagoryID = node.SelectSingleNode("category/id").InnerText; // null reference error
   catagoryName = node.SelectSingleNode("category/name").InnerText; // null reference error
   catagoryTags = node.SelectSingleNode("category/default_tags").InnerText; // null reference error

Body:
If you are reading different elements that may or may not exist, use ?. after the SelectSingleNode method. This will ensure you dont get the error Object Reference Not Set to an Instance of an object.

?. in essence checks if there is a value before proceeding to evaluate the next method or proprety.

string xml = @"<incident>
<id>1234</id>
<number>5678</number>
<name>This is a name</name>
<state>Awaiting Input</state>
<priority>Medium</priority>
<category>
    <id>99999</id>
    <name>Applications</name>
    <default_tags>applications</default_tags>
    <parent_id nil=""true"" />
    <default_assignee_id nil=""true"" />
</category>
</incident>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        var node = doc.DocumentElement;

        var id = node.SelectSingleNode("id")?.InnerText;  //works fine
       var number = node.SelectSingleNode("number")?.InnerText;  //works fine

       var name = node.SelectSingleNode("name")?.InnerText;  //works fine
       var descHTML = node.SelectSingleNode("description")?.InnerText;  //ERRORS because there is no description.
       var desc = node.SelectSingleNode("description_no_html")?.InnerText;  //works fine
       var state = node.SelectSingleNode("state")?.InnerText;  //works fine
       var priority = node.SelectSingleNode("priority")?.InnerText;  //works fine

       var catagoryID = node.SelectSingleNode("//category/id")?.InnerText; // null reference error
       var catagoryName = node.SelectSingleNode("//category/name")?.InnerText; // null reference error
       var catagoryTags = node.SelectSingleNode("//category/default_tags")?.InnerText; // null reference error

        Console.WriteLine($"name: {name}");
        Console.WriteLine($"descHTML: {descHTML}");
        Console.WriteLine($"desc: {desc}");
        Console.WriteLine($"state: {state}");
        Console.WriteLine($"priority: {priority}");
        Console.WriteLine($"catagoryID: {catagoryID}");
        Console.WriteLine($"catagoryName: {catagoryName}");
        Console.WriteLine($"catagoryTags: {catagoryTags}");

Output it prints out

name: This is a name
descHTML:
desc:
state: Awaiting Input
priority: Medium
catagoryID: 99999
catagoryName: Applications
catagoryTags: applications

Code on #dotnetfiddle


问:
Erase and rewrite over and over again the text and card number in the same location in turtle graphics?
A concentration game requires users to be able to turn a card over many times before they correctly match it with the matching card.  This was not working consistently? It worked the first time a card was turned and immediately there after but if this card was skipped over one turn than  there after was undefined behavior.</p>
```<code>import turtle
from turtle import *
import tkinter.font
from tkinter import *
import time

t = turtle.Turtle()
screen = Screen()
screen.setup(width=800, height=800, startx=10, starty=10)
eraseble = []

''' this function allows the square to be erased and rewriten '''
def erasableWrite(tortoise, name, font, align, reuse=None):
    eraser = turtle.Turtle() if reuse is None else reuse
    eraser.hideturtle()
    eraser.up()
    eraser.setposition(tortoise.position())
    eraser.write(name, font=font, align=align)
    print('eraser = {} name = {}.'.format(eraser, name))
    return eraser

startX = -280
startY = -295
textValue = [('1', 'a'), ('2', 'b'), ('3', 'c')]
t.hideturtle()
turtle.speed(0)
t.penup()
counter = 0
count = 0
for n in range(3):
    t.goto(startX, startY)
    t.pendown()
    eraseble.append(erasableWrite(t, textValue[n][0], font=("New Times Roman", 18, "normal"), align="center"))
    print('count = {}, eraseble[counter] = {} counter = {} n = {} textvalue = {}.  '.format(count, eraseble[counter], counter, n, textValue[n][0]))
    time.sleep(2)
    count += 1
    eraseble[counter].clear()
    eraseble.append(erasableWrite(t, textValue[n][1], font=("New Times Roman", 18, "normal"), align="center"))
    time.sleep(2)
    eraseble[counter + 1].clear()
    print('eraseble[counter] = {} counter = {} n = {} textvalue = {}.  '.format(eraseble[counter], counter, n, textValue[n][1]))
    eraseble[counter -1] = (erasableWrite(t, textValue[n][0], font=("New Times Roman", 18, "normal"), align="center"))
    count +=1
    startX +=40
    startY += 20
    t.penup()
    counter +=2

` replace 1 with a `
startX = -280
startY = -295
t.goto(startX, startY)
print('count = {}, eraseble[0] = {}'.format(count, eraseble[0]))
count +=1
eraseble[0].clear()
textVal = textValue[0][0]
eraseble[0] = (erasableWrite(t, textVal, font=("New Times Roman", 18, "normal"), align="center"))
print('count = {}, eraseble[0] = {}'.format(count, eraseble[0]))
count +=1
eraseble[0].clear()
textVal = textValue[0][1]
eraseble[1] = (erasableWrite(t, textVal, font=("New Times Roman", 18, "normal"), align="center"))
time.sleep(2)

print('\n\neraseble = {}   !...!'.format(eraseble))
</code>```

答:
You seem to be confusing how the return value, and reuse argument to erasableWrite work.  I've rewritten your example code below (exaggerating the font and distances slightly):

```<code>from turtle import Screen, Turtle
import time

FONT = ("New Times Roman", 24, "bold")

def erasableWrite(tortoise, name, font, align, reuse=None):
    eraser = Turtle() if reuse is None else reuse
    eraser.hideturtle()
    eraser.up()
    eraser.setposition(tortoise.position())
    eraser.write(name, font=font, align=align)

    return eraser

screen = Screen()
screen.setup(width=800, height=800, startx=10, starty=10)

turtle = Turtle()
turtle.hideturtle()
turtle.penup()

erasable = []

startX = -280
startY = -295
textValue = [('1', 'a'), ('2', 'b'), ('3', 'c')]

for n in range(3):
    turtle.goto(startX, startY)

    erasable.append(erasableWrite(turtle, textValue[n][0], font=FONT, align="center"))
    time.sleep(2)
    erasable[n].clear()

    erasableWrite(turtle, textValue[n][1], font=FONT, align="center", reuse=erasable[n])
    time.sleep(2)
    erasable[n].clear()

    erasableWrite(turtle, textValue[n][0], font=FONT, align="center", reuse=erasable[n])

    startX += 80
    startY += 40

time.sleep(2)

startX = -280
startY = -295
turtle.goto(startX, startY)

erasable[0].clear()
textVal = textValue[0][1]
erasableWrite(turtle, textVal, font=FONT, align="center", reuse=erasable[0])
time.sleep(2)

erasable[0].clear()
textVal = textValue[0][0]
erasableWrite(turtle, textVal, font=FONT, align="center", reuse=erasable[0])
time.sleep(2)

screen.mainloop()
</code>```

It displays the three "cards" and their values, and then goes back and exposes the first card's value again before covering it up.

Body:
A concentration game requires users to be able to turn a card over many times before they correctly match it with the matching card.  This was not working consistently? It worked the first time a card was turned and immediately there after but if this card was skipped over one turn than  there after was undefined behavior.

import turtle
from turtle import *
import tkinter.font
from tkinter import *
import time

t = turtle.Turtle()
screen = Screen()
screen.setup(width=800, height=800, startx=10, starty=10)
eraseble = []

''' this function allows the square to be erased and rewriten '''
def erasableWrite(tortoise, name, font, align, reuse=None):
    eraser = turtle.Turtle() if reuse is None else reuse
    eraser.hideturtle()
    eraser.up()
    eraser.setposition(tortoise.position())
    eraser.write(name, font=font, align=align)
    print('eraser = {} name = {}.'.format(eraser, name))
    return eraser

startX = -280
startY = -295
textValue = [('1', 'a'), ('2', 'b'), ('3', 'c')]
t.hideturtle()
turtle.speed(0)
t.penup()
counter = 0
count = 0
for n in range(3):
    t.goto(startX, startY)
    t.pendown()
    eraseble.append(erasableWrite(t, textValue[n][0], font=("New Times Roman", 18, "normal"), align="center"))
    print('count = {}, eraseble[counter] = {} counter = {} n = {} textvalue = {}.  '.format(count, eraseble[counter], counter, n, textValue[n][0]))
    time.sleep(2)
    count += 1
    eraseble[counter].clear()
    eraseble.append(erasableWrite(t, textValue[n][1], font=("New Times Roman", 18, "normal"), align="center"))
    time.sleep(2)
    eraseble[counter + 1].clear()
    print('eraseble[counter] = {} counter = {} n = {} textvalue = {}.  '.format(eraseble[counter], counter, n, textValue[n][1]))
    eraseble[counter -1] = (erasableWrite(t, textValue[n][0], font=("New Times Roman", 18, "normal"), align="center"))
    count +=1
    startX +=40
    startY += 20
    t.penup()
    counter +=2

` replace 1 with a `
startX = -280
startY = -295
t.goto(startX, startY)
print('count = {}, eraseble[0] = {}'.format(count, eraseble[0]))
count +=1
eraseble[0].clear()
textVal = textValue[0][0]
eraseble[0] = (erasableWrite(t, textVal, font=("New Times Roman", 18, "normal"), align="center"))
print('count = {}, eraseble[0] = {}'.format(count, eraseble[0]))
count +=1
eraseble[0].clear()
textVal = textValue[0][1]
eraseble[1] = (erasableWrite(t, textVal, font=("New Times Roman", 18, "normal"), align="center"))
time.sleep(2)

print('\n\neraseble = {}   !...!'.format(eraseble))

Body:
You seem to be confusing how the return value, and reuse argument to erasableWrite work.  I've rewritten your example code below (exaggerating the font and distances slightly):

from turtle import Screen, Turtle
import time

FONT = ("New Times Roman", 24, "bold")

def erasableWrite(tortoise, name, font, align, reuse=None):
    eraser = Turtle() if reuse is None else reuse
    eraser.hideturtle()
    eraser.up()
    eraser.setposition(tortoise.position())
    eraser.write(name, font=font, align=align)

    return eraser

screen = Screen()
screen.setup(width=800, height=800, startx=10, starty=10)

turtle = Turtle()
turtle.hideturtle()
turtle.penup()

erasable = []

startX = -280
startY = -295
textValue = [('1', 'a'), ('2', 'b'), ('3', 'c')]

for n in range(3):
    turtle.goto(startX, startY)

    erasable.append(erasableWrite(turtle, textValue[n][0], font=FONT, align="center"))
    time.sleep(2)
    erasable[n].clear()

    erasableWrite(turtle, textValue[n][1], font=FONT, align="center", reuse=erasable[n])
    time.sleep(2)
    erasable[n].clear()

    erasableWrite(turtle, textValue[n][0], font=FONT, align="center", reuse=erasable[n])

    startX += 80
    startY += 40

time.sleep(2)

startX = -280
startY = -295
turtle.goto(startX, startY)

erasable[0].clear()
textVal = textValue[0][1]
erasableWrite(turtle, textVal, font=FONT, align="center", reuse=erasable[0])
time.sleep(2)

erasable[0].clear()
textVal = textValue[0][0]
erasableWrite(turtle, textVal, font=FONT, align="center", reuse=erasable[0])
time.sleep(2)

screen.mainloop()

It displays the three "cards" and their values, and then goes back and exposes the first card's value again before covering it up.


问:
how to clear JavaScript variable value after few minutes / seconds / times
I have set a value in JavaScript local variable which is given below:

```<code>document.getElementById("class").value = getSavedValue("class");    // set the value to this input
document.getElementById("group").value = getSavedValue("group");   // set the value to this input
document.getElementById("section").value = getSavedValue("section");   // set the value to this input
document.getElementById("session").value = getSavedValue("session");   // set the value to this input
document.getElementById("shift").value = getSavedValue("shift");   // set the value to this input
document.getElementById("version").value = getSavedValue("version");   // set the value to this input
/* Here you can add more inputs to set value. if it's saved */

//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
    var id = e.id;  // get the sender's id to save it .
    var val = e.value; // get the value.
    localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}

//get the saved value function - return the value of "v" from localStorage.
function getSavedValue  (v){
    if (!localStorage.getItem(v)) {
        return "";// You can change this to your defualt value.
    }
    return localStorage.getItem(v);
}
</code>```

i want to when its value is saved then a certain amount of time it only that (specific) variable will be unset / clear automatically.

Thank you

答:
The only possibility to do this, as I think, is setInterval function:</p>

```<code>// Repeat function alert every 2 sec
let timerId = setInterval(() => alert('tick'), 2000);

// Stop repeating after 5 sec
setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);`
</code>```

Body:
I have set a value in JavaScript local variable which is given below:

document.getElementById("class").value = getSavedValue("class");    // set the value to this input
document.getElementById("group").value = getSavedValue("group");   // set the value to this input
document.getElementById("section").value = getSavedValue("section");   // set the value to this input
document.getElementById("session").value = getSavedValue("session");   // set the value to this input
document.getElementById("shift").value = getSavedValue("shift");   // set the value to this input
document.getElementById("version").value = getSavedValue("version");   // set the value to this input
/* Here you can add more inputs to set value. if it's saved */

//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
    var id = e.id;  // get the sender's id to save it .
    var val = e.value; // get the value.
    localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}

//get the saved value function - return the value of "v" from localStorage.
function getSavedValue  (v){
    if (!localStorage.getItem(v)) {
        return "";// You can change this to your defualt value.
    }
    return localStorage.getItem(v);
}

i want to when its value is saved then a certain amount of time it only that (specific) variable will be unset / clear automatically.

Thank you

Body:
The only possibility to do this, as I think, is setInterval function:

// Repeat function alert every 2 sec
let timerId = setInterval(() => alert('tick'), 2000);

// Stop repeating after 5 sec
setTimeout(() => { clearInterval(timerId); alert('stop'); }, 5000);`


答:
There is technically one way, which is analogous to how it is possible to get the length of a null terminated string: Use particular argument value to designate the end of the argument list.

However, note that in order to use va_start, there must be at least one named parameter. In your example you attempt to pass a local variable into va_start which is not allowed. That macro doesn't take "the number of arguments". It takes "last named argument  before variadic parameters start".

That said: I recommend against using C-style variadic functions.

Title: How would it be possible to use variadic function without passing number of arguments and only with 3 dots?

Body:
Considering the code below, is it possible to define a variadic function without getting number of arguments?

void printFunction(...)
{
    int noOfArgs = "Any way to get number of arguments?";
    va_list args;
    va_start(args, noOfArgs);
    cout << va_arg(args, int) << endl;
    for (int i = 2; i <= noOfArgs; i++)
    {
        cout << va_arg(args, int) << endl;
    }
    va_end(args);
}

int main()
{

    printFunction(1, 2, 3, 4, 5);

    return 0;
}


答:
In C++ 11 and after, it is very easy:

```<code>template<typename... Arguments>
void printFunction(Arguments &&...args) {
    auto noOfArgs = sizeof...(Arguments);
</code>```

However, you are using an old-style, plain-C, preprocessor macro style, which is very different.
First, to use the preprocessor macros you need to have at least one named parameter, which will be used to start the va_list, and that's the beginning of the complications.

I think there is no standard way to count the number of arguments, it can be implemented in a number of ways, if that is what you are really asking, which I would have tagged as C instead of C++.

How to access the arguments: there are two choices, let us call it the "machine gun" and the "drip-drip-drip" --these are my names--:

```<code>#include <utility>

template<typename... Ts>
void ignoreResults(Ts &&...) {}

template<typename Argument>
int machineGunBullet(Argument &&arg);

inline void drip() {} // do nothing

template<typename A1, typename... Tail>
void drip(A1 &&a1, Tail &&...tail) {
    // do something here with a1
    drip(std::forward<Tail>(tail)...);
}

template<typename... Arguments>
void printFunction(Arguments &&...args) {
    ignoreResults(machineGunBullet(std::forward<Arguments>(args))...);
    // or
    drip(std::forward<Arguments>(args)...);
}
</code>```

This builds in the compiler explorer,
https://godbolt.org/z/aSx2wv

Body:
In C++ 11 and after, it is very easy:

template<typename... Arguments>
void printFunction(Arguments &&...args) {
    auto noOfArgs = sizeof...(Arguments);

However, you are using an old-style, plain-C, preprocessor macro style, which is very different.
First, to use the preprocessor macros you need to have at least one named parameter, which will be used to start the va_list, and that's the beginning of the complications.

I think there is no standard way to count the number of arguments, it can be implemented in a number of ways, if that is what you are really asking, which I would have tagged as C instead of C++.

How to access the arguments: there are two choices, let us call it the "machine gun" and the "drip-drip-drip" --these are my names--:

#include <utility>

template<typename... Ts>
void ignoreResults(Ts &&...) {}

template<typename Argument>
int machineGunBullet(Argument &&arg);

inline void drip() {} // do nothing

template<typename A1, typename... Tail>
void drip(A1 &&a1, Tail &&...tail) {
    // do something here with a1
    drip(std::forward<Tail>(tail)...);
}

template<typename... Arguments>
void printFunction(Arguments &&...args) {
    ignoreResults(machineGunBullet(std::forward<Arguments>(args))...);
    // or
    drip(std::forward<Arguments>(args)...);
}

This builds in the compiler explorer,
https://godbolt.org/z/aSx2wv


问:
Re-connect local folder to remote repository
A number of months ago, I cloned a repository into a local directory. Since then, all git files were removed (not sure how), so I no longer have a connection to the remote repository and cannot pull any changes made in that remote repository since. I have also made many changes to my local code, so I need to be able to pull the remote code and merge it properly.

How can I re-connect my local directory to the same remote repository, and pull any new updates that have been made to the remote repository into my local directory since then?

If it helps, I can use Sourcetree or Github Desktop in addition to command line.

答:
You can use

```<code>git remote add
</code>```

example

```<code>git remote add origin https://github.com/user/repo.git
</code>```

check the remote with

```<code>git remote -v
</code>```

Also check the git docs

Body:
You can use

git remote add

example

git remote add origin https://github.com/user/repo.git

check the remote with

git remote -v

Also check the git docs


问:
How can I print image big size in A4 paper c#
I want to print image from picturebox in big size in my current code its print in original size ,
I tried the following code :

```<code>private void btnID_Click(object sender, EventArgs e)
        {
            PrintDialog pd = new PrintDialog();
            PrintDocument pdoc = new PrintDocument();
            pdoc.PrintPage += doc_printID;
            pd.Document = pdoc;
            if (pd.ShowDialog() == DialogResult.OK)
                pdoc.Print();

        }

        private void doc_printID(object sender, PrintPageEventArgs e)
        {
            Bitmap bm = new Bitmap(pictureIDIQAMA.Width, pictureIDIQAMA.Height);
            pictureIDIQAMA.DrawToBitmap(bm, new Rectangle(0, 0, pictureIDIQAMA.Width, pictureIDIQAMA.Height));
            e.Graphics.DrawImage(bm, 200,400);
            bm.Dispose();
        }
</code>```

How can I print the image in bigger size at lease double original size ?

答:
To draw the image that is within the margin of your page

e.Graphics.DrawImage(bm, args.MarginBounds);

or

To draw the image across total area of the page

e.Graphics.DrawImage(bm, args.PageBounds);

Body:
I want to print image from picturebox in big size in my current code its print in original size ,
I tried the following code :

private void btnID_Click(object sender, EventArgs e)
        {
            PrintDialog pd = new PrintDialog();
            PrintDocument pdoc = new PrintDocument();
            pdoc.PrintPage += doc_printID;
            pd.Document = pdoc;
            if (pd.ShowDialog() == DialogResult.OK)
                pdoc.Print();

        }

        private void doc_printID(object sender, PrintPageEventArgs e)
        {
            Bitmap bm = new Bitmap(pictureIDIQAMA.Width, pictureIDIQAMA.Height);
            pictureIDIQAMA.DrawToBitmap(bm, new Rectangle(0, 0, pictureIDIQAMA.Width, pictureIDIQAMA.Height));
            e.Graphics.DrawImage(bm, 200,400);
            bm.Dispose();
        }

How can I print the image in bigger size at lease double original size ?


问:
Changing .scnp in GitHub pod doesn't take the effects on run
Hi I'm using the pod https://github.com/roytornado/RSLoadingView
I changed Twins.scnp effects and added image to the animation, but the changes doesn't have effect when I run the app.

```<code>let loadingView = RSLoadingView(effectType: .twins)
loadingView.show(on: tabBarController!.view)
</code>```

It appears with this code over the screen, but it's still original version of it.

答:
This framework does not support custom .sncp files from what I can tell. But I'll try to answer anyways.

I'm assuming you're loading the example project for the pod, but my answer applies if you're installing it it to your project as well.

Changing the Twins.scnp wouldn't change the effect because the example has the pod which is built and loaded already as a framework. The Twins.scnp file is embedded in the framework, you just changed the source file that builds the pod. You'd have to rebuild the pod and install that new built pod into the example app to see your changes. This approach is likely too cumbersome for your needs.

You generally shouldn't change source files for the framework unless you're planning on forking and rebuilding, or you're working on the framework with the author.

If you really want to change the source of the framework and rebuild it with your changes you can do this:

Fork the project, pull your forked version to your computer

Adjust the .sncp files to your liking

git commit/push your changes to your forked repo, make sure to push to the master branch

install the pod in the project you'd like to see this in with this line:

pod 'RSLoadingView', :git => 'https://github.com/yourUsername/RSLoadingView.git', :branch => 'master'

replace yourUsername based on what you see in GitHub for the url of your forked repo.

If you do all this you'll see the changes, but this approach is generally not a sustainable solution. You wouldn't get updates from the original author and you're essentially making your own version of the pod.

Body:
Hi I'm using the pod https://github.com/roytornado/RSLoadingView
I changed Twins.scnp effects and added image to the animation, but the changes doesn't have effect when I run the app.

let loadingView = RSLoadingView(effectType: .twins)
loadingView.show(on: tabBarController!.view)

It appears with this code over the screen, but it's still original version of it.


问:
How to restrict matches to the first 5 lines of an email body using regex in GAS
I'm using the following script which is working correctly to pull 2 fields out of an email body.

This is causing the script execution time to increase significantly due to the amount of content in the body. Is there a way to make this search through only the first 5 lines of the email body?

First lines of e-mail:

Name: Full Report
Store: River North (Wells St)
Date Tripped: 19 Feb 2020 1:07 PM
Business Date: 19 Feb 2020 (Open)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 15 minutes.
```

<p>Script:</p>

```//gets first(latest) message with set label
var threads = GmailApp.getUserLabelByName('South Loop').getThreads(0,1);
if (threads && threads.length > 0) {
  var message = threads[0].getMessages()[0];
  // Get the first email message of a threads
  var tmp,
    subject = message.getSubject(),
    content = message.getPlainBody();
  // Get the plain text body of the email message
  // You may also use getRawContent() for parsing HTML

  // Implement Parsing rules using regular expressions
  if (content) {

    tmp = content.match(/Date Tripped:\s*([:\w\s]+)\r?\n/);
    var tripped = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

    tmp = content.match(/Business Date:\s([\w\s]+\(\w+\))/);
    var businessdate = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';
  }
}
```

答:
You can use the pattern /^(?:.*\r?\n){0,5}/ to grab the first 5 lines of the email, then run your search against this smaller string. Here's a browser example with hardcoded content, but I tested it in Google Apps Script.

const Logger = console; // Remove this for GAS!

const content = `Name: Full Report
Store: River North (Wells St)
Date Tripped: 19 Feb 2020 1:07 PM
Business Date: 19 Feb 2020 (Open)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 15 minutes.`;

const searchPattern = /(Date Tripped|Business Date): *(.+?)\r?\n/g;
const matches = [...content.match(/^(?:.*\r?\n){0,5}/)[0]
                           .matchAll(searchPattern)]

const result = Object.fromEntries(matches.map(e => e.slice(1)));
Logger.log(result);```
</div>
</div>
</p>

<p>If you wish to dynamically inject the search terms, use:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Logger = console; // Remove this for GAS!

const content = `Name: Full Report
Store: River North (Wells St)
Date Tripped: 19 Feb 2020 1:07 PM
Business Date: 19 Feb 2020 (Open)
Foo: this will match because it's on line 5
Bar: this won't match because it's on line 6
Information:
`;

const searchTerms = ["Date Tripped", "Business Date", "Foo", "Bar"];
const searchPattern = new RegExp(`(${searchTerms.join("|")}): *(.+?)\r?\n`, "g");
const matches = [...content.match(/^(?:.*\r?\n){0,5}/)[0]
                           .matchAll(searchPattern)]

const result = Object.fromEntries(matches.map(e => e.slice(1)));
Logger.log(result);</code>```

ES5 version if you're using the older engine:

var Logger = console; // Remove this for GAS!

var content = "Name: Full Report\nStore: River North (Wells St)\nDate Tripped: 19 Feb 2020 1:07 PM\nBusiness Date: 19 Feb 2020 (Open)\nMessage:\nInformation:\nThis alert was tripped based on a user defined trigger: Every 15 minutes.\n";

var searchPattern = /(Date Tripped|Business Date): *(.+?)\r?\n/g;
var truncatedContent = content.match(/^(?:.*\r?\n){0,5}/)[0];
var result = {};

for (var m; m = searchPattern.exec(content); result[m[1]] = m[2]);

Logger.log(result);```

Body:
I'm using the following script which is working correctly to pull 2 fields out of an email body.

This is causing the script execution time to increase significantly due to the amount of content in the body. Is there a way to make this search through only the first 5 lines of the email body?

First lines of e-mail:

Name: Full Report
Store: River North (Wells St)
Date Tripped: 19 Feb 2020 1:07 PM
Business Date: 19 Feb 2020 (Open)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 15 minutes.

Script:

//gets first(latest) message with set label
var threads = GmailApp.getUserLabelByName('South Loop').getThreads(0,1);
if (threads && threads.length > 0) {
  var message = threads[0].getMessages()[0];
  // Get the first email message of a threads
  var tmp,
    subject = message.getSubject(),
    content = message.getPlainBody();
  // Get the plain text body of the email message
  // You may also use getRawContent() for parsing HTML

  // Implement Parsing rules using regular expressions
  if (content) {

    tmp = content.match(/Date Tripped:\s*([:\w\s]+)\r?\n/);
    var tripped = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';

    tmp = content.match(/Business Date:\s([\w\s]+\(\w+\))/);
    var businessdate = (tmp && tmp[1]) ? tmp[1].trim() : 'N/A';
  }
}

Body:
You can use the pattern /^(?:.*\r?\n){0,5}/ to grab the first 5 lines of the email, then run your search against this smaller string. Here's a browser example with hardcoded content, but I tested it in Google Apps Script.

const Logger = console; // Remove this for GAS!

const content = `Name: Full Report
Store: River North (Wells St)
Date Tripped: 19 Feb 2020 1:07 PM
Business Date: 19 Feb 2020 (Open)
Message:
Information:
This alert was tripped based on a user defined trigger: Every 15 minutes.`;

const searchPattern = /(Date Tripped|Business Date): *(.+?)\r?\n/g;
const matches = [...content.match(/^(?:.*\r?\n){0,5}/)[0]
                           .matchAll(searchPattern)]

const result = Object.fromEntries(matches.map(e => e.slice(1)));
Logger.log(result);

If you wish to dynamically inject the search terms, use:

const Logger = console; // Remove this for GAS!

const content = `Name: Full Report
Store: River North (Wells St)
Date Tripped: 19 Feb 2020 1:07 PM
Business Date: 19 Feb 2020 (Open)
Foo: this will match because it's on line 5
Bar: this won't match because it's on line 6
Information:
`;

const searchTerms = ["Date Tripped", "Business Date", "Foo", "Bar"];
const searchPattern = new RegExp(`(${searchTerms.join("|")}): *(.+?)\r?\n`, "g");
const matches = [...content.match(/^(?:.*\r?\n){0,5}/)[0]
                           .matchAll(searchPattern)]

const result = Object.fromEntries(matches.map(e => e.slice(1)));
Logger.log(result);

ES5 version if you're using the older engine:

var Logger = console; // Remove this for GAS!

var content = "Name: Full Report\nStore: River North (Wells St)\nDate Tripped: 19 Feb 2020 1:07 PM\nBusiness Date: 19 Feb 2020 (Open)\nMessage:\nInformation:\nThis alert was tripped based on a user defined trigger: Every 15 minutes.\n";

var searchPattern = /(Date Tripped|Business Date): *(.+?)\r?\n/g;
var truncatedContent = content.match(/^(?:.*\r?\n){0,5}/)[0];
var result = {};

for (var m; m = searchPattern.exec(content); result[m[1]] = m[2]);

Logger.log(result);


问:
How to insert missing time (by minutes) in data frame? And how to assign corresponding y values for that missing time as NA?
I have a data that looks like this:

```<code>SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:02   1
3   1/27/20 18:04   0
4   1/27/20 18:05   1
5   1/27/20 18:08   0
</code>```

How can make it look like this?

```<code>SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:01   NA
3   1/27/20 18:02   1
4   1/27/20 18:03   NA
5   1/27/20 18:04   0
6   1/27/20 18:05   1
7   1/27/20 18:06   NA
8   1/27/20 18:07   NA
9   1/27/20 18:08   0
</code>```

Basically, my question is how can I insert missing timestamp and assign the corresponding MOTOR values as NA?

I would be thankful if anyone could help. I just started learning R and this is giving me headache since morning.

Thanks.

Body:
I have a data that looks like this:

SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:02   1
3   1/27/20 18:04   0
4   1/27/20 18:05   1
5   1/27/20 18:08   0

How can make it look like this?

SN  TimeStamp      MOTOR
1   1/27/20 18:00   0
2   1/27/20 18:01   NA
3   1/27/20 18:02   1
4   1/27/20 18:03   NA
5   1/27/20 18:04   0
6   1/27/20 18:05   1
7   1/27/20 18:06   NA
8   1/27/20 18:07   NA
9   1/27/20 18:08   0

Basically, my question is how can I insert missing timestamp and assign the corresponding MOTOR values as NA?

I would be thankful if anyone could help. I just started learning R and this is giving me headache since morning.

Thanks.

Body:
Another possible approach is to use library(padr):

library(padr)
library(dplyr)

df %>%
  pad(interval = 'min') %>%
  mutate(SN = row_number())

Output

  SN           TimeStamp Motor
1  1 2020-01-27 18:00:00     0
2  2 2020-01-27 18:01:00    NA
3  3 2020-01-27 18:02:00     1
4  4 2020-01-27 18:03:00    NA
5  5 2020-01-27 18:04:00     0
6  6 2020-01-27 18:05:00     1
7  7 2020-01-27 18:06:00    NA
8  8 2020-01-27 18:07:00    NA
9  9 2020-01-27 18:08:00     0

Data

df <- data.frame(
  SN = 1:5,
  TimeStamp = as.POSIXct(c("1/27/20 18:00", "1/27/20 18:02", "1/27/20 18:04", "1/27/20 18:05", "1/27/20 18:08"), format = "%m/%d/%y %H:%M"),
  Motor = c(0,1,0,1,0)
)


问:
Deploying Microservices by triggering a Jenkins pipeline whenever a change is made in a mono repository consisting of various microservices
I have a single repository consisting of various microservices written in node js, I am trying to deploy by triggering a Jenkins pipeline for those microservices where a change is done and trying to maintain only one Jenkins file for the repository. Can this be done? I have been exploring for quite a while now, and I didn't find any useful resources. Any leads to solving this problem statement would be of great help!

Could you suggest any other famous open source CI/CD tools to achieve the same?

答: Yeah, you can achieve what you need using Gitlab. We have pretty much the same use case, multiple Lambda functions in the same repo. The idea is not to redeploy everything each time a function is updated. This is a good starting point: https://aarongorka.com/blog/gitlab-monorepo-pipelines/</p>


问:
Change Srcset of Picture Element on Load Error
I am trying to change srcset to a default image if it doesn't exist.

If it's a window below 465px the img line works to the default if the Small.jpg doesn't exist. I just can't get the srcset to change if the image doesn't exist.
Any ideas? Thanks

```<code><picture>
  <source media="(min-width: 650px)" srcset="Large.jpg" onError="this.onerror=null;this.srcset='Default.jpg';">
  <source media="(min-width: 465px)" srcset="Medium1.jpg" onError="this.onerror=null;this.srcset='Default.jpg';">
  <img src="Small.jpg" alt="Flowers" style="width:auto;" onError="this.onerror=null;this.src='Default.jpg'">
</picture>
</code>```

答:
Welcome to Stack Overflow.

There is something odd going on. If you go here and change the code to this

```<code><picture>
  <source media="(min-width: 6000px)" srcset="img_pink_flowers.jpg">
  <source media="(min-width: 6000px)" srcset="img_white_flower.jpg">
  <img src="img_orage_flowers.jpg" alt="Flowers" style="width:auto;" onerror="console.log(this.src); this.src = 'img_orange_flowers.jpg'; console.log(this.src);">
</picture>
</code>```

You will see that the picture element bypasses the sources, as the min-width filters them out, errors out on the typo in the img src and corrects its own source. You can see it happening in the console.

Same thing works with srcset

```<code><picture>
  <source media="(min-width: 6000px)" srcset="img_pink_flowers.jpg">
  <source media="(min-width: 6000px)" srcset="img_white_flower.jpg">
  <img src="img_orage_flowers.jpg" alt="Flowers" style="width:auto;" onerror="console.log(this.srcset); this.srcset = 'img_orange_flowers.jpg'; console.log(this.srcset);">
</picture>
</code>```

So maybe I'm not understanding but the onerror function for the image seems to be working OK.

If you are actually looking for an onerror handler for the picture element, so that you can handle the case where the picture element is given a non-existent image in the srcset of the first source element, then I believe there's no such handler.

Body:
I am trying to change srcset to a default image if it doesn't exist.

If it's a window below 465px the img line works to the default if the Small.jpg doesn't exist. I just can't get the srcset to change if the image doesn't exist.
Any ideas? Thanks

<picture>
  <source media="(min-width: 650px)" srcset="Large.jpg" onError="this.onerror=null;this.srcset='Default.jpg';">
  <source media="(min-width: 465px)" srcset="Medium1.jpg" onError="this.onerror=null;this.srcset='Default.jpg';">

</picture>

Body:
Welcome to Stack Overflow.

There is something odd going on. If you go here and change the code to this

<picture>
  <source media="(min-width: 6000px)" srcset="img_pink_flowers.jpg">
  <source media="(min-width: 6000px)" srcset="img_white_flower.jpg">
  <img src="img_orage_flowers.jpg" alt="Flowers" style="width:auto;" onerror="console.log(this.src); this.src = 'img_orange_flowers.jpg'; console.log(this.src);">
</picture>

You will see that the picture element bypasses the sources, as the min-width filters them out, errors out on the typo in the img src and corrects its own source. You can see it happening in the console.

Same thing works with srcset

<picture>
  <source media="(min-width: 6000px)" srcset="img_pink_flowers.jpg">
  <source media="(min-width: 6000px)" srcset="img_white_flower.jpg">
  <img src="img_orage_flowers.jpg" alt="Flowers" style="width:auto;" onerror="console.log(this.srcset); this.srcset = 'img_orange_flowers.jpg'; console.log(this.srcset);">
</picture>

So maybe I'm not understanding but the onerror function for the image seems to be working OK.

If you are actually looking for an onerror handler for the picture element, so that you can handle the case where the picture element is given a non-existent image in the srcset of the first source element, then I believe there's no such handler.


问:
Laravel docker deploy
I have a Laravel project where we integrate create container with docker.
I'm using the SSH plugin for laravel to SSH.

I'm trying to execute the follow code:

```<code>SSH::into('production')->run([
                'docker run --expose '.$port.' --expose '.$rpcport.' --name '.$nodeName.' -i cimage:latest bash',
                'docker start '.$nodeName,
                'docker exec -i -t '.$nodeName.' mkdir /usr/local/bin/test',
            ]);
</code>```

The node create perfect and start good.

Problem is the next commands not executing or something in the command is not good.

Can someone help me to get this solve?

答:
It works with execute the commands separate like:</p>

```<code>SSH::into('production')->run([
                'docker run --expose '.$port.' --expose '.$rpcport.' --name '.$nodeName.' -i cimage:latest bash',
            ]);

SSH::into('production')->run([
                'docker exec -i -t '.$nodeName.' mkdir /usr/local/bin/test',
            ]);
</code>```

Title: Laravel docker deploy

Body:
I have a Laravel project where we integrate create container with docker.
I'm using the SSH plugin for laravel to SSH.

I'm trying to execute the follow code:

SSH::into('production')->run([
                'docker run --expose '.$port.' --expose '.$rpcport.' --name '.$nodeName.' -i cimage:latest bash',
                'docker start '.$nodeName,
                'docker exec -i -t '.$nodeName.' mkdir /usr/local/bin/test',
            ]);

The node create perfect and start good.

Problem is the next commands not executing or something in the command is not good.

Can someone help me to get this solve?

Body:
It works with execute the commands separate like:

SSH::into('production')->run([
                'docker run --expose '.$port.' --expose '.$rpcport.' --name '.$nodeName.' -i cimage:latest bash',
            ]);

SSH::into('production')->run([
                'docker exec -i -t '.$nodeName.' mkdir /usr/local/bin/test',
            ]);