Flexigrid: window.resize problem

Question: I managed to come up with a code that can make flexigrid more "fluid", more specifically it can resize depending on the window size on page load, but now I would like to add the function to resize automatically when the size of the window changes without refreshing it.
This is what I have so far:
<code>$(document).ready(function(){
var myWidth;
var myHeight;
var rowno;
    if($(window).resize(function(e) {
  // do something when window resizes
    if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
    var rowno = Math.floor((myHeight - 96)/29)
  }));
    $("#flex1").flexigrid
            (
            {
            url: 'post2.php',
            dataType: 'json',
            colModel : [
                {display: 'ID', name : 'id', width : (myWidth*0.018), sortable : true, align: 'center', hide: false},
                {display: 'URL', name : 'url', width : (myWidth*0.38), sortable : false, align: 'left'},
                {display: 'File Name', name : 'filename', width : (myWidth*0.239), sortable : true, align: 'left'},
                {display: 'Availability', name : 'availability', width : (myWidth*0.038), sortable : true, align: 'center'},
                {display: 'State', name : 'state', width : (myWidth*0.029), sortable : true, align: 'center'},
                {display: 'Total Size', name : 'totalsize', width : (myWidth*0.05), sortable : false, align: 'center'},
                {display: 'Current Size', name : 'currentsize', width : (myWidth*0.05), sortable : false, align: 'center'},
                {display: 'Procent', name : 'procent', width : (myWidth*0.04), sortable : true, align: 'center'},
                {display: 'Log',  width : (myWidth*0.018), sortable : false, align: 'center'},
                ],
            buttons : [
                {name: 'Add', bclass: 'add', onpress : test},
                {name: 'Delete', bclass: 'delete', onpress : test},
                {separator: true},
                {name: 'Start', bclass: 'start', onpress : test},
                {name: 'Stop', bclass: 'stop', onpress : test},
                {separator: true},
                {name: 'Select All', bclass : 'selectall', onpress : test},
                {name: 'DeSelect All', bclass : 'deselectall', onpress : test},
                {separator: true}
                ],
            searchitems : [
                {display: 'URL', name : 'url'},
                {display: 'Filename', name : 'filename', isdefault: true}
                ],
            sortname: "id",
            sortorder: "asc",
            usepager: true,
            title: '',
            useRp: false,
            rp: rowno,
            showTableToggleBtn: true,
            height: (myHeight - 96)
            }
            );
});
</code>
Right now it throws me an error in jquery about an invalid argument, but I am pretty sure is syntax problem.
Thanks,
Cristian.
Answer: if u see the height size of any element and u add it together it 120px aprox.
so if u do something like this (flexigrid config object property), u'll be ok:
<code>$("#tabla").flexigrid({
   ...,
   width:'auto',
   height:$("#container").innerHeight()-120
});
</code>
Answer: better use % for size in place of px or em
it works fine without such big script
** edit **
if u still want to do give a settimeout function which will check every 1 sec the size of the browser window.height and width with window.width :)
if u succeed with this I'm the first one to copy your script I'm searching for the same . . but got used to %
Comment: Can't do it, that's how flexigrid works. The problem with the script is only the window.resize part. Thx.
Comment: Even if this doesn't get an asnwer, you could still use the script, just remove teh code from var myWidth; ---- 'til and including ----   // do something when window resizes and })); before -> $("#flex1").flexigrid. The height and width of the table will be set in accordance to the browser width and height. :)

Flexigrid: window.resize problem


jquery number plugin inserting as an integer into database

Question: i've been using JQuery number plugins to help adding thousand separator in my text value, and i've been trying to insert the value as an integer, for example :

image above is the input where i was trying to insert as a Integer into database.
but here is the value that being catched as a Integer after i convert it into integer :
$insert['nett_budget'] = intval($request->get('nett_budget'));

and here is when they are nvchar :

here is the Jquery in index.php :
$('#nett_budget').number(true);

Is there a way to catch the whole number after the thousand separator as an Integer ? , or there maybe an alternate plugins that i can use, thanks!.
Comment: Use this function `function strReplace(fnd, repl, str) { return str.replace(new RegExp(fnd, 'g'), repl); }`. With this function all str will be replaced.
Answer: Suppose you get this value;
var val = "222,222";

As your value is in string format you should replace your unnecessary character from your value like this;
var finalval = val.replace(",", "");

Here the first parameter is the character you want to remove, and the second parameter is the empty value. Through this technique, you can get the proper integer value in string format. Convert it into an integer if you need it.
First Modification:
Here is the code with your code example, please check this;
set your value into a variable:
var _budget = $('#nett_budget').val(data.nett_budget);

Modify the value and replace unnecessary characters:
var _final_budget = _budget.replace(",", "");

Now use this _final_budget value instead of $('#nett_budget').val(data.nett_budget); this value. You can convert it into an integer.
Comment: sorry im really new in using these language, where should i put the var finalval ?, in my controller it was like :
`$insert['nett_budget'] = intval($request->get('nett_budget'));`,
and my index to get the value from input is :
 `$('#nett_budget').val(data.nett_budget);`.
Thanks again.
Comment: please check the modification
Comment: thanks! it's working now, and the data is finally inputted into the databse.


What is the 'popularity-contest' package for?

Question: I'm installing ubuntu server at the moment, and noticed it in the configuration phase.
What does this package do, what is it for?
Answer: It sends information about installed packages (but this is disabled by default, you can enable it using sudo dpkg-reconfigure popularity-contest) for package popularity/usage statistics.
https://help.ubuntu.com/community/UbuntuPopularityContest
http://popcon.ubuntu.com/
Package description:
The popularity-contest package sets up a cron job that will periodically
 anonymously submit to the Ubuntu developers statistics about the most used
 Ubuntu packages on this system.

 This information helps us making decisions such as which packages should go on
 the first CD. It also lets us improve future versions of Ubuntu so that the
 most popular packages are the ones which are installed automatically for new
 users.

Comment: The description is from Debian which used to be distributed on multiple CDs (good old times before DVDs). The first CD contained minimal set of packages and you could use other CDs as "repositories" to install additional ones (useful for people without Internet access). So the popcon results helped developers to decided what packages put on the first CD.
Comment: What is "the first CD" in this context?
Comment: Just risked an heart attack after finding it on a production server, and parsing the config file where there is a TOR connection method mentioned. Thanks for your old but still effective post, heart rate back to normal.


How to search by text and value in Kendo Dropdown List.

Question: <code>$(document).ready(function() {
                $("#products").kendoDropDownList({
                    filter: "startswith",
                    dataTextField: "ProductName",
                    dataValueField: "ProductID",
                    dataSource: {
                        type: "odata",
                        serverFiltering: true,
                        transport: {
                            read: {
                                url: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Products",
                            }
                        }
                    }
                });
            });
</code>
How can i  search by value and text together in kendo dropdown list. a better example you can find here
Now i can search by only text. suppose I want to search by employee id & name together. now i can search by only name.
is it possible? or not. Give me clue to continue digging.
I will appreciate your help.
Comment: You can prepare your server-side method to expect a number and change the query in this case. You can also set a placeholder text to the search field instructing user to type the *"id or employee name"*.
Answer: Just on the ServerFiltering to true and handle your query in server side and response the result....
below is my angular controller:
<code>$scope.reportingPersonOptoins = {
            filter: "startswith",
            autoBind: true,
            dataSource: {
                serverFiltering: true,
                transport: {
                    read: {
                        dataType: "json",
                        type: "POST",
                        url: baseurl + "employee/get_employee_list"
                    }
                }
            },
            dataTextField: "first_name",
            dataValueField: "employee_id",
            optionLabelTemplate: "---Select Reporting Person---",
            template: '<span>#: data.employee_id #, #: data.first_name # #: data.last_name # </span>',
            valueTemplate: '<span>#: data.employee_id #, #: data.first_name # #: data.last_name # </span>',
        };
</code>
and this is my server wrappers
receive the value by :
<code> header('Content-Type: application/json');
 $receive = $this->input->post();
if (isset($receive['filter'])) {
        $data = $receive['filter']['filters'][0]['value'];
    } else {
        $data = NULL;
    }
</code>
and run the query accordingly
<code>$this->db->select('hr_employee.employee_id, hr_employee.first_name, hr_employee.last_name, hr_employee_employment.branch_id')
            ->join('hr_employee_employment', 'hr_employee.employee_id = hr_employee_employment.employee_id')
            ->where(array("hr_employee.is_active" => 1, "hr_employee.is_admin" => 0));
    if ($data !== NULL) {
        $this->db->or_like("hr_employee.employee_id", $data);
        $this->db->or_like("hr_employee.first_name", $data);
        $this->db->or_like("hr_employee.last_name", $data);
    }
    $query = $this->db->get('hr_employee');
</code>
Wow!!! cheers!!


Angular Karma Jasmin - No provider for LocaleService

Question: When i'm trying to test using karma jasmin, i'm getting this error...
NullInjectorError: StaticInjectorError(DynamicTestModule)[DaterangepickerDirective -> LocaleService]:
  StaticInjectorError(Platform: core)[DaterangepickerDirective -> LocaleService]:
    NullInjectorError: No provider for LocaleService!

My component
import { Component, OnInit } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { ApiService } from '../../../services/api.service';
import * as moment from 'moment';

@Component({
  selector: 'ngx-item-analytics',
  templateUrl: './item-analytics.component.html',
  styleUrls: ['./item-analytics.component.scss']
})
export class ItemAnalyticsComponent implements OnInit {

  data: any;
  data2: any;
  showBarchart1: boolean = false;
  showBarchart2: boolean = false;
  maxDate: moment.Moment;
  minDate: moment.Moment;
  datepickerChanges:boolean = false;
  dateGrouped:Date;
  alwaysShowCalendars: boolean;
  keepCalendarOpeningWithRange: boolean;
  showRangeLabelOnInput: boolean;
  invalidDates: moment.Moment[] = [];
  selected: any;
  startDate:any;
  endDate:any;
  datagroupedChart:boolean=false;
  datagrouped:any[] =[];
  venues: any = [];
  selectedVenue: any = 'Oahu';
  selVenue: any;

  ranges: any = {
    Today: [moment(), moment()],
    Yesterday: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
    'This Month': [moment().startOf('month'), moment().endOf('month')],
    'Last Month': [
      moment()
        .subtract(1, 'month')
        .startOf('month'),
      moment()
        .subtract(1, 'month')
        .endOf('month')
    ],
    'Last 3 Month': [
      moment()
        .subtract(3, 'month')
        .startOf('month'),
      moment()
        .subtract(1, 'month')
        .endOf('month')
    ]
  };

  isInvalidDate = (m: moment.Moment) =>  {
    return this.invalidDates.some(d => d.isSame(m, 'day') );
  }
  timezone: any;
  constructor(private spinner: NgxSpinnerService,
              private apiService: ApiService,) {
              this.datagrouped = [{"State":"CA","Under 5 Years":2704659,"5 to 13 Years":4499890,"14 to 17 Years":2159981,"18 to 24 Years":3853788,"25 to 44 Years":10604510,"45 to 64 Years":8819342,"65 Years and Over":4114496},{"State":"TX","Under 5 Years":2027307,"5 to 13 Years":3277946,"14 to 17 Years":1420518,"18 to 24 Years":2454721,"25 to 44 Years":7017731,"45 to 64 Years":5656528,"65 Years and Over":2472223},{"State":"NY","Under 5 Years":1208495,"5 to 13 Years":2141490,"14 to 17 Years":1058031,"18 to 24 Years":1999120,"25 to 44 Years":5355235,"45 to 64 Years":5120254,"65 Years and Over":2607672},{"State":"FL","Under 5 Years":1140516,"5 to 13 Years":1938695,"14 to 17 Years":925060,"18 to 24 Years":1607297,"25 to 44 Years":4782119,"45 to 64 Years":4746856,"65 Years and Over":3187797},{"State":"IL","Under 5 Years":894368,"5 to 13 Years":1558919,"14 to 17 Years":725973,"18 to 24 Years":1311479,"25 to 44 Years":3596343,"45 to 64 Years":3239173,"65 Years and Over":1575308},{"State":"PA","Under 5 Years":737462,"5 to 13 Years":1345341,"14 to 17 Years":679201,"18 to 24 Years":1203944,"25 to 44 Years":3157759,"45 to 64 Years":3414001,"65 Years and Over":1910571}];
              this.maxDate = moment().add(0,  'weeks');
              this.minDate = moment().subtract(3, 'days');
              this.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
              this.alwaysShowCalendars = true;
              this.keepCalendarOpeningWithRange = true;
              this.showRangeLabelOnInput = true;
              this.dateGrouped = new Date()
              this.selected = {startDate: moment().subtract(30, 'days'), endDate: moment()};
              setTimeout(() => {
                this.invalidDates = [moment().add(2, 'days'), moment().add(3, 'days'), moment().add(5, 'days')];
              }, 5000);
              var m = moment(this.selected.startDate);
                     m.set({hour:0,minute:0,second:0,millisecond:0})
             this.startDate = m.format('YYYY-MM-DD 00:00');
             this.endDate = moment(this.selected.endDate).format('YYYY-MM-DD 23:59');

               }
  rangeClicked(range) { }
  datesUpdated(range) {
    var m = moment(this.selected.startDate);
            m.set({hour:0,minute:0,second:0,millisecond:0})
    this.startDate = m.format('YYYY-MM-DD 00:00');
    this.endDate = moment(this.selected.endDate).format('YYYY-MM-DD 23:59');
    this.viaAirportAnalytics();
  }

  viaAirportAnalytics(){
    var statrdate = new Date(this.startDate).toISOString();
    var endDate = new Date(this.endDate).toISOString();

    this.spinner.show();
    this.apiService.getVenues().subscribe((res)=>{
      this.spinner.hide();
      this.venues = res.body.venues;
      this.selVenue = this.venues[0];

    for(let sel of this.venues){
      if(sel.name == this.selectedVenue) {
        this.selVenue = sel;
      }
    }
    let arg = {
      startDate:statrdate,
      endDate:endDate,
      venueId:this.selVenue._id
    }
    this.spinner.show();
    this.apiService.getItemAnalyticsItemCategory(arg).subscribe((res)=>{
      this.spinner.hide();
      let dataChart = [];
      res.chartData.map(data =>{
        dataChart.push(
          {gate:data.category, deliveries: data.count})
      })

      if(dataChart.length>0){
        this.showBarchart1 = true;
        this.data = dataChart;
      } else {
        this.showBarchart1 = false;
      }
    });

    this.spinner.show();
    this.apiService.getItemAnalyticsItems(arg).subscribe((res)=>{
      this.spinner.hide();
      let dataChart = [];
      res.chartData.map(data =>{
        dataChart.push(
          {gate:data.menuItem, deliveries: data.count})
      })

      if(dataChart.length>0){
        this.showBarchart2 = true;
        this.data2 = dataChart;
      } else {
        this.showBarchart2 = false;
      }
    });
    });

  }
  onDateSelect(event){
    var m = moment(event);
    m.set({hour:0,minute:0,second:0,millisecond:0})
    var r = moment(event);
    r.set({hour:23,minute:59,second:59,millisecond:59})
    this.startDate = m.format('YYYY-MM-DD 00:00');
    this.endDate = r.format('YYYY-MM-DD 23:59');
      }
  ngOnInit() { }

}

Spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { StoreAnalyticsComponent } from './store-analytics.component';
import { NbCardModule, NbDatepickerModule } from '@nebular/theme';
import { FormsModule } from '@angular/forms';
import { ChartModule } from 'angular2-chartjs';
import { NgxDaterangepickerMd, LocaleService } from 'ngx-daterangepicker-material';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { HttpClient, HttpHandler } from '@angular/common/http';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports:
      [
        NbCardModule,
        FormsModule,
        NbDatepickerModule,
        NgxDaterangepickerMd,
        ChartModule,

      ],
      providers:[
        HttpClient,
        HttpHandler,

      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],

      declarations: [ StoreAnalyticsComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(StoreAnalyticsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

Component 2
Component

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ApiService } from '../../../services/api.service';
import { NgxSpinnerService } from "ngx-spinner";

@Component({
  selector: 'ngx-order-confirmation',
  templateUrl: './order-confirmation.component.html',
  styleUrls: ['./order-confirmation.component.scss']
})
export class OrderConfirmationComponent implements OnInit {

  cartId:any;
  recipientDetails:any;
  subscriptionId:any;

  interval;
  timeLeft: number = 20;

  constructor(public router: Router,public ApiService: ApiService, private spinner: NgxSpinnerService) {
    this.spinner.show();
    this.recipientDetails  = JSON.parse(localStorage.getItem('recipientDetails')) || {};

    this.subscriptionDetail();
  }

  ngOnInit() {

  }

  subscriptionDetail(){
    this.ApiService.subscriptionDetails(this.recipientDetails.recipientAddressesId).subscribe((res)=>{
      if(res && res.body && res.body.subscriptionDetails && res.body.subscriptionDetails[0]){
        this.subscriptionId = res.body.subscriptionDetails[0].subscriptionId;
        this.spinner.hide();
      } else {
        setTimeout(()=>{
          this.subscriptionDetail();
        }, 2000);
      }
     });
  }
}

Spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { OrderConfirmationComponent } from './order-confirmation.component';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ OrderConfirmationComponent ],
      imports: [RouterTestingModule,HttpClientTestingModule],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(OrderConfirmationComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

Thanks.........................................................................................................................................................................................................................................................
Comment: You should try to import `NgxDaterangepickerMd` as root module in your Spec.ts file like `NgxDaterangepickerMd.forRoot()` under `imports` array of `TestBed.configureTestingModule`
Comment: check if that works
Answer: NgxDaterangepickerMd.forRoot() should provide all required services as well as LocaleService
TestBed.configureTestingModule({
  imports: [      [
    ...
    NgxDaterangepickerMd.forRoot(),

Comment: When i'm importing 'HttpHandler', i'm getting this error, `Uncaught TypeError: this.handler.handle is not a function thrown`, is there anything to config?
I have edited my question, and added my component also.
Comment: You should be importing `HttpClientTestingModule` in tests instead of providing `HttpClient` and `HttpHandler`
Comment: i couldn't find the module... could you please share what i have to import....? in angular 8...
Comment: `import { HttpClientTestingModule } from '@angular/common/http/testing';`
Comment: Hi @yurzui Hi have edited and added a another component...
In that component, `HttpClientTestingModule ` is imported, but still showing this error `Uncaught TypeError: this.handler.handle is not a function thrown`
Comment: Please update code of your StoreAnalyticsComponent test. I don't see you included `HttpClientTestingModule` in imports array and removed `HttpClient` and `HttpHandler` from providers array
Comment: Sorry brother..
it was the issue with some other components... i have replaced all the HttpClient, HttpHandler with HttpClientTestingModule... now it's working well....


Reducing a Least sqare with equality and inequality constraints problem.

Question: First, i know that there are a lot of topic about thoose kind of questions, but i thought about a reducing approach that i did not found in the litterature and i wander if the following steps are OK or if i'm making a horrible mistake.
Suppose you want to solve for $x \in \mathbb{R}^n$ the following problem :
$$ \min \frac{1}{2}x' A x - b'x$$
Under the constraints that $Ex = f$ and $Gx \ge h$, where $E$ and $G$ are matrices with $n$ columns and given number of rows $m_E,m_G$ such that $m_E < n$.
My thought are in 3 steps :
1. Treating the equality constraints first
Since $Ex = f$, we can say that $x$ belongs to an affine subspace which is parralel to the linear subspace given by the kernel of $E$. In my particular problem, this linear subspace has a dimension, say $d_{ker(E)}$, smaller than $n$.
Furthermore, I do known a particular solution, say $\lambda$, to $Ex=f$, which gives me the full specification of this affine space :
$$Ex = f \iff x \in S = \{x = \lambda + \sum\limits_{i=1}^{d_{Ker(E)}} y_i e_i, y \in \mathbb{R}^{d_{Ker(E}}\}$$
If we denote by $(e_i)$ a basis of $Ker(E)$.
2. Injecting it into the problem
Then, solving for $y$ under only the inquality constraint the folloiwng problem will be quivalent :
$$ \min \frac{1}{2}(\lambda + \sum\limits_{i=1}^{d_{Ker(E)}} y_i e_i)'A(\lambda + \sum\limits_{i=1}^{d_{Ker(E)}} y_i e_i) - b'(\lambda + \sum\limits_{i=1}^{d_{Ker(E)}} y_i e_i)$$
Which can be simplified by taking out all terms without $y$ to :
$$ \min \sum\limits_{i=1}^{d_{Ker(E)}} \frac{1}{2}(y_i e_i)'A(y_i e_i) + \lambda'A(y_i e_i) + (y_i e_i)'A\lambda - b'y_i e_i$$
3. Back to $x$
Doing this simple process, we reduced the dimension of the problem, and we supressed all equality constraints. The inquality constraints are of course adapted accordingly, and the basis of $Ker(E)$ can be use to get back $x$ from $y$. My question is then 2 parts :
Easy question : Is this simplification correct ?
Harder one : Is it usefull to pre-treat the problem like that before using a QP solver ?
PS : I'm not shure about the tags i used.. Feel free to change them.
Answer: Looks correct, and sometimes you have to do this if the solver doesn't support equalities.
I would typically not recommend you to do it though if you have a solver which supports equalities. You possibly hide structure in the problem, convert a sparse problem to a dense problem, or introduce numerical issues. The solver knows best how to deal with the equalities.
Comment: Thanks for your insight. I agree with you that my solver might be smarter than me ! On the other hand, the matrix $A$ was diagonal and stays so, and the matrix $G$ was sparse and became dense, while the inequality constraints vanished.

On a slightly related topic, do you think i could do something similar for the inequalities $Gx \ge h$ ?
Comment: No. [random text added to reach 12 letters]
Comment: Yeah i'm starting to think it's not doable. Thanks anyway.


How to Get Gnuplot to Read Input File with Hex Data

Question: I'm collecting data from a CAN bus viewer that saves it as a text file in a fixed column format, like this:
  4681)     24123.0  Rx         0488  8  79 00 DF 58 66 00 FF 00

I'd like to have gnuplot create a plot using column 2 for 'x' and the sum of columns 10 and 11 as the 'y' value, where column 10 is the LSB and column 11 is the MSB (so it needs to be multiplied by 256 first). Both columns 10 and 11 are in hexadecimal. The documentation I've read implies that a sprintf format can be used, but I'm not having any luck getting the correct syntax.
Comment: I guess you must use an external tool to do the conversion. In general one can use a format after the `using` statement like `plot 'data.dat' using 1:2 '%lf%lf'. Unfortunately, this format supports only `%lf` an no other (hexadecimal) specifiers.
Comment: Ok. You could also do this on-the-fly without intermediate file. If your python script reads from `sys.stdin` and writes to `sys.stdout` you could do `plot '< python myscript.py < data.dat' using 1:2`.
Comment: @Christoph And that's what I ended up doing. I wrote a short Python script to read the trace data file, do the conversions I needed, and create a new file with just the `x` and `y` data. And then it was just `plot 'data.dat' using 1:2`.
Answer: If I correctly understood that you have a text not binary file with hexadecimal numbers, this would be my suggestion. No need for external scripts, all can be done with gnuplot 4.6.0 (version at the time of OP's question). A few more data lines are added as well as labels on the plot to check the test result.
Data: SO24727223.dat
4681)     24123.0  Rx         0488  8  79 00 DF 58 66 00 FF 00
4681)     24124.0  Rx         0488  8  79 00 DF 58 00 01 FF 00
4681)     24125.0  Rx         0488  8  79 00 DF 58 01 02 FF 00
4681)     24126.0  Rx         0488  8  79 00 DF 58 FF 01 FF 00

Code: (works with gnuplot>=4.6.0)
### construct/plot hex numbers
reset

FILE = "SO24727223.dat"

HexToInt(col1,col2) = int("0x".strcol(col1).strcol(col2))
myLabel(col1,col2)  = sprintf("0x%s%s\n=%d",strcol(col1),strcol(col2),HexToInt(col1,col2))

set key noautotitle
set offsets 0.5,0.5,50,50

plot FILE u 2:(HexToInt(11,10)) w lp pt 7, \
       '' u 2:(HexToInt(11,10)):(myLabel(11,10)) w labels offset 1,-1
### end of code

Result:


Changing a variable from a different form on VB

Question: Iv'e been creating a game on VB for a school assignment and I am having trouble creating a difficulty setting. I have four buttons on my title screen in which you can choose a difficulty. when you click one of the buttons it's supposed to add to the "speed" variable on the main game. I've tried a few methods and it still doesn't seem to work.
Here's the code that I am using.
Main game variables:
Public speed As Single = 5
Dim xVel As Single = Math.Cos(speed) * speed
Dim yVel As Single = Math.Sin(speed) * speed

Title screen code (difficulty select):
Private Sub btnPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPlay.Click
    gameMain.Show()

    If btnEasy.Enabled = False Then
        gameMain.speed = 5
    End If

    If btnMedium.Enabled = False Then
        gameMain.speed = gameMain.speed + 2
    End If

    If btnHard.Enabled = False Then
        gameMain.speed = gameMain.speed + 5
    End If

    If btnInsane.Enabled = False Then
        gameMain.speed = gameMain.speed + 10
    End If

End Sub

So when you click a button it gets disabled and changes color. when you start the game, if one of the buttons is disabled its supposed to add the corresponding amount to the "speed" variable.
I've also tried putting similar code on the Main game form and that also didn't work.
I'm trying to keep the code as simple as possible as I am still an amateur at VB.
Any answers would be appreciated.
Comment: So what's happening right now? `gameMain.speed` is always set to 5?
Comment: Have you debugged through the code to see that it actually gets executed? Maybe `gameMain.Show()` takes execution away from the rest of your method. Try moving that to the last line and see if it helps.
Comment: it says there's no errors and putting it on the last line didn't work either.
Comment: Its a bit of a hack but can you move the speed variable into a global module, make it a global static variable and see if that works?
Comment: I've never used a global module before but i'll give it a try, thanks.
Comment: The module method worked, it works great now, thank you!
Comment: @NeilKennedy : Please post solution as an answer and ask the author to accept it, if it really helped. This would save the time of community who are looking for un-answered questions.
Answer: Your code only changes the "speed" field, it doesn't re-calculate the values for xVel and yVel.
You solve this problem by making speed a property instead of a field.  The property setter can adjust the velocity vector:
Private _speed As Single
Private xVel As Single
Private yVel As Single
Private angle As Single

Public Sub New()
    InitializeComponent()
    Speed = 5
End Sub

Public Property Speed() As Single
    Get
        Return _speed
    End Get
    Set(ByVal value As Single)
        _speed = value
        xVel = _speed * Math.Cos(angle)
        yVel = _speed * Math.Sin(angle)
    End Set
End Property

You'll need to work on angle next.
Comment: I fixed the problem by using a global module, but the point you made about the angle is interesting. I might look into it, thanks
Comment: Well, don't do that.  Global variables rarely ever solved a problem, they just add new ones.
Answer: As suggested by @AYK I'm posting my comment above as an answer so we can close out this question....
Its a bit of a hack but can you move the speed variable into a global module, make it a global static variable and see if that works?


Is there a way to make sure a function is overwritten?

Question: I have a class where I want to be able to run children of the class at various frequencies: either every minute or every second. I use an Enum to decide whether I want to be called every second, every minute, both, or neither. Here's an example:
from enum import Flag, auto
import time

class FREQUENCY(Flag):
    MINUTELY = auto()  # call every_minute
    SECONDLY = auto()  # call every_second

class Parent:
    def __init__(self, frequency):
        self.frequency = frequency

    def every_minute(self):
        raise NotImplementedError()

    def every_second(self):
        raise NotImplementedError()

class HighFrequencyIdea(Parent):
    def __init__(self):
        super().__init__(FREQUENCY.SECONDLY)  # oops!

    def every_minute(self):
        print("I expect to be called every minute but I put wrong frequency")

    def every_second(self):
        print("I am called every second")

if __name__ == "__main__":
    obj = HighFrequencyIdea()
    elapse = 0
    while True:
        time.sleep(1)
        elapse += 1
        if FREQUENCY.SECONDLY in obj.frequency:
            obj.every_second()
        if FREQUENCY.MINUTELY in obj.frequency and elapse % 60 == 0:
            obj.every_minute()

Is there a way to prevent children of the class Parent from implementing something that they haven't set the correct frequency for (in this case make some error for implementing every_minute despite having a frequency of FREQUENCY.SECONDLY -- either having a frequency of FREQUENCY.SECONDLY|FREQUENCY.minutely or implementing just every_second in HighFrequencyIdea would be acceptable but implementing every_minute while not having FREQUENCY.minutely is unacceptable).
Answer: That's a badly designed abstraction.
How about having single method named tick(...) that does whatever is supposed to be done along with a frequency() property?
Answer: You could add a property to the class called last_call_time that stores the time of the last call. Then when being called with the 1 minute caller, if the difference between current time and last_call_time isn't 60s or more you can pop an error.


Why do you require connection in the open mapping theorem and maximum modulus principle?

Question: I cannot understand why we require the connection in these two theorems (or at least I've been taught this way, and also in some books you have it).
The first states that every non-constant analytic function defined from an open and connected subset $U$ of $\mathbb{C}$ to $\mathbb{C}$ is open.
The second says that if the norm of an analytic function defined in an open and connected subset $U$ of the complex plane has a real maximum in a point internal to $U$, then the function is constant. I'll try to prove these two theorems without using connection (or maybe I use that without realising).
First, I want to prove that for every  analytic function $f$ defined in an open subset $U$ such that $f(z) \ne 0 \forall z \in U$ and $\forall n$ positive integers, there is an analytic function $g$ such that $f(z)=g(z)^{n}$.(Here the teacher supposed $U$ to be connected or maybe even simply connected, it isn't clear in my notes).
You just have to consider a primitive $F$ of $\frac{f'}{f}$ and than it is easy to verify that $e^{(F(z)-c)/n}$ for some constant $c$ works. The only thing here that I'm not sure about (and it's where I think the problem is) is that I don't know if I can consider that primitive $F$. I don't see why I shouldn't though, as $f$ is uniquely representable by a power series in balls contained in $U$, and so I should also be able to define a primitive of $f$ locally.
Ok, so let's try to prove the open mapping theorem
To prove that, you suppose $0 \in U$, consider an open ball $B$ contained in $U$ and require $f(0)=0$ (it shouldn't change anything, it's just translations). $f(z)=z^{k}g(z)$, where $k$ is the order of $f$, that is the minimum integer for which the coefficent of $z^k$ isn't 0. Then you have $g(z)$ an holomorpic function in $B$ such that $g(0) \ne 0$. By continuity, there is an open neighborhood  where $g$ is never 0. Using the result proven above, I can write $g(z)=(h(z))^{k}$, and so $f(z)=(zh(z))^k$. You can verify that $(zh)'(0) \ne 0$ and then using the inverse function theorem and the fact that $z \to z^k$ is an open mapping, you conclude.
The second theorem is now trivial, as for every point $a$ in the internal part of $U$ you can send an open neighborhood of $a$ in an open neighborhood of $f(a)$, and so  $f(a)$ cannot be a maximum.
I don't see why these proofs shouldn't work, or where I've used unconsiously the connection. thanks for the help.
Comment: You need a simply connected domain for every zero-free $f$ to be an $n^{\text{th}}$ power for all $n$. As for the necessity of connectedness, consider $U = D_1(-2) \cup D_1(2)$ and $f(z) = 0$ on $D_1(-2)$, $f(z) = 1$ on $D_1(2)$. Not constant, not open, $\lvert f\rvert$ has local maxima in the interior.
Comment: Consider the region consisting of two open disks or radius one, with centers far apart.  And the function =1 on one disk, =2 on the other disk.  Try to see what happens in your proof applied to this function.
Comment: @DanielFischer ok, but where does the proof given fail? I know I should consider a simply connected domain for the first result (and I don't see why, however), but since in the other proofs I work with balls, shouldn't it work? (Obviously it doesn't, you gave me a counterexample, but I don't see the error in teh proof)
Comment: This argument based on primitives fails because it is based on being able to draw a path between two points inside the domain. You can't do that in a disconnected domain. Thus the same proof tells you that such a function is constant *on each connected component* but not globally necessarily.
Answer:
and so I should also be able to define a primitive of $f$ locally.

Yes, locally. Every holomorphic function has local primitives. But we need a global primitive of $f'/f$, and the existence of global primitives for all holomorphic functions is equivalent to simple connectedness [of each connected component of the open set]. To get a global primitive, we must be able to choose the local primitives in such a way that any two local primitives agree on the intersection of their domains. If you look at $z \mapsto 1/z$ on $\mathbb{C}\setminus \{0\}$, and try to piece together local primitives on the unit circle, you will note that when you come around the circle, the local primitives differ by $2\pi i$. There is hence no global primitive.
Your argument for the open mapping theorem assumes that $f$ doesn't vanish identically on a neighbourhood of $0$. If $f(z) = 0$ for all $z$ with $\lvert z\rvert < \varepsilon$, then we cannot write $f(z) = z^kg(z)$ with $k \in \mathbb{N}$ and a non-vanishing $g$. The identity theorem asserts that a holomorphic $f\colon U \to \mathbb{C}$ vanishing on $\{ z : \lvert z\rvert < \varepsilon\}$ is identically zero on the connected component of $U$ containing $0$, but if $U$ has more than one connected component, such an $f$ need not be globally constant. If we consider only connected $U$, then being locally constant implies being globally constant, and the arguments work. For disconnected $U$, we don't have the local $\to$ global implication.
Comment: Why is the existence of a global primitive equivalent to simple connection? I try to guess: every differential form $\omega= f(z) dz$ with $f$ holomorphic is closed, and every closed form in a simple connected set is exact, so there is a holomorphic function $F$ such that $F'=f$. is this the reason or there's something else?
Comment: That's one half, simple connectedness implies the existence of global primitives. For the other half, if all $f\in \mathscr{O}(U)$ have a global primitive, then $\frac{1}{z-a}$ has a primitive on $U$ for every $a \in \mathbb{C}\setminus U$, and therefore $$n(\gamma,a) = \frac{1}{2\pi i}\int_{\gamma} \frac{1}{z-a}\,dz = 0$$ for all cycles $\gamma$ in $U$. But that is the definition of simple connectedness (well, _a_ definition, there are several equivalent ones).
Answer: When proving the Open Mapping Theorem, in order to use the Argument Principle, it's necessary to choose a certain disk with its center at some preimage of an open set's image point, ensuring careful selection of the radius of this disk to guarantee that there is only one preimage point within the disk. This fact relies on the property that the zeros of non-constant holomorphic functions on a connected open set do not accumulate.
As for why this property of zeros not accumulating needs to be on a domain, it's because we establish this property by demonstrating that the zero set, being both open and closed, combined with connectedness, leads to the proof.
And the Maximum Modulus Principle is a straightforward corollary of the Open Mapping Theorem, while the Local Maximum Principle requires the use of an additional Identity Theorem. The Identity Theorem also holds on connected open sets.


how to get traffic data using api

Question: Hi I am working on a project that needs traffic data
I am trying to use APIs like tomtom or HERE but i can't get it to work
All I want is to collect the traffic count (number of cars in each route) and stock it in pandas df
I tried this but it didn't give me traffic count
response = requests.get('https://api.tomtom.com/traffic/services/4/incidentDetails/s3/-35.871247%2C140.910645%2C-28.902397%2C153.566895/22/-1/json?key='+apiKey+'&projection=EPSG4326&originalPosition=true')
dict = json.loads(response.content)
print(dict)
keys = dict.keys()
values = dict.values()

I can use any other api instead of tomtom if it can provide data too
Comment: What is the error?
Comment: What is contained in `response.content`?
Comment: a bytes blob, most likely
Comment: whats the apiKey for?
Answer: Try this here code:
from json import dumps as to_json_func_from_the_json_module

from requests import get

key = 'tada!'
response = get(f'https://api.tomtom.com/traffic/services/4/incidentDetails/s3/-35.871247%2C140.910645%2C-28.902397%2C153.566895/22/-1/json?{key=!s}&projection=EPSG4326&originalPosition=true')
dct = response.json()

print(to_json_func_from_the_json_module(dct, indent=2, default=str))
print('N. (#) Keys:', len(dct))

It should work. Let me know if not.
Comment: the apikey is key that is provided by tomtom after sing in up it is used to connect to tomtom api
the code does not give any errors it just dosen't provide traffic count
here is the output
{'@id': '1682942440',
  'poi': [{'id': '0aab15fcf8096e2691de5f01aa5b06f8',
    'p': {'x': 140.8933447, 'y': -34.2666487},
    'op': {'x': 140.8933443, 'y': -34.2666511},
    'ic': 9,
    'ty': 0,
    'cs': 0,
    'd': 'roadworks',
    'sd': '2023-04-19T08:23:00Z',
    'f': 'Loxton Main Road (Sturt Highway)',
    't': 'West Settlement Road (Sturt Highway)',
    'l': 3788,
    'r': 'A20'},
Answer: Those services do not return number of cars.
Answer: To get the number of cars (samples) within a route, you can use either Traffic Stats API or O/D Analysis from TomTom. but you need a custom payment for it. you can have a free trial for only a month using the Move portal but it's pretty limited in terms of date range available and number of reports you can make. regarding HERE's, I explored that before and they don't provide the number of cars at all. if someone has a better experience using these services I hope they can add more on this.

how to get traffic data using api


How to short list same SSID in Android Wifi?

Question: I'm working in the android wifi Application. I created the wifi list from wifiManager.getScanResults(). Now I have problem with two same SSID. I want short the two same SSID in to one based on strongest signal strength. Please help me to solve this problem.
WifiReceiver.java(extends BroadcastReceiver) :
@Override
public void onReceive(final Context context, Intent intent) {

wifiSRList = wifiManager.getScanResults();

Collections.sort(wifiSRList, new Comparator<ScanResult>() {
        @Override
        public int compare(ScanResult lhs, ScanResult rhs) {
            return (lhs.level > rhs.level ? -1 : (lhs.level == rhs.level ? 0 : 1));
        }
    });
for (int i = 0; i < wifiSRList.size(); i++) {
    wifiListString[i] = (wifiSRList.get(i).SSID);
}

wifiListView.setAdapter(new ArrayAdapter<>(context, R.layout.custom_wifi_list, wifiListString));

}

Answer: wifiSRList is sorted so try to check if wifiListString contains your ssid and ignore duplicates.
String ssid="";
    for (int i = 0; i < wifiSRList.size(); i++) {
        ssid=wifiSRList.get(i).SSID;
        if(!wifiListString.contains(ssid)){
            wifiListString.add(ssid);
        }
    }

but first you need to parse your array wifiListString to List. Example:
Arrays.asList(wifiListString ).contains(ssid)


Racket : How do i print the mysql result in a HTML page

Question: I am trying print the values from the DB on the HTML page generated in APPLICATION.rkt
but this is what i see when i execute the code below
&createstring;&db-conn;SELECT * from students

Here is what I am trying to execute:

#lang racket
(require db)
(require web-server/servlet)
(provide/contract (start (request? . -> . response?)))

(define db-conn
      (virtual-connection
         (lambda () (mysql-connect   #:server "localhost"
                 #:port 8889
                 #:database "SOB"
                 #:user "root"
                 #:password "root"))))

(define (start request)
  (define (createstring id name sid)
    (string-append "id is " id "and name is " name "and sid is "  sid))
  (response/xexpr
   '(html
     (head (title "SOB"))
     (body
      ,@(map (h1) (map createstring (in-query db-conn "SELECT * from students"))))
     )))

(require web-server/servlet-env)
(serve/servlet start
               #:launch-browser? #f
               #:quit? #f
               #:listen-ip #f
               #:port 8080
               #:extra-files-paths
               (list (build-path "/Users/lalith/Documents/LALITH FILES/MDX/SOB/" "htmlfiles"))
               #:servlet-path
               "/servlets/APPLICATION.rkt")

Any suggestions as to what I'm doing wrnog?
Answer: There are a couple problems.
First, use quasiquote (or "backquote") instead of quote; otherwise you can't escape from it with ,@ (ie, unquote-splicing). In other words, change
'(html ___)

to
`(html ___)

Then, inside the ,@ escape, your maps are wrong, and map doesn't work with in-query anyway. You probably want something like this instead:
,@(for/list ([(id name sid)
              (in-query db-conn "SELECT id, name, sid from students")])
    `(h1 ,(createstring id name sid)))

Or something like that. (The code above would make a level-1 header for each row in the table, if that's what you want.)

Edited in response to comment: It looks like id is a numeric column in the database. If you have a recent version of Racket, I recommend using ~a, which is like string-append but automatically converts non-string values to strings first. Change the definition of createstring to this:
(define (createstring id name sid)
  (~a "id is " id "and name is " name "and sid is "  sid))

In older versions of Racket (before ~a), use format instead (see the docs for how).
Comment: Thanks a lot for your prompt and very useful reply..

the query is excuted now and getting the reply, but i get a 'contract violation' error message

Sorry am a begginner in Racket

string-append: contract violation
  expected: string?
  given: 1
  argument position: 2nd
  other arguments...:
   "id is "
   "and name is "
   "A"
   "and sid is "
   "B"


Ionic: Intercept PDF URLs with cordova-plugin-inappbrowser

Question: I am building an Android/iOS Application with ionic 3, which simply consists of a webview by cordova-plugin-inappbrowser (version 3.0.0) and a responsive homepage. The homepage holds different links to websites as well as to (online) PDF files.
As I've learned, the webview in Android (I haven't tried iOS, yet) does not support opening PDF files.
That's why I wanted to intercept the called URLs, and open them in some other way, if they end on '.pdf':
import { Component } from '@angular/core';
import {InAppBrowser, InAppBrowserObject, InAppBrowserOptions} from "@ionic-native/in-app-browser";

export class HomePage {

  options : InAppBrowserOptions = {
    location : 'no',//Or 'no'
    hidden : 'no', //Or  'yes'
    clearcache : 'yes',
    clearsessioncache : 'yes',
    zoom : 'no',//Android only ,shows browser zoom controls
    hardwareback : 'yes',
    mediaPlaybackRequiresUserAction : 'no',
    shouldPauseOnSuspend : 'no', //Android only
    closebuttoncaption : 'Close', //iOS only
    disallowoverscroll : 'no', //iOS only
    toolbar : 'no', //iOS only
    enableViewportScale : 'no', //iOS only
    allowInlineMediaPlayback : 'no',//iOS only
    presentationstyle : 'pagesheet',//iOS only
    fullscreen : 'yes'//Windows only
  };

  constructor(private inAppBrowser: InAppBrowser) {
    this.openWithCordovaBrowser('http://url.tohomepage.com');
  }

  public openWithCordovaBrowser(url : string){
    let target = "_self";
    this.browser = this.inAppBrowser.create(url,target,this.options);
    this.browser.on('loadstart').subscribe((event) => {
      if(event.url.endsWith('.pdf'))
      {
        //Open PDF in some other way
      }
    });
    this.browser.on('loadstop').subscribe((event) => {
    });
    this.browser.on('exit').subscribe((event) => {
    });
  }
}

My problem now is, that when an PDF-URL is called, none of the 3 events (loadstart, loadstop, loaderror) are fired. With an usual URL these events fire as expected.
Is there any other way I could intercept these calls? (The beforeload event does not exist in this version as far as I can see)
Thanks for any help/hints!

EDIT:
I installed the cordova-plugin-inappbrowser directly from the github master as suggested.
The 'beforeload' channel is implemented in the module as far as I can see.
But the 'beforeload' event is still not firing. ('loadstart' however is working for none-PDF URLs).
declare var cordova: any;
...

constructor() {
    var iabRef = cordova.InAppBrowser.open("http://someurl.com", "_blank", "beforeload=yes");

    iabRef.addEventListener('beforeload', function(params, callback){
      alert('Beforeload fired');

      // If the URL being loaded is a PDF
      if(params.url.match(".pdf")){
        // Open PDFs in system browser (instead of InAppBrowser)
        cordova.inAppBrowser.open(params.url, "_system");
      }else{
        // Invoke callback to load this URL in InAppBrowser
        callback(params.url);
      }
    });

    iabRef.addEventListener('loadstart', function(params, callback){
      alert('Loadstart fired');
    });
}

Answer: If you install cordova-plugin-inappbrowser directly from the Github master branch, there's an unreleased feature added by PR #276 which adds a beforeload event.
First install the plugin direct from master:
cordova plugin add https://github.com/apache/cordova-plugin-inappbrowser

Then use it something like this:
// Open InAppBrowser on initial page
var iabRef = cordova.InAppBrowser.open("http://www.someurl.com", "_blank", "beforeload=yes");

// Add beforeload event handler which is called before each new URL is loaded into the InAppBrowser Webview
iabRef.addEventListener('beforeload', function(params, callback){
    // If the URL being loaded is a PDF
    if(params.url.match(".pdf")){
        // Open PDFs in system browser (instead of InAppBrowser)
        cordova.InAppBrowser.open(params.url, "_system");
    }else{
        // Invoke callback to load this URL in InAppBrowser
        callback(params.url);
    }
});

Comment: The 'beforeload' event is still not firing, as opposed to 'loadstart'. I updated my question. Thank you for your help!
Comment: Turned out it still used the 'old' ionic native inAppBrowser plugin somehow. Resetting everything solved it and 'beforeload' is called now.
Now, opening a PDF file with `cordova.InAppBrowser.open(params.url, "_system");` works, but when I return to the original browser from the PDF, I cannot open any more links and the browser is stuck on the page. Any ideas?
Comment: not sure, it's not a scenario I've tested (opening PDF in system browser), but could be a bug in the new implementation. if it's reproducible in isolation, then [open an issue against cordova-plugin-inappbrowser](https://github.com/apache/cordova-plugin-inappbrowser/issues)
Comment: Problem here is that the current master version crashes on Android 7 or below
Comment: There is an issue on iOS with `beforeload=yes` when POST requests stop working. You can use `beforeload=get` to intercept GET requests only. Details can be found at
https://github.com/apache/cordova-plugin-inappbrowser/issues/779
Answer: So finally with some workarounds I made it work:
declare var cordova: any;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  private iabRef;

  constructor(private inAppBrowser: InAppBrowser, private platform: Platform, private spinnerDialog: SpinnerDialog, private file: File, private fileTransfer: FileTransfer, private fileOpener: FileOpener) {

    this.platform.ready().then(() => {
      if (this.platform.is('android')) {
        this.androidBrowser();
      } else {
        this.iosBrowser();
      }
    });
  }

  iosBrowser() {
    let browser = this.inAppBrowser.create("http://someurl.com", "_blank", "location=no,navigationbuttoncolor=#ffffff);
  }

  androidBrowser() {
    let that = this;

    this.iabRef = cordova.InAppBrowser.open("http://someurl.com", "_blank", "beforeload=yes,location=no");

    this.iabRef.addEventListener('beforeload', function(params, callback){
      // If the URL being loaded is a PDF
      if(params.url.match(".pdf")){
        that.openPDF(params.url);
      } else {
        callback(params.url);
      }
    }, false);

    this.iabRef.addEventListener('loadstart', function(params, callback){
      that.spinnerDialog.show(null, null, true);
    });

    this.iabRef.addEventListener('loadstop', function(params, callback){
      that.spinnerDialog.hide();
    });

    this.iabRef.addEventListener('exit', function(params, callback){
      that.platform.exitApp();
    });
  }

  openPDF(url: string) {
    let title = url.substring(
      url.lastIndexOf("/") + 1,
      url.lastIndexOf(".pdf")
    );

    let path =  this.file.dataDirectory;

    const transfer = this.fileTransfer.create();
    transfer.download(url, path + title + '.pdf').then(entry => {
      let url = entry.toURL();
      this.fileOpener.open(url, 'application/pdf');
    });
  }
}

After installing the Cordova plugin directly from the GitHub repository the 'beforeload' event is firing (although sometimes only after a second click on the pdf link, but I will have to live with that now).
At first I tried to open the PDF-URL with another cordova.InAppBrowser.open("http://someurl.com/pdffile.pdf", "_system");
That worked, but, as soon as I returned to my original inAppBrowser, the website was stuck. The buttons and links showed feedback that they were clicked, but the browser did not react anymore. Since I could not solve that issue, I am now downloading the pdf file and opening it with the FileOpener Plugin. When I now return to the app from the pdf, the browser is still working as before.
For iOS I could not get it running with the direct Cordova plugin as with android. So if the device is running iOS, I open it with the ionic native inAppBrowser plugin. The iOS Webview works just fine with pdfs, although there are no possibilities to download the displayed pdf, for which I couldn't find a solution yet.
Answer: You can use this way
downloadFile(url: string) {

    if (this.platform.is('ios')) {
      this.pdfFileOpen(url, this.file.syncedDataDirectory);
    } else {
      this.pdfFileOpen(url, this.file.dataDirectory);
    }

  }

  pdfFileOpen(url, fileDir) {

    const pdfFileName = url.split('/')[4]
    this.file.createDir(fileDir, 'FolderName', true)
    .then(resp => {

      const fileTransfer: FileTransferObject = this.transfer.create();
      fileTransfer.download(url, resp.toURL() + pdfFileName)
        .then(entry => {

          this.fileOpener.showOpenWithDialog(resp.toURL() + pdfFileName, 'application/pdf');

        });

      });
  }

Answer: In order to open pdf file in android in-app browser:
 openPdfFile(url) {
       if (url.match('.pdf')) {
            let urlLink = encodeURIComponent(url)
            this.inAppBrowser.create('https://docs.google.com/viewer
            url=' +urlLink);
       }
  }


derivative logical meaning basic question

Question: The question is about the logical meaning of $\frac{df(x-1)}{dx}$, I did a single transform, which is $\frac{df(x-1)}{dx} = \frac{df(x-1)}{d(x-1)} * \frac{d(x-1)}{dx}$, since latter part $\frac{d(x-1)}{dx}$ is $1$, so $\frac{df(x-1)}{dx} = \frac{df(x-1)}{d(x-1)} = \frac{df(x)}{d(x)}$?
To me it seems $\frac{df(x-1)}{dx}$ is not the same as $\frac{df(x)}{d(x)}$? If anyone could explain the logical meaning of $\frac{df(x-1)}{dx}$ and how it equals to $\frac{df(x)}{d(x)}$, it will be great. :)
BTW, similarly, I can also get $\frac{df(1-x)}{dx}$ is $-\frac{df(x)}{dx}$
Please any steps is not correct, please feel free to correct me.
thanks in advance,
Lin
Comment: I think you have misapplied the chain rule in the first step. You should have $\frac{df(x-1)}{dx} = \frac{df}{d(x-1)} * \frac{d(x-1)}{dx}$
Comment: Thanks @BernardWojcik, vote up, I think your formula is the same as mine, what is the differences? I see there is an additional sign of `-`?
Answer: Let's look at the chain rule using a different notation, since I suspect that's what's tripping you up. It says that $$(f\circ u)'(a) = f'(u(a))\,u'(a).$$ Note that the derivative of $f$ is taken at $u(a)$. This is an important detail that in my opinion the Leibnitz notation obscures. (You can find a similar, but probably better-presented, explanation of the chain rule in this answer.)
In your case, we have $u:\xi\mapsto \xi+1$, so $(f\circ u)'(x) = f'(x+1)\cdot1 = f'(x+1)$. This makes intuitive sense: $f\circ u$ is just $f$ shifted to the left by one unit, so one would expect $(f\circ u)'$ to be $f'$ shifted left by one as well.
Using Leibnitz notation, you started off well enough, but appear to have lost the fact that the derivative of $f$ must be taken at $x+1$. Keeping explicit track of where the derivatives are evaluated, we have $${df(\xi+1)\over d\xi}\Big|_{\xi=x} = {df(\xi+1)\over d(\xi+1)}\Big|_{\xi=x}{d(\xi+1)\over d\xi}\Big|_{\xi=x} = {df(\eta)\over d\eta}\Big|_{\eta=x+1}\cdot1\Big|_{\xi=1} = {df(\eta)\over d\eta}\Big|_{\eta=x+1}.$$ I've introduced some new variables to distinguish what are effectively dummy variables from the points at which the derivatives are evaluated. This is more or less te derivation you had, except that derivative of $f$ is evaluated at $x+1$ instead of at $x$. A similar derivation gives $${df(1-\xi)\over d\xi}\Big|_{\xi=x} = -{df(\eta)\over d\eta}\Big|_{\eta=1-x}$$ which is again what you had except evaluated at $1-x$.
As a concrete example, take $u:(\cdot)\mapsto(\cdot)+1$ again and let $f:(\cdot)\mapsto (\cdot)^3-2(\cdot)+1$. (Here I'm using $(\cdot)$ to stand for the function parameter so that there's no chance of confusing it with the variables in the arguments to the functions.) The derivative of $f$ at any point is given by $f':(\cdot)\mapsto 3(\cdot)^2-2$ and the chain rule essentially tells us that we can find $(f\circ u)'(x)$ by plugging $u(x)=x+1$ into $f'$ (and multiplying by $u'(x)$, which is $1$ here). Doing so gives us $3(x+1)^2-2 = 3x^2+6x+1$. We check this by expanding $f(x+1)$ and differentiating the result: $$f(x+1)=(x+1)^3-2(x+1)+1=x^3+3x^2+x$$ and differentiating this yields $3x^2+6x+1$ again.
Comment: The $\circ$ stands for function composition: $f\circ u$ is the function defined by $f\circ u: \xi\mapsto f(u(\xi))$. The notation $(f\circ u)(x)$ means "evaluate $f\circ u$ at $x$." Similarly, $(f\circ u)'(x)$ means "evaluate the derivative of $f\circ u$ at $x$."
Comment: @LinMa The problem lies in the last step, when you substituted $x$ for $x+1$ in the derivative. That part itself is fine, but when you do that you have to remember to evaluate it at $x+1$.
Comment: @LinMa Yes, that would be a good idea.
Comment: Thanks amd, vote up for your reply. What is the meaning of sign $\circ$ in $f \circ u$? Also lost in your formula $(f \circ u)' (x)$ means  $(f \circ u)' * (x)$
Comment: Thanks amd, vote up for your reply. Studied and learned a lot in your reply, and last question is, what is wrong in my original post (I mean if any steps I posted in original post is not correct in your mind)? :)
Comment: Thanks amd, vote up for your comments. Do I should name $x+1$ or $x-1$ as another variable to reduce confusion, for example, $t=x+1$ and $s=x-1$? Then represent it as $\frac{df(t)}{dt}$ and $\frac{df(s)}{ds}$, correct? Thanks.
Comment: Thanks amd, mark your reply as answer. Sorry for the late response. Enjoy remaining time of weekend. :)


Association class in NHibernate

Question: i want to map two classes m:n associated using NHibernate. NH would map a simple m:n association in a link table with foreign key constraints to the entity tables. Now I want to attach more attributes to the association as seen on this example:
image link broken; image removed
(and I want NHibernate to store these attributes in the link table)
image link broken; image removed
This UML diagram shows how you would "resolve" the association class for programming. Up to now, I did this myself and coded 3 classes Person, Book and PersonBookLink with PersonBookLink having the returnDate attribute. NHibernate is fine with the mapping, but I'm looking for a less complex way to navigate through this model.
How would you do the mapping in NHibernate?
Answer: There isn't a less complex way. A many-to-many relationship with extra attributes is mapped as two one-to-many relationships. You will have to decide which one side manages the relationship and set the inverse attribute in your mapping on the other one side so that NHibernate doesn't try to insert the link record twice.
I would model this as Person, Book, and Lending and let Person control the relationship (Person borrows Book).
PS - I would also use this project as an opportunity to write a Librarian class with a Shhhh(IEnumerable<Person> patrons) method.
Comment: Also known as an "objectified relationship."

Association class in NHibernate


When connect server xmpp has error

Question: Has anyone used androidpn? When I connect server, xmpp has this error:
<code>02-27 21:24:34.720: D/RegisterTask.PacketListener(3144): packet=<iq id="8dMsj-0" from="kwant.cn" type="error"><query xmlns="jabber:iq:register"><password>abc</password><username>abc</username></query><error code="400" type="MODIFY"><bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/></error></iq>
02-27 21:24:34.720: E/Androidpn_XmppManager(3144): Unknown error while registering XMPP account! bad-request
</code>
It hints: XMPP connected successfully. But it can not login in all the time. I do not know why.
Comment: You get a XMPP error 'bad-request' back from the server. It's hard to tell what's going on here without seeing at least every XMPP stanza involved in the login process.
Answer: I use the following code for connecting and sign-in using Smack API in Android and it runs like a charm:
<code>        private XMPPClient xmppClient;
        private XMPPConnection connection;
        private ArrayList<String> messages = new ArrayList();

public void login(String userName, String password) throws XMPPException
            {
            ConnectionConfiguration config = new ConnectionConfiguration("HOST",PORT, "SERVICE");
            connection = new XMPPConnection(config);
            connection.connect();

            //LOGIN USING THE FOLLWING login()

            connection.login(userName, password);
            xmppClient.setConnection(connection);
            }
</code>

When connect server xmpp has error


Delete from database from php

Question: I am about to make a function so the person i am making a homepage for is able to delete products from a database.
I want it to  be in a select and i have got the products into it.
But now i need to make the products remove from the database when i check a product in the select list.

<form action="adminremove1.php" method="post">

Products

        <select name="product">

<?php
          include 'include/inc.connect.php';
          $query = "SELECT name FROM products";
          $result =$tilslut->query($query);
          while($out=$result->fetch_assoc()) {
          printf ("<option value='%s'>%s</option>\n", $out['name'], $out['name']);

    }
?>
 </select>
<input type="submit" name="submit" value="Fjern produkt">
</form>

How can i make it delete the products? :-)
I hope you can help me!
thanks!
Comment: After submitting the form, run a `DELETE FROM products WHERE name = ` query. Make sure you use prepared statements on that one, as it contains user-input.
Comment: I would query for ID and name. Use the name in the list to show, use the ID as value for the option. Then in adminremove1.php, check for the selected, as mentioned above, and do a delete for the ID.
Comment: OK. So im really new to this. :D

I've tried the
$query = "DELETE FROM produkter WHERE navn = ";
But it doesn't remove it from my database.. What am i doing wrong?
Comment: @NataschaHedegaard Because the `` is a placeholder for a variable or a value, a demonstration only. It's not a correct syntax. You need to use `$_POST['product']`, but like I said, use prepared statements on that, which would make the query `DELETE FROM products WHERE name = ?` in `prepare()`, then use `bind_param()` and `execute()`. See the PHP manual for those `mysqli_*` functions.
Answer: firstly you please use the product_id in select options values then on the basis of that you can run the delete query on post page of form adminremove1.php
if yoy have unique id for each prodcut then you can use that also
Now if you want to delete multiple products at a time then select tag will be like this
<select name="products[]" multiple>
<?php
          include 'include/inc.connect.php';
          $query = "SELECT product_id, name FROM products";
          $result =$tilslut->query($query);
          while($out=$result->fetch_assoc()) {
          printf ("<option value='%s'>%s</option>\n", $out['product_id'], $out['name']);

    }
?>
</select>

And in adminremove1.php file you can get value
$product_ids =implode(',',$_POST['products']);

 $query = "DELETE FROM products where product_id in ($product_ids)";

Comment: Thanks. But how should the delete sentence be after all this? That is my biggest problem. It wont delete from the database..
Comment: $query = "DELETE FROM products where product_id in ($product_ids)";
Comment: If i want to have it so the one who should delete the product can see the product_id also in the select box, how then? :-)
Comment: Right now i can only see the name from the database in the selectbox. Is it possible to get like "16 - Apple" in the select box - the id + the name :)
Comment: yes you have to change the select quey in  $query = "SELECT product_id, name FROM products";

Delete from database from php


Qt doesn't load any database drivers

Question: I'm porting my project from qt4.8.4 on windows server 2003(32bit) to qt5.3.1 on win7(64bit), I build qt source statically, and build qsqlmysql dynamically, but my code can not load mysql qt driver. The error is like follows,
QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers:()

My code is as follows,
db = QSqlDatabase::addDatabase("QMYSQL", "*****");
db.setHostName("*****");
db.setDatabaseName("*****");
db.setUserName("*****");
db.setPassword("*****");

When I search "QMYSQL" in registry, I get nothing, it seems qmysql driver is not registered.
Any ideas?
Answer: A default configuration will only give you sqlite support, maybe ODBC will be auto-detected on windows. You will need to specify sql support and possibly provide libs and include paths too. For example (using mardiadbclient for mysql):
Pre Qt 5.8:

-qt-sql-mysql -L E:\msys64\mingw64\lib -l mysqlclient -I E:\msys64\mingw64\include\mariadb

Post Qt 5.8:

-sql-mysql MYSQL_INCDIR=E:\msys64\mingw64\include\mariadb MYSQL_LIBDIR=E:\msys64\mingw64\lib MYSQL_LIBS="-l mysqlclient" -L
  E:\msys64\mingw64\lib
Comment: I build qt source with the following optioin:-qt-sql-sqlite -qt-sql-odbc -plugin-sql-sqlite -plugin-sql-odbc at first, then I build qt-mysql driver separately..
Comment: Which qt version?
Answer: in qt4.8.4, when you link qsqlmysql statically, you should write:
    Q_IMPORT_PLUGIN(qsqlmysql)
but in qt5.3.1, the name changed, you should write the macro as following:
    Q_IMPORT_PLUGIN(QMYSQLDriverPlugin)
That's why i always get a unresolved external... error. After change the name, i can link mysql successfully.

Qt doesn't load any database drivers


Storing and downloading files from Redis in Django Celery Queue

Question: I'm zipping a large number of files in my app, which leads to problems with performance. So now I've decided to zip files in a separate queue, store results in Redis and make available to user as soon as the process is done. I'm storing data in Redis to make it faster, and because I don't need files to be stored on server hard drive.
Here is my task.py:
@shared_task
def zip_files(filenames, key):
  compression = zipfile.ZIP_STORED
  s = BytesIO()
  zf = zipfile.ZipFile(s, mode="w")
  for fpath in filenames:
      fdir, fname = os.path.split(fpath)
      zf.write(fpath, fname, compress_type=compression)
  zf.close()
  caches['redis'].set(hash_key, {'file':s.getvalue()})
  return hash_key

And then here is my simple download view:
def folder_cache(request, folder_hash):
   cache_data = caches['redis'].get(folder_hash)
   if cache_data:
      response = FileResponse(cache_data['file'], content_type="application/x-zip-compressed")
      response['Content-Disposition'] = 'attachment; filename=hello.zip'
      response['Content-Length'] = len(cache_data['file'])
      return response
  return HttpResponse("Cache expired.")

Problem is that I can only download a part of the file, then the download is stopped by "Network connection was lost" message. The downloaded file seems to contain a set of numbers (not binary data). But I don't know, maybe I use FileResponse wrong? Or I need to serialize data before / after putting it to Redis cache?
I also tried same code in shell, it works when I use fopen and write data from Redis cache directly to server hard drive.
Answer: Finally, I found out that I only had to wrap file data into ContentFile class. So here is the latest working code:
def folder_cache(request, folder_hash):
    cache_data = caches['redis'].get(folder_hash)
    if cache_data:
        if (cache_data['status'] == 'complete'):
            ...
            response = FileResponse(ContentFile(cache_data['file']), content_type="application/x-zip-compressed")
            response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
            response['Content-Length'] = len(cache_data['file'])
            return response


How to link all pages & exclude current page in PHP

Question: I currently have some PHP working exactly as I want it to (generating a list of all pages with the same page template).
<?php $pages = get_pages(
    array('meta_key' => '_wp_page_template','meta_value' => 'template.php'));
    foreach($pages as $page){
        echo "
$page->post_title
";
    }
?>

But now I want to do two things.
First - I want each p tag to also have an href, linking to the corresponding page.
Second - I want to exclude the page I am on from being on the list (otherwise it will be linking to the page the viewer is already on, making it repetitive).
Thank you very much in advance!
Comment: `p` elements don't have a `href` attribute. You want an `a` element inside of your paragraph. _"I want to exclude the page I am on from being on the list"_ - then go research how you find out the ID of the page you are currently on, and then simply exclude it from being output via a simple if-condition around the output in your loop …
Answer: You can utilise the WP_Query class to perform a targeted lookup of almost anything in Wordpress.
In this case, we filter with the post__not_in and the _wp_page_template meta lookup, before doing the "pages loop". Remember to call wp_reset_postdata() at the end of the loop to make it so that the various (get_)the_* functions return data for the current page again:
$query = new WP_Query(array(
    'post_type' => 'page',
    'post_status' => array('publish', 'future'),
    'post__not_in' => array(
        get_the_ID()
    ),
    'meta_query' => array(
        'relation' => 'and',
        array(
            'key' => '_wp_page_template',
            'value' => 'template.php',
            'compare' => '='
        )
    )
));

if($query->have_posts()) {
    while($query->have_posts()) {
        $query->the_post();

        echo '
' . get_the_title() . '
';
    }

    wp_reset_postdata();
}

Comment: Thank you so much!


How to update progress bar max with changing values automatically?

Question: I am working on a fitness app using Google fit API.
Step data from the API is passed to a method stepDisplayer with e.g. params (3300, "steps").
I am trying to update the progress bar once value == daily1 so that the max of bar is then pbStepBar.setMax(daily2) and again to pbStepBar.setMax(daily3) when value == daily2, while the progress of the bar is always set to value e.g. 3500/4000 then 4102/8000 and 8900/12000.
I tried to use a switch statement comparing the goals to value with a method called setNextGoal(value) with getter and setter methods getCurrentGoal() and setCurrentGoal() as seen below, but that did not work. Max value does not change from daily1 when I run the application and it looks something like this 5050/4000.
What am I doing wrong? Can I replace pbStepBar with another progress bar and and switching visibility?
Layout
<ProgressBar
        android:id="@+id/pbStepBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="300dp"
        android:layout_height="15dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="25dp"
        android:indeterminate="false"
        android:scaleY="3"
        />

public class MainActivity {

//these are goals
int daily1 = 4000
int daily2 = 8000
int daily3 = 12000

//set to this onCreate
pbStepBar.setMax = daily1

private void stepDisplayer(final int value, final String field) {
    tvHomeSteps = (TextView) findViewById(R.id.tvHomeSteps);
    pbStepBar = (ProgressBar) findViewById(R.id.pbStepBar);
    setNextGoal(value);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            tvHomeSteps.setText("today's " + field + " " + value + "/" + dailyStepGoal);
        }
    });

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (value <= getCurrentGoal()) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        pbStepBar.setProgress(value);
                    }
                });
                try {
                    Thread.sleep(25);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (getCurrentGoal() == value) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "Well done you reached your daily goal of " + getCurrentGoal() + " " + field,
                                    Toast.LENGTH_LONG).show();

                        }
                    });
                }

                setNextGoal(value);
            }
        }
    }).start();
}

private void setNextGoal (final int value) {
    switch (value) {

        case dailyStepGoal:
            setCurrentGoal(dailyStepGoal + stepGoalIncrement);
            pbStepBar.setMax(dailyStepGoal + stepGoalIncrement);
            break;

        case dailyStepGoal + stepGoalIncrement:
            setCurrentGoal(dailyStepGoal + (stepGoalIncrement*2));
            pbStepBar.setMax(dailyStepGoal + (stepGoalIncrement*2));
            break;

        case dailyStepGoal + (stepGoalIncrement*2):
            setCurrentGoal(dailyStepGoal + (stepGoalIncrement*3));
            pbStepBar.setMax(dailyStepGoal + (stepGoalIncrement*3));
            break;

        case dailyStepGoal + (stepGoalIncrement*3):
            setCurrentGoal(dailyStepGoal + (stepGoalIncrement*4));
            pbStepBar.setMax(dailyStepGoal + (stepGoalIncrement*4));
            break;

        case dailyStepGoal + (stepGoalIncrement*4):
            setCurrentGoal(dailyStepGoal + (stepGoalIncrement*5));
            pbStepBar.setMax(dailyStepGoal + (stepGoalIncrement*5));
            break;
    }
}

Answer: I found the solution.
I used an int variable currentGoal as seen below to keep track of the current goal. I think the problem was that I was trying to call methods in the activity from the UI thread. I used a simple if statement, don't know why I didn't think of this earlier.
I also tested the solution it works well.
private void stepDisplayer(final int value, final String field) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (value >= currentGoal) {
                Toast.makeText(getApplicationContext(), "Well done you reached your daily goal of " + currentGoal + " " + field,
                        Toast.LENGTH_LONG).show();
                currentGoal += stepGoalIncrement;
                tvHomeSteps.setText("today's " + field + " " + value + "/" + currentGoal);
            }
            else {
                tvHomeSteps.setText("today's " + field + " " + value + "/" + currentGoal);
            }
        }
    });

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (value <= currentGoal) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        pbStepBar.setProgress(value);

                        if (value >= pbStepBar.getMax()) {
                            pbStepBar.setMax(currentGoal);
                            pbStepBar.setProgress(value);
                        }
                        else {
                            pbStepBar.setProgress(value);
                        }
                    }
                });
                try {
                    Thread.sleep(25);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //setNextGoal(pbStepBar, value);
            }
        }
    }).start();
}


Turn off sorting of modified files in Project Explorer in Eclipse

Question: Eclipse's Project Explorer tries to be smart and sort modified files at the beginning of the folder. This is extremely annoying for large projects with tens or hundreds of files. Anyone knows a way to turn this feature off?
Comment: I guess it is one of these extensions. Could you uncheck them one by one to find which is responsible for the sorting?
Comment: The sorting in plain Eclipse Oxygen's  _Project Explorer_ is primary folder before files and secondary alphabetical. Which version do you use and which plug-ins do you have installed?
Comment: I am using Eclipse for Parallel Application Developers which has EGit plugin. Perhaps it's commit from the plugin...
Comment: In the view menu of the _Project Explorer_ choose _Filters and Customization..._: Which extensions to show are selected in the _Content_ tab?
Comment: @howlger checked: Synchronize Elements (twice), Working sets, Fortran Elements, Build Targets, C/C++ Elements, TMF Elements, Resources.  unchecked: Nexted projects
Comment: you were right, i turned off **both** `Synchronize Elements` and the sorting goes away! Thank you!
Comment: Great, I added it as answer.
Answer: In the Project Explorer the default sorting/ordering is primary folder before files and secondary alphabetical. Obviously, the chronological sorting comes from an Project Explorer extension. To disable the unwanted Project Explorer extension do the following:

In Project Explorer's view menu choose Filters and Customization...
In the Content tab of the Filters and Customization dialog uncheck unwanted extensions to show, in your case probably Synchronize Elements
Comment: Running Eclipse Version: 2023-12 (4.30.0). This solution doesn't work any more. "Synchronize Elements" no longer under "Content".
Any other solution?
Comment: @BernieP In the Eclipse IDE for Java Developers there was never "Synchronize Elements". In this specific case here , "Synchronize Elements" was from a plugin that the questioner installed. If you don't have "Synchronize elements", that's a different issue for which you please better ask a separate question with more information (what additional plugins do you have installed; a screenshot of what you see with a description of what you expect instead; etc.).


Posts not displaying properly after if else loop put in

Question: 2 problems:
1) the Recent Posts function in my view file (for the single post page) no longer shows posts.
2) On the articles page which shows all of the posts, the posts with no slug do not work. when I click on the post, it redirects to /articles. Only posts with a slug work.
I have 2 kinds of URLs for my posts: slug and url.  The difference?  URL is longer.  Slug is shorter and used for SEO purposes.  Why not use just slug?  Because for some posts, I don't want to waste time creating a slug.  The data in the slug column for those posts is blank/empty.  The generated url is fine.  For other posts, I want a slug made.
Here is my controller code for posts.
Old version:
public function viewpost($url,$slug){
if ( empty($slug) ) {
$url ='articles/'.$url;
}  else {
$url = 'articles/'.$slug;

}

$posts = posts::where('post_status', '')->get();
if ( empty($slug) ) {
$post = $posts->where('url', $url)->first();
}  else {
$post = $posts->where('slug', $slug)->first();
}

if ( empty($post) )
return redirect()->back();

return view('viewpost')->with('post', $post)->with('posts', $posts);
}

New version (modified):
public function viewpost($url){

  $posts = posts::where('post_status', '');
  $post = $posts->where('url', $url)->orWhere('slug' , $url)->first();

  if ( empty($post) )
return redirect()->back();

return view('viewpost')->with('post', $post)->with('posts', $posts);
}

The new modified controller file broke the posts without a slug.
Here is the view file for the Recent Posts which broke:

Recent Posts

 @foreach($posts as $post)

url) }}">thumbnail)}}" class="responsive">

     url) }}">{{substr(($post->title),0,88)}}..

  @endforeach

My Routes code:
Route::get('articles/{url}', 'postsController@viewpost');

My view file code for the posts page which displays all the posts:
                    @foreach($post as $post)

                        @if(!empty($post->slug))
                            dd(11);
                        slug}}" class="latest-heading">{{substr(($post->title),0,88)}}..

                        @else
                        dd(22);
                        url)}}" class="latest-heading">{{substr(($post->title),0,88)}}..
                        @endif
                            thumbnail)}}" class="img-responsive">

                   @endforeach

Comment: This is somethink odd `@foreach($post as $post)`
Comment: @C2486 - "There is somethink off" doesn't really offer a solution.
Comment: Did you tried woth like `@foreach($post as $p)`
Comment: $p isn't even mentioned or defined in the code.
Answer:
1) the Recent Posts function in my view file (for the single post page) no longer shows posts.

That's because unlike your old code, you're not retrieving the data:
$posts = posts::where('post_status', '');

This will only return your query Builder object, so to get those posts, you need to add ->get(); to get the collection, so the code becomes:
$posts = posts::where('post_status', '')->get();

After that you can filter the one post your looking for via (->first()), by filtring the collection, as it doesn't support the orWhere method (or just use two where() as you did in the old code):
$post = $posts->filter(function($object, $key) use ($url) {
     return !strcmp($object->url, 'articles/'.$url) or !strcmp($object->slug, $url);
})->first();

Also correct that:
@foreach($post as $post)

2) On the articles page which shows all of the posts, the posts with no slug do not work. when I click on the post, it redirects to /articles. Only posts with a slug work.

I'm not sure but what i saw in your code, and basing on the old method you showed above, I think you have a problem here:
slug}}" ...
url)}}" ...

doesn't the second one needs also to be (?):
url}}" ...

Comment: For #2, the two a hrefs code are different because of how it is setup in the database.  The slug is inputted into the database as "custom-post-name".  A url is inputted into the database as "articles/generated-url-here".  A post will only display if "articles/" is in the URL.
Comment: The Recent Post section works now.  But on my articles page (https://collegeconnect.ph/articles), if you click on the second article on the top row (it is uses a url, no slug), you get redirected back to the article page not to the post itself.  Click on the first article (it uses a slug) and you get directed to the post.
Comment: If the Url is insert into DB as "articles/generated-url-here", the the query you've set will never found it. Then you should add 'articles' string to the url got from the request. Cause according to what you say, the code above will look for "generated-url-here" instead of "articles/generated-url-here", I'll edit the filter part of the answer to show you
Comment: Now the problem is that the URL for the post using the slug is different under Recent Posts.  Go to https://collegeconnect.ph/articles, click on the first post in the first row, then look at the URL of that same post in the Recent Posts section.
Comment: That's because in this section you're using the $post->url instead of the slug
Comment: Yep, I just put in the same if else loop and it worked.  Thanks for your help!
Answer: This is probably the causing factor:
return view('viewpost')->with('post', $post)->with('posts', $posts);

and your loop is doing:
@foreach($posts as $post)

and your other loop is doing:
@foreach($post as $post)

If you look at your with you are passing both post and posts, as a result it is probably mixing the looped variable with the with variable.
Try and change the keys of the variables in the with to something more distinct. You could add an _ before the single $post variable.
Comment: There was no problem with the views code before.  It only broke when the code in the controller file was modified.


Hot water is potable?

Question: I have some vague, probably erroneous memory of seeing some hot water fixture that said it wasn't meant for potable water, which made me believe that residential hot water in the USA may have different standards than cold. It might've been something related to the hot water heater. I know things like garden hoses and spigots do NOT meet the same standards for potable water and often have labels that make it clear.
Anyway, does hot water plumbing meet the same standards as cold water?
There may be other reasons why you don't want to drink hot water (eg, it might leach more easily), but I'm just curious about the standard practices in the USA.
Answer: Residential hot water in the USA is potable.
Source: (CIC) National Standard Plumbing Code 10.1 QUALITY OF WATER SUPPLY
a. Only potable water shall be supplied to plumbing fixtures used for drinking, bathing, culinary use, laundry use, cleaning, or the processing of food, medical, or pharmaceutical products
Comment: However, hot water is more likely to pick up traces of chemicals, including lead from soldered pipes. It's a minor issue, but general advice is to prefer cold water for consumption, or to let the water run a little while to flush the pipes first. That last may be worth considering for cold water too, actually.
Comment: If you have old pipes and/or lead solder, a test kit would tell you if you need to run a bit of water before running water for consumption. Applies to both hot and cold.
Answer: Some oddball facilities, such as freeway rest areas in remote and challenging locations, have water sourced in equally oddball ways.  It may not be unsafe to clean with, but they don't want you drinking it.

A recently emerging issue is growth of legionella and other bacteria and exhaustion of chlorine in hot water tanks.
The workaround is to raise tanked heater temperature to a rather hot temperature.  Which in turn means it's no longer safe to have old fashioned shower valves, and everything is going to either hotel style valves, or tankless heaters.
I know our old water heater had no chance of getting that hot, as I kept it max'd for longer showers.   I'm sure there was a transitional time where the requirement was known but the heaters on the market were incapable of it (or incapable and still hit their mandated efficiency ratings).  During such a time I could see such stickers.
Comment: The solution is a thermostatic mixing valve on the output of the water heater. This way the tank can be at 140-160F but the water leaving can be at no more than 120F. These same valves are also used for anti-scald protection.
Comment: @DanD. -- the solution is indeed a thermostatic mixing valve, but it goes at the bathroom, if not at individual fixtures (otherwise, you're making your dishwasher work harder for no good reason, *and* risking Legionella growth in infrequently used hot water pipework)

Hot water is potable?


Sql query for selecting the first 3 characters

Question: I am trying to select the records from 2 tables in which the 1st table column named DESC (first 3 characters) should match with the project column of the 2nd table.
select SUBSTRING(a.[DESC],1,3) from Table1 a
left outer join Table2 b
on a.[DESC] = b.project
where SUBSTRING(a.[DESC],1,3) like b.project

Input:
1st Table DESC Column:
Value: '2AB F YY'
2nd Table Project Column:
Value: '2AB'
Expected Output:
Return all the records of value 2AB
Comment: Not sure why somebody downvoted this. The question is clear and for somebody new to t-sql this might be easy to research or figure out. They posted all the information need to provide an answer.
Comment: Input and expected output please ?
Comment: If at all possible you should consider fixing your data model. You seem to be storing multiple pieces of data in TableA. The project and a bunch of other stuff. This violates 1NF when you shove multiple data points together like that. And it forces your queries to be nonSARGable. Even a persisted computed column would be better.
Comment: just edited my question
Comment: @SeanLange thanks for your suggestion!
Comment: @SeanLange that's what I was thinking too.
Answer: select SUBSTRING(a.[DESC],1,3),* from Table1 a
join Table2 b
on SUBSTRING(a.[DESC],1,3) = b.project

Comment: You could also use LEFT(a.[Desc], 3) instead of substring since it is the first 3 characters.
Comment: Oh yeah that's great. Thanks
Answer: PLEASE VOID USING RESERVED KEYWORDS LIKE DESC
SQL Fiddle
MS SQL Server 2017 Schema Setup:
CREATE TABLE Table1 ([DESC] varchar(255))
CREATE TABLE Table2 (Project varchar(255))
INSERT INTO Table1([DESC])values('2AB F YY')
INSERT INTO Table2(Project)values('2AB')

Query 1:
select SUBSTRING(a.[DESC],1,3)
from Table1 a
join Table2 b
on SUBSTRING(a.[DESC],1,3) = b.project

Results:
|     |
|-----|
| 2AB |


What is wrong with next jQuery code?

Question: can you help me why it returns error.
part of code /publications/deleteItem/' + valueClicked works ok, i checked (proper item is properly deleted).
var valueClicked = 123456;
$.ajax({
    type: "post",
    url: '/publications/deleteItem/' + valueClicked, // 100% works!
    success: function(xml) {
        alert('602!');
    },
    error:function (XMLHttpRequest, textStatus, errorThrown) {
        alert(errorThrown); // throwns undefined?!
    }

});

so, alert('602!') never exetutes...
Comment: What response are you getting from the server?
Comment: A slight correction to the answers below, the only statuses jQuery accepts (at the time of this comment) are 200-299, 304, 1223 and 0 (which opera gives for a 304).  301/302 will be transparently followed by the XmlHttpRequest, so jQuery doesn't see *those*, it sees whatever the destination code is.
Answer: There's nothing wrong with this jQuery code. The server simply didn't return a HTTP 2nn or 3nn response, but a 4nn or 5nn response. This will cause the error handler being invoked instead of the success handler.
You can use Firebug's Net panel to check the response headers and the status.
Comment: can i somehow make that it always return 'success'?
Comment: You can do that by ensuring that the HTTP response status is 2nn or 3nn. A normal success response code is 200. This is the default when your PHP code runs without errors/dies/wrong-redirects/etc.
Answer: open up the net panel in firebug and look at the response codes. successful response codes are 2xx or 3xx.
also try changing the success and error callbacks as follows and report back what you get.
success:function(data, status, xml) {
    alert(status);
},
error:function(data, status, xml) {
    alert(status);
},

Answer: Since you are trying to create a REST interface you should test direct calls for what do you want to do in the first place.
Let's imagine you domain is: http://www.mydomain.com
Try to call http://www.mydomain.com/publications/deleteItem/123456 and see what is returned from the server. The most probably your server is doing a redirect or outputting some error,and that's the source of your problem.

What is wrong with next jQuery code?


Loop through JSON array: uncaught syntax error, uncaught reference error

Question: I'm still new to JQuery and I'm trying to use it to iterate through a JSON array and update my webpage with the data in the array.
The JSON file looks like this:
[
    {
        "firstname":"John",
        "lastname":"Doe",
        "studentnumber":"666"
    },
    {
        "firstname":"Foo",
        "lastname":"Bar",
        "studentnumber":"777"
    }
]

My HTML document looks like this:
<!DOCTYPE html>

Members

You can see that I'm trying to use the .each function to accomplish this task. The above code is giving the following error:
VM2028:1 Uncaught SyntaxError: Unexpected token o
(anonymous function) @ index-v1.html:10
fire                 @ jquery-2.2.3.js:3187
self.fireWith        @ jquery-2.2.3.js:3317
done                 @ jquery-2.2.3.js:8785
(anonymous function) @ jquery-2.2.3.js:9151

After looking at some previous questions here, I tried replacing JSON.parse(data) with just data, and this resulted in the following error:
Uncaught ReferenceError: html is not defined
(anonymous function) @ index-v1.html:12
jQuery.extend.each   @ jquery-2.2.3.js:371
(anonymous function) @ index-v1.html:11
jQuery.extend.each   @ jquery-2.2.3.js:365
(anonymous function) @ index-v1.html:10
fire                 @ jquery-2.2.3.js:3187
self.fireWith        @ jquery-2.2.3.js:3317
done                 @ jquery-2.2.3.js:8785
(anonymous function) @ jquery-2.2.3.js:9151

What could be causing these problems and how do I fix them?
Comment: "After looking at some previous questions here, I tried replacing JSON.parse(data) with just data" — Err… so you've fixed the problem in your question title already…
Comment: @Quentin You're right, the title is poorly worded. I'll edit it now.
Answer: Cause of error: JSON.parse() expects a text but object is passed.(Thanks to @Rayon)
As data is already in JSON format, there is no need of using JSON.parse() on it.
$.getJSON('us.json', function(data){

    // Problem is here
    $.each(JSON.parse(data), function(key, value) {

Don't parse data
$.getJSON('us.json', function(data) {
    $.each(data, function(key, value) {

For second error

Uncaught ReferenceError: html is not defined

Define html variable before using it.
var html = ''; // Add before `each`.

Also, there is no need of nested each as the data passed in first each is already member object. Here's code written using Array#forEach.
$.getJSON('us.json', function (data) {
    var html = '';
    data.forEach(function(member) {
        html += '
';
        html += '
' + member.firstname + ' ' + member.lastname + '
';
        html += '
' + 'has the following member number:' + member.studentnumber + '
';
        html += '
';
    });

    $('#members').html(html);
});

Comment: Cause of error: _`JSON.parse` expects a `text` but `object` is passed.._
Comment: @Rayon Thanks. Added.
Comment: This has fixed the errors that were occurring, thank you. However it seems your code skips over the first object in the JSON array. What could be the reason for this?
Comment: @PythonNewb Can't say from here, can you check if there is any error in browser console? Also check in ELEMENTS tab if the first item is hidden or misplaced.
Comment: @Tushar There are no errors and it doesn't seem like any elements are hidden. However I added a `console.log()` statement and found that both objects were logged to the console. Could it be because the first element is overwritten by the second one? They both have the same html class.
Comment: "already return data in JSON format. There is no need of converting it to JSON " — No. It gets JSON and then it parses it into JavaScript objects/arrays/strings/etc. Parsing JSON doesn't turn something into JSON, it does the opposite of that.