Q: How can I map the result set of query to a different entity other than table I am trying to fetch data from db and mapping it to different entity but I get
java.lang.IllegalArgumentException: java.lang.ArrayIndexOutOfBoundsException: 0

My Table looks like
@Entity
@Table(name = "Student")
@NamedNativeQueries({
    @NamedNativeQuery(name = "findAll", query = "Select a.student_id as id, a.student_code as code from Student a")
    })
public class Student {

    @Id
    private Long student_id;
    private String student_code;
    private String student_user_id;
    private String student_first_name;

    //Some other fields, getters and setters
}

My BO Looks like
@Entity
public class Generic{

    @Id
    private Long id;
    private String code;
    private String user_id;

    //getters and setters
}

My DAO call class something like this
Query query = entityManager.createNamedQuery("findAll", Generic.class);
query.getResultList();

I get exception on
entityManager.createNamedQuery("findAll", Generic.class);

This is the stack trace I have
    Caused by: java.lang.IllegalArgumentException: java.lang.ArrayIndexOutOfBoundsException: 0
at org.hibernate.internal.AbstractSharedSessionContract.buildQueryFromName(AbstractSharedSessionContract.java:774)
at org.hibernate.internal.AbstractSharedSessionContract.createNamedQuery(AbstractSharedSessionContract.java:869)
at org.hibernate.internal.AbstractSessionImpl.createNamedQuery(AbstractSessionImpl.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:301)
at com.sun.proxy.$Proxy157.createNamedQuery(Unknown Source)

A:
I am trying to fetch data from db and mapping it to a different entity
  but I get ArrayIndexOutOfBoundsException

But in the following line, you are not doing that, you are trying to get the list of Student entity list. And what's your different Entity here?
entityManager.createNamedQuery("findAll", Student.class);
But as you provided another entity Generic, I assume you want your data to be loaded in that. There are different possible solutions to this problem. Lets figure out.
Using the SELECT NEW keywords
Update your Native query to this
@NamedNativeQueries({
    @NamedNativeQuery(name = "Student.findAll", query = "SELECT NEW Generic(a.student_id, a.student_code) FROM Student a")
})

You have to define a Constructor in the Generic class as well that qualifies this call
public void Generic(Long id, String code) {
     this.id = id;
     this.code = code;
}

And update the query execution in DAO as
List<Generic> results = em.createNamedQuery("Student.findAll" , Generic.class).getResultList();

Note: You may have to place the fully qualified path for the Generic class in the Query for this
Construct from List<Object[]>
Alternatively the straight forward and simplest solution would fetch the result list as a list of Object[] and populate to any new Object you want.
List<Object[]> list = em.createQuery("SELECT s.student_id, s.student_code FROM Student s")
                        .getResultList();

for (Object[] obj : list){
    Generic generic = new Generic();
    generic.setId(((BigDecimal)obj[0]).longValue());
    generic.setCode((String)obj[1]);
}


Q: C# Multi-threading logical error I am new to multi-threading, but I don't know what's wrong with my code:
public int k;
private void button2_Click(object sender, EventArgs e)
{
    k = 10;
    ThreadPool.SetMinThreads(2, 6);
    ThreadPool.SetMaxThreads(2, 6);
    ThreadPool.QueueUserWorkItem(aki);
    ThreadPool.QueueUserWorkItem(aki);
}

public void aki(object ab)
{
    do
        {
           this.SetText1(textBox1.Text +
           " thread     " + Thread.CurrentThread.GetHashCode() +
           "               valu=   " + k + Environment.NewLine);
            k--;
        } while (k > 0);
        if (k < 0) Thread.CurrentThread.Abort();
}

For the above, I am getting the following output:
 thread     11               valu=   10
 thread     11               valu=   8
 thread     11               valu=   6
 thread     11               valu=   4
 thread     11               valu=   2
 thread     10               valu=   0

I am expecting an output in 10,9,8,7,6,5,4,3,2,1,0
Please guide me on what is wrong with this.
I am trying to run two threads at a time.
What to do?
EDIT: After rohit's answer, I tried this but i got the following output:
 thread     11               valu=   10
 thread     12               valu=   9
 thread     12               valu=   8
 thread     11               valu=   7
 thread     11               valu=   6
 thread      6               valu=   7
 thread      6               valu=   6
 thread      6               valu=   5
 thread     13               valu=   3
 thread     14               valu=   2
 thread     14               valu=   1

In this run, 7 and 6 are repeating twice.

A: Problem here is both thread working on same instance variable k of your class.
So, when one thread modifies the value, it gets reflected in other thread.
The output will always be indeterministic. Like i got this output -
 thread     18               valu=   10
 thread     21               valu=   10
 thread     18               valu=   9
 thread     18               valu=   7
 thread     18               valu=   6
 thread     18               valu=   5
 thread     18               valu=   4
 thread     18               valu=   3
 thread     18               valu=   2
 thread     18               valu=   1
 thread     21               valu=   8

You should used local variable inside aki method -
public void aki(object ab)
{
    int k = 10; // <---- HERE
    do
        {
           this.SetText1(textBox1.Text +
                          " thread     " + Thread.CurrentThread.GetHashCode() +
                          "               valu=   " + k + Environment.NewLine);
            k--;
        } while (k >= 0); // It should be less than and equal to 0 to print 0.
        if (k < 0) Thread.CurrentThread.Abort();
}


Q: Post serialized form data with ajax I have this form

There are currently a total of $traders traders and this session has a total of Ksh $total you can earn this very minute.

   <form class="form-horizontal" name="trade">

      Telephone Number:

        <input type="text" class="form-control" id="email" placeholder="Enter Telephone Number" name="telephone"  required/>

      Id Number:

        <input type="number" class="form-control" id="email" placeholder="Enter Id Number" name="nid"  required/>

      Amount:

        <input type="number" class="form-control" id="email" placeholder="Enter Amount" name="amount"  required/>

      Direction:

       <select class="form-control" name="direction"><option value="up">Up</option><option value="down">Down</option></select>

        <button type="submit" class="btn btn-success pull-right">Submit</button>

  </form>

I have this as my jquery
 $(document).ready(function(){

  var datastring = $("#trade").serialize();
   $.ajax({
    type: "POST",
    url: "http://localhost/lords/trade.php",
    data: datastring,
    dataType: "json",
    success: function(data) {
       alert(data);
    },
    error: function() {

    }
    });

   });

However, i am not stopping default and the form reloads and no data is posted.
I have tried this
var frm = $('#trade');
    frm.submit(function (ev) {
        $.ajax({
            type: 'post',
            url: 'http://localhost/lords/trade.php',
            data: frm.serialize(),
            success: function (data) {
                alert(data);
            }
        });
        ev.preventDefault();
    });

But this does not post data. I am using jquery 3.3.1
This is the fiddle https://jsfiddle.net/e3zc1gpb/3/

A: add id="name" on form tag,
or change
var frm = $('#trade');

to
var frm = $('form[name="trade"]')


Q: Bus Error when using recursion So, I'm using recursion and going through an array named code which contains integers and a value is computed after
traversing through the array. But I don't know for what reason this is giving a BUS ERROR : 10.
I even tried manually going through the array and everything seems fine, array is sufficiently big.
//change to bits/stdc++.h
#include "stdc++.h"
#define MAX 5001
typedef unsigned long long ull;
typedef  long long ll;

using namespace std;
int code[MAX];
int co_code;

ull rec(int i, int j, int k){
   if(k==j-1)
     return 0;
   if(i==j-1)
     return (rec(k+2, j, k+2));
   int temp = code[i]*10 + code[i+1];
   if(temp<=26)
      return (1 + rec(i+1, j, k));
   else
     return (rec(i+1, j, k));
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    while(1){
        memset(code, 0, sizeof(code[0])*MAX);
        string str;
        cin>>str;
        size_t size = str.length();
        co_code = 0;
        while(co_code!= size){
            code[co_code] = str[co_code] - '0';
            co_code++;
           }
        if(code[0] == 0)
            break;
        cout<<rec(0, co_code-1, 0) + 1;
       }
return 0;
}

A: The error is in accessing the array outside the size given by co_code,
so it can be fixed by changing the if condition.
Corrected : -
if(k>=j-1)


Q: Cannot read properties of this object values of parent component to child component function in angular I'm calling a function declared in parent component in the child component in the form of callback.
Parent Component
translation-editor.component.ts
export class TranslationEditorComponent implements OnInit {
    textGuid: string = this.actRoute.snapshot.params['textGuid'];
    editDataset: any;
    currentTopBarConfig: any;
    summaryTopbarConfig = [
      {
        "label": "Save Text",
        "function": this.save,    //see save function below
      },
      {
        "label": "Delete Text",
        "function": this.delete,
      }
    ];
  constructor(
    private translationService:TranslationService,
    public actRoute: ActivatedRoute,
  ) {
  }

  ngOnInit(): void {
    this.loadDataToEdit();
  }
  loadDataToEdit(){
    this.translationService.getTextById(this.textGuid).subscribe(res => {
      this.editDataset = res;
    })
    this.currentTopBarConfig = this.summaryTopbarConfig;
  }
  save(){
    console.log("this.textGuid",this.textGuid);
    if(this.textGuid){
      this.translationService.updateText(this.textGuid, this.editDataset).subscribe((res:any)=>{
        console.log(res);
      });
    }
  }
  delete(){
 console.log("delete code lies here");
  }
}

translation-editor.component.html
<topbar [config]="currentTopBarConfig"></topbar>

<form  [ngClass]="{'hidden':currentTab!=='summary'}" >
    <fieldset>
      <legend>Field</legend>

        <ng-container  *ngFor="let key of objectKeys(editDataset)" >

              <input type="text" value="{{editDataset[key]}}" readonly>
              {{key}}

        </ng-container>

    </fieldset>

  </form>

I'm calling the save function in the below component as a callback to initiateFunction() function.
Child Component
topbar.component.html

<ng-container *ngFor="let btn of config">

    <button
      (click)="initiateFunction(btn.function)"
      {{btn.label}}
    </button>

</ng-container>

topbar.component.ts
export class TopbarComponent implements OnInit {
    @Input() config: any[] | undefined;
    constructor(private location: Location) { }
    ngOnInit(): void {
    }
    initiateFunction(fnct:any){
      fnct();
    }
  }

Here when function is executed I'm getting an error:
ERROR TypeError: Cannot read properties of undefined (reading 'textGuid')
Where I'm not able access the this.textGuid.
Please give me suggestions on how to solve this.

A: I think the issue is caused because the save() function isn't bound to the correct object, so instead you can use Angular component interaction features. You can use @Output decorator and emit an event that will be handled by parent component.
First, update your TopbarComponent to add that event:
topbar.component.ts

export class TopbarComponent implements OnInit {
  @Input() config: any[] | undefined;
  @Output() save: EventEmitter<any> = new EventEmitter();

  constructor(private location: Location) {}

  ngOnInit(): void {}
  onSave() {
    this.save.emit();
    //fnct();
  }
}

topbar.component.html there was a typo on in button start tag >

<ng-container *ngFor="let btn of config">

    <button
      (click)="onSave()">
      {{btn.label}}
    </button>

</ng-container>

Next, update the TranslationEditorComponent component to bind to that event:
translation-editor.component.html

<topbar [config]="currentTopBarConfig" (save)="save()"></topbar>

You can do the same for other types of events like delete or update. Refer to Angular docs for more details about components interaction and sharing data https://angular.io/guide/inputs-outputs

A: Your this context has been changed when you call fnct();. In order to pass the this context to the function you can use javascript bind method.
So you just need to change the config property:
summaryTopbarConfig = [
      {
        "label": "Save Text",
        "function": this.save.bind(this),    //bind current context
      }
    ];

Read more about bind: https://www.w3schools.com/js/js_function_bind.asp


Q: Test a simple function in jasmine karma - Angular Basically i have this function
function getDP() {
    if (someFunctionOutsideAngular()) {
        var str = vm.dp;
        var selectedDate = '';
        if (vm.dp == null) {
            selectedDate = new Date();
        } else {
            selectedDate = vm.dp;
        }
        var options = {
            date: selectedDate,
            mode: 'date'
        };
        function onSuccess(date) {
            vm.dt = new Date(date);
        }
        function onError(error) { // Android only
            console.log('Error: ' + error);
        }
        datePicker.show(options, onSuccess, onError);
    } else {
        return false;
    }
}

I'm writing Unit test for this function. This is what i have written till now.
(function(){

describe('test', function(){

    var sut,
        dataContext,
        $q,
        deferred,
        $location;

        beforeEach(module('app'));

        beforeEach(inject(function(_$controller_, _dataContext_, _$q_,$location) {
             inject(function($injector) {
                sut = contFactory("mods", { $scope: $scope });
             });
         }));

        describe('Definition tests', function(){
            it('Should define the controller', function(){
                expect(sut).toBeDefined();
            });

            var testCases = ['getDatePicker'];

            _.forEach(testCases, function(testCase){
                it(testCase + ' should be defined', function(){
                    expect(sut[testCase]).toBeDefined();
                })
            });
        });

        describe('and calling the getDatePicker function', function () {
            it('and should define getDatePicker',function(){
                expect(sut.getDatePicker).toBeDefined();
            });

            var lastCalibration;
            it('return null lastCalibration', function(){
                lastCalibration = sut.lastCalibration(null);
            });

            it('return true for lastCalibration', function(){

            });

        });

I'm stuck here.. i need to check if else condition, success, and onError.. i have declared varialble.. and stuck if i have to do spyOn. How to write condition for these?


Q: django model's inheritance I want to have two registration type. for example : employee and employer type. i want two different form.
i override AbstractUser and after i use this class (inheritance)
class User(AbstractUser):

  age=models.BooleanField(default=True)

class employee(User):
  is_employee=models.BooleanField(default=True)
  ser=models.BooleanField()
  sag=models.CharField(max_length=1)

  class Meta:
    verbose_name="employee"

class employer(User):
  is_employer=models.BooleanField(default=True)
  address=models.CharField(max_length=100)

but when i save employee or employer class also created User class. can i do when i save only employee save just that and not User

A: I think it depends on the state of the User table - the way you have it now there will be a User table and a Employee table and a One to One relationship.
If you want it so that both the Employee and Employer Table includes an 'age' attribute you have to make the User table abstract.
https://docs.djangoproject.com/en/3.1/topics/db/models/#model-inheritance
The way to do this is :
class User(AbstractUser):
    class Meta:
          abstract = True

    age=models.BooleanField(default=True)

Even though you have inherited from Abstract User, I wouldn't assume that the Meta settings are inherited.


Q: Weird matrix array behavior in C I have some piece of code which I used for making some zeros on Matrix Array to 1 and printing it. I am making 4 0s to 1 in first while, but it says there are 5 1s on the array on second loop. Could not figure it out. Can you explain what is wrong in my code. Thanks for your time
#include <stdio.h>
main(){

    int n;

    printf("Desenin buyuklugunu giriniz: ");
    scanf("%d",&n);

    int satirlar[n][n]= {0};

    int i=0, j=n-1;
    while(i<(n/2) && j>n/2) {
        satirlar[i][j] = 1;
        i++;
        j--;
    }

    for(int i=0; i< n; i++) {
        for(int j=0; j< n; j++) {

            if(satirlar[i][j] == 1) {
                printf("*");
            }
            else printf("k");
        }
    printf("\n");
    }
}

I Print "k" for seeing how many times loop worked.
I get an output like this.
kkkk
kkkkk

A: You have not shown a complete program, so we have to guess at what your program actually is. It appears you declared int arr[9][9]; inside a function. In that case, it is not initialized, and the values of its elements are indeterminate. They might be zeros. They might not. They might even change from use to use.
To initialize the array, change the definition to int arr[9][9] = { 0 };.
If the array is defined as a variable-length array, then write a loop to set the entire array to zeros immediately after the definition:
…
int array[n][n];
for (int i = 0; i < n; ++i)
    for (int j = 0; j < n; ++j)
        arr[i][j] = 0;

Or write a loop to both set chosen elements to 1 and others to 0:
for (int i = 0; i < n; ++i)
    for (int j = 0; j < n; ++j)
        arr[i][j] = i == j && i < n/2 ? 1 : 0;

In the existing loop test, i<(n/2) & j>n/2 happens to work, but the conventional way to express this in C would be i < n/2 && j > n/2, because '&&is for the Boolean AND of two expressions, while&is for the bitwise AND of two integers. Additionally, there seems to be little point in testing bothiandj`. As the loop is written, testing just one of them will suffice to control the loop, unless you are intending the loop to handle non-square matrices in future code revisions.


Q: Validating the data entered in numeric input in RShiny I am developing the Shiny app in which if the user enters non-numeric characters, the value should be changed to the value mentioned in updateNumericInput().
Here is my Rcode
library(shiny)
ui <- fluidPage (
  numericInput("current", "Current Week",value = 40, min = 40, max = 80)
)

server <- function(input, output, session) {
  observeEvent(input$current, {
    updateNumericInput(session,"current", value = ({ if(!(is.numeric(input$current))){40}
                           if(!(is.null(input$current) || is.na(input$current))){
                           if(input$current < 40){
                             40
                           }else if(input$current > 80){
                             80
                           } else{
                             return (isolate(input$current))
                           }
                         }
      })
    )
  })

  }

shinyApp(ui=ui, server = server)

Can anyone help me with this code?

A: Something like this?
library(shiny)
ui <- fluidPage (
  numericInput("current", "Current Week",value = 40, min = 40, max = 80)
)

server <- function(input, output, session) {
  observeEvent(input$current, {
    updateNumericInput(session,"current", value = ({ if(!(is.numeric(input$current))){40}
      else if(!(is.null(input$current) || is.na(input$current))){
        if(input$current < 40){
          40
        }else if(input$current > 80){
          80
        } else{
          return (isolate(input$current))
        }
      }
      else{40}
    })
    )
  })

}

shinyApp(ui=ui, server = server)


Q: Displaying child records based on parent id from URL I have one model Dataset and another one called DatasetReview, where DatasetReview has a foreign key connection to Dataset. I would like to display all of the DatasetReview models that are tied to a specific Dataset in a separate page.
I can currently view each Dataset like so: http://127.0.0.1:8000/dataset/3/ and would like to see all of the DatasetReview models for Dataset 3 like so: http://127.0.0.1:8000/dataset/3/reviews But I am unsure how to set this up.
I am not sure how to phrase this question well so I had difficulty finding other posts discussing how to do something like this. Here is my code:
urls.py:
from django.urls import path
from .views import (
    DatasetListView,
    DatasetDetailView,
    DatasetCreateView,
    DatasetUpdateView,
    DatasetDeleteView,
    DatasetReviewsView
    )
from . import views

urlpatterns = [
    path('', DatasetListView.as_view(), name='argo-home'),
    path('dataset/<int:pk>/', DatasetDetailView.as_view(), name='dataset-detail'),
    path('dataset/new/', DatasetCreateView.as_view(), name='dataset-create'),
    path('dataset/<int:pk>/update', DatasetUpdateView.as_view(), name='dataset-update'),
    path('dataset/<int:pk>/delete', DatasetDeleteView.as_view(), name='dataset-delete'),
    path('dataset/<int:pk>/reviews', DatasetReviewsView.as_view(), name='dataset-review'),
    path('about/', views.about, name='argo-about'),
]

views.py:
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import (
    ListView,
    DetailView,
    CreateView,
    UpdateView,
    DeleteView
)
from .models import Dataset, DatasetReview

def home(request):
    context = {
        'datasets' : Dataset.objects.all(),
    }
    return render(request, 'argo/home.html', context)

class DatasetListView(ListView):
    model = Dataset
    template_name = 'argo/home.html' # <app>/<model>_<viewtype>.html
    context_object_name = 'datasets'
    ordering = ['-date_posted']

class DatasetDetailView(DetailView):
    model = Dataset

class DatasetCreateView(LoginRequiredMixin, CreateView):
    model = Dataset
    fields = ['title', 'description', 'access']

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.instance.affiliation = self.request.user.affiliation
        return super().form_valid(form)

class DatasetUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Dataset
    fields = ['title', 'description']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        Dataset = self.get_object()
        if self.request.user == Dataset.author:
            return True
        return False

class DatasetDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Dataset
    success_url = '/'

    def test_func(self):
        dataset = self.get_object()
        if self.request.user == dataset.author:
            return True
        return False

class DatasetReviewsView(DetailView):
    model = DatasetReview
    success_url = '/'

    def test_func(self):
        datasetReview = self.get_object()
        if self.request.user == datasetReview.author:
            return True
        return False

def about(request):
    return render(request, 'argo/about.html', {'title': 'About'})

models.py:
from django.db import models
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator
from django.urls import reverse
from users.models import User, Affiliation

# from django.contrib.auth.models import User

class Dataset(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    affiliation = models.ForeignKey(Affiliation, on_delete=models.CASCADE, related_name='posted_datasets')
    access = models.ManyToManyField(Affiliation, related_name='available_datasets')
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('dataset-detail', kwargs={'pk' : self.pk})

class DatasetReview(models.Model):
    dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE, related_name='reviews_obj')
    reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reviews')
    comments = models.TextField()
    rating = models.FloatField(
        default=3.0,
        validators=[MaxValueValidator(5.0), MinValueValidator(1.0)]
     )

    def __str__(self):
        return self.dataset.title + ' review by ' + self.reviewer.username

    def get_absolute_url(self):
        return reverse('dataset-review', kwargs={'rpk' : self.pk})

admin.py:
from django.contrib import admin
from .models import Dataset, DatasetReview

admin.site.register(Dataset)
admin.site.register(DatasetReview)

Any tips would be super helpful, very new to django.

A: Figured this out.
The key is within class DatasetReviewsView(DetailView) in views.py. I first needed to change this inheritance to a ListView to enable what I was looking for.
Next, I just needed to provide context for what I wanted to show in my html page. This is easily done by overriding the get_context_data function, which provides the context data for templates displaying this class based view.
It makes it very easy to leverage python to provide the information I want. I could query the id of the dataset I was looking at with id = self.kwargs['pk'] (which must be included in the function parameters for get_context_data), and then I could just filter all reviews to just those with a dataset matching this id. Within the html I could then iterate over the variable num_reviews.
There is some other code that averages all the ratings to provide an overall rating as well.
class DatasetReviewsView(ListView):
    model = DatasetReview
    context_object_name = 'reviews'
    success_url = '/'

    def get_context_data(self, **kwargs):
        id = self.kwargs['pk']
        context = super(DatasetReviewsView, self).get_context_data(**kwargs)
        context['id'] = id
        context['name'] = Dataset.objects.get(pk=id).title
        context['num_reviews'] = len(DatasetReview.objects.filter(dataset=id))
        tot = 0
        for review in DatasetReview.objects.filter(dataset=id):
            tot += review.rating
        context['avg_rating'] = tot / context['num_reviews']
        return context


Q: How to redirect users and integrate whmcs bridge using htaccess? I have a wordpress blog and whmcs client area. For bridging whmcs and wordpress I have used the whmcs-bridge plugin. It allows me to access the whmcs area using the url,
/client-area?ccce=cart for page /clients/cart.php
/clients/cart.php --> /client-area?ccce=cart
Thus, all the pages within the clients/ folder are redirected to the /client-area page with argument (without the extenstion ,.php)
How can I do that using htaccess?
Presently I have this,
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


Q: How to clip children in qml? I have webView element that display google maps page. I need to show only map, without search input and other content. I have no idea except something like this:
Rectangle {
    x: 0
    y: 51
    height: 549
    //something like android clipChildren property

    WebView {
        id: mapView
        x:0
        y: -51
        width: 800
        height: 600
        url: ""
        onUrlChanged: {
            mapView.reload()
        }
    }
}

but I don't know property that can do it.

A: Maybe use the clip: true; property which is present on every item in QtQuick ?


Q: Are C standard library structures compatible between compilers and library versions on macOS or Linux? My host application took over the ownership of e.g. a FILE object which came from a dynamic library. Can I call fclose() on this object safely even though my host application and the dynamic library are compiled with different versions of clang / gcc?
Background
On Windows (with different VS runtimes) it would be illegal and I have to first extract the fclose() function from the runtime library which is used by the dynamic library since all runtimes have their own pools and internal structures for file or memory objects.
An illustration for the situation in Windows would look like this:

Does this restriction apply for Linux and macOS as well?

A: The issue is not whether your application and the dynamic libraries were compiled with different versions of clang and/or gcc.  The issue is whether, ultimately, there's one underlying C library that manipulates one kind of FILE * object and has one, compatible implementation of fclose().
Under MacOS and Linux, at least, the answer to all these questions is likely to be "yes".  In my experience it's hard to get two different, incompatible C libraries into the mix; you'd have to really work at it.

Addendum: I suppose I should admit, however, that my experience may be getting dated.  In my experience, on any Unix-like system, there's exactly one C library, generally /lib/libc.{a,so}.  But I gather that "modern" compilers are tending to access their own compiler- and version-specific libraries off in special places, meaning that the scenario you're worried about could be a problem.  To me, it seems, this way lies madness, but then again, it seems that more and more of the world seems to be embracing dependency hell, rather than trying to eliminate it.

A: It is not generally safe to use a library designed for one compiler with code compiled by a different compiler. A compiler may generate code that implements the nominal functions in the standard library using internal routines or interfaces, and those routines or interfaces may be different or missing in the library designed for another compiler.
Nor is it safe to take any pointer to some internal data structure from one library and use it with another library.
If the sources are just compiled with different versions of one compiler (e.g., clang 73 and clang 89), not different compilers (e.g., Apple clang versus GCC), the compiler might offer some guarantee about library compatibility. You would have to check its documentation. Or, if the compiler is intended to use the library provided with the operating system, that could work. Again, you would have to check its documentation.

A: On Linux, if both your code and the other library dynamically link to the same library (such as libc.so.6), both will get the same version and implementation of that library at runtime.  You can check which libraries a given dynamic library links to with ldd.
If you were linking to a library that statically linked in a supporting library, you would need to be careful to pass any structures to or from it against the same version of the library.  But this is more likely to come up in practice with libc++ and libstdc++ than with libc.
So, don't statically link your library to another and then pass a data structure that requires client code to separately link to the same library.


Q: SQL multiple start dates to end date I have a table with the following format (which I cannot change)
ClientID  |  RefAd1  |  Cluster Start Date  |  Cluster End Date

100001    |   R1234  |    2014-11-01        |
100001    |   R1234  |    2014-11-10        |
100001    |   R1234  |    2014-11-20        |

What I would like to come out with is:
ClientID  |  RefAd1  |  Cluster Start Date  |  Cluster End Date

100001    |   R1234  |    2014-11-01        |     2014-11-10
100001    |   R1234  |    2014-11-10        |     2014-11-20
100001    |   R1234  |    2014-11-20        |     NULL

I've searched on here, and had many attempts myself, but just can't get it working.
I can't update the source table (or add another table into the database) so I'm going to do this in a view (which I can save)
Any help would be gratefully appreciated, been going round in circles with this for a day and a bit now!

A: Use Self join to get next record
;WITH CTE AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY [Cluster Start Date])RNO,*
    FROM YOURTABLE
)
SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date]
FROM CTE C1
LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1

*

*Click here to view result

EDIT :
To update the table, you can use the below query
;WITH CTE AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY [Cluster Start Date])RNO,*
    FROM #TEMP
)
UPDATE #TEMP SET [Cluster End Date] = TAB.[Cluster End Date]
FROM
(
    SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date]
    FROM CTE C1
    LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1
)TAB
WHERE TAB.[Cluster Start Date]=#TEMP.[Cluster Start Date]

*

*Click here to view result

EDIT 2 :
If you want this to be done for ClientId and RefAd1.
;WITH CTE AS
(
    -- Get current date and next date for each type of ClientId and RefAd1
    SELECT ROW_NUMBER() OVER(PARTITION BY ClientID,RefAd1 ORDER BY [Cluster Start Date])RNO,*
    FROM #TEMP
)
UPDATE #TEMP SET [Cluster End Date] = TAB.[Cluster End Date]
FROM
(
    SELECT C1.ClientID,C1.RefAd1,C1.[Cluster Start Date],C2.[Cluster Start Date] [Cluster End Date]
    FROM CTE C1
    LEFT JOIN CTE C2 ON C1.RNO=C2.RNO-1 AND C1.ClientID=C2.ClientID AND C1.RefAd1=C2.RefAd1
)TAB
WHERE TAB.[Cluster Start Date]=#TEMP.[Cluster Start Date] AND TAB.ClientID=#TEMP.ClientID AND TAB.RefAd1=#TEMP.RefAd1

*

*Click here to view result

If you want to do it only for ClientId, remove the conditions for RefAd1

A: Here is the script if you just want the view you described:
CREATE VIEW v_name as
SELECT
  ClientId,
  RefAd1,
  [Cluster Start Date],
  ( SELECT
      min([Cluster Start Date])
    FROM yourTable
    WHERE
      t.[Cluster Start Date] < [Cluster Start Date]
) as [Cluster End Date]
FROM yourtable t


Q: How to pass state values from a component into another child component that contains param settings? I have a basic component that goes out and gets user info via axios and then sets the users state. But in the component, I have another nested component that is a form type component that sets placeholders, defaultValue, etc.
This is the lifecyle method that gets the data and sets state:
   componentDidMount() {
     axios.get('https://niftyURLforGettingData')
     .then(response => {
       console.log(response.data);
       const users = response.data;
       this.setState({ users });
     })
     .catch(error => {
       console.log(error);
     });
   }

Nested within this component is my form component:
<FormInputs
   ncols={["col-md-5", "col-md-3", "col-md-4"]}
   properties={[
    {
     defaultValue: "I NEED VALUE HERE: this.state.users.id",
    }
/>

if I use just:
{this.state.users.id} outside the component it works... but inside form...nothing.
I am quite sure I have to pass the state into this component... but can't quite get it.

A: I am pretty sure it doesn't work because users is undefined when your component renders for the first time.
Try to initialize that variable in the state doing something like this:
state = {
 users: {}
}

and then use a fallback since id will also be undefined doing this:
<FormInputs
   ncols={["col-md-5", "col-md-3", "col-md-4"]}
   properties={[
    {
     defaultValue: this.state.users.id || "Fallback Value", // this will render "Fallback value" if users.id is undefined
    }
/>

If this is not the case please share more information about your situation.


Q: Did a stopwatch using time libraries, it worked as expected, but it returns none also I'm new to python, so I was following a few tutorials to understand how to do something I liked to do. A stopwatch returning not only the time passed but also the time it started and finished. My plan started creating two variables with time.time, one for the start and another for the finish. So I subtracted the final time minus the start, and get time lapsed. Then I added two more variables, one for the time the program stopped counting, and another for the time it started. For the finish time it was easy, just used dateTime.now(), and for the time start I decided timeDelta might be usefull, so I did subtracted current time minus time lapsed, and get time started. It worked as expected as I said in the title, except for a little detail, which is also returning a None value apart of my time lapsed, so I'm not quite sure why being new to Python and being all I know from tutorials that don't explained these things. If you could give me any sort of explanation it'll help a lot!
import time
from datetime import datetime, timedelta

time_ended=datetime.now()

def time_convert(sec):
  mins = sec // 60
  sec = sec % 60
  hours = mins // 60
  mins = mins % 60
  print("Time Lapsed = {0}:{1}:{2}".format(int(hours),int(mins),sec))

input("Press Enter to start")
start_time = time.time()

input("Press Enter to stop")
end_time = time.time()

time_lapsed = end_time - start_time
time_started=timedelta(((time_lapsed/24)/60)/60)

print("Time started: ",time_ended-time_started)
print(time_convert(time_lapsed))
print("Time finished: ",time_ended)

This is what happen after running the program

Press Enter to start
Press Enter to stop
Time started:  2022-06-08 14:01:20.396229
Time Lapsed = 0:0:53.04069781303406
None
Time finished:  2022-06-08 14:02:13.436927

BTW, I did try to delete the first "import time" but it brokes my code, and trying to do something like putting at the end of the second line a ",time" deleting the first line again, it doesn't work neither.

A: print(time_convert(time_lapsed))
Is your problem.
The tine_convert method doesn't return anything. So by encapsulating the function in a print function it just prints none.
Try returning a string in the end of your method like:
Return "test"


Q: Nested query to reference field from parent query Simplified example:
select
    ticket_id,
    `number` as 'ticket number',
    (SELECT count(*) from ost_thread_entry join ost_thread on ost_thread_entry.thread_id = ost_thread.id where ost_thread.object_id = 1234) as 'number of posts in ticket'
from
    ost_ticket

I need to reference the value from ticket_id instead of 1234

A: You may use table aliases here:
SELECT
    ticket_id,
    number AS `ticket number`,
    (SELECT COUNT(*)
     FROM ost_thread_entry ote
     INNER JOIN ost_thread ot ON ote.thread_id = ot.id
     WHERE ot.object_id = t.ticket_id) AS `number of posts in ticket`
FROM ost_ticket t;

Note that you might also be able to write your query without the correlated subquery, instead using joins:
SELECT
    t.ticket_id,
    t.number AS `ticket number`,
    COUNT(ote.thread_id) AS `number of posts in ticket`
FROM ost_ticket t
LEFT JOIN ost_thread ot ON ot.object_id = t.ticket_id
LEFT JOIN ost_thread_entry ote ON ote.thread_id = ot.id
GROUP BY
    t.ticket_id,
    t.number;


Q: Why am I getting a NoMethodError when calling an instance method from global scope? I have searched around for the answer to this and I can see a lot of similar problems but I still do not understand what I am doing wrong here. I have declared a Ruby class and attempted to new it and then call some instance methods on the instance, so why do I get the NoMethodError on my start method?
class MyClass

  def initialize
    self.class.reset
  end

  def self.reset
    ...
  end

  def self.start(port)
    ...
  end
end

test = MyClass.new
test.start '8082'  <- here <- undefined method `start' for #<MyClass:0x2f494b0> (NoMethodError)

As you can see I am a Ruby noob. Any help would be appreciated. I can change my class structure but I would really like to understand what I am doing wrong here.

A: here start is a class method.
By your current approach, you can use it in the following way
MyClass.start '8080'
But if you want to use it on instance of class then use the following code
class MyClass

  def initialize
    self.class.reset
  end

  def self.reset
    ...
  end

  def start(port)
    ...
  end
end

test = MyClass.new
test.start '8080'

A: You are using start as a Class variable, the method names preceded with self-keyword make those methods as Class methods. So if you really want to not change your class then you should call it like this:

MyClass.start '8080'

Else you can remove the self from your reset and start methods and make them as Instance methods and use them as:

test = MyClass.new
test.start '8082'


Q: Passing 'this' to prototype function nested function what's the best style to pass 'this.dayNames' and use it within the nested function (createCalendar())?
function DateNames()
{
    this.dayNames = ["Su", "M", "T", "W", "Th", "F", "S"];
}

DateNames.prototype.render = function(date)
{
    console.log(date);
    createCalendar()
    function createCalendar()
    {
        console.log(this.dayNames);
    }
}


Q: Unable to read response from server using Socket.IO client in Swift I am trying to connect to my Socket.io server (Node/Express) from an iOS client.
Here is the code for the server (JS):
// Server Code
io.on('connection', (socket) => {

    console.log('user connected');

})

And here is my client code (Swift):
override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        // Testing Socket.io
        let manager = SocketManager(socketURL: URL(string: "http://<my ip address>:3001")!, config: [.log(true), .compress])
        let socket = manager.defaultSocket

        socket.on("connection") {data, ack in
            print("EG socket connected")
        }

        socket.connect()
    }

I am expecting the Swift console to print "EG socket connected." Instead this is what I recieve:
2021-07-09 22:02:16.481690-0400 Skull-King iOS Client[62477:10032406] LOG SocketIOClient{/}: Adding handler for event: connection
2021-07-09 22:02:16.482397-0400 Skull-King iOS Client[62477:10032406] LOG SocketIOClient{/}: Handling event: statusChange with data: [connecting, 2]
2021-07-09 22:02:16.482630-0400 Skull-King iOS Client[62477:10032406] LOG SocketIOClient{/}: Joining namespace /
2021-07-09 22:02:16.482906-0400 Skull-King iOS Client[62477:10032406] LOG SocketManager: Tried connecting socket when engine isn't open. Connecting
2021-07-09 22:02:16.483073-0400 Skull-King iOS Client[62477:10032406] LOG SocketManager: Adding engine
2021-07-09 22:02:16.484655-0400 Skull-King iOS Client[62477:10032406] LOG SocketManager: Manager is being released
2021-07-09 22:02:16.484700-0400 Skull-King iOS Client[62477:10032656] LOG SocketEngine: Starting engine. Server: http://<my ip address>:3001
2021-07-09 22:02:16.484879-0400 Skull-King iOS Client[62477:10032656] LOG SocketEngine: Handshaking
2021-07-09 22:02:16.484923-0400 Skull-King iOS Client[62477:10032406] LOG SocketIOClient{/}: Client is being released
2021-07-09 22:02:16.487428-0400 Skull-King iOS Client[62477:10032656] LOG SocketEnginePolling: Doing polling GET http://192.168.1.220:3001/socket.io/?transport=polling&b64=1&EIO=4
2021-07-09 22:02:16.653389-0400 Skull-King iOS Client[62477:10032658] LOG SocketEnginePolling: Got polling response
2021-07-09 22:02:16.653593-0400 Skull-King iOS Client[62477:10032658] LOG SocketEnginePolling: Got poll message: 0{"sid":"BateC4jf7tW2ET39AAAF","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
2021-07-09 22:02:16.654032-0400 Skull-King iOS Client[62477:10032658] LOG SocketEngine: Got message: 0{"sid":"BateC4jf7tW2ET39AAAF","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
2021-07-09 22:02:16.656761-0400 Skull-King iOS Client[62477:10032655] LOG SocketEngine: Engine is being released

Am I missing a step?


Q: Why show all data from mysql databese if I hit saarch button by keep search field blank and need extra one HTML button for all Entries.? When i keep search field blank and hit on search button, then show all results from  mysql database, Why.... here is my php code....
I want to create it, when i keep search field blank and click search button... have to show error "no search result" and want to create disallowed white spacing search and need extra one HTML button for all Entries. By one click so that i get all entries......
please help me....
 <?php

$con=mysql_connect('localhost', '1093913', 'tanim1996');
$db=mysql_select_db('1093913');

if(isset($_POST['button'])){    //trigger button click

  $search=$_POST['search'];

  $query=mysql_query("select * from iconic19 where student_id like '%{$search}%' || name like '%{$search}%' || phone like '%{$search}%' || blood like '%{$search}%' || district like '%{$search}%' ");

if (mysql_num_rows($query) > 0) {
  while ($row = mysql_fetch_array($query)) {

 echo "
";
               echo "
";
                echo "".$row['student_id']."	";
               echo "".$row['name']."	";
                 echo ""."".$row['phone'].""."	";
                echo "".$row['blood']."	";
                echo ""."".$row['email'].""."	";
                echo "".$row['district']."	";
                echo "
";
echo "
";

  }
}else{
    echo "
No results

";
  }

}else{                          //while not in use of search  returns all the values
  $query=mysql_query("select * from iconic19");

 while ($row = mysql_fetch_array($query)) {

  }

}

mysql_close();
?>

Its Html Code
<form id="nbc-searchblue1" method="post" enctype="multipart/form-data" autocomplete="off">

    <input id='wc-searchblueinput1' placeholder="Search Iconic..." name="search" type="search" autofocus>

    <input id='nbc-searchbluesubmit1' value="Search" type="submit" name="button">

 Show all

</form>

Its css Code..
.view-all a {
    background: red;
    padding: 10px;
    border-radius: 4px;
    color: #fff;
    text-decoration: none;
}

A: Just check if $_POST['search'] is blank then display your message else execute your query.

A: <?php

$con=mysql_connect('localhost', '1093913', 'tanim1996');
$db=mysql_select_db('1093913');

if(isset($_POST['button'])){    //trigger button click
    $numRows = 0;
    if(!empty($_POST['search'])) {
        $search = mysql_real_escape_string($_POST['search']);
        $query = mysql_query("select * from iconic19 where student_id like '%{$search}%' || name like '%{$search}%' || phone like '%{$search}%' || blood like '%{$search}%' || district like '%{$search}%' ");
        $numRows = (int)mysql_num_rows($query);
    }

    if ($numRows > 0) {
        while ($row = mysql_fetch_array($query)) {

            echo "
";
            echo "
";
            echo "".$row['student_id']."	";
            echo "".$row['name']."	";
            echo ""."".$row['phone'].""."	";
            echo "".$row['blood']."	";
            echo ""."".$row['email'].""."	";
            echo "".$row['district']."	";
            echo "
";
            echo "
";

        }
    } else {
        echo "
No results

";
    }
} else {                          //while not in use of search  returns all the values
    $query = mysql_query("select * from iconic19");

    while ($row = mysql_fetch_array($query)) {

    }
}

mysql_close();

?>

What I have done was creating a new variable $numRows with a default value of 0. If your search is empty there is no query to the database. I escaped your $search variable.
BTW: Please change to mysqli, the mysql extension is no longer supported in newer php versions.


Q: TFX - How to inspect records from CsvExampleGen Question
How to inspect the data loaded into TFX CsvExampleGen?
CSV
Top 3 rows from the california_housing_train.csv looks below.

longitude
latitude
housing_median_age
total_rooms
total_bedrooms
population
households
median_income
median_house_value

-122.05
37.37
27
3885
661
1537
606
6.6085
344700

-118.3
34.26
43
1510
310
809
277
3.599
176500

-117.81
33.78
27
3589
507
1484
495
5.7934
270500

CsvExampleGen
The CSV is loaded into CsvExampleGen. In my understanding, XXXExampleGen is to generate tf.Record instances, hence I wonder if there is a way to iterate through the records from CsvExampleGen.
from tfx.components import (
    CsvExampleGen
)
housing = CsvExampleGen("sample_data/california_housing_train.csv")
housing
----------
CsvExampleGen(
    spec: <tfx.types.standard_component_specs.FileBasedExampleGenSpec object at 0x7fcd90435450>,
    executor_spec: <tfx.dsl.components.base.executor_spec.BeamExecutorSpec object at 0x7fcd90435850>,
    driver_class: <class 'tfx.components.example_gen.driver.FileBasedDriver'>,
    component_id: CsvExampleGen,
    inputs: {},
    outputs: {
        'examples': OutputChannel(artifact_type=Examples,
        producer_component_id=CsvExampleGen,
        output_key=examples,
        additional_properties={},
        additional_custom_properties={})
    }
)

Experiment
for record in housing.outputs['examples']:
    print(record)

TypeError                                 Traceback (most recent call last)
 in
----> 1 for record in housing.outputs['examples']:
2     print(record)
TypeError: 'OutputChannel' object is not iterable

A: Have you got a chance to take a look at this section in tutorials, which explains how to display the artifacts of ExampleGen component? You can modify the code below (Source: TFX Tutorial) to achieve the same.
# Get the URI of the output artifact representing the training examples, which is a directory
train_uri = os.path.join(example_gen.outputs['examples'].get()[0].uri, 'Split-train')

# Get the list of files in this directory (all compressed TFRecord files)
tfrecord_filenames = [os.path.join(train_uri, name)
                      for name in os.listdir(train_uri)]

# Create a `TFRecordDataset` to read these files
dataset = tf.data.TFRecordDataset(tfrecord_filenames, compression_type="GZIP")

# Iterate over the first 3 records and decode them.
for tfrecord in dataset.take(3):
  serialized_example = tfrecord.numpy()
  example = tf.train.Example()
  example.ParseFromString(serialized_example)
  pp.pprint(example)


Q: Looking for render event in delegateEvents in Backbone.View I have one question about Backbone.View and its delegateEvents. You can read in docs here about extend method. Using this method, you can "override the render function, specify your declarative events" etc.
I have a question about declarative events or delegateEvents (not sure how should I call it). They are described here. And here is an example:
  var DocumentView = Backbone.View.extend({
  events: {
    "dblclick"                : "open",
    "click .icon.doc"         : "select",
    "contextmenu .icon.doc"   : "showMenu",
    "click .show_notes"       : "toggleNotes",
    "click .title .lock"      : "editAccessLevel",
    "mouseover .title .date"  : "showTooltip"
  },
  open: function() {
    window.open(this.model.get("viewer_url"));
  },
  select: function() {
    this.model.set({selected: true});
  },
  ...
});

As you can see, you can add different events on specific objects in template DOM. Like click or mouseover. So, having this template:
<foo></foo>
{#myplayers}
<player class="normal" value="{player}" style="{style}"></player>
{/myplayers}

You can add different click event on every single player, like this:
    events: {
        'click player': 'playerClick'
    },
    playerClick: function( e ) {
        var playerValue = e.currentTarget.getAttribute( 'value' );
        // HERE: e.currentTarget I've particular player

    }

My question: Can I declare render event in similar way as click event? I want to catch event when single player (not the whole list) is rendered. I need to get e.currentTarget there and change its css a little bit.
I'm looking for something like this:
events: {
    'render player': 'playerRendered'
},
playerRendered: function( e ) {
    var playerValue = e.currentTarget.getAttribute( 'value' );
    // HERE: e.currentTarget I've particular player

}

How can I do this? Because render in delegateEvents, doesn't work:/

A: Maybe in the initialize function within your view you can have a listenTo with the render. Something like that:
var view = Backbone.View.extend({
    className: 'list-container',
    template: _.template($('#my-template').html()),
    initialize: function () {
      this.listenTo(this, 'render', function () {
        console.info('actions');
      });
    },
    render: function() {
      this.$el.html(this.template(this));
      return this;
    },
});

And then:
var myView = new view();
myView.render();
myView.trigger('render');
$('#container').html(myView.el);

A: var View = Backbone.View.extend({
  events: {
    'render .myselector': 'playerRendered'
},
playerRendered: function( e ) {
    console.log("arguments");
    var playerValue = e.currentTarget.getAttribute( 'value' );
    // HERE: e.currentTarget I've particular player

},
render:function(){

  console.log("render");
 this.$el.html("

");
}
});
var view = new View();
view.render();

and you can trigger with Jquery trigger
   this.$(".myselector").trigger("render");

or outside your view
  view.$(".myselector").trigger("render");


Q: I just shifted my databases to a sql server 2008 cluster connected to a SAN and its started giving me the following errors SQL Server has encountered 1 occurrence(s) of I/O requests taking longer than 15 seconds to complete on file [T:\MSSQL\DATA\%file_name%] in database [%DB_name%] (2).  The OS file handle is 0×00000838.  The offset of the latest long I/O is: 0×000000ebdc0000
Has anyone encountered and solved this?

A: Please see this - you may have IO issues - and physical drive issues
http://blogs.msdn.com/chrissk/archive/2008/06/19/i-o-requests-taking-longer-than-15-seconds-to-complete-on-file.aspx


Q: Synchronized SELECT to web sql I have need for executing SELECT statement to my web sql table and based on response use result or make AJAX call to obtain results.
It is possible to make synchronized ?
I have function like this:
getFile : function( fileName ) {

  var me            = this;

  me.db.transaction( function( tx ) {

         tx.executeSql( "SELECT * FROM content WHERE fileName = '" + fileName + "'", [ ], me.onSuccess, me.onError );
  } );

  // somehow return results as empty array or array with object
  // I know results need to be transformed
},

and later in code want to do something like this:
var r = getFile( name );
if ( r.length > 0 ) {
   // use it
}
else {
   // make AJAX call and store it
}

A: The simplest way would be to create a function with the code you want to execute after the execution of the request, and pass this function in parameter of the getfile function :
getFile : function( fileName, success ) {

    var me            = this;

    me.db.transaction( function( tx ) {
            tx.executeSql( "SELECT * FROM content WHERE fileName = '" + fileName + "'", [ ], me.onSuccess, me.onError );
        },
        success
    );

    // somehow return results as empty array or array with object
    // I know results need to be transformed
});

var r = getFile(
        name,
        function() {
            var r = getFile( name );
            if ( r.length > 0 ) {
               // use it
            }
            else {
               // make AJAX call and store it
            }
        }
);

Otherwise, the best way to perform is to use Promises to resolve asynchronous issues but you'll have to use a library like JQuery.
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/


Q: How do I 'monkey patch' or override User.is_authenticated()? Creates issues with using django-lazysignup I installed django-lazysignup and am facing the challenge now of User.is_authenticated() returning True, for what are not actually authenticated users, but instead lazy-signup users.  I can update any checks for User.is_authenticated() in my code with my own function.  However, other packages like django-allauth, check this method to decide whether a user is already signed-in, and redirect from attempts to reach the login page.
class RedirectAuthenticatedUserMixin(object):
    def dispatch(self, request, *args, **kwargs):
        self.request = request
        if request.user.is_authenticated():
            redirect_to = self.get_authenticated_redirect_url()
            response = HttpResponseRedirect(redirect_to)
            return _ajax_response(request, response)
...

Are there any recommendations that don't require replacing is_authenticated() in every package that I include?  Seems most of them expect it to function a particular way, and django-lazysignup turns that on its head.  Could I monkey patch the User model with a new is_authenticated() method?  If it's possible, where would I do this so that it's attached to the page request?

A: django-lazysignup, which you are using, allows you to deliver a custom LazyUser class (here). All you need to do is to write a subclass of lazysignup.models.LazyUser with defined is_authenticated method and set it as settings.LAZYSIGNUP_USER_MODEL.
But this is not the end of your troubles. Lots of django apps
assume that authenticated user has some properties. Mainly, is_staff, is_superuser, permissions, groups. First and foremost, django.contrib.admin needs them to check if it can let the user in and what to show him. Look how django.contrib.auth.models.AnonymousUser mocks them and copy it. Remark: look how AnonymousUser is not subclassing any user class nor db.Model. Supplied user class only needs to quack.

A: Ended up just having to replace all calls to User.is_authenticated().
To prevent django-allauth from redirecting lazy-users from the login page, this ended up looking something like this:
from allauth.account.views import AjaxCapableProcessFormViewMixin

def _ajax_response(request, response, form=None):
    if request.is_ajax():
        if (isinstance(response, HttpResponseRedirect)
            or isinstance(response, HttpResponsePermanentRedirect)):
            redirect_to = response['Location']
        else:
            redirect_to = None
        response = get_adapter().ajax_response(request,
                                           response,
                                           form=form,
                                           redirect_to=redirect_to)
    return response

class RedirectUserWithAccountMixin(object):
    def dispatch(self, request, *args, **kwargs):
        self.request = request
        if user_has_account(request.user):
            redirect_to = self.get_authenticated_redirect_url()
            response = HttpResponseRedirect(redirect_to)
            return _ajax_response(request, response)
        else:
            response = super(RedirectUserWithAccountMixin,
                             self).dispatch(request,
                                            *args,
                                            **kwargs)
        return response

    def get_authenticated_redirect_url(self):
        redirect_field_name = self.redirect_field_name
        return get_login_redirect_url(self.request,
                                      url=self.get_success_url(),
                                      redirect_field_name=redirect_field_name)

class LoginView(RedirectUserWithAccountMixin,
            AjaxCapableProcessFormViewMixin,
            FormView):
...

Where user_has_account() was my own method for checking whether the user was actually signed in.


Q: Where is page social_django.views.auth? I'm trying to make auth with google. But get
Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/account/login/google/
Raised by:  social_django.views.auth
Backend not found

settings.py
INSTALLED_APPS = [
    ...,
    'social_django',
]

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '...'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...'
SOCIAL_AUTH_URL_NAMESPACE = 'social'

urls.py(root)
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('books.urls')),
    path('account/', include('account.urls')),
    path('comments/', include('django_comments.urls')),
    path('account/', include('social_django.urls', namespace='social'))
]

login.html
Login with Google

I did migrations for social_django

A: Instead of using :

  Login with Google

Use:

  Login with Google

Source : official documentation


Q: Predict Values by using neural net in R I'm new in using R, but the more I get in thouch with, the more I like it.
Howver, I try to utilze R for artificial neural networks.
My input data is a csv-Table with measured soil properties.
Phosphorus, pH, clay content, silt content and so on.
The objective is to train an neural network with neuralnet and predict Phosphorus (P) by using measured pH, clay content, silt content and so on.
Actually my following script works to train a net, but I don't know, if the script really predicts P by computing the test-dataset with the explaining variables.
Code is below.
library(neuralnet)

getwd("F:/Dropbox/Agrar/Fernerkundung_Agrar/ANN_Test/")
setwd("F:/Dropbox/Agrar/Fernerkundung_Agrar/ANN_Test/")
library(gdata)

# This is a script to train a neural net and test it afterward.
# Objectives are to extimate Phosphorus-Contents in Soil from other variables
# Again. Targetparameter is P (Phosphorus) which has to be estimated from pH, ECa (Soil apparent electrical conductivity) (and later other input variables)

# Traininginput is a CSV-File with measured varaiables P, pH, ECa [here called EC2509 because it was measured in September 25th]
traininginput = read.csv("in.csv", header = TRUE, sep = ";", dec = ".")

#Train the neural network
#Going to have 3 hidden layers -> thumb rule input + output variables
#Threshold is a numeric value specifying the threshold for the partial derivatives of the error function as stopping criteria.
# All later considerd parameters are P~ + PH + clay_A + silt_A + sand_A + LS + A_ABAG + TWI + EC2509
# First let's try P and two variables
net.Phos <- neuralnet(P~PH,traininginput, hidden=3, threshold=0.01, rep = 100) # stepmax = 1000000 will be included later

print(net.Phos)
write.table(net.Phos,"ann_setup.txt", header = TRUE, sep = " ", dec = ".")

#Plot the neural network
png(filename="ANN.png")
pdf(filename="ANN.pdf")
plot(net.Phos)
dev.off()

#Test the neural network: Testdata contains measured variables P, pH, ECa and others. Exactly the same setup than input
testdata = read.csv("testann.csv", header = TRUE, sep = ";", dec = ".")
head(testdata)
net.test <- compute(net.Phos, testdata$PH) #Run them through the neural network

#Lets see what properties net.sqrt has
ls(net.Phos)
write.table(net.Phos,"ann_properties.txt", header = TRUE, sep = ",", dec = ".")

#Lets see the test results
print(net.test$neurons[[1]])
print(net.test$net.test)

#Lets display a better version of the results
cleanoutput <- cbind(testdata$PH,testdata$P,
    as.data.frame(net.results$net.result[,1]))
colnames(cleanoutput) <- c("PH","Expected P","Neural Net P")
print(cleanoutput)
write.csv(Cleanout,"ann_setup.csv", header = TRUE, sep = " ", dec = ".")


Q: Use ONVIF Client Test Tool simulator for Profile T I am trying to do the ONVIF Client certification. For HTTPS streaming, I need to use the profile T simulator that is included with the Client Test Tool. As I understand it, the simulator should behave like an ONVIF camera (or some functionalities of a camera), but it doesn't. I can't even use the command getStreamUri(), because the media service doesn't work.
Has anyone had a similar experience? Or is there another way to use the simulator?
CTT version is 22.06 rev 4624


Q: check facebook session onload Below I am trying to check the session of facebook on page load. And want to show different content on page as per login status. What's wrong?
I want first two check the user connection status. Then only appropriate content to be shown on the page.
   <html xmlns="http://www.w3.org/1999/xhtml" >
<head>

</head>
<body>
<script>

window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      appId      : '1781292862',                        // App ID from the app dashboard
//      channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
      status     : true,                                 // Check Facebook Login status
      xfbml      : true                                  // Look for social plugins on the page
    });

    // Additional initialization code such as adding Event Listeners goes here
  };

window.onload(){
FB.init({
    appId  : '178812862', // Your FB app ID from www.facebook.com/developers/
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml  : true  // parse XFBML
});

FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {

    alert("yes");
    var uid = response.authResponse.userID;
    var accessToken = response.authResponse.accessToken;
  } else if (response.status === 'not_authorized') {

  } else {
    // the user isn't logged in to Facebook.
  }
 });
</script>

</body>
</html>

A: Try this
FB.login(function(response) {
    if (response.authResponse) {
        FB.api('/me', function(response) {
            id= response.id;
            if(id==undefined)
            {
            alert('I am logged out');
            }
            else
            {
            alert('I am logged in');
            }
        })
    }
});

A: First, you'll want to use response.status instead of response.session. And since the status is going to be string either way ("connected", "not_authorized", or "unknown"), you'll want to set up your if statements accordingly. The following example is from https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
FB.getLoginStatus(function(response) {
  if (response.status === 'connected') {
    // the user is logged in and has authenticated your
    // app, and response.authResponse supplies
    // the user's ID, a valid access token, a signed
    // request, and the time the access token
    // and signed request each expire
    var uid = response.authResponse.userID;
    var accessToken = response.authResponse.accessToken;
  } else if (response.status === 'not_authorized') {
    // the user is logged in to Facebook,
    // but has not authenticated your app
  } else {
    // the user isn't logged in to Facebook.
  }
 });

Let me know if that makes sense, or if you have any questions :)
Update
Your script is still missing the little closure that loads the facebook sdk into your document (which is why you're getting the error that FB is not defined). Try replacing your whole script block with the following:
<script>
window.fbAsyncInit = function() {
    FB.init({
        appId  : 1343434343, // Your FB app ID from www.facebook.com/developers/
        status : true, // check login status
        cookie : true, // enable cookies to allow the server to access the session
        xfbml  : true  // parse XFBML
    });

    FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            alert("yes");
            var uid = response.authResponse.userID;
            var accessToken = response.authResponse.accessToken;
        } else if (response.status === 'not_authorized') {

        } else {
            // the user isn't logged in to Facebook.
        }
    });
};

// Load the SDK asynchronously
(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>

(^That last part is what loads the facebook sdk.) Try it out and let me know how it goes :)


Q: Sending data from Arduino to MIT app Inventor 2 via bluetooth I have an Arduino Uno microprocessor connected with a temperature sensor, I am able to print the temperature on the Serial Monitor successfully.
The idea is, I wanna dump the value of the temperature into a label sitting on MIT app inventor 2 project via Bluetooth. Anybody has an idea how to do that?
What should I add to the following code to be able to send the data via Arduino.
const int dataPin = 8;
int temperature = -1;
int humidity = -1;

void setup() {
 Serial.begin(115200);

}

int readDHT11(){
  uint8_t recvBuffer[5];
  uint8_t cnt = 7;
  uint8_t idx = 0;
  for(int i = 0; i<5; i++){
    recvBuffer[i] = 0;
  }

  pinMode(dataPin, OUTPUT);
  digitalWrite(dataPin, LOW);
  delay(18);
  digitalWrite(dataPin, HIGH);

  delayMicroseconds(40);
  pinMode(dataPin, INPUT);
  pulseIn(dataPin, HIGH);

  unsigned int timeout = 10000;
  for(int i = 0; i<40; i++){
      timeout = 10000;
      while(digitalRead(dataPin) == LOW){
          if(timeout == 0) return -1;
          timeout--;
      }
  unsigned long t = micros();

  timeout = 10000;
  while(digitalRead(dataPin) == HIGH){
      if(timeout == 0) return -1;
      timeout--;

  }

  if ((micros() - t) > 40) recvBuffer[idx] |= (1 << cnt);
  if(cnt ==0){
    cnt = 7;
    idx++;
  }else{
    cnt--;
  }

  }

  humidity = recvBuffer[0];
  temperature = recvBuffer[2];
  uint8_t sum = recvBuffer[0] + recvBuffer[2];
  if(recvBuffer[4] != sum) return -2;
return 0;

}

void loop() {
  int ret = readDHT11();
  if(ret!=0) Serial.println(ret);
  Serial.print("Humidity: "); Serial.print(humidity); Serial.print(" %\t");

  Serial.print("Temperature: "); Serial.print(temperature); Serial.print(" C\n");

  delay(500);
}

Thanks!!

A: Take a look here. This tutorial was really helpful for me when I was a beginner. Hope that it will helps you too!
Good luck.


Q: AWS Delete items by non-primary key I have a problem, and i don't really know how to ask it
I've tables like this
user table
-----------------------------------
UID (primary key) | name (another key)
-----------------------------------
a1c8d3            | Hugo
f9e2d7            | Thomas
s2c9d4            | Damien

metadata table
-----------------------------------
MID (primary key) | UID (another key)
-----------------------------------
c3d9d3            | a1c8d3
d8f1e6            | a1c8d3
d3j5c2            | f9e2d7

I have a function to get all UID of my user table, they're store in an array
When i delete users of this array, i want to delete items on my metadata table which has same UID than my deleted users
Is it possible to delete items of my metadata table without using the primary key (here, MID) ?
Or did i need to set UID's of my metadata table to a global secondary index ? If yes, how can i do it ?
Thank you in advance
Best regards

A: No.
DeleteItem() requires a primary key for the table (docs)
You'd need to query the metadata table, and delete the rows with the matching UID.
If you don't already have it, I'd recommend a global secondary index with
hash key = UID
sort key = MID
Then a Query(GSI, hash = UID) would using your example data return two rows.
You'd then call DeleteItem(Table, HashKey = MID) for each returned row.
Or better yet, collect both deletes and send once as a BatchWriteItem()


Q: Simple scrollX element with scroll snap, Changing page numbers I'm trying to create simple element with scroll snapping. I've created a demo in Codepen.
I would like to scroll to an other image and after scroll, when other image is visible, change page number and the color of bottom circles.
I've tried to put onscroll"function()" in div .container and calculate somehow winW & scrollX ratios, but this approach is buggy and messy.
How should I make it, please? Thanks a lot.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
}

.container {
  display: flex;
  overflow: auto;
  flex: none;
  width: 100vw;
  height: 100vw;
  flex-flow: row nowrap;
  scroll-snap-type: x mandatory;
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.container::-webkit-scrollbar {
  display: none;
}

.pagination {
  position: absolute;
  top: 16px;
  right: 16px;
  background: #777;
  color: #fff;
  line-height: 40px;
  width: 50px;
  font-size: 12px;
  border-radius: 20px;
  text-align: center;
}

.image {
  width: 100vw;
  height: 100vw;
  scroll-snap-align: center;
  flex: none;
}

#image-1 {
  background: url("https://i.ibb.co/fMp05Jf/tamanna-rumee-ov-U2t-Rgfj-H8-unsplash.jpg");
  background-size: cover;
  beckground-position: center;
}

#image-2 {
  background: url("https://i.ibb.co/Fx3Vm0S/pranav-madhu-KHD8vyputcg-unsplash.jpg");
  background-size: cover;
  beckground-position: center;
}

#image-3 {
  background: url("https://i.ibb.co/4Fznzvs/tijana-drndarski-cj-Es-Ho-Pk-ZOQ-unsplash.jpg");
  background-size: cover;
  beckground-position: center;
}

#image-4 {
  background: url("https://i.ibb.co/bPWXGfR/kristaps-ungurs-trs-Gn-MDb-T2-E-unsplash.jpg");
  background-size: cover;
  beckground-position: center;
}

#image-5 {
  background: url("https://i.ibb.co/5jyBdGK/joanna-kosinska-pj-Pe-CRkl83-M-unsplash.jpg");
  background-size: cover;
  beckground-position: center;
}

.pills {
  padding: 8px;
  display: flex;
  justify-content: center;
}

.circle {
  margin: 8px;
  height: 10px;
  width: 10px;
  border-radius: 5px;
  background: #ccc;
}

#circle-1 {
  background: #777;
}

1 / 5

A: You could simply add anchor tags with the ID name of the slide to automatically scroll to them:
pills (with anchor tag)


Q: Props is not defined using render props I want to build an app that uses render.props. I created the component where all my logic is stored:

import React, {useState} from 'react';

function Test(){
    let [click, setClick] = useState(0);
    function funClick(){
    setClick(click++)
  }
  return(

    {props.render(click, setClick)}

  )
}
export default Test;

The issue is that i've got an error Line 10:  'props' is not defined  no-undef. What means this error and how to solve it?

A: You need props as an argument for your component.
import React, {useState} from 'react';

function Test(props) {
    let [click, setClick] = useState(0);
    function funClick(){
    setClick(click++)
  }
  return(

    {props.render(click, setClick)}

  )
}
export default Test;


Q: call the same name functions in jquery? i have 2 file js in my asp website named
1-jquery.datepick.js

2-jquery.hijridatepick.js

these file have the same name functions but second one apear popup hijricalender i call it by
  <script type="text/javascript">
      $(function () {
          $('[id$=TextBox1]').datepick({ dateFormat: 'dd/mm/yyyy' });
       });
  </script>

for textbox2 i wanna 2 use datepick function from first file how icall it cause i refrenced the first file as
 $('[id$=TextBox2]').datepick({ dateFormat: 'dd/mm/yyyy' });

but this call again the function of second file
???

A: The second file is overwriting the first. You must change the name of one of the functions to avoid the collision.
You'll find something like this in the files:
jQuery.fn.datepick = function() {
    // etc.
};

This is where the jQuery plugin method is created. Just change datepick in one or both files to something different and unique.

A: As noted in FishBasketGordo's answer, the second function to load will overwrite the first, and changing the name of one will fix this, however there is a deeper problem that needs to be addressed.
The reason this happens is that the functions are being added to the global namespace. In javascript the file that the code comes from is irrelevant. One way to avoid avoid polluting the global namespace is to wrap functions inside an object, so in your case you might have:
/* 1-jquery.datepick.js */
datepick = new Object;
datepick.datepick = function() {
    /* function definition here */
    alert('first file function');
};

/* 2-jquery.hijridatepick.js */
hijridatepick = new Object;
hijridatepick.datepick = function() {
    /* function definition here */
    alert('second file function');
};

These functions can then be accessed using:
datepick.datepick();
/* alerts 'first file function' */

hijridatepick.datepick();
/* alerts 'second file function' */


Q: barplot with 2 columns I would like to create barplot horizontal with the following dataframe
studentData = {
0 : {
    'stylevel' : 'bachelor',
    'q' : 'agree',
    'Type' : 'Nascent'
    },
1 : {
    'stylevel' : 'bachelor',
    'q' : 'very',
    'Type' : 'Nascent'
    },
2 : {
    'stylevel' : 'master',
    'q' : 'very',
    'Type' : 'Active'
    },
3 : {
    'stylevel' : 'master',
    'q' : 'agree',
    'Type' : 'Active'
    },
4 : {
    'stylevel' : 'master',
    'q' : 'agree',
    'Type' : 'Student'
    },
}

dfObj = pd.DataFrame(studentData)
dfObj = dfObj.T

I'm using the following code to plot the graph
dfObj['q'].value_counts().plot(kind='barh')

Could you tell me how I could create the same graph using the Type column in the original dataframe to split the q data in 3 subgroups (i.e. Student, Active and nascent)?

A: You have three options.
using pandas:
dfObj.groupby('Type')['q'].value_counts().plot(kind='barh')

using pandas stacked bars:
dfObj.groupby('Type')['q'].value_counts().unstack(level=0).plot.barh(stacked=True)

using seaborn.catplot:
import seaborn as sns
df2 = dfObj.groupby('Type')['q'].value_counts().rename('count').reset_index()
sns.catplot(data=df2, x='q', hue='Type', y='count', kind='bar')


Q: How to use implicit wait and explicit wait together? In my framework we are using singleton driver and we are mainly using explicit wait. As documentation suggests we shouldn't use both together but at some points because of synchronization issues I need to use implicit wait.
In that case I found a workaround, I add implicit wait to my driver, then at the end of this test I just create brand new driver.
But I would like to know if there is any other way to do that ?

A: As per the documentation:

Warning: Do not mix implicit and explicit waits. Doing so can cause unpredictable wait times. For example, setting an implicit wait of 10 seconds and an explicit wait of 15 seconds could cause a timeout to occur after 20 seconds.


Q: How can I limit the input number range with angular I would like to limit the input number that can go up to the current year, the user cannot enter a year higher than the current one. How can I do it?
My code:
<ion-content >
 <form>
  <ion-list>
    <ion-item>
      <ion-label>Stagione</ion-label>
      <ion-input [(ngModel)]="season.Description"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Year</ion-label>
      <ion-input [(ngModel)]="season.Year" type="number"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Primavera/Estate</ion-label>
      <ion-checkbox [(ngModel)]="season.IsSpringSummer"></ion-checkbox>
    </ion-item>
    <ion-item>
      <ion-label>Default</ion-label>
      <ion-checkbox [(ngModel)]="season.IsDefault"></ion-checkbox>
    </ion-item>
    <ion-item>
      <ion-label>Nascosto</ion-label>
      <ion-checkbox [(ngModel)]="season.IsHidden"></ion-checkbox>
    </ion-item>

  </ion-list>

</ion-content>
<ion-footer>
  <ion-toolbar color="footer">
    <ion-buttons right>
  <button ion-button clear color="dark" (click)="save()">Save

      </button>

    </ion-buttons>
  </ion-toolbar>

</ion-footer>

A: You can make use of the min and max properties.
Bind the max property to the current year like so: <ion-input [(ngModel)]="season.Year" type="number" [max]="{{(new Date()).getFullYear()}}"></ion-input>.
The logic for getting the full year could be moved to the typescript file and could be stored in a variable like currentYear. In the template we can then bind to max like so: [max]="currentYear".

A: You can do it simply by HTML only:
<input type="number" oninput="if(value > (new Date()).getFullYear()) alert('Year exceeds current year')">

If you really want to do it by Angular only you have to create custom Validator which you can find in the link given below:
Min / Max Validator in Angular 2 Final
If you are using Angular 6 then you can use min and max validators which you can find in the link given below:
https://angular.io/api/forms/Validators#min

A: I suggest you simply to do a check in function save().
It can be like this:
if((new Date()).getFullYear() < this.season.Year) {
   //display an error message, maybe using alert or toast
}


Q: Alpha animation works, then does not work My app is about users picking three buttons: Sad, Happy and Confuse. If they click the Sad button, the image changes into a sad emoji. If they click the Happy button, happy emoji is displayed. Simple.
But, when I run my app, and I click any of the buttons, the alpha animation works. If I then click another button, the alpha animation does not work anymore. The alpha animation only works once. The alpha animation is only for the images.
Here's my Java code:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Happy_Btn = findViewById(R.id.Happy_Btn);
        Sad_Btn = findViewById(R.id.Sad_Btn);
        Confuse_Btn = findViewById(R.id.Confuse_Btn);
        Feeling_txtView = findViewById(R.id.Feeling_txtView);
        Face_Img = findViewById(R.id.Face_Img);

        Animation animation = new AlphaAnimation(0f, 1.0f);
        animation.setDuration(2000);

        Feeling_txtView.setText("You are feeling happy!");
        Happy_Btn.setEnabled(false);

        Sad_Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sad_Btn.setEnabled(false);
                Happy_Btn.setEnabled(true);
                Confuse_Btn.setEnabled(true);

                Feeling_txtView.setText("You are feeling sad...");
                Face_Img.setAnimation(animation);
                Face_Img.setImageResource(R.drawable.sad);
            }
        });

        Happy_Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sad_Btn.setEnabled(true);
                Happy_Btn.setEnabled(false);
                Confuse_Btn.setEnabled(true);

                Feeling_txtView.setText("You are feeling happy!");
                Face_Img.setAnimation(animation);
                Face_Img.setImageResource(R.drawable.happyface);
            }
        });

        Confuse_Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sad_Btn.setEnabled(true);
                Happy_Btn.setEnabled(true);
                Confuse_Btn.setEnabled(false);

                Feeling_txtView.setText("You are feeling confused?");
                Face_Img.setAnimation(animation);
                Face_Img.setImageResource(R.drawable.confuse);
            }
        });
    }

(EDIT)
I made few changes to my code and then when I run it, my issue is solved! But I'm not sure if this is the right way to do it. What I did was I first cut these two lines:
Animation animation = new AlphaAnimation(0f, 1.0f);
animation.setDuration(2000);

and then paste them into each buttons (Sad, Happy and Confuse)
My app works the way I wanted it to be.

A: you should renew AlphaAnimation
you do it is the right


Q: Cancel sharepoint workflow when cancel sharepoint workflow by web browser or programatically by code
SPWorkflowManager.CancelWorkflow()

All task in my workflow task list was deleted, where i can turn off this, i need this task to reporting.

A: This is the way SharePoint works, canceling a workflow deletes all related tasks, but the workflow history is kept. Do not rely on tasks as a proof that something did or did not happen.


Q: How "==" works for objects? public static void main(String [] a)
{
    String s = new String("Hai");
    String s1=s;
    String s2="Hai";
    String s3="Hai";
    System.out.println(s.hashCode());
    System.out.println(s1.hashCode());
    System.out.println(s2.hashCode());
    System.out.println(s3.hashCode());
    System.out.println(s==s2);
    System.out.println(s2==s3);

}

From the above code can anyone explain what is going behind when JVM encounters this line (s==s2) ?

A: It compares references - i.e. are both variables referring to the exact same object (rather than just equal ones).

*

*s and s2 refer to different objects, so the expression evaluates to false.

*s and s1 refer to the same objects (as each other) because of the assignment.

*s2 and s3 refer to the same objects (as each other) because of string interning.

If that doesn't help much, please ask for more details on a particular bit. Objects and references can be confusing to start with.
Note that only string literals are interned by default... so even though s and s2 refer to equal strings, they're still two separate objects. Similarly if you write:
String x = new String("foo");
String y = new String("foo");

then x == y will evaluate to false. You can force interning, which in this case would actually return the interned literal:
String x = new String("foo");
String y = new String("foo");
String z = "foo";

// Expressions and their values:
x == y: false
x == z: false
x.intern() == y.intern(): true
x.intern() == z: true

EDIT: A comment suggested that new String(String) is basically pointless. This isn't the case, in fact.
A String refers to a char[], with an offset and a length. If you take a substring, it will create a new String referring to the same char[], just with a different offset and length. If you need to keep a small substring of a long string for a long time, but the long string itself isn't needed, then it's useful to use the new String(String) constructor to create a copy of just the piece you need, allowing the larger char[] to be garbage collected.
An example of this is reading a dictionary file - lots of short words, one per line. If you use BufferedReader.readLine(), the allocated char array will be at least 80 chars (in the standard JDK, anyway). That means that even a short word like "and" takes a char array of 160 bytes + overheads... you can run out of space pretty quickly that way. Using new String(reader.readLine()) can save the day.

A: == compars objects not the content of an object. s and s2 are different objects. If you want to compare the content use s.equals(s2).

A: I suppose you know that when you test equality between variables using '==', you are in fact testing if the references in memory are the same. This is different from the equals() method that combines an algorithm and attributes to return a result stating that two Objects are considered as being the same. In this case, if the result is true, it normally means that both references are pointing to the same Object. This leaves me wondering why s2==s3 returns true and whether String instances (which are immutable) are pooled for reuse somewhere.

A: Think of it like this.
  Identical twins look the same but they are made up differently.
If you want to know if they "look" the same use the compare.
If you want to know they are a clone of each other use the "=="

:)

A: == compares the memory (reference) location of the Objects. You should use .equals() to compare the contents of the object.
You can use == for ints and doubles because they are primitive data types

A: It should be an obvious false. JVM does a thing like using the strings that exist in the Memory . Hence s2,s3 point to the same String that has been instantiated once. If you do something like s5="Hai" even that will be equal to s3.
However new creates a new Object. Irrespective if the String is already exisitng or not. Hence s doesnot equal to s3,s4.
Now if you do s6= new String("Hai"), even that will not be equal to s2,s3 or s.

A: The literals s2 and s3 will point to the same string in memory as they are present at compile time. s is created at runtime and will point to a different instance of "Hai" in memory. If you want s to point to the same instance of "Hai" as s2 and s3 you can ask Java to do that for you by calling intern. So s.intern == s2 will be true.
Good article here.

A: You are using some '==' overload for String class...


Q: Trouble with UPDATE query I'm having problems trying to use the UPDATE query in SQL server.
this is my query:
UPDATE THEATER
SET SeatsAvailable = SeatsAvailable - 1
FROM THEATER
INNER JOIN CINEMA_SESSION ON CINEMA_SESSION.tid = THEATER.tid
WHERE THEATER.tid = 2 AND CINEMA_SESSION.sid = 2

-tid is the pk for THEATER
-sid is the pk for CINEMA_SESSION
When I use a SELECT statement to search for the SeatsAvailable in CINEMA_SESSION.sid = 3, which also has .tid=2, it also comes with the updated value for the CINEMA_SESSION.sid = 2.
The statement that I'm using is this simple Select statement:
SELECT THEATER.SeatsAvailable as SeatsAvailable FROM THEATER
INNER JOIN CINEMA_SESSION ON CINEMA_SESSION.tid = THEATER.tid
WHERE CINEMA_SESSION.sid = 3 AND THEATER.tid = 2

Here I want to specify the THEATER.tid which is the same in the UPDATE query but in a different CINEMA_SESSION.sid in which the SeatsAvailable should have remained the same.

A: The update statement is decrementing the value of SeatsAvailable on the Theatre table for tid=2 (the AND CINEMA_SESSION.sid = 2 is immaterial - you are updating the row on the THEATER table). Since tid is the primary key for theatre, there is only one record with that value, and that record is updated.
Your select for session sid=3 joins to theatre by the tid column, and it's matching the row where tid=2, which is why you're seeing the new value - it is matching the record that you just updated.
This may make more sense if you just look at the contents of the THEATER table (without any joins).
If you are trying to indicate that a seat has been booked for a particular session, then I would suggest you need to be updating a field on a different table. I'll leave that to you to work out. Hope this helps.


Q: how to get the variable list from each data frame in a list I have a list of df, and I would like to rename the df as df1, df2, df3. and then create a summary like below to capture the variables in each df. What should I do?

I tried to use map to setNames for the data frames in lst, but I must do it in the wrong way. my current codes set variable names to df1, df2, def3.
lst<- map( lst ~
  setNames(.x, str_c("df", seq_along(lst))))

sample data:
lst<-list(structure(list(ID = c("Tom", "Jerry", "Mary"), Score = c(85,
85, 96), Test = c("Y", "N", "Y")), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame")), structure(list(ID = c("Tom", "Jerry",
"Mary", "Jerry"), Score = c(75, 65, 88, 98), try = c("Y", NA,
"N", NA)), row.names = c(NA, -4L), class = c("tbl_df", "tbl",
"data.frame")), structure(list(ID = c("Tom", "Jerry", "Tom"),
    Score = c(97, 65, 96), weight = c("A", NA, "C")), row.names = c(NA,
-3L), class = c("tbl_df", "tbl", "data.frame")))

A: We get the column names with names/colnames by looping, paste to a single string with toString, convert to a data.frame column and bind the elements (_dfr).
library(purrr)
library(dplyr)
library(stringr)
setNames(lst, str_c("df", seq_along(lst))) %>%
    map_dfr(~ tibble(Var = toString(names(.x))), .id = 'Data')

-output
# A tibble: 3 × 2
  Data  Var
  <chr> <chr>
1 df1   ID, Score, Test
2 df2   ID, Score, try
3 df3   ID, Score, weight


Q: Check for uniformity of a multidimensional list Following my other question I was surprised to know that Numpy is pretty loose on the definition of array_like objects. Basically np.array(1) is a valid numpy ndarray of shape () and dimension of 0! also np.array([[1,2],[3]]) is a valid ndarray of shape (2,) and dimension of 1. Basically np.array digs as many dimensions as possible till it reaches nonuniformity or zero-dimensional values. This implementation might be pretty fast, but is not necessarily safe. In fact it is very error prone. if somebody forgets one element of an input list, the function returns no error, leading to other most probably more confusing errors down the code.
I was thinking if it is possible to write a checkArr function to check the homogeneity and uniformity of the multidimensional list, with the least possible overhead. Scavenging over a couple of other SO post I ended up with this recursive solution:
def checkArr(A):
    assert isinstance(A, (list,tuple,range)),
             "input must be iterable (list, tuple, range)"
    assert all(isinstance(a, type(A[0])) for a in A[1:]),
             "elements of the input must of a the same type, input must be homogeneous"
    if isinstance(A[0], (list,tuple,range)):
        assert all(len(a)==len(A[0]) for a in A[1:]),
             "elements of the input must of a the same size, input must be uniform"
        [checkArr(a) for a in A]

now my question is if this is the fastest solution or more performant/Pythonic implementations are possible?

A: Specifying dtype argument when creating an array avoids the unintentional creation of object arrays from jagged matrices, without writing any additional code.
np.array([[1, 2], [3, 4]], dtype=int)  # okay
np.array([[1, 2], [3]], dtype=int)     # ValueError
np.array([[1, "b"]], dtype=int)        # ValueError

(Regarding the last one, np.array([1, "b"]) would silently convert "1" to a string if the data type was not set.)

A: There's Python saying that it's easier to ask forgiveness than permission.  So there might be less overhead if you just call np.array and then check for object dtype.
One other thing that you need to watch out for is when it throws an error.  For example:
In [273]: np.array((np.zeros((2,3)), np.ones((2,4))))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-273-70f6273e3371> in <module>()
----> 1 np.array((np.zeros((2,3)), np.ones((2,4))))

ValueError: could not broadcast input array from shape (2,3) into shape (2)

If the non-uniformity is in the first dimension, it produces an object dtype array, e.g. np.array((np.zeros((2,3)), np.ones((1,4)))).  But when it's at a deeper level it appears to allocate  the result array, and then has problems copying one or more of the component arrays to it.  This is a tricky case to diagnose.
Or consider:
In [277]: np.array([[1,2,3],[4,5,'6']])
Out[277]:
array([['1', '2', '3'],
       ['4', '5', '6']], dtype='<U21')

The last element in the nested list forces the string dtype.  And if that last element is some other PYthon object, we may be a object dtype:
In [279]: np.array([[1,2,3],[4,5,{}]])
Out[279]:
array([[1, 2, 3],
       [4, 5, {}]], dtype=object)

But if the object is a list, we get a variant on the broadcasting error:
In [280]: np.array([[1,2,3],[4,5,['6']]])
ValueError: setting an array element with a sequence

But if you do want to check first, np.stack might a good model.  With axis=0 it behaves much like np.array if given arrays or lists.


Q: PostgreSQL: "index row requires 1460216 bytes, maximum size is 8191" I'm new to PostgreSQL and I'm trying to populate a table with the content of a list of dictionaries built in Python, which looks like:
diclist = [{'accession':'value', 'species':'value', 'seq':'value', 'length': 'value'},
            {'accession':'value', 'species':'value', 'seq':'value', 'length': 'value'},
...]
'seq' values are strings with sometimes > 300.000 characters...
However, my data include genetic sequences which are pretty long so when I try to load these data into the table, PostgreSQL claims the following:

index row requires 1460216 bytes, maximum size is 8191

Is there a way to increase the row index maximum size?? Or is there a way to compress the space required by my data?
I know BioPython and BioSQL are made to handle genetic sequences, but they don't exactly match what I need...
This is the function I've built for the moment (diclist is the list of dictionaries):
def insert_biosequence(diclist):
try:
params = config()
conn = psycopg2.connect(**params)
cur = conn.cursor()
cur.executemany("""INSERT INTO biosequence(accession, species, seq, length) VALUES (%(accession)s, %(species)s, %(seq)s, %(length)s)""", diclist)
conn.commit()
cur.close()
  except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
  conn.close()

My CREATE TABLE command is the following:
CREATE TABLE biosequence (
accession TEXT,
species TEXT,
seq TEXT PRIMARY KEY,
length INTEGER

);
I'm not using any INDEX commands, I think it's done by default by PostgreSQL... should I?

A: Given that your data is structured, you probably want to create a schema that better suits your structure and then load it in that format rather than just raw source data, or at the very least load the raw data and then transform it into your structure format for easier searching.
Otherwise, you might be able to use full text search with GIN index or a GIN index with the pg_trgm operators.


Q: Is there a way to play a specific tone using python3? I'm working on a python3 project (in PyCharm, using Windows 10) and I'm trying to play a series of tones and save them all to a mp3 file.
I can get it to play a series of notes with winsound:
import winsound
while True:
    winsound.Beep(1000, 1000)

But I can't save it.
All help appreciated!

A: If you want to save output to a file, rather than just play it, probably the most ideal way of doing this is to generate midi files. There are a few packages that can help you create midi files in a similar way.
This example uses the package called mido
from mido import Message, MidiFile, MidiTrack

mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)

track.append(Message('note_on', note=64, velocity=64, time=32))

mid.save('new_song.mid')

You can convert midi files to MP3s easily if needed (many programs or even online tools can do this) although, midi files are generally well-supported in most applications.
See also
Although perhaps dated, you can also check the PythonInMusic wiki for references to more MIDI and other audio libraries.
Alternatively, you can use a separate program to record your audio output when running your python script using winsound.