问:
bootstrap carousel : apply same animation effect on both forward and backward sliding animation
I have implemented a  bootstrap carousel. problem occurs when left arrow is pressed. the animation is different from the forward sliding. I want same animation for both forward and backward sliding. how can I achieve that?

html

```<code><!------ Include the above in your HEAD tag ---------->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <link rel="stylesheet" href="./ashik.css">
</head>
<body>
    <div class="row myrow">
        <div class="container-fluid">
            <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="9000">
                <div class="carousel-inner row myrow w-100 mx-auto" role="listbox">
                    <div class="carousel-item col-md-6 col-lg-4 active">
                       <div class="panel panel-default">
                          <div class="panel-thumbnail">
                            <a href="#" title="image 1" class="thumb">
                              <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=1" alt="slide 1">
                            </a>
                          </div>
                        </div>
                    </div>
                    <div class="carousel-item col-md-6 col-lg-4">
                       <div class="panel panel-default">
                          <div class="panel-thumbnail">
                            <a href="#" title="image 3" class="thumb">
                             <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=2" alt="slide 2">
                            </a>
                          </div>
                        </div>
                    </div>
                    <div class="carousel-item col-md-6 col-lg-4">
                       <div class="panel panel-default">
                          <div class="panel-thumbnail">
                            <a href="#" title="image 4" class="thumb">
                             <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=3" alt="slide 3">
                            </a>
                          </div>
                        </div>
                    </div>
                    <div class="carousel-item col-md-6 col-lg-4">
                        <div class="panel panel-default">
                          <div class="panel-thumbnail">
                            <a href="#" title="image 5" class="thumb">
                             <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=4" alt="slide 4">
                            </a>
                          </div>
                        </div>
                    </div>
                    <div class="carousel-item col-md-6 col-lg-4">
                      <div class="panel panel-default">
                          <div class="panel-thumbnail">
                            <a href="#" title="image 6" class="thumb">
                              <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=5" alt="slide 5">
                            </a>
                          </div>
                        </div>
                    </div>
                    <div class="carousel-item col-md-6 col-lg-4">
                       <div class="panel panel-default">
                          <div class="panel-thumbnail">
                            <a href="#" title="image 7" class="thumb">
                              <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=6" alt="slide 6">
                            </a>
                          </div>
                        </div>
                    </div>
                    <div class="carousel-item col-md-6 col-lg-4">
                       <div class="panel panel-default">
                          <div class="panel-thumbnail">
                            <a href="#" title="image 8" class="thumb">
                              <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=7" alt="slide 7">
                            </a>
                          </div>
                        </div>
                    </div>
                     <div class="carousel-item col-md-6 col-lg-4">
                        <div class="panel panel-default">
                          <div class="panel-thumbnail">
                            <a href="#" title="image 2" class="thumb">
                             <img class="img-fluid mx-auto d-block" src="//via.placeholder.com/600x400?text=8" alt="slide 8">
                            </a>
                          </div>

                        </div>
                    </div>

                </div>
                <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                    <span class="sr-only">Previous</span>
                </a>
                <a class="carousel-control-next text-faded" href="#carouselExample" role="button" data-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                    <span class="sr-only">Next</span>
                </a>
            </div>
        </div>
    </div>

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> -->

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
<script src="./ashik.js"></script>

</body>
</html>
</code>```

css

```<code>@media (min-width: 768px) {

    /* show 3 items */
    .carousel-inner .active,
    .carousel-inner .active + .carousel-item,
    .carousel-inner .active + .carousel-item + .carousel-item,
    .carousel-inner .active + .carousel-item + .carousel-item + .carousel-item  {
        display: block;
    }

    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left),
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item,
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item + .carousel-item,
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item + .carousel-item + .carousel-item {
        transition: none;
    }

    .carousel-inner .carousel-item-next,
    .carousel-inner .carousel-item-prev {
      position: relative;
      transform: translate3d(0, 0, 0);
    }

    .carousel-inner .active.carousel-item + .carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: absolute;
        top: 0;
        right: -25%;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* left or forward direction */
    .active.carousel-item-left + .carousel-item-next.carousel-item-left,
    .carousel-item-next.carousel-item-left + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(-100%, 0, 0);
        visibility: visible;
    }

    /* farthest right hidden item must be abso position for animations */
    .carousel-inner .carousel-item-prev.carousel-item-right {
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* right or prev direction */
    .active.carousel-item-right + .carousel-item-prev.carousel-item-right,
    .carousel-item-prev.carousel-item-right + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(100%, 0, 0);
        visibility: visible;
        display: block;
        visibility: visible;
    }

}

.row.myrow {
    flex-wrap: nowrap !important;
}
</code>```

js

```<code>
$('#carouselExample').on('slide.bs.carousel', function (e) {

    var $e = $(e.relatedTarget);
    var idx = $e.index();
    var itemsPerSlide = 4;
    var totalItems = $('.carousel-item').length;

    if (idx >= totalItems-(itemsPerSlide-1)) {
        var it = itemsPerSlide - (totalItems - idx);
        console.log({it});
        for (var i=0; i<it; i++) {
            // append slides to end
            if (e.direction=="left") {
                $('.carousel-item').eq(i).appendTo('.carousel-inner');
            }
            else {
                $('.carousel-item').eq(0).appendTo('.carousel-inner');
            }
        }
    }
});

  $('#carouselExample').carousel({
                interval: false,
        });

  $(document).ready(function() {
/* show lightbox when clicking a thumbnail */
    $('a.thumb').click(function(event){
      event.preventDefault();
      var content = $('.modal-body');
      content.empty();
        var title = $(this).attr("title");
        $('.modal-title').html(title);
        content.html($(this).html());
        $(".modal-profile").modal({show:true});
    });

  });
</code>```

live:

https://bootsnipp.com/snippets/dl6ez

Body:
I have implemented a  bootstrap carousel. problem occurs when left arrow is pressed. the animation is different from the forward sliding. I want same animation for both forward and backward sliding. how can I achieve that?

html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <link rel="stylesheet" href="./ashik.css">

                    Previous

                    Next

css

@media (min-width: 768px) {

    /* show 3 items */
    .carousel-inner .active,
    .carousel-inner .active + .carousel-item,
    .carousel-inner .active + .carousel-item + .carousel-item,
    .carousel-inner .active + .carousel-item + .carousel-item + .carousel-item  {
        display: block;
    }

    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left),
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item,
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item + .carousel-item,
    .carousel-inner .carousel-item.active:not(.carousel-item-right):not(.carousel-item-left) + .carousel-item + .carousel-item + .carousel-item {
        transition: none;
    }

    .carousel-inner .carousel-item-next,
    .carousel-inner .carousel-item-prev {
      position: relative;
      transform: translate3d(0, 0, 0);
    }

    .carousel-inner .active.carousel-item + .carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: absolute;
        top: 0;
        right: -25%;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* left or forward direction */
    .active.carousel-item-left + .carousel-item-next.carousel-item-left,
    .carousel-item-next.carousel-item-left + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item + .carousel-item,
    .carousel-item-next.carousel-item-left + .carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(-100%, 0, 0);
        visibility: visible;
    }

    /* farthest right hidden item must be abso position for animations */
    .carousel-inner .carousel-item-prev.carousel-item-right {
        position: absolute;
        top: 0;
        left: 0;
        z-index: -1;
        display: block;
        visibility: visible;
    }

    /* right or prev direction */
    .active.carousel-item-right + .carousel-item-prev.carousel-item-right,
    .carousel-item-prev.carousel-item-right + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item + .carousel-item,
    .carousel-item-prev.carousel-item-right + .carousel-item + .carousel-item + .carousel-item + .carousel-item {
        position: relative;
        transform: translate3d(100%, 0, 0);
        visibility: visible;
        display: block;
        visibility: visible;
    }

}

.row.myrow {
    flex-wrap: nowrap !important;
}

js

$('#carouselExample').on('slide.bs.carousel', function (e) {

    var $e = $(e.relatedTarget);
    var idx = $e.index();
    var itemsPerSlide = 4;
    var totalItems = $('.carousel-item').length;

    if (idx >= totalItems-(itemsPerSlide-1)) {
        var it = itemsPerSlide - (totalItems - idx);
        console.log({it});
        for (var i=0; i<it; i++) {
            // append slides to end
            if (e.direction=="left") {
                $('.carousel-item').eq(i).appendTo('.carousel-inner');
            }
            else {
                $('.carousel-item').eq(0).appendTo('.carousel-inner');
            }
        }
    }
});

  $('#carouselExample').carousel({
                interval: false,
        });

  $(document).ready(function() {
/* show lightbox when clicking a thumbnail */
    $('a.thumb').click(function(event){
      event.preventDefault();
      var content = $('.modal-body');
      content.empty();
        var title = $(this).attr("title");
        $('.modal-title').html(title);
        content.html($(this).html());
        $(".modal-profile").modal({show:true});
    });

  });

live:

https://bootsnipp.com/snippets/dl6ez


来源: stackexchange

问:
Assign image to a form field in django.views
I am in the middle of a project and I am stuck. I have a edit profile feature where a user can edit their profile. Everytime a profile is created with an empty profile_picture field a default value is provided. But once an image is assigned to field and then deleted. The field gets blank.
What I want is everytime the field becomes None I want to reassign the default image by mentioning the file path.

Heres My view where I save the model form:-

```<code>           if form.is_valid():
                form.save(commit=False)

                print(form.cleaned_data)
                if 'avatar' in form.cleaned_data:

                    if form.cleaned_data.get('avatar') is False:
                        form.cleaned_data['avatar'] = image

                form.save()
</code>```

I want to mention the image path in place of image. Also suggest me some better ways for doing this. Thanks in advance

ContentLicense: CC BY-SA 4.0

Body:
I am in the middle of a project and I am stuck. I have a edit profile feature where a user can edit their profile. Everytime a profile is created with an empty profile_picture field a default value is provided. But once an image is assigned to field and then deleted. The field gets blank.
What I want is everytime the field becomes None I want to reassign the default image by mentioning the file path.

Heres My view where I save the model form:-

           if form.is_valid():
                form.save(commit=False)

                print(form.cleaned_data)
                if 'avatar' in form.cleaned_data:

                    if form.cleaned_data.get('avatar') is False:
                        form.cleaned_data['avatar'] = image

                form.save()

I want to mention the image path in place of image. Also suggest me some better ways for doing this. Thanks in advance


问:
how to resolve image directory in android
I'm picking an image from my android emulator gallery in order to serve it to the server but whenever I tried that, I got this error D/Main: /document/1AE6-2C19:Download/food2.jpg: open failed: ENOENT (No such file or directory). I have tried all the solutions for similar problems from stack overflow here yet that couldn't be resolved.
Here is the code</p>
```<code>    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode== PICK_IMAGE_REQUEST && resultCode== RESULT_OK ){

            profileImageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),profileImageUri);
                profilePicture.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
            profileImagePath = profileImageUri.toString();
        }
    }

    public void uploadProfileImage(){
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),profileImagePath);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file",profileImagePath,requestBody);

        Call<ImageDto> imageDtoCall = BaseUrlClient
                .getInstance().getApi().uploadProfileImage(body);
        imageDtoCall.enqueue(new Callback<ImageDto>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(Call<ImageDto> call, Response<ImageDto> response) {
                if (response.code()==201){
                    assert response.body() != null;
                    Log.d("Main","The image url is "+response.body().getDownloadUrl());
                    //createPatient(response.body().getDownloadUrl());
                }else {
                    Log.d("Main","Response code is "+response.code());
                    Toast.makeText(PatientRegistrationActivity.this, "Error Uploading Profile Image, Please Try Again", Toast.LENGTH_SHORT).show();
                    try {
                        Log.d("Main",response.errorBody().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ImageDto> call, Throwable t) {
                Log.d("Main",t.getMessage());
                Toast.makeText(PatientRegistrationActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });
    }

My Interface

@Multipart
    @POST("profileImage/upload")
    Call<ImageDto> uploadProfileImage(@Part MultipartBody.Part image);

My baseUrl class

public class BaseUrlClient {

    private static final String BASE_URL = "http://192.168.43.5:8080/";

    private static BaseUrlClient mInstance;
    private Retrofit retrofit;

    private BaseUrlClient(){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                //.addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    public static synchronized BaseUrlClient getInstance(){
        if (mInstance ==null){
            mInstance = new BaseUrlClient();
        }
        return mInstance;
    }
    public ApiClient getApi(){
        return retrofit.create(ApiClient.class);
    }
}

Response class

public class ImageDto {

    private String fileName;
    private String downloadUrl;
    private String fileType;
    private long fileSize;

    public String getFileName() {
        return fileName;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public String getFileType() {
        return fileType;
    }

    public long getFileSize() {
        return fileSize;
    }

    public ImageDto() {
    }
}
</code>```

Body:
I'm picking an image from my android emulator gallery in order to serve it to the server but whenever I tried that, I got this error D/Main: /document/1AE6-2C19:Download/food2.jpg: open failed: ENOENT (No such file or directory). I have tried all the solutions for similar problems from stack overflow here yet that couldn't be resolved.
Here is the code

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode== PICK_IMAGE_REQUEST && resultCode== RESULT_OK ){

            profileImageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),profileImageUri);
                profilePicture.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
            profileImagePath = profileImageUri.toString();
        }
    }

    public void uploadProfileImage(){
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),profileImagePath);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file",profileImagePath,requestBody);

        Call<ImageDto> imageDtoCall = BaseUrlClient
                .getInstance().getApi().uploadProfileImage(body);
        imageDtoCall.enqueue(new Callback<ImageDto>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(Call<ImageDto> call, Response<ImageDto> response) {
                if (response.code()==201){
                    assert response.body() != null;
                    Log.d("Main","The image url is "+response.body().getDownloadUrl());
                    //createPatient(response.body().getDownloadUrl());
                }else {
                    Log.d("Main","Response code is "+response.code());
                    Toast.makeText(PatientRegistrationActivity.this, "Error Uploading Profile Image, Please Try Again", Toast.LENGTH_SHORT).show();
                    try {
                        Log.d("Main",response.errorBody().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ImageDto> call, Throwable t) {
                Log.d("Main",t.getMessage());
                Toast.makeText(PatientRegistrationActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });
    }

My Interface

@Multipart
    @POST("profileImage/upload")
    Call<ImageDto> uploadProfileImage(@Part MultipartBody.Part image);

My baseUrl class

public class BaseUrlClient {

    private static final String BASE_URL = "http://192.168.43.5:8080/";

    private static BaseUrlClient mInstance;
    private Retrofit retrofit;

    private BaseUrlClient(){
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                //.addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    public static synchronized BaseUrlClient getInstance(){
        if (mInstance ==null){
            mInstance = new BaseUrlClient();
        }
        return mInstance;
    }
    public ApiClient getApi(){
        return retrofit.create(ApiClient.class);
    }
}

Response class

public class ImageDto {

    private String fileName;
    private String downloadUrl;
    private String fileType;
    private long fileSize;

    public String getFileName() {
        return fileName;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public String getFileType() {
        return fileType;
    }

    public long getFileSize() {
        return fileSize;
    }

    public ImageDto() {
    }
}


问:
How do I subset and manipulate time series data with lubridate and dplyr in Rstudio?
I have loaded in time series data of creek depth and am needing to calculate total annual values (Oct-April) for each year. The following is what I have tried thus far:

```<code>depth <- read_csv("Depth.Water_Depth-_All_Instruments@GCNP_-_Robber's_Roost_Spring.EntireRecord .csv")

</code>```

The following is a screenshot of the resulting data frame
enter image description here

These are my attempts at making the timestamp column (ISO_UTC) into a date class. Although, each attempt makes all values for ISO_UTC into N/A values instead of dates / times.

```<code>ymd_hm(depth$ISO_UTC)

depth$ISO_UTC<- as.Date(depth$ISO_UTC, format = "%Y-%m-%dT%H:%M")

depth$ISO_UTC<- as.POSIXct(depth$ISO_UTC, format = "%Y-%m-%d %H:%M", tz = "US/Pacific")
</code>```

Please help me to put these data into usable datetime values.

Please see the above details.

Body:
I have loaded in time series data of creek depth and am needing to calculate total annual values (Oct-April) for each year. The following is what I have tried thus far:

depth <- read_csv("Depth.Water_Depth-_All_Instruments@GCNP_-_Robber's_Roost_Spring.EntireRecord .csv")

The following is a screenshot of the resulting data frame
enter image description here

These are my attempts at making the timestamp column (ISO_UTC) into a date class. Although, each attempt makes all values for ISO_UTC into N/A values instead of dates / times.

ymd_hm(depth$ISO_UTC)

depth$ISO_UTC<- as.Date(depth$ISO_UTC, format = "%Y-%m-%dT%H:%M")

depth$ISO_UTC<- as.POSIXct(depth$ISO_UTC, format = "%Y-%m-%d %H:%M", tz = "US/Pacific")

Please help me to put these data into usable datetime values.

Please see the above details.


问:
import "streamlit_webrtc" could not be resolved Pylance(reportMissingImports)
enter image description here
Whenever I run my streamlit server on terminal "streamlit run app.py" I got that error shown on the pictures. Streamlit is working fine but streamlit_webrtc makes me in trouble.

I have tried every possible ways to solve this error like uninstall re-install Python, re-install streamlit,streamlit-webrtc. I have also created virtual private network to run this codes on several IDE but unable to fix that error.

Guys help me to out from this.


问:
creating a confusion maxtrix out of various data files but getting ValueError : x and y must be the same size
I'm new to python and trying to create a sentiment analysis using VADER

I pulled various artists (13) data into individual dataframes, converted the lyrics to words, found only the unique words, remove stopwords and all that then put it all into a single df

```<code>#for all the artists clean, get the single event of the word and place it in the list
df_allocate = []
for df in df_all:
    df_clean = cleaning(df)
    df_words = to_unique_words(df_clean)
    df_allocate.append(df_words)

frames = df_allocate
# create the new column with the information of words lists
df_main = pd.concat(frames, ignore_index=True)
df_main = df_main.reset_index(drop=True)
</code>```

Now I'm trying to train a logistic regression model, predict test results and get a confusion matrix.

I think I'm getting confused about how data frames work and also how to train_test_split the data correctly.

Right now, I have:

```<code>for column_name in df_all:
    cv = CountVectorizer(max_features=100000)
    X = cv.fit_transform(df_main['Artist']).toarray()
    y = column_name.sentiment

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.50, random_state=20)

    classifier = LogisticRegression(random_state= 25)
    classifier.fit(X_train, y_train)

    y_predict = classifier.predict(X_test)

    print_confusionMatrix = confusion_matrix(y_test, y_predict)
    print(print_confusionMatrix)
    print("accuracy score : ", accuracy_score(y_test, y_predict))
</code>```

When I debug the program, I see why it's complaining however, I don't know how to fix it. I looked over how to iterate through dataframe and tried doing

```<code>for df in df_all.index
</code>```

but it didn't work.

The columns are Artist, Title, Album, Date, Lyric, Year, and sentiment. What I want to accomplish is to iterate through each artist (df_all has the data frames of each individual artist, and that is why I use it), and get a prediction of the sentiment analysis of their lyrics to build a confusion matrix for all the 13 artists.

Previous tries are changing x to, and y keep it as that, so it's:

```<code>X = cv.fit_transform(df_main).toarray()
y = df_main.sentiment
</code>```

however, this is where I get the error that x and y must be the same size.

Please push me in the right direction. I'm quite lost.

Body:
I'm new to python and trying to create a sentiment analysis using VADER

I pulled various artists (13) data into individual dataframes, converted the lyrics to words, found only the unique words, remove stopwords and all that then put it all into a single df

#for all the artists clean, get the single event of the word and place it in the list
df_allocate = []
for df in df_all:
    df_clean = cleaning(df)
    df_words = to_unique_words(df_clean)
    df_allocate.append(df_words)

frames = df_allocate
# create the new column with the information of words lists
df_main = pd.concat(frames, ignore_index=True)
df_main = df_main.reset_index(drop=True)

Now I'm trying to train a logistic regression model, predict test results and get a confusion matrix.

I think I'm getting confused about how data frames work and also how to train_test_split the data correctly.

Right now, I have:

for column_name in df_all:
    cv = CountVectorizer(max_features=100000)
    X = cv.fit_transform(df_main['Artist']).toarray()
    y = column_name.sentiment

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.50, random_state=20)

    classifier = LogisticRegression(random_state= 25)
    classifier.fit(X_train, y_train)

    y_predict = classifier.predict(X_test)

    print_confusionMatrix = confusion_matrix(y_test, y_predict)
    print(print_confusionMatrix)
    print("accuracy score : ", accuracy_score(y_test, y_predict))

When I debug the program, I see why it's complaining however, I don't know how to fix it. I looked over how to iterate through dataframe and tried doing

for df in df_all.index

but it didn't work.

The columns are Artist, Title, Album, Date, Lyric, Year, and sentiment. What I want to accomplish is to iterate through each artist (df_all has the data frames of each individual artist, and that is why I use it), and get a prediction of the sentiment analysis of their lyrics to build a confusion matrix for all the 13 artists.

Previous tries are changing x to, and y keep it as that, so it's:

X = cv.fit_transform(df_main).toarray()
y = df_main.sentiment

however, this is where I get the error that x and y must be the same size.

Please push me in the right direction. I'm quite lost.


问:
After Cancel button click on Windows Authentication is not showing again under Angular WebApp + IIS
I have deployed my Angular Web App over the IIS and we have a page where router guard is enabled and that's the first page, that'll come after the authentication popup.

Within the Auth Guard we have called an API which in turn return current windows login username and we have an interceptor for the same which in between check weather the endpoint returns 401 Unauthorized error and after catching the same I'm reloading the page using window.location.reload().

So on click of Cancel of Windows Authentication popup in chrome after page reload able to see the windows authentication popup. But the same popup is not visible under Edge and Firefox again on click of cancel.

Because I have given the fix as to reload the page on the 401: Unauthorized Error with window.location.reload() under the interceptor.

error-handler.interceptor.ts

```<code>import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { GlobalMessages } from '../data/messages';
import { MessageDialogType } from '../types/message-type';
import { MessageService } from './message-service';

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {

  constructor( private msg: MessageService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
      event => event instanceof HttpResponse ? 'succeeded' : '',
      err => {
        if(err.status === 401){
          window.location.reload();
        }else{
          // Some error message popup
        }
      }
    ))
  }
}

</code>```

app.routing.ts

app.module.ts

Windows Authentication Popup

Issue: On cancel after page reload popup is not coming again in Firefox and Microsoft Edge. But the same is working in chrome

Body:
I have deployed my Angular Web App over the IIS and we have a page where router guard is enabled and that's the first page, that'll come after the authentication popup.

Within the Auth Guard we have called an API which in turn return current windows login username and we have an interceptor for the same which in between check weather the endpoint returns 401 Unauthorized error and after catching the same I'm reloading the page using window.location.reload().

So on click of Cancel of Windows Authentication popup in chrome after page reload able to see the windows authentication popup. But the same popup is not visible under Edge and Firefox again on click of cancel.

Because I have given the fix as to reload the page on the 401: Unauthorized Error with window.location.reload() under the interceptor.

error-handler.interceptor.ts

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { GlobalMessages } from '../data/messages';
import { MessageDialogType } from '../types/message-type';
import { MessageService } from './message-service';

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {

  constructor( private msg: MessageService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(tap(
      event => event instanceof HttpResponse ? 'succeeded' : '',
      err => {
        if(err.status === 401){
          window.location.reload();
        }else{
          // Some error message popup
        }
      }
    ))
  }
}

app.routing.ts

app.module.ts

Windows Authentication Popup

Issue: On cancel after page reload popup is not coming again in Firefox and Microsoft Edge. But the same is working in chrome


问:
how to use cakePHP addUnauthenticatedActions() with tokens in the URL
I am working in Cake 4 and have successfully included the authentication plugin that replaces the deprecated Auth(). To avoid an infinite redirect loop I have added the actions I want excluded from authentication similar to that shown in the Cake CMS tutorial.

UsersController:

$this->Authentication->addUnauthenticatedActions(['login', 'forgotpassword', 'resetpassword']);

I intend to use tokens for the resetpassword action and a reset link sent to a user will look something like this.

http://localhost/axletrace/users/resetpassword7724d1bbd400e0bd624411549a2dd64c6b73481e

Because the action requested now looks like 'resetpassword7724d1bbd400e0bd624411549a2dd64c6b73481e', it is not a match to the exclusions listed above and it redirects to the login page.

I have tried using a wildcard as shown below but it makes no difference.
$this->Authentication->addUnauthenticatedActions(['login', 'forgotpassword', 'resetpassword*']);

Given that the token is not a static value what is the way to handle this situation. I am trying to use the token as an authentication token only. I would prefer not to use JWT Authentication and I am not worrying about session tokens for the time being.

Any help would be apprecated, thanks.


Title: Huggingface model inference issue

Body:
I'm trying to use my pre-trained huggingface model to predict.

    outputs = model(
        ids,
        mask,
        token_type_ids
    )
    outputs = torch.sigmoid(outputs.last_hidden_state).cpu().detach().numpy()
    return outputs[0][0]

The I got is

[[[0.5144298  0.68467325 0.4045368  ... 0.5698948  0.6843927  0.230076  ]
  [0.526383   0.6108195  0.46920577 ... 0.6635995  0.70778817 0.22947823]
  [0.47112644 0.6557672  0.49308282 ... 0.61219037 0.5811446  0.22059086]
  ...
  [0.46904904 0.66370267 0.4091996  ... 0.5381582  0.70973885 0.2500361 ]
  [0.47025025 0.6625398  0.40454543 ... 0.5423772  0.71071064 0.24768841]
  [0.47398427 0.658539   0.40038437 ... 0.53121835 0.7094869  0.2417065 ]]]

What I want is

[{'label': 'POSITIVE', 'score': 0.9998743534088135},
 {'label': 'NEGATIVE', 'score': 0.9996669292449951}]

Thanks ahead!!!


问:
AttributeError list object has no attribute splitlines
I'm working on an object detection project using Python. Because I'm new to Python, I don't know how to fix this. I try all I can and still can't fix it. It was on loop detection.
I'm trying to use yolo and pytesseract at the same time.

Here is my program

```<code>

    class_ids = []
    confidences = []
    boxes = []
    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.5:
                # Object detected
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)

                # Rectangle coordinates
                x = int(center_x - w / 2)
                y = int(center_y - h / 2)

                boxes.append([x, y, w, h])
                confidences.append(float(confidence))
                class_ids.append(class_id)

    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
    print(indexes)
    font = cv2.FONT_HERSHEY_PLAIN
    for i in range(len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]
            label = str(classes[class_ids[i]])
            color = colors[class_ids[i]]
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            cv2.putText(frame, label, (x, y + 30), font, 3, color, 3)

    for box in boxes.splitlines():
        box = box.split(' ')

        x, y, w, h = int(box[1]), int(box[2]), int(box[3]), int(box[4])
        name = box[0]

        print(text)
        cv2.rectangle(frame, (x, height-y), (w, height-h), (50,50,255), 1)
        cv2.putText(frame, name, (x, height-y+25), cv2.FONT_HERSHEY_PLAIN, 1, (50,50,255), 2)

</code>```

Body:
I'm working on an object detection project using Python. Because I'm new to Python, I don't know how to fix this. I try all I can and still can't fix it. It was on loop detection.
I'm trying to use yolo and pytesseract at the same time.

Here is my program

    class_ids = []
    confidences = []
    boxes = []
    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.5:
                # Object detected
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)

                # Rectangle coordinates
                x = int(center_x - w / 2)
                y = int(center_y - h / 2)

                boxes.append([x, y, w, h])
                confidences.append(float(confidence))
                class_ids.append(class_id)

    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
    print(indexes)
    font = cv2.FONT_HERSHEY_PLAIN
    for i in range(len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]
            label = str(classes[class_ids[i]])
            color = colors[class_ids[i]]
            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
            cv2.putText(frame, label, (x, y + 30), font, 3, color, 3)

    for box in boxes.splitlines():
        box = box.split(' ')

        x, y, w, h = int(box[1]), int(box[2]), int(box[3]), int(box[4])
        name = box[0]

        print(text)
        cv2.rectangle(frame, (x, height-y), (w, height-h), (50,50,255), 1)
        cv2.putText(frame, name, (x, height-y+25), cv2.FONT_HERSHEY_PLAIN, 1, (50,50,255), 2)


问:
data-widget="pushmenu" Not Working Admin LTE 3
I am confused somehow the push menu is not working. When the view changes to mobile, the menu will not appear.

Heres My view :

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <?= $this->load->view($head); ?>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <nav class="main-header navbar navbar-expand navbar-dark navbar-light">
            <ul class="navbar-nav">
                <li class="nav-item">
                    <a class="nav-link" data-widget="pushmenu" href="#"><i class="fas fa-bars"></i></a>
                </li>
            </ul>
            <ul class="navbar-nav ml-auto">
</code>```

Please if there is a case similar to mine to share

Body:
I am confused somehow the push menu is not working. When the view changes to mobile, the menu will not appear.

Heres My view :

<!DOCTYPE html>

    <?= $this->load->view($head); ?>

Please if there is a case similar to mine to share


问:
Cypress BDD Cucumber Framework- Step Definition misconfigured issue
While running the test the following issue arises,

We tried searching for files containing step definitions using the following search pattern templates:

cypress\e2e\features/[filepath]/*/.{js,mjs,ts,tsx}

cypress\e2e\features/[filepath].{js,mjs,ts,tsx}

cypress/support/step_definitions/*/.{js,mjs,ts,tsx}

These templates resolved to the following search patterns:

cypress\e2e\features\login*.{js,mjs,ts,tsx}

cypress\e2e\features\login.{js,mjs,ts,tsx}

cypress\support\step_definitions*.{js,mjs,ts,tsx}

These patterns matched no files containing step definitions. This almost certainly means that you have misconfigured stepDefinitions.

Trying to run the test with BDD-cucumber framework in Cypress


问:
Dealing with trailing decimals at the end of a DateTime
I am trying to convert the string below into a datetime object using datetime.strptime, and I just can't seem to figure out .746Z at the end.

```<code>datetime_str = '2022-04-21T08:17:49.746Z'

datetime_object = datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S.%z')
print(datetime_object)
</code>```

Body:
I am trying to convert the string below into a datetime object using datetime.strptime, and I just can't seem to figure out .746Z at the end.

datetime_str = '2022-04-21T08:17:49.746Z'

datetime_object = datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S.%z')
print(datetime_object)


问:
Data Copy from Kernal Space to User Space regarding reading data from disk
I want to understand how ready system call work and its design.

My understanding on reading data from disk:

Process makes a system call, read, to Operating system

OS coordinates with driver, hardware to fetch disk blocks into the page cache

OS copy the data from page cache to process's buffer

Am I correct?

If I'm correct, I have 2 follow-up questions

Why OS needs to copy data from page cache (kernel space) into process's buffer (user space)?

I saw people were talking about the copy_to_user & copy_from_user functions, it does some sanity check during the copy & prevent illegal copy. However, couldn't we just check if the copy is legal or not and return the reference to the process? If the request is legal, we return the reference. If the request is illegal, we reject.

In case the process needs to write the data and we don't want the process to manipulate the kernel space (for security reason or the data is shared by other processes), we only copy data to user space at this moment.

When OS copies the data from page cache to process's buffer, do physical memory hold 2 pieces of data? 1 for page cache & another for process's buffer. Or there is only 1 piece of data in physical memory, data from page cache and process's buffer map to this single piece of data?


问:
RDLC adding parameter to report causes report definition to change from 2008 to 2016
Using Visual Studio 2019 Enterprise with SQL Server 2014. When adding a RDLC report the report definition changes from 2008 to 2016 and the report throws an error.

When I first create a blank rdlc with no datasource and open in with HTML editor, I see

```<code><Report xmlns=“https://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition” xmlns:rd=“https://schemas.microsoft.com/SQLServer/reporting/reportdesigner”>
</code>```

After I add a parameter with still no datasource it changes to this.

```<code><Report xmlns=“https://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition” xmlns:rd=“https://schemas.microsoft.com/SQLServer/reporting/reportdesigner”>
</code>```

before add parameter
enter image description here

after add parameter
enter image description here

error
enter image description here

about property
enter image description here

and project properties
enter image description here

Body:
Using Visual Studio 2019 Enterprise with SQL Server 2014. When adding a RDLC report the report definition changes from 2008 to 2016 and the report throws an error.

When I first create a blank rdlc with no datasource and open in with HTML editor, I see

<Report xmlns=“https://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition” xmlns:rd=“https://schemas.microsoft.com/SQLServer/reporting/reportdesigner”>

After I add a parameter with still no datasource it changes to this.

<Report xmlns=“https://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition” xmlns:rd=“https://schemas.microsoft.com/SQLServer/reporting/reportdesigner”>

before add parameter
enter image description here

after add parameter
enter image description here

error
enter image description here

about property
enter image description here

and project properties
enter image description here


问:
Deadlock due to keylock and page lock in SQL Server
We are facing deadlock for 2 to 3 times a day. When we analysed it is due to keylock and pagelock happening together.

We found deadlock is between the database replication job and other ETL job

Keylock is owned as Exclusive lock (x) by the database replication job on the clustered index column, and when ETL process is trying to get shared lock (s) on the same index it is failing as victim.

The page lock is owned by the ETL process as shared lock (s) and the replication job is getting an Intent Exclusive lock (ix) on the same.

When we try re-running the failed ETL job after some time it is getting completed. ETL job has only select query and no updates, inserts or deletes. It is only truncate and load. Further it is not happening in all jobs which is hitting the same server, only few jobs are getting failed. The replication job is set to run all the time.

Will SELECT(NO LOCK) help in this case? Or increasing the deadlock priority of ETL job?

Could anyone help how to resolve this deadlock?


问:
mysqldump in .php file
What's wrong with the exec() function

```<code><?php

exec('mysqldump --host=localhost --user=root --password="" testing > C:/Users/deleo/Desktop/newfile.sql');

?>
</code>```

when I run this code it's nothing happen but only white screen

I expected the output .sql file with my database(testing) table structure and data itself

When I did this

`

```<code><?php
define("BACKUP_PATH", "C:/Users/deleo/Desktop/");

$server_name   = "localhost";
$username      = "root";
$password      = "";
$database_name = "testing";
$date_string   = date("Ymd");

$cmd = "mysqldump --hex-blob --routines --skip-lock-tables --log-error=mysqldump_error.log -h {$server_name} -u {$username} -p{$password} {$database_name} > " . BACKUP_PATH . "{$date_string}_{$database_name}.sql";

$arr_out = array();
unset($return);

exec($cmd, $arr_out, $return);

if($return !== 0) {
    echo "mysqldump for {$server_name} : {$database_name} failed with a return code of {$return}\n\n";
    echo "Error message was:\n";
    $file = escapeshellarg("mysqldump_error.log");
    $message = `tail -n 1 $file`;
    echo "- $message\n\n";
}
?>
</code>```

`

I got this error
mysqldump for localhost : tapsihannibhey failed with a return code of 1 Error message was: -

Title: mysqldump in .php file

Body:
What's wrong with the exec() function

<?php

exec('mysqldump --host=localhost --user=root --password="" testing > C:/Users/deleo/Desktop/newfile.sql');

?>

when I run this code it's nothing happen but only white screen

I expected the output .sql file with my database(testing) table structure and data itself

When I did this

`

<?php
define("BACKUP_PATH", "C:/Users/deleo/Desktop/");

$server_name   = "localhost";
$username      = "root";
$password      = "";
$database_name = "testing";
$date_string   = date("Ymd");

$cmd = "mysqldump --hex-blob --routines --skip-lock-tables --log-error=mysqldump_error.log -h {$server_name} -u {$username} -p{$password} {$database_name} > " . BACKUP_PATH . "{$date_string}_{$database_name}.sql";

$arr_out = array();
unset($return);

exec($cmd, $arr_out, $return);

if($return !== 0) {
    echo "mysqldump for {$server_name} : {$database_name} failed with a return code of {$return}\n\n";
    echo "Error message was:\n";
    $file = escapeshellarg("mysqldump_error.log");
    $message = `tail -n 1 $file`;
    echo "- $message\n\n";
}
?>

`

I got this error
mysqldump for localhost : tapsihannibhey failed with a return code of 1 Error message was: -


问:
Why is my HTML template in Django not rendering in browser?
I am having issues with rendering an HTML template that has variables passed to it from my views.py in the Django project.

Everything seems to be working with the exception that when you visit the HTML in a browser on my local machine it renders the HTML code, instead of the designed page with content.

the files are below.

VIEWS.PY

```<code>from django.shortcuts import render
import datetime
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

db = firestore.Client()

config = {
    "apiKey": "XXXXXXXXXXXXXXXXXXX",
    "authDomain": "XXXXXXXXXXXXXXXXXXX.firebaseapp.com",
    "databaseURL": "https://XXXXXXXXXXXXXXXXXXX.firebaseio.com",
    "projectId": "XXXXXXXXXXXXXXXXXXX",
    "storageBucket": "XXXXXXXXXXXXXXXXXXX.appspot.com",
    "messagingSenderId": "XXXXXXXXXXXXXXXXXXX",
    "appId": "XXXXXXXXXXXXXXXXXXX",
    "measurementId": "XXXXXXXXXXXXXXXXXXX",
    "serviceAccount": "XXXXXXXXXXXXXXXXXXX.json",
    }

# DATABASE
# Use the application default credentials.
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred)
firestore_client = firestore.client()

# TIME & DATE
today_date = datetime.datetime.now()
tomorrow_date = today_date + datetime.timedelta(days=1)
games_today = today_date.date()
games_tomorrow = tomorrow_date.date()
games_today_formatted = games_today.strftime("%Y-%m-%d")
games_tomorrow_formatted = games_tomorrow.strftime("%Y-%m-%d")

def basketball_nba(request):

    ############################################################################
    # ENTAIN (NEDS/LADBROKES)
    ############################################################################
    # Query firestore database for NBA games
    nba_events = db.collection('entain_au').document('basketball_nba').collection('event_odds').stream()
    event_info = [doc.to_dict() for doc in nba_events]

    # print(event_info)

    # Filter NBA games by dates
    events_today = [event for event in event_info if event['event_odds']['Event']['StartTime'][:10] == games_today]
    events_tomorrow = [event for event in event_info if
                       event['event_odds']['Event']['StartTime'][:10] == games_tomorrow]

    # print(events_today)
    # print('Tomorrow:', events_tomorrow)

    # List of NBA games today win odds data
    entain_h2h_today = []
    # List of NBA games tomorrow win odds data
    entain_h2h_tomorrow = []

    # Iterate through NBA games json for today's games to get win odds data
    try:
        for h2h in events_today:
            if h2h['event_odds']['Event']['Markets']:
                for market in h2h['event_odds']['Event']['Markets']:
                    if market['Name'] == 'Head To Head':
                        print(market['Selections'])
                        if market['Selections']:
                            game_data = {}  # Create empty dictionary to store game data
                            for selection in market['Selections']:
                                if selection['Role'] == 'Home':
                                    game_data['home_team'] = selection['Name']
                                    game_data['home_odds'] = selection['WinPrice']
                                if selection['Role'] == 'Away':
                                    game_data['away_team'] = selection['Name']
                                    game_data['away_odds'] = selection['WinPrice']
                            entain_h2h_today.append(game_data)  # Append game data to list
    except KeyError:
        print('No NBA games today')

    # Iterate through NBA games json for today's games to get win odds data
    try:
        for h2h in events_tomorrow:
            if h2h['event_odds']['Event']['Markets']:
                for market in h2h['event_odds']['Event']['Markets']:
                    if market['Name'] == 'Line':
                        print(market['Selections'])
                        if market['Selections']:
                            game_data = {}  # Create empty dictionary to store game data
                            for selection in market['Selections']:
                                if selection['Role'] == 'Home':
                                    game_data['home_team'] = selection['Name']
                                    game_data['home_handicap'] = selection['Handicap']
                                    game_data['home_odds'] = selection['WinPrice']
                                if selection['Role'] == 'Away':
                                    game_data['away_team'] = selection['Name']
                                    game_data['away_odds'] = selection['WinPrice']
                            entain_h2h_tomorrow.append(game_data)  # Append game data to list
    except KeyError:
            print('No NBA games tomorrow')

    ############################################################################
    # UNIBET
    ############################################################################

    # Query firestore database for NBA games
    nba_events = firestore_client.collection('unibet_au') \
        .document('basketball_nba') \
        .collection('event_odds') \
        .stream()

    # Convert the nba_events generator object to a list
    nba_events_list = list(nba_events)

    # Print the number of events in the nba_events_list variable
    print(len(nba_events_list))

    # Parse event data
    event_info = [doc.to_dict() for doc in nba_events_list]
    # print(event_info)

    # Filter NBA games by dates
    events_today = [event for event in event_info if
                    event['event_odds']['events'][0]['start'][:10] == games_today_formatted]
    events_tomorrow = [event for event in event_info if
                       event['event_odds']['events'][0]['start'][:10] == games_tomorrow_formatted]

    # Print the number of events today and tomorrow
    print(len(events_today))
    # print(len(events_tomorrow))

    # Print the events today and tomorrow
    # print(events_today)
    # print(events_tomorrow)

    # List of NBA games today win odds data
    unibet_h2h_today = []
    # List of NBA games tomorrow win odds data
    unibet_h2h_tomorrow = []

    # Set the market type you are looking for
    market_type = "Head To Head - Including Overtime"

    # Use a list comprehension to extract the data for each event
    h2h_data = [{"game": event['event_odds']['events'][0]['name'],
                 "market_type": bet_offer['criterion']['label'],
                 "home_team": bet_offer['outcomes'][0]['englishLabel'],
                 "home_team_h2h_odds": bet_offer['outcomes'][0]['odds'],
                 "away_team": bet_offer['outcomes'][1]['englishLabel'],
                 "away_team_h2h_odds": bet_offer['outcomes'][1]['odds'],
                 }
                for event in event_info
                for bet_offer in event['event_odds']['betOffers']
                if bet_offer['criterion']['label'] == market_type]

    # Filter & print the h2h_data list
    for win_odds in h2h_data:
        game = win_odds['game']
        home_team = win_odds['home_team']
        home_team_h2h_odds = win_odds['home_team_h2h_odds'] / 1000
        away_team = win_odds['away_team']
        away_team_h2h_odds = win_odds['away_team_h2h_odds'] / 1000
        unibet_h2h_today.append({
            "game": game,
            "home_team": home_team,
            "home_team_h2h_odds": home_team_h2h_odds,
            "away_team": away_team,
            "away_team_h2h_odds": away_team_h2h_odds,
        })
        print(unibet_h2h_today)
        unibet_h2h_tomorrow.append({
            "game": game,
            "home_team": home_team,
            "home_team_h2h_odds": home_team_h2h_odds,
            "away_team": away_team,
            "away_team_h2h_odds": away_team_h2h_odds,
        })

        # Create an HttpResponse object by rendering an HTML template
        response = render(request, "nba.html", {
            'entain_h2h_today': entain_h2h_today,
            'entain_h2h_tomorrow': entain_h2h_tomorrow,
            'unibet_h2h_today': unibet_h2h_today,
            'unibet_h2h_tomorrow': unibet_h2h_tomorrow,
        })
        # Return the response
        return response

</code>```

URLS.PY

```<code>from django.contrib import admin
from django.urls import path
import nba.views as views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('nba/', views.basketball_nba, name='basketball_nba'),
]
</code>```

NBA.HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>NBA TESTING</title>
</head>
<body>
<!-- TODAY'S EVENTS - WIN ODDS -->
<h3>Today's NBA Games Odds</h3>

<div class="table-responsive" style="width: 1000px;">
    <table class="table">
        <thead>
            <tr>
                <th>Bookie</th>
                <th>Home</th>
                <th>Home Odds</th>
                <th>Away</th>
                <th>Away odds</th>
            </tr>
        </thead>
        <tbody>
            {% for h2h in entain_h2h_today %}
                <tr>
                    <td>Entain</td>
                    <td>{{ h2h.home_team }}</td>
                    <td>{{ h2h.home_odds }}</td>
                    <td>{{ h2h.away_team }}</td>
                    <td>{{ h2h.away_odds }}</td>
                </tr>
            {% endfor %}
            {% for h2h in unibet_h2h_today %}
                <tr>
                    <td>unibet</td>
                    <td>{{ h2h.home_team }}</td>
                    <td>{{ h2h.home_team_h2h_odds }}</td>
                    <td>{{ h2h.away_team }}</td>
                    <td>{{ h2h.away_team_h2h_odds }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

</body>
</html>
</code>```

Page in browser look:

Body:
I am having issues with rendering an HTML template that has variables passed to it from my views.py in the Django project.

Everything seems to be working with the exception that when you visit the HTML in a browser on my local machine it renders the HTML code, instead of the designed page with content.

the files are below.

VIEWS.PY

from django.shortcuts import render
import datetime
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

db = firestore.Client()

config = {
    "apiKey": "XXXXXXXXXXXXXXXXXXX",
    "authDomain": "XXXXXXXXXXXXXXXXXXX.firebaseapp.com",
    "databaseURL": "https://XXXXXXXXXXXXXXXXXXX.firebaseio.com",
    "projectId": "XXXXXXXXXXXXXXXXXXX",
    "storageBucket": "XXXXXXXXXXXXXXXXXXX.appspot.com",
    "messagingSenderId": "XXXXXXXXXXXXXXXXXXX",
    "appId": "XXXXXXXXXXXXXXXXXXX",
    "measurementId": "XXXXXXXXXXXXXXXXXXX",
    "serviceAccount": "XXXXXXXXXXXXXXXXXXX.json",
    }

# DATABASE
# Use the application default credentials.
cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred)
firestore_client = firestore.client()

# TIME & DATE
today_date = datetime.datetime.now()
tomorrow_date = today_date + datetime.timedelta(days=1)
games_today = today_date.date()
games_tomorrow = tomorrow_date.date()
games_today_formatted = games_today.strftime("%Y-%m-%d")
games_tomorrow_formatted = games_tomorrow.strftime("%Y-%m-%d")

def basketball_nba(request):

    ############################################################################
    # ENTAIN (NEDS/LADBROKES)
    ############################################################################
    # Query firestore database for NBA games
    nba_events = db.collection('entain_au').document('basketball_nba').collection('event_odds').stream()
    event_info = [doc.to_dict() for doc in nba_events]

    # print(event_info)

    # Filter NBA games by dates
    events_today = [event for event in event_info if event['event_odds']['Event']['StartTime'][:10] == games_today]
    events_tomorrow = [event for event in event_info if
                       event['event_odds']['Event']['StartTime'][:10] == games_tomorrow]

    # print(events_today)
    # print('Tomorrow:', events_tomorrow)

    # List of NBA games today win odds data
    entain_h2h_today = []
    # List of NBA games tomorrow win odds data
    entain_h2h_tomorrow = []

    # Iterate through NBA games json for today's games to get win odds data
    try:
        for h2h in events_today:
            if h2h['event_odds']['Event']['Markets']:
                for market in h2h['event_odds']['Event']['Markets']:
                    if market['Name'] == 'Head To Head':
                        print(market['Selections'])
                        if market['Selections']:
                            game_data = {}  # Create empty dictionary to store game data
                            for selection in market['Selections']:
                                if selection['Role'] == 'Home':
                                    game_data['home_team'] = selection['Name']
                                    game_data['home_odds'] = selection['WinPrice']
                                if selection['Role'] == 'Away':
                                    game_data['away_team'] = selection['Name']
                                    game_data['away_odds'] = selection['WinPrice']
                            entain_h2h_today.append(game_data)  # Append game data to list
    except KeyError:
        print('No NBA games today')

    # Iterate through NBA games json for today's games to get win odds data
    try:
        for h2h in events_tomorrow:
            if h2h['event_odds']['Event']['Markets']:
                for market in h2h['event_odds']['Event']['Markets']:
                    if market['Name'] == 'Line':
                        print(market['Selections'])
                        if market['Selections']:
                            game_data = {}  # Create empty dictionary to store game data
                            for selection in market['Selections']:
                                if selection['Role'] == 'Home':
                                    game_data['home_team'] = selection['Name']
                                    game_data['home_handicap'] = selection['Handicap']
                                    game_data['home_odds'] = selection['WinPrice']
                                if selection['Role'] == 'Away':
                                    game_data['away_team'] = selection['Name']
                                    game_data['away_odds'] = selection['WinPrice']
                            entain_h2h_tomorrow.append(game_data)  # Append game data to list
    except KeyError:
            print('No NBA games tomorrow')

    ############################################################################
    # UNIBET
    ############################################################################

    # Query firestore database for NBA games
    nba_events = firestore_client.collection('unibet_au') \
        .document('basketball_nba') \
        .collection('event_odds') \
        .stream()

    # Convert the nba_events generator object to a list
    nba_events_list = list(nba_events)

    # Print the number of events in the nba_events_list variable
    print(len(nba_events_list))

    # Parse event data
    event_info = [doc.to_dict() for doc in nba_events_list]
    # print(event_info)

    # Filter NBA games by dates
    events_today = [event for event in event_info if
                    event['event_odds']['events'][0]['start'][:10] == games_today_formatted]
    events_tomorrow = [event for event in event_info if
                       event['event_odds']['events'][0]['start'][:10] == games_tomorrow_formatted]

    # Print the number of events today and tomorrow
    print(len(events_today))
    # print(len(events_tomorrow))

    # Print the events today and tomorrow
    # print(events_today)
    # print(events_tomorrow)

    # List of NBA games today win odds data
    unibet_h2h_today = []
    # List of NBA games tomorrow win odds data
    unibet_h2h_tomorrow = []

    # Set the market type you are looking for
    market_type = "Head To Head - Including Overtime"

    # Use a list comprehension to extract the data for each event
    h2h_data = [{"game": event['event_odds']['events'][0]['name'],
                 "market_type": bet_offer['criterion']['label'],
                 "home_team": bet_offer['outcomes'][0]['englishLabel'],
                 "home_team_h2h_odds": bet_offer['outcomes'][0]['odds'],
                 "away_team": bet_offer['outcomes'][1]['englishLabel'],
                 "away_team_h2h_odds": bet_offer['outcomes'][1]['odds'],
                 }
                for event in event_info
                for bet_offer in event['event_odds']['betOffers']
                if bet_offer['criterion']['label'] == market_type]

    # Filter & print the h2h_data list
    for win_odds in h2h_data:
        game = win_odds['game']
        home_team = win_odds['home_team']
        home_team_h2h_odds = win_odds['home_team_h2h_odds'] / 1000
        away_team = win_odds['away_team']
        away_team_h2h_odds = win_odds['away_team_h2h_odds'] / 1000
        unibet_h2h_today.append({
            "game": game,
            "home_team": home_team,
            "home_team_h2h_odds": home_team_h2h_odds,
            "away_team": away_team,
            "away_team_h2h_odds": away_team_h2h_odds,
        })
        print(unibet_h2h_today)
        unibet_h2h_tomorrow.append({
            "game": game,
            "home_team": home_team,
            "home_team_h2h_odds": home_team_h2h_odds,
            "away_team": away_team,
            "away_team_h2h_odds": away_team_h2h_odds,
        })

        # Create an HttpResponse object by rendering an HTML template
        response = render(request, "nba.html", {
            'entain_h2h_today': entain_h2h_today,
            'entain_h2h_tomorrow': entain_h2h_tomorrow,
            'unibet_h2h_today': unibet_h2h_today,
            'unibet_h2h_tomorrow': unibet_h2h_tomorrow,
        })
        # Return the response
        return response

URLS.PY

from django.contrib import admin
from django.urls import path
import nba.views as views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('nba/', views.basketball_nba, name='basketball_nba'),
]

NBA.HTML

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>NBA TESTING</title>

Today's NBA Games Odds

                Bookie
                Home
                Home Odds
                Away
                Away odds

            {% for h2h in entain_h2h_today %}

                    Entain
                    {{ h2h.home_team }}
                    {{ h2h.home_odds }}
                    {{ h2h.away_team }}
                    {{ h2h.away_odds }}

            {% endfor %}
            {% for h2h in unibet_h2h_today %}

                    unibet
                    {{ h2h.home_team }}
                    {{ h2h.home_team_h2h_odds }}
                    {{ h2h.away_team }}
                    {{ h2h.away_team_h2h_odds }}

            {% endfor %}

Page in browser look:


问:
I need a solution for RnAlarmNotification.h file not found issue in ios app on xcode
My React native app working fine two days ago but when I  installed new library and did pod install then app is not running and showing error "RnAlarmNotification.h file not found" in ios app on xcode.

I tried to run application for implementing Stripe 3ds but app is not running. now I need to solve "RnAlarmNotification.h" file not found issue to further development.

Screen shot the error what issue I am facing.


问:
Trino Invalid partition spec:
I've created a external partition table in trino, I'm using hive connector.

I'm changing the partition location with unregister partition using command
system.unregister_partition(schema_name, table_name, partition_columns, partition_values)
and then register new partition location using system.register_partition(schema_name, table_name, partition_columns, partition_values, location).

Now If I run sync_partition_metadata system.sync_partition_metadata(schema_name, table_name, mode, case_sensitive) it is getting failed with below error

```<code>trino:default> call system.sync_partition_metadata('default','register_tbl1','full');
Query 20221207_050340_00129_cs2qk failed: Invalid partition spec: /path/default/compact_register_tbl1/partition_col=2022-12-07
</code>```

Is there any other way to handle this call if we are changing the partition locations ??

Thanks in advance!

Title: Trino Invalid partition spec:

Body:
I've created a external partition table in trino, I'm using hive connector.

I'm changing the partition location with unregister partition using command
system.unregister_partition(schema_name, table_name, partition_columns, partition_values)
and then register new partition location using system.register_partition(schema_name, table_name, partition_columns, partition_values, location).

Now If I run sync_partition_metadata system.sync_partition_metadata(schema_name, table_name, mode, case_sensitive) it is getting failed with below error

trino:default> call system.sync_partition_metadata('default','register_tbl1','full');
Query 20221207_050340_00129_cs2qk failed: Invalid partition spec: /path/default/compact_register_tbl1/partition_col=2022-12-07

Is there any other way to handle this call if we are changing the partition locations ??

Thanks in advance!


问:
API access to GCP control plane
I have an app that is built in Java and runs on app engine. This app will be installed by users in their own GCP account.

I want to build the capability where

Users can come to my website

Users can use “login with google” and provide access to my website.

My website app will use GCP API to create a project and install the application with app engine.

Also, want this permission to be temporary for 1 hr.

Is there a guide or documentation to do this?

Title: API access to GCP control plane


问:
How to perform CPU throttling on mobile app performance testing
I'm using android Google Pixel 4 device and I want to check mobile app performance on different CPU level.

Example:

Use Case 1: I want to calculate the my app launch time When the CPU usage on device is about to 30%.

Use Case 2: I want to calculate the my app launch time When the CPU usage on device is about to 50%.

Use Case 3: I want to calculate the my app launch time When the CPU usage on device is about to 80%.

It's kind of performance testing based on the CPU throttling.

Is there any tool which help me to simulate the CPU usage on my device so that I can test this use cases by manual?


问:
Audio output latency on BASS un4seen on android
I have been trying to stream mic feed directly from mic to speaker in which i am facing audio latency which varies from device to device.

Following is the code i have tried so far.

The library i am using right now is BASS un4seen for Android

```<code>val rchan = BASS.BASS_RecordStart(
        freq, chans, BASS.BASS_RECORD_PAUSE,
        { handle, _, _, _ ->
            BASSenc.BASS_Encode_IsActive(handle) != 0 // continue recording if encoder is alive
        }, 0
    )
val StreamProc =
        BASS.STREAMPROC { handle, buffer, length, user ->
            BASS.BASS_ChannelGetData(rchan, buffer, length) // get data from the recording stream
        }

    chanPlay = BASS.BASS_StreamCreate(44100, 1, 0, StreamProc, null);
    BASS.BASS_ChannelPlay(chanPlay, false);
    BASS.BASS_ChannelPlay(rchan, false)
</code>```

Body:
I have been trying to stream mic feed directly from mic to speaker in which i am facing audio latency which varies from device to device.

Following is the code i have tried so far.

The library i am using right now is BASS un4seen for Android

val rchan = BASS.BASS_RecordStart(
        freq, chans, BASS.BASS_RECORD_PAUSE,
        { handle, _, _, _ ->
            BASSenc.BASS_Encode_IsActive(handle) != 0 // continue recording if encoder is alive
        }, 0
    )
val StreamProc =
        BASS.STREAMPROC { handle, buffer, length, user ->
            BASS.BASS_ChannelGetData(rchan, buffer, length) // get data from the recording stream
        }

    chanPlay = BASS.BASS_StreamCreate(44100, 1, 0, StreamProc, null);
    BASS.BASS_ChannelPlay(chanPlay, false);
    BASS.BASS_ChannelPlay(rchan, false)


问:
How to keep unused columns/index after groupby action (SOLVED in post)
First, I appreciate any help that you can provide. I am getting a bit familiar with pandas but I still lack a lot of knowledge. The solution for this is probably easy, but I have been stuck for some time, so please help me if possible.

My current dataframe is way bigger with a ton of more options, but to make it simpler, let's say I have a dataframe that looks like this:

I will add a code to recreate the dataframe at the end.

Each subject answered three questions each day for two days, and I would like to know the number of correct or incorrect responses per day, per subject. I know I can achieve that by doing:
n_resp=df.groupby(['Subject','Day','Response']).count()

However, in that final result, the Group column is replaced by the result from count().I would like to conserve the 'Group' column because I will use it to create a plot that will differentiate between the two. How can I achieve that?

I tried adding 'Group' to the groupby, but the result comes back empty:
n_resp=df.groupby(['Group','Subject','Day','Response']).count() -> Dataframe with 4 indexed columns and 0 values.

I also tried to index the column that I don't need for groupby and then groupby, but it comes back empty and the indexed column is substituted by the groupby cols:
n_resp=df.set_index('Group').groupby(['Subject','Day','Response']).count()

Finally, I tried the groupby options as_index=False and group_keys=False after adding all the cols to groupby but it didn't work either.

I have also tried to look for it online, but don't know exactly how to. I am probably misunderstanding the basics of how index and groupby work in DataFrames, so if that's it, please explain or direct me to a guide for it. I have read the groupby webpage but I didn't find any example that could help me.

Thank you for any help.

SOLUTION: Provided by @jezrael in comments and based on this response.

The suggested dupe question requires to groupby all the columns, even if not needed. This solution doesn't require that:

```<code>n_resp=df.copy() # To avoid modifying original DataFrame
n_resp['count'] = n_resp.groupby(['Subject','Day','Response'])['Response'].transform('count') # Create new column where count will be stored
n_resp.drop_duplicates(['Subject','Day','Response'], inplace=True) # Remove duplicated rows
</code>```

This is how the result looks (might vary depending on randomized responses):

And here is the code to recreate the simplified DataFrame:

```<code>import pandas as pd
import random as rand

def rand_array_string(str_array,len_database):
    rand_array=['']*len_database
    for i in range(len_database):
        rand_array[i]=rand.choice(str_array)
    return rand_array

def repeat_strings(str_array,len_database):
    n_rep=int(len_database/len(str_array))
    rep_array=['']*len_database
    pos=0
    for i in range(n_rep):
        for string in str_array:
            rep_array[pos]=string
            pos+=1
    return rep_array

length=24

resp=rand_array_string(['Right','Wrong'], length)
subs=sorted(repeat_strings(['S1','S2','S3','S4'],length))
days=[str(n) for n in range(1,3)]
days=(sorted(days*3))*4
group=sorted(repeat_strings(['Young','Old'], length))

df = pd.DataFrame({'Group':group,
                   'Subject':subs,
                   'Day':days,
                   'Response':resp})
</code>```

Body:
First, I appreciate any help that you can provide. I am getting a bit familiar with pandas but I still lack a lot of knowledge. The solution for this is probably easy, but I have been stuck for some time, so please help me if possible.

My current dataframe is way bigger with a ton of more options, but to make it simpler, let's say I have a dataframe that looks like this:

I will add a code to recreate the dataframe at the end.

Each subject answered three questions each day for two days, and I would like to know the number of correct or incorrect responses per day, per subject. I know I can achieve that by doing:
n_resp=df.groupby(['Subject','Day','Response']).count()

However, in that final result, the Group column is replaced by the result from count().I would like to conserve the 'Group' column because I will use it to create a plot that will differentiate between the two. How can I achieve that?

I tried adding 'Group' to the groupby, but the result comes back empty:
n_resp=df.groupby(['Group','Subject','Day','Response']).count() -> Dataframe with 4 indexed columns and 0 values.

I also tried to index the column that I don't need for groupby and then groupby, but it comes back empty and the indexed column is substituted by the groupby cols:
n_resp=df.set_index('Group').groupby(['Subject','Day','Response']).count()

Finally, I tried the groupby options as_index=False and group_keys=False after adding all the cols to groupby but it didn't work either.

I have also tried to look for it online, but don't know exactly how to. I am probably misunderstanding the basics of how index and groupby work in DataFrames, so if that's it, please explain or direct me to a guide for it. I have read the groupby webpage but I didn't find any example that could help me.

Thank you for any help.

SOLUTION: Provided by @jezrael in comments and based on this response.

The suggested dupe question requires to groupby all the columns, even if not needed. This solution doesn't require that:

n_resp=df.copy() # To avoid modifying original DataFrame
n_resp['count'] = n_resp.groupby(['Subject','Day','Response'])['Response'].transform('count') # Create new column where count will be stored
n_resp.drop_duplicates(['Subject','Day','Response'], inplace=True) # Remove duplicated rows

This is how the result looks (might vary depending on randomized responses):

And here is the code to recreate the simplified DataFrame:

import pandas as pd
import random as rand

def rand_array_string(str_array,len_database):
    rand_array=['']*len_database
    for i in range(len_database):
        rand_array[i]=rand.choice(str_array)
    return rand_array

def repeat_strings(str_array,len_database):
    n_rep=int(len_database/len(str_array))
    rep_array=['']*len_database
    pos=0
    for i in range(n_rep):
        for string in str_array:
            rep_array[pos]=string
            pos+=1
    return rep_array

length=24

resp=rand_array_string(['Right','Wrong'], length)
subs=sorted(repeat_strings(['S1','S2','S3','S4'],length))
days=[str(n) for n in range(1,3)]
days=(sorted(days*3))*4
group=sorted(repeat_strings(['Young','Old'], length))

df = pd.DataFrame({'Group':group,
                   'Subject':subs,
                   'Day':days,
                   'Response':resp})


问:
Why is this c program showing the output Information Technology
```<code>#include<stdio.h>

void main( )

{

    float x=3.14;

    if (x == 3.14)

    printf("Computers Science");

    else

    printf("Information Technology");

}
</code>```

Um... Can you help me why ?? Just answer why okay thanks
I am not clear why it is happening i am a beginner and this is... Pls help

Body:
#include<stdio.h>

void main( )

{

    float x=3.14;

    if (x == 3.14)

    printf("Computers Science");

    else

    printf("Information Technology");

}

Um... Can you help me why ?? Just answer why okay thanks
I am not clear why it is happening i am a beginner and this is... Pls help


问:
Alert in MQL by some conditions
I need a piece of code or an indicator in mql that checks several conditions at any tick and alerts me with a sound if they are met.
The conditions are as follows:
First, if at that moment there are less than 20 seconds left until the end of the current candle (that is, we have between 1 and 20 seconds until the end of the candle),
And secondly, the length of the body of the candle should be longer than the length of the upper shadow and also longer than the length of the lower shadow.
I would be grateful if anyone could help me.</p>

Title: Alert in MQL by some conditions


问:
Alfresco 6.2 - PDF Toolkit Addon
I have installed Alfresco 6.2 from the link https://javaworld-abhinav.blogspot.com/2020/12/setup-acs62-ga-and-ass14-distribution-stepbystep.html . For this alfresco 6.2 I need to add PDF toolkit addon, I am unable to find the solution to it.
Please find me a solution to this.

Thanks & Regards
Sai Kumar S

I have tried the alfresco PDF toolkit of alfresco 5.2 and I was getting error and unable to login into alfresco.

Title: Alfresco 6.2 - PDF Toolkit Addon


问:
How can I override a class' method in a Scala 3 compiler plugin?
I want to auto-generate an overriden method in a compiler plugin (Scala 3) for a class like:

trait SpecialSerialize {
  def toJson(sb: StringBuilder, c:SJConfig): Unit = {println("wrong")}
}

case class Person(name:String, age:Int) extends SpecialSerialize
```
<p>The plugin would generate:</p>
<pre class="lang-scala prettyprint-override"><code>case class Person(name:String, age:Int) extends SpecialSerialize {
  override def toJson(sb: StringBuilder, c:SJConfig): Unit = ... // code here
}
</code>```

I have a phase:

class ReflectionWorkerPhase extends PluginPhase {
  import tpd._

  val phaseName = "reflectionWorker"

  override val runsAfter = Set(Pickler.name)

  override def transformTypeDef(tree: TypeDef)(implicit ctx: Context): Tree =
    if tree.isClassDef && !tree.rhs.symbol.isStatic then  // only look at classes

      // 0. Get a FreshContext so we can set the tree to this tree. (for '{} later)
      implicit val fresh = ctx.fresh
      fresh.setTree(tree)
      QuotesCache.init(fresh)
      implicit val quotes:Quotes = QuotesImpl.apply()  // picks up fresh
      import quotes.reflect.*

        // 1. Set up method symbol, define parameters and return type
        val toJsonSymbol = Symbol.newMethod(
          Symbol.spliceOwner,
          "toJson",
          MethodType(
            List("sb","config"))( // parameter list
              _ => List( // types of the parameters
                TypeRepr.of[StringBuilder],
                TypeRepr.of[SJConfig],
                ),
              _ => TypeRepr.typeConstructorOf(classOf[Unit])  // return type
            ),
            Flags.Override, // Note override here
            Symbol.noSymbol
          )

        // 2. Get our class' Symbol for ownership reassignment
        val classDef = tree.asInstanceOf[ClassDef]
        val classSymbol = classDef.symbol

        // 3. Define our method definition (DefDef) using our method symbol defined above
        val toJsonMethodDef = DefDef(
          toJsonSymbol,
          {
            case List(List(sb: Term, config: Term)) =>
              given Quotes = toJsonSymbol.asQuotes
              Some({
                // Multiple quotes here intentional...
                // Real code will generate a list of quoted statements
                quoted.Expr.ofList(List(
                  '{ println("Hello") },
                  '{ println("World") }
                ))
              }.asTerm.changeOwner(toJsonSymbol))
          }
        ).changeOwner(classSymbol)

        // 4. Add toJsonMethodDef to tree and return
        val cd = ClassDef.copy(classDef)(
          name = classDef.name,
          constr = classDef.constructor,
          parents = classDef.parents,
          selfOpt = classDef.self,
          body = toJsonMethodDef +: classDef.body
        )
        cd.asInstanceOf[dotty.tools.dotc.ast.tpd.Tree]
      else
        tree
}
```
<p>When I use the plugin on a sample Person class, I get this error on compile:</p>
```Exception in thread "sbt-bg-threads-1" java.lang.ClassFormatError: Duplicate method name "toJson" with signature "(Lscala.collection.mutable.StringBuilder;Lco.blocke.scala_reflection.SJConfig;)V" in class file com/foo/Person
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1013)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150)
    at java.base/java.net.URLClassLoader.defineClass(URLClassLoader.java:524)
    at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:427)
    at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:421)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:712)
...
```

So something in the other compile phases failed to recognize my generated method as being an override and tried to copy in the "master" method from the trait, and of course the JVM lost its mind at runtime, finding 2 copies of toJson with the same signature.

How can I fix this so my generated method is recognized as a valid override such that a 2nd toJson method won't be generated in a later phase?

Body:
I want to auto-generate an overriden method in a compiler plugin (Scala 3) for a class like:

trait SpecialSerialize {
  def toJson(sb: StringBuilder, c:SJConfig): Unit = {println("wrong")}
}

case class Person(name:String, age:Int) extends SpecialSerialize

The plugin would generate:

case class Person(name:String, age:Int) extends SpecialSerialize {
  override def toJson(sb: StringBuilder, c:SJConfig): Unit = ... // code here
}

I have a phase:

class ReflectionWorkerPhase extends PluginPhase {
  import tpd._

  val phaseName = "reflectionWorker"

  override val runsAfter = Set(Pickler.name)

  override def transformTypeDef(tree: TypeDef)(implicit ctx: Context): Tree =
    if tree.isClassDef && !tree.rhs.symbol.isStatic then  // only look at classes

      // 0. Get a FreshContext so we can set the tree to this tree. (for '{} later)
      implicit val fresh = ctx.fresh
      fresh.setTree(tree)
      QuotesCache.init(fresh)
      implicit val quotes:Quotes = QuotesImpl.apply()  // picks up fresh
      import quotes.reflect.*

        // 1. Set up method symbol, define parameters and return type
        val toJsonSymbol = Symbol.newMethod(
          Symbol.spliceOwner,
          "toJson",
          MethodType(
            List("sb","config"))( // parameter list
              _ => List( // types of the parameters
                TypeRepr.of[StringBuilder],
                TypeRepr.of[SJConfig],
                ),
              _ => TypeRepr.typeConstructorOf(classOf[Unit])  // return type
            ),
            Flags.Override, // Note override here
            Symbol.noSymbol
          )

        // 2. Get our class' Symbol for ownership reassignment
        val classDef = tree.asInstanceOf[ClassDef]
        val classSymbol = classDef.symbol

        // 3. Define our method definition (DefDef) using our method symbol defined above
        val toJsonMethodDef = DefDef(
          toJsonSymbol,
          {
            case List(List(sb: Term, config: Term)) =>
              given Quotes = toJsonSymbol.asQuotes
              Some({
                // Multiple quotes here intentional...
                // Real code will generate a list of quoted statements
                quoted.Expr.ofList(List(
                  '{ println("Hello") },
                  '{ println("World") }
                ))
              }.asTerm.changeOwner(toJsonSymbol))
          }
        ).changeOwner(classSymbol)

        // 4. Add toJsonMethodDef to tree and return
        val cd = ClassDef.copy(classDef)(
          name = classDef.name,
          constr = classDef.constructor,
          parents = classDef.parents,
          selfOpt = classDef.self,
          body = toJsonMethodDef +: classDef.body
        )
        cd.asInstanceOf[dotty.tools.dotc.ast.tpd.Tree]
      else
        tree
}

When I use the plugin on a sample Person class, I get this error on compile:

Exception in thread "sbt-bg-threads-1" java.lang.ClassFormatError: Duplicate method name "toJson" with signature "(Lscala.collection.mutable.StringBuilder;Lco.blocke.scala_reflection.SJConfig;)V" in class file com/foo/Person
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1013)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150)
    at java.base/java.net.URLClassLoader.defineClass(URLClassLoader.java:524)
    at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:427)
    at java.base/java.net.URLClassLoader$1.run(URLClassLoader.java:421)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:712)
...

So something in the other compile phases failed to recognize my generated method as being an override and tried to copy in the "master" method from the trait, and of course the JVM lost its mind at runtime, finding 2 copies of toJson with the same signature.

How can I fix this so my generated method is recognized as a valid override such that a 2nd toJson method won't be generated in a later phase?


问:
How to migrate from Google Cloud Endpoints to Google Api Gateway?
How would one migrate their Google Cloud Endpoints GAE app to Google Api Gateway GAE app?

Also, would you recommend doing so? Api Gateway looks like the new Cloud Endpoints.


问:
I keep getting permission denied?
```<code>import os
import tensorflow as tf

# Get the current working directory
path = os.getcwd()

# Define the path components
filename = 'Downloads'
filename2 = 'crops'
filename3 = 'train'
filename4 = 'banana'

# Join the path components using the correct path separator
file_path = os.path.join(path, filename, filename2, filename3, filename4)

# Check if the file or directory exists
if os.path.exists(file_path):
    # If it exists, grant read and write permissions to the owner of the directory
    os.system('icacls ' + file_path + ' /grant "Alex":(OI)(CI)(RX,W)')
    print('success')
else:
    # If the file or directory does not exist, print an error message
    print("fail")

# Load the data
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data(file_path)

# Reshape the data to have a single channel
X_train = X_train.reshape((X_train.shape[0], 28, 28, 1))
X_test = X_test.reshape((X_test.shape[0], 28, 28, 1))

# Convert the data to floating point values and normalize them
X_train = X_train.astype(np.float32) / 255.0
X_test = X_test.astype(np.float32) / 255.0

# Create a CNN model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

# Compile the model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# Train the model
model.fit(X_train, y_train, epochs=5)

# Save the trained model
model.save('food_recognition')
</code>```

I cut off all the code below the following:

```<code>if os.path.exists(file_path):
    # If it exists, grant read and write permissions to the owner of the directory
    os.system('icacls ' + file_path + ' /grant "Alex":(OI)(CI)(RX,W)')
    print('success')
else:
    print("fail")
</code>```

to check and it returns success, so I know the path exists but it fails when I actually try and read from the directory, so I guess that means my method of granting permissions is not working? Also when I check the path of file_path it returns

```<code>C:\\Users\\Alex\\Downloads\\crops\\train\\banana
</code>```

but in my file browser there are no \ only \ so could that have something to do with it?

Title: I keep getting permission denied?

Body:
import os
import tensorflow as tf

# Get the current working directory
path = os.getcwd()

# Define the path components
filename = 'Downloads'
filename2 = 'crops'
filename3 = 'train'
filename4 = 'banana'

# Join the path components using the correct path separator
file_path = os.path.join(path, filename, filename2, filename3, filename4)

# Check if the file or directory exists
if os.path.exists(file_path):
    # If it exists, grant read and write permissions to the owner of the directory
    os.system('icacls ' + file_path + ' /grant "Alex":(OI)(CI)(RX,W)')
    print('success')
else:
    # If the file or directory does not exist, print an error message
    print("fail")

# Load the data
(X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data(file_path)

# Reshape the data to have a single channel
X_train = X_train.reshape((X_train.shape[0], 28, 28, 1))
X_test = X_test.reshape((X_test.shape[0], 28, 28, 1))

# Convert the data to floating point values and normalize them
X_train = X_train.astype(np.float32) / 255.0
X_test = X_test.astype(np.float32) / 255.0

# Create a CNN model
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(64, activation='relu'))
model.add(tf.keras.layers.Dense(10, activation='softmax'))

# Compile the model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# Train the model
model.fit(X_train, y_train, epochs=5)

# Save the trained model
model.save('food_recognition')

I cut off all the code below the following:

if os.path.exists(file_path):
    # If it exists, grant read and write permissions to the owner of the directory
    os.system('icacls ' + file_path + ' /grant "Alex":(OI)(CI)(RX,W)')
    print('success')
else:
    print("fail")

to check and it returns success, so I know the path exists but it fails when I actually try and read from the directory, so I guess that means my method of granting permissions is not working? Also when I check the path of file_path it returns

C:\\Users\\Alex\\Downloads\\crops\\train\\banana

but in my file browser there are no \ only \ so could that have something to do with it?


问:
ADJUST TABLE ROW WIDTH with 100 Percent TABLE WIDTH Style
I have a table width set 100% and I have a td custom class named bordered.

source code:
`

```<code>table {
  border-collapse: collapse;
  border-spacing: 0;
  width: 100%;
  border: 0px;
}
</code>```
```<code>tr.bordered {

    border-bottom: 1px solid #000;
}
</code>```

I don't want the bordered tr to be 100% width also.

I want it to be just 540px width. But when I set width under tr.bordered it doesn't reflect.

Body:
I have a table width set 100% and I have a td custom class named bordered.

source code:
`

table {
  border-collapse: collapse;
  border-spacing: 0;
  width: 100%;
  border: 0px;
}

tr.bordered {

    border-bottom: 1px solid #000;
}

I don't want the bordered tr to be 100% width also.

I want it to be just 540px width. But when I set width under tr.bordered it doesn't reflect.


问:
Unclosed Character Literal error while writing an integer data in a file
I tried to write Integer data to my file using java.io.FileWriter it shows me

```<code>error: unclosed character literal
</code>```

the error line:

```<code>        FileWriter fw=new FileWriter("fw.txt");
        fw.write(new char[]{'10','20','30'});
        fw.flush();
</code>```

but when I try to write an character in the file using character array, there's no problem with the literals.

Trying to Read and Write integer data in a file only using java.io.BufferedReader.

Body:
I tried to write Integer data to my file using java.io.FileWriter it shows me

error: unclosed character literal

the error line:

        FileWriter fw=new FileWriter("fw.txt");
        fw.write(new char[]{'10','20','30'});
        fw.flush();

but when I try to write an character in the file using character array, there's no problem with the literals.

Trying to Read and Write integer data in a file only using java.io.BufferedReader.