text:
Q: Change the value of an animation and restart it I created a counter animation that increments for x seconds.
When the user arrives at the widget, the animation starts correctly via an initState.
I also created textfield begins and end to allow the user to update the start and end value and restart the animation.
Problem when the user pressed the button to restart the animation, it does not work.
PS: You can test the code if you want by copying the whole into a new project in main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ShowCounter(),
    );
  }
}

//
// The animation
//

class AnimatedCounter extends StatefulWidget {
  // Variables
  int startValue;
  int endValue;
  Duration timeAnim;
  Color color;
  double factor;

  // Constructor
  AnimatedCounter({
    int startValue,
    int endValue,
    Duration timeAnim: const Duration(seconds: 3),
    color: Colors.black,
    factor: 5.4,
  }) {
    this.startValue = startValue;
    this.endValue = endValue;
    this.timeAnim = timeAnim;
    this.color = color;
    this.factor = factor;
  }

  @override
  _AnimatedCounterState createState() => _AnimatedCounterState();
}

class _AnimatedCounterState extends State<AnimatedCounter>
    with SingleTickerProviderStateMixin {
  Animation<double> animCounter;
  AnimationController _controller;
  String i;

  @override
  void initState() {
    super.initState();

    // AnimationController
    _controller = AnimationController(duration: widget.timeAnim, vsync: this);

    // Animation
    animCounter = Tween<double>(
            begin: widget.startValue.toDouble(),
            end: widget.endValue.toDouble())
        .animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeOutCirc,
    ))
          ..addListener(() {
            setState(() {
              i = animCounter.value.toStringAsFixed(0);
            });
          });
    _controller.forward().orCancel;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  // Layout
  @override
  Widget build(BuildContext context) {
    return Text(
      '$i',
      textScaleFactor: widget.factor,
      style: TextStyle(color: widget.color),
    );
  }
}

//
// Display and layout
//

class ShowCounter extends StatefulWidget {
  @override
  _ShowCounterState createState() => _ShowCounterState();
}

class _ShowCounterState extends State<ShowCounter> {
  // Variable
  AnimatedCounter counter;
  int startvalue;
  int endValue;

  @override
  void initState() {
    super.initState();
    startvalue = 0;
    endValue = 42;
    counter = AnimatedCounter(startValue: startvalue, endValue: endValue);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Counter animated"),
      ),
      body: Scaffold(
        backgroundColor: Colors.blue[100],
        body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                counter,
                Card(
                    margin: EdgeInsets.only(left: 20.0, right: 20.0),
                    child: Container(
                      padding: EdgeInsets.all(10),
                      child: Column(children: <Widget>[
                        TextField(
                          keyboardType: TextInputType.number,
                          decoration:
                              InputDecoration(labelText: "Starting value"),
                          onChanged: (String string) {
                            setState(() {
                              startvalue = int.tryParse(string);
                            });
                          },
                        ),
                        TextField(
                          keyboardType: TextInputType.number,
                          decoration: InputDecoration(labelText: "End value"),
                          onChanged: (String string) {
                            setState(() {
                              endValue = int.tryParse(string);
                            });
                          },
                        ),
                        Container(
                          height: 10,
                        ),
                        SizedBox(
                          width: double.infinity,
                          child: RaisedButton(
                            child: Text("Run"),
                            onPressed: () {
                              setState(() {
                                // Desperate attempt to restart animation with new start/end value (not working)
                                counter = AnimatedCounter(
                                    startValue: startvalue, endValue: endValue);
                              });
                            },
                          ),
                        ),
                      ]),
                    ))
              ]),
        ),
      ),
    );
  }
}

A: You have to create a globalkey of state, so that you can access method of state from parent widget.
You have to pass globalkey to that widget and then create a method from initstate content and call that method from parent widget.
following full code will help you more.
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ShowCounter(),
    );
  }
}

//
// The animation
//

class AnimatedCounter extends StatefulWidget {
  // Variables
  int startValue;
  int endValue;
  Duration timeAnim;
  Color color;
  double factor;

  AnimatedCounter(
      {int startValue,
      int endValue,
      Duration timeAnim: const Duration(seconds: 3),
      color: Colors.black,
      factor: 5.4,
      Key key})
      : super(key: key) {
    this.startValue = startValue;
    this.endValue = endValue;
    this.timeAnim = timeAnim;
    this.color = color;
    this.factor = factor;
  }

  @override
  AnimatedCounterState createState() => AnimatedCounterState();
}

class AnimatedCounterState extends State<AnimatedCounter>
    with TickerProviderStateMixin {
  Animation<double> animCounter;
  AnimationController _controller;
  String i;

  @override
  void initState() {
    print("object");
    super.initState();
    // AnimationController
    startanimation();
  }

  startanimation() {
    _controller = AnimationController(duration: widget.timeAnim, vsync: this);

    // Animation
    animCounter = Tween<double>(
            begin: widget.startValue.toDouble(),
            end: widget.endValue.toDouble())
        .animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeOutCirc,
    ))
          ..addListener(() {
            setState(() {
              i = animCounter.value.toStringAsFixed(0);
            });
          });
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  // Layout
  @override
  Widget build(BuildContext context) {
    return Text(
      '$i',
      textScaleFactor: widget.factor,
      style: TextStyle(color: widget.color),
    );
  }
}

//
// Display and layout
//

class ShowCounter extends StatefulWidget {
  @override
  _ShowCounterState createState() => _ShowCounterState();
}

class _ShowCounterState extends State<ShowCounter> {
  // Variable
  AnimatedCounter counter;
  int startvalue;
  int endValue;
  GlobalKey<AnimatedCounterState> state = GlobalKey<AnimatedCounterState>();
  @override
  void initState() {
    super.initState();
    startvalue = 0;
    endValue = 42;
    counter = AnimatedCounter(
      startValue: startvalue,
      endValue: endValue,
      key: state,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Counter animated"),
      ),
      body: Scaffold(
        backgroundColor: Colors.blue[100],
        body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                counter,
                Card(
                    margin: EdgeInsets.only(left: 20.0, right: 20.0),
                    child: Container(
                      padding: EdgeInsets.all(10),
                      child: Column(children: <Widget>[
                        TextField(
                          keyboardType: TextInputType.number,
                          decoration:
                              InputDecoration(labelText: "Starting value"),
                          onChanged: (String string) {
                            setState(() {
                              startvalue = int.tryParse(string);
                            });
                          },
                        ),
                        TextField(
                          keyboardType: TextInputType.number,
                          decoration: InputDecoration(labelText: "End value"),
                          onChanged: (String string) {
                            setState(() {
                              endValue = int.tryParse(string);
                            });
                          },
                        ),
                        Container(
                          height: 10,
                        ),
                        SizedBox(
                          width: double.infinity,
                          child: RaisedButton(
                            child: Text("Run"),
                            onPressed: () {
                              setState(() {
                                counter = AnimatedCounter(
                                  startValue: startvalue,
                                  endValue: endValue,
                                  key: state,
                                );
                                state.currentState.startanimation();
                              });
                            },
                          ),
                        ),
                      ]),
                    ))
              ]),
        ),
      ),
    );
  }
}


text:
Q: Converting coordinates to lat lon in Madrid? I am using Python script for accessing this API for getting madrid traffic data. But I am really confused on how to get the geographic coordinates from this data. It has 2 fields st_x and st_y which I feel contain the information for the coordinates. I want to get those coordinates in lat long.

A: Could be useful to calculate the coordinates: https://github.com/bewest/proj4js or https://www.npmjs.com/package/utm-latlng

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get a map of repeated values in R? I have a data frame with several duplicated values, as follow:
df = data.frame(position = c(1,2,3,4,5,6,7), names = c('AAA','BBB','CCC','BBB','AAA','DDD','AAA'))

I would like to get a new data frame with a mapping of the duplicated values such as:
new_df = data.frame(column1 = c(1,1,5,2), column2 = c(5,7,7,4))

I have tried the code below, but it only mapped based on the first position, I would like all of them.
df['pos'] = data.frame(position = match(df$`names`, unique(df$`names`)))
df = df %>%  select(., position, pos)

A: in base R you could do something like:
t(do.call(cbind,tapply(df$position,df$names,function(x)if(length(x)>1)combn(x,2))))
     [,1] [,2]
[1,]    1    5
[2,]    1    7
[3,]    5    7
[4,]    2    4


text:
Q: Writing an Excel Spreadsheet Formula I need an Excel formula that will find the most efficient combination of products based on the value of a single cell.
e.g., I have a product list as follows: 400 / 220 / 150 / 110 / 72 / 60.
I need a formula that will apply items from the list based on a value of another "cell".
The combined items taken from the list need to add up to the closest but greater number above the value of the "cell" using the least number of items from the list.
So if the value of the "cell" is 660. the formula needs to know that instead of 6 x 110 the formula needs to know the correct response is:  1 x 400 (+) 1 x 220 (+) 1 x 60  = 680
How do I write the formula?

A: I think it would help if you would qualify your requirements in formulae e.g.
Say you have sorted items a,b,c,d,e,f with a > b > c > d > e > f
Then with a target cell x, you need to find m,n,o,p,q,r (all positive integers) so that
ma + nb + oc + pd + qe + rf >= x
and
y = m+n+o+p+q+r, where y < y(mi,ni,oi,pi,qi,ri)  for all combinations of mi,ni,oi,pi,qi,ri

and perhaps with another criteria like
ma + nb + oc + pd + qe + rf <= 1.1 * x
In some ways this is similar to the route optimisation problem I answered here (Excel Formula for optimizing a route where each row represents a different "station" that can do different things) but with the added complexity that you can visit a route more than once, which means the bit math trick no longer applies. To brute force this, you would need to generate the answer for all possible combinations, where the max of any single m, n... or r is QUOTIENT(x, m or n or...r)+1. For your example the solution space would span m,n,o,p,q,r = {0..2, 0..4, 0..5, 0..7, 0..10, 0..12}. You can generate such a table in excel using variations of MOD(QUOTIENT(ROW()-2,(n+1)(o+1)...(r+1)),m+1). Then calculate the total for each row/combination and compare that to the target value. In an adjacent column calculate the number of items y and multi-sort first by the total and then by the number of items.


text:
Q: Adding a dynamic column primeNG Angular 2. Make column for each object in the array I have a list of person which I want to display in a primeng datatable. The person object has this fields (firstName, lastName, continentsVisited). continentVisited field is an array of continent visited by the person. This continentsVisited is dynamic. What I want is to have a seperate column for each continent visited in addition to firstName and lastName.
export class AppComponent {
    persons: any [] = [
        {"firstName": "paolo","lastName":"revira","continentsVisited": [
               { "continent":"Europe", "name": "UK" },
               { "continent":"Asia", "name": "China" },
               { "continent":"North America", "name": "US" }
          ]},
        {"firstName": "kenneth","lastName":"santos"},"continentsVisited": [
               { "continent":"Europe", "name": "France" },
               { "continent":"Asia", "name": "Japan" },
               { "continent":"North America", "name": "Canada" }
          ]},
        {"firstName": "chris","lastName":"kenndy"},,"continentsVisited": [
               { "continent":"Europe", "name": "Germany" },
               { "continent":"Asia", "name": "Philippines" },
               { "continent":"North America", "name": "Mexico" }
          ]},
        ];

    ngOnInit() {

    }
}

<p-dataTable [value]="persons" [editable]="true"  resizableColumns="true" reorderableColumns="true">
    <p-column field="firstName" header="First Name" [editable]="true"></p-column>
    <p-column field="lastName" header="Last Name"></p-column>
</p-dataTable>

I have created a plunkr for this. here's the link https://plnkr.co/edit/gS1wsI?p=preview

A: You can use the below code,
<p-dataTable [value]="persons">
    <p-column *ngFor="let col of cols" [field]="col.field" [header]="col.header"></p-column>
</p-dataTable>

Typescript code
export class App {
  name:string;
  value:any;
   persons: any [] = [
        {"firstName": "paolo","lastName":"revira","continentsVisited": [
               { "continent":"Europe", "name": "UK" },
               { "continent":"Asia", "name": "China" },
               { "continent":"North America", "name": "US" }
          ]},
        {"firstName": "kenneth","lastName":"santos","continentsVisited": [
               { "continent":"Europe", "name": "France" },
               { "continent":"Asia", "name": "Japan" },
               { "continent":"North America", "name": "Canada" }
          ]},
        {"firstName": "chris","lastName":"kenndy","continentsVisited": [
               { "continent":"Europe", "name": "Germany" },
               { "continent":"Asia", "name": "Philippines" },
               { "continent":"North America", "name": "Mexico" }
          ]}
        ];
cols:any[]=[];
  constructor() {
    Object.keys(this.persons[0]).forEach(item=>{
      console.log(item)
      this.cols.push({field: item, header: item});
    })
  console.log(this.cols    );
    this.name = `Angular Prime Data table Dynamic columns`
  }

Update 1 : Based on screenshot
HTML will look like
<p-dataTable [value]="newPersons">
    <p-column *ngFor="let col of cols" [field]="col.field"
               [header]="col.header"></p-column>
</p-dataTable>

Typescript code :
for(let i =0 ; i <this.persons.length;i++){
  let temp={
    firstName : this.persons[i].firstName,
    lastName : this.persons[i].lastName
  }
  this.persons[i].continentsVisited.forEach(item=>{
  let keyValue = Object.values(item);
  console.log(keyValue)
   temp[keyValue[0].toString()] = keyValue[1]

}
 this.newPersons.push(temp);
}
console.log(this.newPersons)
Object.keys(this.newPersons[0]).forEach(item=>{
  this.cols.push({field: item, header: item});
})

Note: Update in the below demo
LIVE DEMO


text:
Q: Unable to connect config client with config server when deployed in the weblogic I am facing issue when we deployed config server and config client in weblogic server and run it as part of same process which is running on port 7001.
In client app, configured URL to point config-server(http://localhost:7001/) but its not able to connect, whhile troubleshooting, getting below issue -
2022-10-17 20:04:15,234 INFO org.springframework.boot.context.config.ConfigDataLoader  [[STANDBY] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'] Fetching config from server at : http://localhost:7001/
2022-10-17 20:04:15,234 INFO org.springframework.boot.context.config.ConfigDataLoader  [[STANDBY] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'] Connect Timeout Exception on Url - http://localhost:7001/. Will be trying the next url if available
2022-10-17 20:04:15,234 WARN org.springframework.boot.context.config.ConfigDataLoader  [[STANDBY] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'] Could not locate PropertySource ([ConfigServerConfigDataResource@2fe99575 uris = array<String>['http://localhost:7001/'], optional = true, profiles = list['production']]): I/O error on GET request for "http://localhost:7001/common-service,employee-service/production": Tried all: '2' addresses, but could not connect over HTTP to server: 'localhost', port: '7001'
Due to this , unable to fetch properties.

However, if I run same codebase of config-server as a separate process and point that url from client application which is deployed on weblogic 7001 port, then able to connect (http://localhost:8079/)
2022-10-17 20:40:41,434 DEBUG com.oraclecorp.cc.wstemplate.ServletInitializer  [[ACTIVE] ExecuteThread: '6' for queue: 'weblogic.kernel.Default (self-tuning)'] Running with Spring Boot v2.5.14, Spring v5.3.20
2022-10-17 20:40:41,435 INFO com.oraclecorp.cc.wstemplate.ServletInitializer  [[ACTIVE] ExecuteThread: '6' for queue: 'weblogic.kernel.Default (self-tuning)'] The following 1 profile is active: "production"
2022-10-17 20:40:41,499 INFO org.springframework.boot.context.config.ConfigDataLoader  [[ACTIVE] ExecuteThread: '6' for queue: 'weblogic.kernel.Default (self-tuning)'] Fetching config from server at : http://localhost:8079/
2022-10-17 20:40:41,499 INFO org.springframework.boot.context.config.ConfigDataLoader  [[ACTIVE] ExecuteThread: '6' for queue: 'weblogic.kernel.Default (self-tuning)'] Located environment: name=common-service,employee-service, profiles=[production], label=null, version=1c8f98727c7e2e6f0892e8e7d4a5174e0b5b2220, state=null

Please let me know if anyone has any idea or came across with similar situations.


text:
Q: Django cannot run tests when DATABASES 'default' is empty I have some troubles running tests with setting DATABASES['default'] = {}.
I got the folowing error when running ./manage.py test
$ ./manage.py test --failfast
Creating test database for alias 'mydb'...
E
======================================================================
ERROR: test_admin (myapp.test.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 182, in __call__
    self._pre_setup()
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 754, in _pre_setup
    self._fixture_setup()
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 887, in _fixture_setup
    if not connections_support_transactions():
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 874, in connections_support_transactions
    for conn in connections.all())
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/test/testcases.py", line 874, in <genexpr>
    for conn in connections.all())
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/utils/functional.py", line 55, in __get__
    res = instance.__dict__[self.func.__name__] = self.func(instance)
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 782, in supports_transactions
    self.connection.leave_transaction_management()
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 338, in leave_transaction_management
    if managed == self.get_autocommit():
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 345, in get_autocommit
    self.ensure_connection()
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 133, in ensure_connection
    self.connect()
  File "/home/thomas/.virtualenvs/tmpapp/local/lib/python2.7/site-packages/django/db/utils.py", line 86, in __exit__
    db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
AttributeError: 'DatabaseWrapper' object has no attribute 'Database'

----------------------------------------------------------------------
Ran 0 tests in 0.001s

FAILED (errors=1)
Destroying test database for alias 'mydb'...

settings.py
..
DATABASES = {
    'default': {},
    'mydb': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
}
DATABASE_ROUTERS = ['myapp.router.MyRouter']

router.py
class MyRouter:
    def db_for_read(self, model, **hints):
        return 'mydb'

    def db_for_write(self, model, **hints):
        return 'mydb'

    def allow_migrate(self, db, model):
        if db == 'default':
            return False
        return True

test.py
from django.test import TestCase

class MyTest(TestCase):

    def test_admin(self):
        self.assertEqual(1, 1)

I did some investigation and find that self.connect() was called on the dummy backend associated with 'default' alias. Since the dummy backend does not implement much fonctionnalities, the call fails. How can I run tests with DATABASES['default'] = {} ?

A: Use different settings.py files for production/development/testing (best).
And or use Sqlite as default entry (quickest).


text:
Q: Passthrough / Oculus Integration using Legacy XR only (without OpenXR) I'm using a plugin that requires Unity 2019.3.3 and Legacy 'Built-in' XR in the project. I would also like to use Oculus Integrations passthrough API, but that requires OpenXR.
Is there a way to either use Oculus Integration using the Legacy XR system (e.g. via an older version of OI) or a way to have both Legacy XR and OpenXR without things breaking.
Thanks!


text:
Q: Typhoon won't inject into plain NSObject derived class I have a Swift 3 app using Typhoon which successfully injects a NSObject-derived object into a property in several objects deriving from UIViewController. I added code to inject the same object into an object that derives only from NSObject, and the property is always nil upon executing any code in that object.
My assembly looks like this:
class CoreComponents: TyphoonAssembly {
dynamic func appInitializer() -> Any {
    return TyphoonDefinition.withClass(AppInitializer.self) {
        (definition) in

        definition!.injectProperty(Selector(("settings")), with: self.provideSettings())
    }
}

dynamic func sideMenu() -> Any {
    return TyphoonDefinition.withClass(SideMenuTableView.self) {
        (definition) in

        definition!.injectProperty(Selector(("settings")), with: self.provideSettings())
    }
}

dynamic func mapViewController() -> Any {
    return TyphoonDefinition.withClass(MapViewController.self) {
        (definition) in

        definition!.injectProperty(Selector(("settings")), with: self.provideSettings())
    }
}

dynamic func provideSettings() -> Any {
    return TyphoonDefinition.withClass(Settings.self) {
        (definition) in
        definition!.scope = TyphoonScope.singleton
    }
}

}
In that, only the injection specified by the first method fails to inject. The object it wants to inject into is declared like this:
class AppInitializer: NSObject {
    var settings: Settings? // Injected property

    // Other code here
}

Does anybody see anything I'm doing wrong?
Here is the relevant portion of a class where the injection works:
class SideMenuTableView: UITableViewController {
    var settings: Settings?  // Injected property
    // Other code
}

Thanks!

A: To get this to work, I abandoned the Objective-C compatible version of Typhoon and switched to the "pure swift" version of Typhoon at their website. The setup is more work, but the code ends up simplified:
class CoreComponents: Assembly {
    func provideSettings() -> Definition {
        return Definition(withClass: Settings.self) { d in
            d.setScope(Definition.Scope.Singletone)
        }
    }
}

class AppInitializer: NSObject {
    let settings = CoreComponents.assembly.provideSettings()
    // More code here
}

That required instantiating the assembly in my AppDelegate's "didFinishLaunchingWithOptions" method with this line:
Typhoon.activateAssemblies()


text:
Q: Performance Evaluation of Prototype I would like to evaluate a prototype I am working on. The prototype is implementing CQRS design pattern where the update in write database should be reflected asynchronously to the read database. My prototype is working fine but I now need to evaluate the performance of my application by measuring the following metrics:

*

*Latency (time taken from the insert/update/delete operation in write database to be reflected in the read database)

*Failover time (I have two instances of a component in my write side such that in case of failure of any one component, the other could take over)

*Stress test

Are there any tools that could help me in measuring these metrics for my prototype?
P.S. Kindly suggest more metrics and tools that could help me to better evaluate my prototype.


text:
Q: ElseIf statement wont run the whole code VB Ok so I've been working on a program I'm making and for some reason when I put a bit of my code into an else if statement, it won't run the statement at all not even the original If statement, However when I put it in a regular If and else statement it works perfectly.
This bit of code works:
  If TextBox5.Text > TextBox1.Text & TextBox6.Text > TextBox2.Text Then 'NE
        Bearing = Atan(X2 / Y2) * 57.3
    Else
        Bearing = Atan(Y2 / X2) * 57.3
        Bearing = Bearing + -Bearing + -Bearing + 90
        If BOFF > 0 Then
            Bearing = Bearing - Math.Round(BOFF)
        Else
            Bearing = Bearing + Math.Round(BOFF)

        End If

    End If

And this bit of code doesnt work:
    If TextBox5.Text > TextBox1.Text & TextBox6.Text > TextBox2.Text Then 'NE
        Bearing = Atan(X2 / Y2) * 57.3
    ElseIf TextBox5.Text > TextBox1.Text & TextBox6.Text < TextBox2.Text Then
        Bearing = Atan(Y2 / X2) * 57.3
        Bearing = Bearing + -Bearing + -Bearing + 90
        If BOFF > 0 Then
            Bearing = Bearing - Math.Round(BOFF)
        Else
            Bearing = Bearing + Math.Round(BOFF)

        End If

    End If

Could be a syntax error something, but it doesn't come up with an error at all, runs the code perfectly and all that. I don't know what I'm doing wrong here.

A: You should use AND instead of &
AND is the logical operator on the other hand & is  for joining strings

It is the logical as well as bitwise AND operator. If both the
  operands are true, then condition becomes true. This operator does not
  perform short-circuiting, i.e., it evaluates both the expressions.

If TextBox5.Text > TextBox1.Text And TextBox6.Text > TextBox2.Text Then 'NE
       'Code
ElseIf TextBox5.Text > TextBox1.Text And TextBox6.Text < TextBox2.Text Then
       'Code
End If

Note:
If values of TextBox1.Text =4, TextBox6.Text=1 then TextBox1.Text & TextBox6.Text will yields 41
See this demo
& is used to concatenate two strings


text:
Q: boost::asio signal_set handler only executes after first signal is caught and ignores consecutive signals of the same type I have a program and would like to stop it by sending SIGINT for writing some data to a file instead of exiting immediately. However, if the user of the program sends SIGINT again, then the program should quit immediately and forget about writing data to a file.
For portability reason I would like to use boost::asio for this purpose.
My initial (simplified) approach (see below) did not work. Is this not possible or am I missing something?
The handler seems to be called only once (printing out the message) and the program always stops when the loop has reached the max iteration number.
void handler(
const boost::system::error_code& error,
int signal_number) {
    if (!error) {
        static bool first = true;
        if(first) {
            std::cout << " A signal(SIGINT) occurred." << std::endl;
            // do something like writing data to a file
            first = false;
        }
        else {
            std::cout << " A signal(SIGINT) occurred, exiting...." << std::endl;
            exit(0);
        }
    }
}

int main() {
    // Construct a signal set registered for process termination.
    boost::asio::io_service io;
    boost::asio::signal_set signals(io, SIGINT);

    // Start an asynchronous wait for one of the signals to occur.
    signals.async_wait(handler);
    io.run();
    size_t i;

    for(i=0;i<std::numeric_limits<size_t>::max();++i){
        // time stepping loop, do some computations
    }

    std::cout << i << std::endl;
    return 0;
}

A: When your first event is handled, you don't post any new work on the service object, so it exits.
This means that then (after the ioservice exited) the tight loop is started. This may not be what you expected.

*

*If you want to listen for SIGINT again, you have to wait for the signal set again from the handler:
#include <boost/asio.hpp>
#include <boost/asio/signal_set.hpp>
#include <boost/bind.hpp>
#include <boost/atomic.hpp>
#include <iostream>

void handler(boost::asio::signal_set& this_, boost::system::error_code error, int signal_number) {
    if (!error) {
        static boost::atomic_bool first(true);
        if(first) {
            // do something like writing data to a file
            std::cout << " A signal(SIGINT) occurred." << std::endl;
            first = false;

            this_.async_wait(boost::bind(handler, boost::ref(this_), _1, _2));
        }
        else {
            std::cout << " A second signal(SIGINT) occurred, exiting...." << std::endl;
            exit(1);
        }
    }
}

int main() {
    // Construct a signal set registered for process termination.
    boost::asio::io_service io;
    boost::asio::signal_set signals(io, SIGINT);

    // Start an asynchronous wait for one of the signals to occur.
    signals.async_wait(boost::bind(handler, boost::ref(signals), _1, _2));
    io.run();
    return 2;
}

As you can see I bound the signal_set& reference to the handler in order to be able to async_wait on it after receiving the first signal. Also, as a matter of principle, I made first an atomic (although that's not necessary until you run the io_service on multiple threads).

*Did you actually wish to run the io_service in the background? In that case, make it look like so:
signals.async_wait(boost::bind(handler, boost::ref(signals), _1, _2));

boost::thread(boost::bind(&boost::asio::io_service::run, boost::ref(io))).detach();

while (true)
{
    std::cout << "Some work on the main thread...\n";
    boost::this_thread::sleep_for(boost::chrono::seconds(1));
}

With typical output:
Some work on the main thread...
Some work on the main thread...
Some work on the main thread...
^CSome work on the main thread...
 A signal(SIGINT) occurred.
Some work on the main thread...
Some work on the main thread...
^CSome work on the main thread...
 A second signal(SIGINT) occurred, exiting....


text:
Q: Can't find a way to modify cormen's mergeSort algorithm into a 3 way merge I have an assignment about modifying Cormen's merge sort algorithm into a 3 way merge. My instructor does not like outside book materials, so I am strictly abiding by cormen's algorithm. Now, I have tried to do that, but how ever it shows something like this
Exception in thread "main" java.lang.NegativeArraySizeException: -1
        at Algorithms.Mergemod.merge(Mergemod.java:10)
        at Algorithms.Mergemod.mergeSort(Mergemod.java:60)
        at Algorithms.Mergemod.mergeSort(Mergemod.java:58)
        at Algorithms.Mergemod.mergeSort(Mergemod.java:59)
        at Algorithms.Mergemod.mergeSort(Mergemod.java:58)
        at Algorithms.Mergemod.main(Mergemod.java:83)

I have tried the debugger and there in the mergeSort function I see r holds value sometimes 1, sometimes 3 and not 11. Here is my confusion why r would hold 1 or 3 and not 11. I have passed the last index of the array as r in the function.
My code:
package Algorithms;
import java.util.Scanner;
public class Mergemod {

    static void merge(int [] A, int p, int q, int t, int r ){
        int n1 = q-p+1;
        int n2 = t-q;
        int n3 = r-t;

        int [] L = new int[n1];
        int [] M = new int[n2];
        int [] R = new int[n3];

        //inserting values from A to L
        for (int i = 0; i < L.length; i++) {
            L[i] = A[p+i];
        }
        //inserting values from A to M
        for (int j = 0; j < M.length; j++) {
            M[j] = A[q+j+1];
        }
        //inserting values from A to R
        for (int k = 0; k < R.length; k++) {
            R[k] = A[t+k+1];
        }

        int i = 0 , j = 0, k = 0, l;
        //sorting and merging
        for (l = p; l <=r && i<n1 && j<n2 && k<n3; l++) {
            if(L[i]<=M[j] && L[i]<=R[k]){
                A[l] = L[i];
                i++;
            }
            else if(M[j]<=L[i] && M[j]<=R[k]){
                A[l] = M[j];
                j++;
            }
            else{
                A[l] = R[k];
                k++;
            }
        }
        while(i<n1){
            A[l++] = L[i++];
        }
        while(j<n2){
            A[l++] = M[j++];
        }
        while(k<n3){
            A[l++] = R[k++];
        }
    }
    static void mergeSort(int [] A, int p, int r){
        if(p<r)
        {   int q = (p+r)/3;
            int t = (q+1+r)/2;
            mergeSort(A, p, q);
            mergeSort(A, q+1, t);
            mergeSort(A, t+1, r);
            merge(A, p, q, t, r);
        }

    }
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of the array: ");
        int [] arr = new int [sc.nextInt()];
        System.out.println("Enter numbers : 11 5 20 3 4 8 0 15 2 13 1 6");
        for (int i = 0; i < arr.length; i++) {
            arr[i]= sc.nextInt();
        }
        System.out.println("Before merge sort");
        for (var x : arr) {
            System.out.print(x+" ");
        }

        int firstIndex = 0;
        int lastIndex = arr.length-1;
        System.err.println(" ");
        System.out.println("After merge sort ");
        mergeSort(arr, firstIndex, lastIndex);
        for (var k : arr) {
            System.out.print(k+" ");
        }
        sc.close();
    }
}

I do not know if my logic is correct or not but if anybody would help me out that would mean so much. Also I am not very good in java, so sorry for if there is any readability issue.
Thanks!

A: I'll update this answer as you make progress. Update your question as you make progress.
int q = p + (r+1-p)/3;   // split
int t = q + (r+2-p)/3;

In merge():
if (r-p) < 1, return
if (r-p) < 2, compare a[p] : a[r], swap if out order, return

3 way merge,
 if the end of L[] is reached, L = M, M = R, i = j, j = k, break to 2 way merge
 if the end of M[] is reached, M = R, j = k, break to 2 way merge
 if the end of R[] is reached, break to 2 way merge

2 way merge L[] and M[] using i and j
 if the end of L[] is reached, L = M, i = j break to copy
 if the end of M[] is reached, break to copy

copy the rest of L[]

A: instead of doing that, I tried my luck using a priority queue. Loaded three of the arrays into the min heap and then removed every item from the minheap to my array A.

        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        for (Integer x : L) {
            minHeap.add(x);
        }
        for (Integer v : M) {
            minHeap.add(v);
        }
        for (Integer g : R) {
            minHeap.add(g);
        }
        for (int i = p; i <=r; i++) {
            A[i]= minHeap.remove();
        }

Thank you so much for that modified split from you. Worked like a charm. @rcgldr


text:
Q: Hadoop job issues: map 0% reduce 0% Recently I'm trying wordaccount through MapReduce in Hadoop2.7.1. But the job always stuck at map 0% reduce 0%. Here is all the information:
No configs found; falling back on auto-configuration
No configs specified for hadoop runner
Looking for hadoop binary in /usr/local/hadoop/bin...
Found hadoop binary: /usr/local/hadoop/bin/hadoop
Using Hadoop version 2.7.1
Looking for Hadoop streaming jar in /usr/local/hadoop...
Found Hadoop streaming jar: /usr/local/hadoop/share/hadoop/tools/lib/hadoop-streaming-2.7.1.jar
Creating temp directory /tmp/wordaccount.xjj.20220524.013439.681080
uploading working dir files to hdfs:///user/xjj/tmp/mrjob/wordaccount.xjj.20220524.013439.681080/files/wd...
Copying other local files to hdfs:///user/xjj/tmp/mrjob/wordaccount.xjj.20220524.013439.681080/files/
Running step 1 of 1...
  packageJobJar: [/tmp/hadoop-unjar3955585943094314924/] [] /tmp/streamjob2959762167969354976.jar tmpDir=null
  Connecting to ResourceManager at /0.0.0.0:8032
  Connecting to ResourceManager at /0.0.0.0:8032
  Total input paths to process : 1
  number of splits:2
  Submitting tokens for job: job_1653356019342_0001
  Submitted application application_1653356019342_0001
  The url to track the job: http://master:8088/proxy/application_1653356019342_0001/
  Running job: job_1653356019342_0001
  Job job_1653356019342_0001 running in uber mode : false
   map 0% reduce 0%

I entered the url and check the job, the content of the url is here enter image description here
Then I checked the resourcemanager-master.log:
2022-05-24 09:47:09,400 INFO org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncher: Error cleaning master
java.net.ConnectException: Call From master/192.168.70.128 to master:36309 failed on connection exception: java.net.ConnectException: 拒绝连接; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:792)
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:732)
    at org.apache.hadoop.ipc.Client.call(Client.java:1480)
    at org.apache.hadoop.ipc.Client.call(Client.java:1407)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:229)
    at com.sun.proxy.$Proxy32.stopContainers(Unknown Source)
    at org.apache.hadoop.yarn.api.impl.pb.client.ContainerManagementProtocolPBClientImpl.stopContainers(ContainerManagementProtocolPBClientImpl.java:110)
    at org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncher.cleanup(AMLauncher.java:139)
    at org.apache.hadoop.yarn.server.resourcemanager.amlauncher.AMLauncher.run(AMLauncher.java:268)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: 拒绝连接
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:531)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:495)
    at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:609)
    at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:707)
    at org.apache.hadoop.ipc.Client$Connection.access$2800(Client.java:370)
    at org.apache.hadoop.ipc.Client.getConnection(Client.java:1529)
    at org.apache.hadoop.ipc.Client.call(Client.java:1446)
    ... 9 more
2022-05-24 09:49:03,136 INFO logs: Aliases are enabled

and the nodemanager-master.log:
2022-05-24 09:35:00,684 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServices: Got event CONTAINER_INIT for appId application_1653356019342_0001
2022-05-24 09:35:00,684 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServices: Got event APPLICATION_INIT for appId application_1653356019342_0001
2022-05-24 09:35:00,684 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServices: Got APPLICATION_INIT for service mapreduce_shuffle
2022-05-24 09:35:00,694 INFO org.apache.hadoop.mapred.ShuffleHandler: Added token for job_1653356019342_0001
2022-05-24 09:35:00,697 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServices: Got event CONTAINER_INIT for appId application_1653356019342_0001
2022-05-24 09:35:00,697 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServices: Got event APPLICATION_INIT for appId application_1653356019342_0001
2022-05-24 09:35:00,697 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.AuxServices: Got APPLICATION_INIT for service mapreduce_shuffle
2022-05-24 09:35:00,697 INFO org.apache.hadoop.mapred.ShuffleHandler: Added token for job_1653356019342_0001
2022-05-24 09:35:00,698 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl: Container container_1653356019342_0001_01_000003 transitioned from LOCALIZING to LOCALIZED
2022-05-24 09:35:00,698 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl: Container container_1653356019342_0001_01_000002 transitioned from LOCALIZING to LOCALIZED
2022-05-24 09:35:00,735 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl: Container container_1653356019342_0001_01_000002 transitioned from LOCALIZED to RUNNING
2022-05-24 09:35:00,735 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainersMonitorImpl: Neither virutal-memory nor physical-memory monitoring is needed. Not running the monitor-thread
2022-05-24 09:35:00,737 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl: Container container_1653356019342_0001_01_000003 transitioned from LOCALIZED to RUNNING
2022-05-24 09:35:00,737 INFO org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainersMonitorImpl: Neither virutal-memory nor physical-memory monitoring is needed. Not running the monitor-thread
2022-05-24 09:35:00,743 INFO org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor: launchContainer: [bash, /usr/local/hadoop/tmp/nm-local-dir/usercache/xjj/appcache/application_1653356019342_0001/container_1653356019342_0001_01_000002/default_container_executor.sh]
2022-05-24 09:35:00,744 INFO org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor: launchContainer: [bash, /usr/local/hadoop/tmp/nm-local-dir/usercache/xjj/appcache/application_1653356019342_0001/container_1653356019342_0001_01_000003/default_container_executor.sh]

So what could be the problem? Connection refused or not enough memory? Thanks for your help.


text:
Q: org.hibernate.LazyInitializationException: could not initialize proxy - no Session for hibernate + JPA I'm trying to query database from a tomcat listener via hibernate session before tomcat container starts. Here I'm getting the org.hibernate.LazyInitializationException: could not initialize proxy - no Session error. Also When trying to attach the object with hibernate session it's giving error
My Setup:
1. have a tomcat listener where the same implements ServletContextListener
2. start spring applicationcontext via this listener
3. configured hibernate with JPA within spring
listener : in this listener I'm trying to load my spring applicationContext and call my DAO via hibernate session to get DB data. Also I'm starting one thread pool to allocate the task depends on the DB query
@Override
    public void contextInitialized(ServletContextEvent sce) {

    ServletContext servletContext = sce.getServletContext();

        logger.debug("initializing the servletContextListener for AlarmThreadPool...");

        try {

            String springFileName = sce.getServletContext().getInitParameter("CONFIG_SPRING_FILE");
            ApplicationContextContainer.getInstance(springFileName, sce.getServletContext());

            IAriCloudDAO ariCloudDAO = (IAriCloudDAO) ApplicationContextContainer.getBean("ariCloudDAO");
            logger.debug("got the dao bean...");
            if (null != ariCloudDAO) {
                System.out.println("got the instace of DAO");
                int metricID = 1;
                List<CloudAlarmConfig> cloudAlarmConfigs = ariCloudDAO.getAllUsageAlarm(metricID);
                logger.info("the DAO entry got as " +cloudAlarmConfigs);
            }

            ThreadFactory threadFactory = new ThreadFactoryBuilder()
                    .setNameFormat("alarm-thread-%d")
                    //.setDaemon(true)
                    .build();

            ScheduledExecutorService exec = Executors.newScheduledThreadPool(2, threadFactory);
            servletContext.setAttribute("alarmThreadPool", exec);

        }catch (Exception e) {
            logger.fatal("ERROR::", e);
        }
    }

DAO IMPL:
@Override
@Transactional
@SuppressWarnings("unchecked")
public List<CloudAlarmConfig> getAllUsageAlarm(int metricID) {

    Session session = mySessionFactory.getCurrentSession();

    Query q = session
            .createQuery("SELECT e FROM CloudAlarmConfig e WHERE METRIC=:METRIC");
    q.setParameter("METRIC", metricID);
    logger.debug("query string got as :"+ q.getQueryString());
    List<CloudAlarmConfig> cloudAlarmConfigs = q.list();

    if (!cloudAlarmConfigs.isEmpty()) {
        return cloudAlarmConfigs;
    } else {
        return new ArrayList<CloudAlarmConfig>();
    }
}

JPA entity:
I'm using LazyInitialization for entity joining.
@JsonIgnore
    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "USER_ID", referencedColumnName = "ID")
    private UserEntity userEntity;

Getting the below exception when trying to execute the DAO call.

org.hibernate.LazyInitializationException: could not initialize proxy
  - no Session  at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
    at
  org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
    at
  org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at
  com.aricent.aricloud.entity.UserEntity_$$_javassist_6.toString(UserEntity_$$_javassist_6.java)
    at java.lang.String.valueOf(String.java:2902)   at
  java.lang.StringBuilder.append(StringBuilder.java:128)    at
  com.aricent.aricloud.entity.CloudAlarmConfig.toString(CloudAlarmConfig.java:234)
    at java.lang.String.valueOf(String.java:2902)   at
  java.lang.StringBuilder.append(StringBuilder.java:128)

As I understood from several post that the hibernate session lives for one request and then it closed, the entity has been detached from session. But when trying to reattach the same with below code in DAO impl it gives me different error
Session session = mySessionFactory.getCurrentSession();
session.update(CloudAlarmConfig.class);

org.hibernate.MappingException: Unknown entity: java.lang.Class   at
  org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:1141)
    at
  org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1433)
    at
  org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:233)
    at
  org.hibernate.event.internal.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:55)
    at
  org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at
  org.hibernate.internal.SessionImpl.fireUpdate(SessionImpl.java:786)
    at org.hibernate.internal.SessionImpl.update(SessionImpl.java:778)
    at org.hibernate.internal.SessionImpl.update(SessionImpl.java:774)
    at
  com.aricent.aricloud.dao.AricloudDAOImpl.getAllUsageAlarm(AricloudDAOImpl.java:959)

How can I overcome this. Please suggest.

A: You are overriding the toString() method of CloudAlarmConfig class and trying to access the lazily loaded instances of UserEntity.
So in your code -
List<CloudAlarmConfig> cloudAlarmConfigs = ariCloudDAO.getAllUsageAlarm(metricID);
logger.info("the DAO entry got as " +cloudAlarmConfigs);

This makes call to toString method which internally tries to access the "UserEntity", so when you are trying to access the entity outside the Hibernate session, you are getting Lazy exception as org.hibernate.LazyInitializationException: could not initialize proxy - no Session at.
To fix this issue, you have to load the instances of UserEntity when the session is still open.
Coming to second exception which is org.hibernate.MappingException: Unknown entity: java.lang.Class at, Jens has provided explanation in his comments. The code should be like this:
Session session = mySessionFactory.getCurrentSession();
session.update(cloudAlarmConfig);

Here cloudAlarmConfig represents the instance of CloudAlarmConfig class.
Update:
To update a record, first you should have a valid object with proper id in it. So you can try like this:
 Session session = mySessionFactory.getCurrentSession();
 CloudAlarmConfig cloudAlarmConfig = (CloudAlarmConfig) session.get(CloudAlarmConfig.class,100); // Assuming 100 is one of the primary key in Databse table for CloudAlarmConfig entity.

// Do some modifications to this object, then call the update operation.
session.update(cloudAlarmConfig);


text:
Q: Issue trying to output records stored in MySql I have a simple page which basically gets unique input text from user and queries the database to see if that any contact record belonging to that input. So far I know connection is established and it is trying to query the database.
However, no record is retrieved. This is what the code looks like:

<form action="processAttendance.php" method="POST">

    <input type="text" class="button" id="inviteCode" name="inviteCode" placeholder="Enter invite code i.e. E2562SA">
    <input type="submit" class="button" id="submit" value="Register">

</form>

<?php
include 'dbh.php';
$inviteCode = $_POST['inviteCode'];
echo $inviteCode;
$sql = "SELECT `FirstName`, `LastName`, `Confirmed`, `InviteCode`, `PlusOnes` FROM `Guest` WHERE 'InviteCode' = '$inviteCode'";
$result = $conn->query($sql);
$row = mysqli_fetch_assoc($result);
echo "my result" . $row."
";
echo "my result" . $row['classtype'];

The result printed back is as follows:
TEST
my resultArray
my result
Could anyone offer some insight as to why this could be the case?

A: Youre not fetching your rows correctly. Youre using mysqli OOP, so you should use ->fetch_assoc() and you need to iterate over your results to get your rows. Something like this:
$sql = "SELECT `FirstName`, `LastName`, `Confirmed`, `InviteCode`, `PlusOnes` FROM `Guest` WHERE 'InviteCode' = '$inviteCode'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {

        echo "
";
        print_r($row);
        echo "
";

        echo "my FirstName: " . $row['FirstName'];
    }
} else {
    echo "No results";
}
$conn->close();

BTW, you should use prepared statements to prevent sql injections.

A:
However, no record is retrieved

Incorrect. If you didn't get a record that you wouldn't get:

my resultArray

mysqli_fetch_assoc returns NULL if there are no results. You are getting an array.
$row['classtype'] is blank because you didn't include classtype in the list of fields you were selecting.

A: Your sql statement is this:

SELECT FirstName, LastName, Confirmed, InviteCode, PlusOnes
  FROM Guest WHERE 'InviteCode' = '$inviteCode'

You are attempting to output $row['classtype'], but look at the SELECT part of your SQL, that column was not selected.
Use classtype to your sql statement to make it available, assuming that is a field in your table.

SELECT `classtype` FROM `Guest` WHERE 'InviteCode' = '$inviteCode'

After getting $row, you can run the statement var_dump($row) to output the entire object.

A: Here is a method I use:
for($row as $data) {
echo $data['classtype'];

}
Try this. I am assuming you will be dealing with the rows of all members you have there. It will go through all the rows with whatever info you want.


text:
Q: Why does passing a static dependency to an useEffect causes it to be called every render? Why does the following useEffect is fired on every render if the dependency never changes?
useEffect(() => {
   console.log('Here')
}, [['1', '2', '3']]);

A: Each item of dependency array is checked using strict equality. That means it uses the === operator.
So it checks if oldDeps[0] === newDeps[0] and then checks oldDeps[1] === newDeps[1], and so on. It will execute the effect if any of those checks are false.
Lastly, two arrays with the items are not strictly equal:
[1,2,3] === [1,2,3] // false

const a = [1,2,3]
const b = a
a === b // true

This is because they are two different arrays, they just happen to contain the same content. But in the above code, a === b is true because both variables reference the same array.

Typically, you do not want to construct an array as one of a hooks dependencies for this reason. If you have a list of id's, you can do things like convert it to a string instead:
}, [[1,2,3].join('-')]);

This works because strings are strictly equal with the same content:
"1-2-3" === "1-2-3" // true


text:
Q: Using scanner to create an object identifier? Is there any way to create the name of an object depending on user input?
eg.
Object scan.nextLine() = new Object();

A: No you can't do this.
I would suggest having a custom class and store the instanceName:
public class MyClass {

    private String instanceName;
    public MyClass(String instanceName) {
        this.instanceName = instanceName;
    }

}

MyClass myObj = new MyClass(scan.nextLine());

A: No it is not possible. There are no dynamic variables in Java. Java variable name have to be declared in the source code  during compile time.
If want to store the Object with the user entered values you can try using a Map to save the data as below.
Map<String, Object> objects = new HashMap<String, Object>();
String name = scan.nextLine();

Object obj = new Object();
objects.put(name, obj); // saving the objects in Map

A: No. You cannot do that in java. Since you should already have a class defined to create a object of it.

A: There are some ways you could fake doing this. You could use a map to give the perception of dynamically named Objects. But since you say you are a beginner, the short answer is no. Make sure you know what you are asking for in your example though. Your example is the equivalent of saying:
String line = "foo";
Object line = new Object();

My guess would be that's not what you wanted (and isn't possible).

A: Given the line
Type variable_name = expression ;

The name variable_name is simply used in the rest of the scope for referencing the outcome of expression. You know that Java is a compiled language, and these names are only useful to the programmer. Once the compiler does its job, it can use a translation table and replace those names with whatever ID it wants.
Since those name don't even exist at runtime, there's no way of choosing the name for a variable at runtime.
However you may need to access an object depending on user input (for example like in PHP variable variables $$a_var). Depending on your context, you may use reflection to access instance members, or a simple Map<String, Object>. Example with reflection:
public class VariableRuntime {

    static class Person {
        public String first, last, city;
    }

    public static void main(String[] args) throws Exception {
        Person homer = new Person();

        homer.first = "Homer";
        homer.last = "Simpson";
        homer.city = "Springfield";

        System.out.println("What do you want to know about Homer? [first/last/city]");

        String what = new Scanner(System.in).nextLine();
        Field field = Person.class.getDeclaredField(what);

        System.out.println(field.get(homer));
    }

}

The same with a Map<String, String>:
public class VariableRuntime {

    public static void main(String[] args) throws Exception {
        Map<String, String> homer = new HashMap<String, String>();

        homer.put("first", "Homer");
        homer.put("last", "Simpson");
        homer.put("city", "Springfield");

        System.out.println("What do you want to know about Homer? [first/last/city]");

        String what = new Scanner(System.in).nextLine();

        System.out.println(homer.get(what));
    }

}


text:
Q: StrawberryShake GraphQl Dto constructor can't be empty I'm having some problem with one of my data in strawberry shake. It's a simple query but when I try to create an object of it, the generated code dtoData ask for a type in the constructor.
All my other query don't required anything in the constructor.
I use the Dto for model in the ViewModel for mapping.
Example of a working one.
public clas ProjectModelVM : ViewModelBase
{
    //The ProjectDtoInput class is created by the Generation code.
    // If I create a new Instance of ProjectDtoInput the constructor is empty and it's working
    // var project = new ProjectDtoInput()

    public ProjectDtoInput _projectModel;

    public ProjectModelVM(ProjectDtoInput projectModel)
    {
        _projectModel = projectModel;
    }
}

the query is
query GetActiveProject{
    activeProject{
        cL_PROJET_NO,
        cL_PROJET_NOM
    }
}

And the Dto in the server side is
public class QmProdFormDto
{
    public int? FormID { get; set; }
    public string? FormName { get; set; }
    public string? ProjectNo { get; set; }
    public string? ProjectName { get; set; }
    public string? DivName { get; set; }
    public string? SubDivName { get; set; }
}

Example of a NON working one
public class PaintBrandModelVM : ViewModelBase
{
    // The QmProdPaintDtoData class is created by the Generation code.
    // If I create a new Instance of QmProdPaintDtoData the constructor ask me for some __type input
    public QmProdPaintDtoData _paintBrandModel;

    public PaintBrandModelVM(QmProdPaintDtoData paintBrandModel)
    {
        _paintBrandModel = paintBrandModel;
    }
}

the query is
query GetPaintLst{
  paintLst{
    paintBrandID,
    paintBrandName
  }
}

And the Dto on the server side is
public class QmProdPaintDto
{
    public int? PaintBrandID { get; set; }
    public string? PaintBrandName { get; set; }
}

I don't understand why one of the DTO ask me for mendatory input.
Can someone give me a hand on this.
Tell me if you need more of the code.
Thanks.
Jc


text:
Q: How to limit the number of boxes checked in ListView This is the first time I'm developing an Android application so this question might be a no-brainer.
I want to limit the number of checkboxes selected (i.e., the user should only be able to select a amximum of 2 checkboxes). How do I do this in onCheckedChanged()?
package com.mainak.walkbuddy;

import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class InteractiveArrayAdapter extends ArrayAdapter<Model>
{
    private final List<Model> list;
    private final Activity context;

    public InteractiveArrayAdapter(Activity context, List<Model> list)
    {
        super(context, R.layout.activity_show_content, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder
    {
        protected TextView text;
        protected CheckBox checkbox;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View view = null;
        int checkBoxCounter = 0;
        int checkBoxInitialized = 0;
        if (convertView == null)
        {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.activity_show_content, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.text = (TextView) view.findViewById(R.id.label);
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
            viewHolder.checkbox.setOnCheckedChangeListener(
                    new CompoundButton.OnCheckedChangeListener()
                    {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                        {
                            Model element = (Model) viewHolder.checkbox.getTag();
                            element.setSelected(buttonView.isChecked());
                        }
                    }
                    );
            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(list.get(position));
        }
        else
        {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.text.setText(list.get(position).getName());
        holder.checkbox.setChecked(list.get(position).isSelected());
        return view;
    }
}

A: Add an int counter representing the number of checked items, every time an Item is being checked you check if the counter is not bigger than 2.
If it is bigger than 2 then don't do anything(don't set the flag to checked), otherwise just change the flag and increment the counter.
And you should set onClickListener to the view and there change the checked flag to checked/unchecked, and then just call notifydatasetchanged() to change the checked state.
Because there might be some issues keeping the checked state when adding onCheckedChangedListener.


text:
Q: Highcharts 12hr time format of x-axis labels I have a Highcharts column chart that is fed with 24 different y-values corresponding to x values from 0-23 representing the hour of the day.
Does Highcharts have a built in format for hours 0-23 such that I can have the X-axis show time labels like this:
12am, 1am ...... 12pm, 1pm.....11pm ??
I tried this but Highcharts ignored the x-values:
series: [{
   name: 'Time of Day',
   data: [['12am', 6],['1am', 1],['3am', 1],['5am', 1],['7am', 2],['8am', 19],['9am', 54],['10am', 80],['11am', 73],['Noon', 92],['1pm', 105],['2pm', 87],['3pm', 100],['4pm', 74],['5pm', 59],['6pm', 38],['7pm', 24],['8pm', 7],['9pm', 10],['10pm', 4],['11pm', 8],]
}]

EDIT:
The data may not include a value for every hour, as you can see in this sample data.

A: You can specify the format of date/time to be displayed using the php strftime format, http://php.net/manual/en/function.strftime.php.
So for example if you want to change the hours(when and if they are displayed) and minutes(when and if they are displayed) to 12 hour format use %I instead of %H.
xAxis: {
    type: 'datetime',
    dateTimeLabelFormats: {
        day: '%e of %b',
        minute:  '%I:%M',
        hour: '%I:%M'
    }
}

jsfiddle - http://jsfiddle.net/xya6kato/

A: You can define your x-axis captions and series separately.
        xAxis: {
            categories: ['12 am', '1 am', '2 am', '3 am', '4 am', '5 am', '6 am', '7 am', '8 am', '9 am', '10 am', '11 am', 'Noon', '1 pm', '2 pm', '3 pm', '4 pm', '5 pm', '6 pm', '7 pm', '8 pm', '9 pm', '10 pm', '11 pm']
        }

        series: [{
            name: 'Time of Day',
            data: [6, 1, 3, 1, 1, 3, 2, 19, 30, 54, 80, 73, 92, 105, 87, 100, 59, 38, 24, 7, 10, 4, 8, 10]
        }]

Edit--
If you don't have data for all hours, you can define your xAxis as datetime and provide values in the series for specific hours.
        xAxis: {
            type: 'datetime',
        },
        series: [{
            name: 'Time of Day',
            data: [
                [Date.UTC(2014, 2, 28, 10), 5  ],
                [Date.UTC(2014, 2, 28, 12), 33 ],
                [Date.UTC(2014, 2, 28, 13), 20 ],
                [Date.UTC(2014, 2, 28, 15), 26 ]
            ]
        }]


text:
Q: converting output of R's "by" command to data frame I'm trying to use R's by command to get column means for subsets of a data frame.  For example, consider this data frame:
> z = data.frame(labels=c("a","a","b","c","c"),data=matrix(1:20,nrow=5))
> z
  labels data.1 data.2 data.3 data.4
1      a      1      6     11     16
2      a      2      7     12     17
3      b      3      8     13     18
4      c      4      9     14     19
5      c      5     10     15     20

I can use R's by command to get the column means according to the labels column:
> by(z[,2:5],z$labels,colMeans)
z[, 1]: a
data.1 data.2 data.3 data.4
   1.5    6.5   11.5   16.5
------------------------------------------------------------
z[, 1]: b
data.1 data.2 data.3 data.4
     3      8     13     18
------------------------------------------------------------
z[, 1]: c
data.1 data.2 data.3 data.4
   4.5    9.5   14.5   19.5

But how do I coerce the output back to a data frame?  as.data.frame doesn't work...
> as.data.frame(by(z[,2:5],z$labels,colMeans))
Error in as.data.frame.default(by(z[, 2:5], z$labels, colMeans)) :
  cannot coerce class '"by"' into a data.frame

A: The output of by is a list so you can use do.call to rbind them and then convert this:
as.data.frame(do.call("rbind",by(z[,2:5],z$labels,colMeans)))
  data.1 data.2 data.3 data.4
a    1.5    6.5   11.5   16.5
b    3.0    8.0   13.0   18.0
c    4.5    9.5   14.5   19.5

A: You can use ddply from plyr package
library(plyr)
ddply(z, .(labels), numcolwise(mean))
  labels data.1 data.2 data.3 data.4
1      a    1.5    6.5   11.5   16.5
2      b    3.0    8.0   13.0   18.0
3      c    4.5    9.5   14.5   19.5

Or aggregate from stats
aggregate(z[,-1], by=list(z$labels), mean)
  Group.1 data.1 data.2 data.3 data.4
1       a    1.5    6.5   11.5   16.5
2       b    3.0    8.0   13.0   18.0
3       c    4.5    9.5   14.5   19.5

Or dcast from reshape2 package
library(reshape2)
dcast( melt(z), labels ~ variable, mean)

Using sapply :
 t(sapply(split(z[,-1], z$labels), colMeans))
  data.1 data.2 data.3 data.4
a    1.5    6.5   11.5   16.5
b    3.0    8.0   13.0   18.0
c    4.5    9.5   14.5   19.5

A: Dealing with the by output can be really annoying. I just found a way to withdraw what you want in a format of a data frame and you won't need extra packages.
So, if you do this:
aux <- by(z[,2:5],z$labels,colMeans)

You can then transform it in a data frame by doing this:
  aux_df <- as.data.frame(t(aux[seq(nrow(aux)),seq(ncol(aux))]))

I'm just getting all the rows and columns from aux, transposing it and using as.data.frame.
I hope that helps.


text:
Q: Вернуть массив объектов класса Есть класс Field для которого я хочу написать функцию, которая вернула бы указатель или ссылку на вот этот член класса
CCell* Cell[DEFAULT_COUNT][DEFAULT_COUNT];

Вопрос банальный, но вот никак не получается написать эту функцию.
Моя попытка
CCell* CField::GetShips() {
     return Cell;
}

A: Соответствующая функция -член класса, которая возврщает ссылку на массив, может выглядеть следующим образом
CCell* ( & getArray() )[DEFAULT_COUNT][DEFAULT_COUNT]
{
    return Cell;
}

Или
typedef CCell* ( &RCell )[DEFAULT_COUNT][DEFAULT_COUNT];

RCell getArray()
{
    return Cell;
}

Или
using RCell = CCell* ( & )[DEFAULT_COUNT][DEFAULT_COUNT];

RCell getArray()
{
    return Cell;
}

В клиентском коде вы можете написать
decltype( auto ) rcell = objectOfTheClass.getArray();

или
RCell rcell = objectOfTheClass.getArray();

Или же можете явно определить ссылку.
Похожим образом будут выглядеть объявления для указателя на первый элемент массива
CCell* ( * getArray() )[DEFAULT_COUNT]
{
    return Cell;
}

Или
typedef CCell* ( *PCell )[DEFAULT_COUNT];

PCell getArray()
{
    return Cell;
}

Или
using PCell = CCell* ( * )[DEFAULT_COUNT];

PCell getArray()
{
    return Cell;
}

В клиентском коде вы можете написать
auto pcell = objectOfTheClass.getArray();

или
PCell pcell = objectOfTheClass.getArray();

Или же можете явно определить указатель.
Возможно вместо массива вам следует использовать другой контейнер, как, например, std::vector или, возможно, одномерный массив объектов типа std::array.
Например,
std::array<CCell*, DEFAULT_COUNT> Cell[DEFAULT_COUNT];


text:
Q: Penalized least squares in R Disclaimer: It might be a purely R question, but i thought i'd post it here giving the goal.
Using a smaller subset of movielens data , i'm trying to penalize sparsely rated movies by lambdas and barely rating users by zetas separately:
library(tidyverse)
library(dslabs)
data("movielens")

RMSE_adj <- function(l, z){
  dat <- movielens  #data set
  mu <- mean(dat$rating) #mean

  b_i <- dat %>%
    group_by(movieId) %>%
    summarize(b_i = sum(rating - mu)/(n()+l))

  b_u <- dat %>%
    left_join(b_i, by="movieId") %>%
    group_by(userId) %>%
    summarize(b_u = sum(rating - b_i - mu)/(n()+z))

  predicted_ratings <-
    dat %>%
    left_join(b_i, by = "movieId") %>%
    left_join(b_u, by = "userId") %>%
    mutate(pred = mu + b_i + b_u) %>%
    pull(pred)

  return(sqrt(mean((dat$rating - predicted_ratings)^2)))

}

lambdas <- seq(0, 10, 0.25)
zetas <- seq(0,10, 0.25)

rmses1 <- mapply(RMSE_adj, lambdas, zetas)

However, there is no improvement in MSE compared to using lambdas only evidenced by:
lambdas[which.min(rmses1)]
[1] 0.25
zetas[which.min(rmses1)]
[1] 0.25

I suspect the issue is in mapply function which is used pairwise , i.e., for each l=0.5, it would pull a z such as z=0.5 when lists are equal. Do I need to use some nested apply function to work around?


text:
Q: HTML Color Input "oninput" event behaving differently on Chrome on Windows On firefox, the oninput event of a color type input is fired while the OS color picker window is opened, everytime the user switches a color.
Now, on chrome it works exactly as the onchange event, it only fires if the actual color changes after pressing ok on the color picker window.
Is there a way to get the expected behavior on chrome? Is this a bug or a implementation choice?
Also, is there an event that fires even if the user doesn't change the color but only opens the color picker and presses ok? A onclick wouldn't be ideal as that would also trigger if the user presses cancel.

const colorInput = document.getElementById('color');
color.oninput = evt => {
  console.log('oninput');
}
<input id="color" type="color">

Edit : It seems that chrome and edge behave the same.

A: Unfortunately, this is a Windows limitation. The ChooseColor function is responsible for that dialog and it only outputs the color information when the user closes the dialog.
If you want the user to be able to change colors live, consider using a library like jscolor.


text:
Q: Broadband firmware upgrade My broadband- MTNL
My ISP- MTNL
When I enter my public ip address in google search, it opens some site after entering default username and password.
When I tried to update my firmware, I got stuck. See image-firmware upgrade
Now it ask locations, but I can't select a location. When I click choose file, it opens a dialog box but what file I choose I can't understand.

A: Never update firmware over WiFi. Nor from the upstream network.
Never allow your router to be accessed from the world.
It is your router, correct ?
When you downloaded the firmware (!) Where did you save it?
Did you make a backup of your firmware ?  Where did you save that?
The file should have the extension .rom or .bin - if it is compressed you may need to extract it.
It sounds like this question needs a localised answer, you should check forums and your ISP's help pages before coming here.
But seriously, disconnect from the internet first, and use an ethernet cable.
It is almost certainly a Beetel 450tc1, but your ISP may have a custom ROM image you may be required to use. This is likely given the custom logo.
Seriously as well, ask your ISP.


text:
Q: Variable in the url, xcode I need to insert a variable in the URL
Exmp: http:// www.sito.com/frasi/ip.php?destinatario= LALBELTEXT
I have this code:
//creo una costante di tipo NSURL
let url = NSURL(string: "http:// www.sito.com/frasi/ip.php?destinatario=IOS")

//creo una richiesta di accesso a quello specifico indirizzo
let request = NSURLRequest(URL: url!)
myWebView.loadRequest(request)

A: Construct the url as a string first:
    var URLstring = "http:// www.sito.com/frasi/ip.php?destinatario=\(labeltext.text)"
    var theURL = NSURL(string: URLstring)
    let request = NSURLRequest(URL: theURL!)
    myWebView.loadRequest(request)


text:
Q: Prevent USB_DEVICE_ATTACHED launching app after a reboot I have an activity listening for the USB_DEVICE_ATTACHED broadcast intent, which launches when the user plugs in my USB device and selects our app. My problem is the android host devices reboot themselves once a day (usually around 4am), at which point the attached USB_DEVICE_ATTACHED intent is also fired by itself.
In this circumstance, I definitely don't want to launch my activity as it doesn't know how to close itself. How can I prevent that from happening? I tried to use the PowerManager.isScreenOn() boolean to not launch my activity (target is API 17), but it thinks the screen is indeed on.
 PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        if (powerManager.isInteractive()) {
            startActivity(intent);
        }
    }
    else{
        //noinspection deprecation
        if (powerManager.isScreenOn()) {
            startActivity(intent);
        }
    }

A: I don't think you have enough information to determine if the USB_DEVICE_ATTACHED broadcast is due to your user plugging something in, or the device rebooting itself.
What I would do is launch the Activity in any case and have the Activity close itself if the user hasn't performed any action within a certain period of time (1 minute or 10 minutes or whatever).


text:
Q: Enquire.js seems not to work with Vue.js version 2.0 I want to use Enquire.js in my Vue.js(v 2.0) project. There are a bunch of examples on the internet where users integrating Enquire with Vue.js.
For example here: https://jsfiddle.net/Linusborg/843dk9zs/
When I integrate Enquire.js in my Vue.js/webpack project it doesn't work and gave no error messages at all in the console. I don't know exactly what I'm doing wrong here.
This is my code, located in main.js My root file for the application.
import Vue from 'vue'
import Enquire from 'enquire.js' //installed using NPM
require('./stylesheet.css')

new Vue({
  el: "#app",
  data: {
    displayIsLarge: false,
    displayIsSmall: true
  },
  ready: function() {
    var self = this;
    // Listen for changes in the browser's size
    enquire.register("screen and (max-width:400px)", {
      match: function() {
        self.displayIsSmall = true;
        console.log("the screen is now small");
      },
      unmatch: function() {
        self.displayIsLarge = true;
        console.log("the screen is now large");
      }
    })
  }


text:
Q: PHPUnit: how to mock one specific method in class which is called from not mocked one Having class like following:
class MyClass{

     public static function create($data){

         $dataModified= $self::doCurlRequest($data);

         //doing something else with data

         return $dataModifiedAlot;
     }

     public static function doCurlRequest($someData){
         //doing request here
     }

 }

is it possible to mock only the doCurlRequest($someData)? I tried this:
class MyClassTest extends PHPUnit_Framework_TestCase{

     public function testCreate(){

         $mock = $this->getMockBuilder('MyClass')->setMethods(array('doCurlRequest'))->getMock();

         $mock::staticExpects($this->any())
                ->method('doCurlRequest')
                ->with($someDataNeededForRequest)
                ->will($this->returnValue("some JSON rensponse"));

         $response = $mock::create($data);

     }

 }

and the problem is that method doCurlRequest($someData) returns the real value instead of expected one :/ A I doing something wrong?

A: You need to call the method in your class using static::doCurlRequest().  staticExpects uses late static binding to create the mock.  Because of this, the method needs to be called via static rather than self or $this-> which will call the actual method.
Your class needs to look like this:
class MyClass{

     public static function create($data){

         $dataModified= static::doCurlRequest($data);

         //doing something else with data

         return $dataModifiedAlot;
     }

     public static function doCurlRequest($someData){
         //doing request here
     }

 }

FYI: staticExpects was removed in PHPUnit 4.0
https://github.com/sebastianbergmann/phpunit/wiki/Release-Announcement-for-PHPUnit-4.0.0#backwards-compatibility-issues


text:
Q: Count with join still not displaing correct count What I am trying to do is create a list of how many replies this thread has. I can count the number of replys fine.
But what I would like to be able to do is count the user thread also.
This is what the out put looks like. It only counts it from my replys table cannot seem to get it to count from my join as well.
Username    Post
demo         2
admin        1

Should out put like
Username    Post
demo         3 <-- Because the user has asked the Question / "thread" and has replied twice
admin        1

Question How to make sure it can count the user id from the join() thread table?

Model function
public function number_of_replies($user_id, $thread_id) {
    $this->db->select('*');
    $this->db->from('reply');
    $this->db->join('thread', 'thread.user_id = reply.user_id', 'left');
    $this->db->where('reply.user_id', $user_id);
    $query = $this->db->get();

    if ($query->num_rows() > 0) {
        return $query->num_rows();
    } else {
        return 0;
    }
}

Controller
<?php

class Who_replied extends MX_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index($thread_id = '') {
        $data['users'] = array();

        $data['thread_id'] = $thread_id;

        $results = $this->get_users_who_replied($thread_id);

        if (isset($results)) {

            foreach ($results as $result) {
                $data['users'][] = array(
                    'user_id' => $result['user_id'],
                    'username' => $result['username'],
                    'total' => $this->number_of_replies($result['user_id'], $thread_id),
                );
            }

        }

        $data['total_posts'] = '';

        return $this->load->view('default/template/forum/categories/who_replied_view', $data);

    }

    public function get_users_who_replied($thread_id) {
        $this->db->select('user.username, user.user_id, reply.thread_id');
        $this->db->distinct();
        $this->db->from('reply');
        $this->db->join('user', 'user.user_id = reply.user_id', 'left');
        $this->db->join('thread', 'thread.user_id = user.user_id', 'left');
        $this->db->where('reply.thread_id', $thread_id);
        $this->db->order_by('thread.user_id', 'desc');
        $query = $this->db->get();

        if ($query->num_rows() > 0) {

            return $query->result_array();

        }
    }

    public function number_of_replies($user_id, $thread_id) {
        $this->db->select('*');
        $this->db->from('reply');
        $this->db->join('thread', 'thread.user_id = reply.user_id', 'left');
        $this->db->where('reply.user_id', $user_id);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            return $query->num_rows();
        } else {
            return 0;
        }
    }
}

Thread Table

Reply Table

A: Do sum 2 tables user_id columns
public function number_of_replies($user_id, $thread_id) {
    $this->db->select('t1.*, count(t2.user_id)+count(t1.user_id) AS total_posts');
    $this->db->from('reply AS t1');
    $this->db->join('thread AS t2', 't2.user_id = t1.user_id', 'left');
    $this->db->where('t1.user_id', $user_id);
    $query = $this->db->get();

    if ($query->num_rows() > 0) {
        return $query->num_rows();
    } else {
        return 0;
    }
}

A: I seem to have got it working mostly now bit more testing to do
What I have had to do is create to functions for counting one for replies and one for threads
public function replies_by_users($user_id, $thread_id) {
    $this->db->where('user_id', $user_id);
    $this->db->where('thread_id', $thread_id);
    return $this->db->count_all_results('reply');
}

public function thread_by_user($user_id, $thread_id) {
    $this->db->where('user_id', $user_id);
    $this->db->where('thread_id', $thread_id);
    return $this->db->count_all_results('thread');
}

Then combine them and using plus + and then return it
public function total_replies_and_thread($user_id, $thread_id) {
    return $this->replies_by_users($user_id, $thread_id) + $this->thread_by_user($user_id, $thread_id);
}

And then use the total_replies_and_thread($user_id, $thread_id) in the array itself like
$results = $this->get_replies($thread_id);

    if ($results) {
        foreach ($results as $result) {
            $data['users'][] = array(
                'reply_id' => $result['reply_id'],
                'user_id' => $result['user_id'],
                'thread_id' => $result['thread_id'],
                'username' => $result['username'],
                'total' => $this->total_replies_and_thread($result['user_id'], $result['thread_id'])
            );
        }
    }

Out put now correct

Controller HMVC
<?php

class Who_replied extends MX_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index($user_id, $thread_id) {
        $data['users'] = array();

        $results = $this->get_replies($thread_id);

        if ($results) {
            foreach ($results as $result) {
                $data['users'][] = array(
                    'reply_id' => $result['reply_id'],
                    'user_id' => $result['user_id'],
                    'thread_id' => $result['thread_id'],
                    'username' => $result['username'],
                    'total' => $this->total_replies_and_thread($result['user_id'], $result['thread_id'])
                );
            }
        }

        $data['user_id'] = $user_id;

        return $this->load->view('default/template/forum/categories/who_replied_view', $data);

    }

    // Model code is just on here for testing purpose you should all ways create a model for it self.

    public function get_replies($thread_id) {
        $this->db->select('reply.*, user.username');
        $this->db->from('reply');
        $this->db->join('user', 'user.user_id = reply.user_id');
        $this->db->where('thread_id', $thread_id);
        $this->db->group_by('user_id');
        $this->db->order_by('thread_id', 'desc');
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            return $query->result_array();
        }
    }

    public function total_replies_and_thread($user_id, $thread_id) {
        return $this->replies_by_users($user_id, $thread_id) + $this->thread_by_user($user_id, $thread_id);
    }

    public function replies_by_users($user_id, $thread_id) {
        $this->db->where('user_id', $user_id);
        $this->db->where('thread_id', $thread_id);
        return $this->db->count_all_results('reply');
    }

    public function thread_by_user($user_id, $thread_id) {
        $this->db->where('user_id', $user_id);
        $this->db->where('thread_id', $thread_id);
        return $this->db->count_all_results('thread');
    }
}


text:
Q: What is the meaning of _Space in C? I have seen this expression in the code of other developer and I cannot get the meaning of it, the code line is:
typedef struct _Space Space;

So, for the syntax I reckon that _Space  is a kind of variable or something similar but I do not know what kind of variable it is (integer, string, Boolean, etc).
Anyone have any idea??

A: struct _Space refers to a definition of a struct _Space elsewhere.  The typedef ... Space means you can refer to a struct _Space as simply Space, saving you some typing.
For example, consider the difference in brevity and clarity between
struct _Space mySpace; // Oh god! memories

vs
Space mySpace;


text:
Q: MyFirstApp android tutorial error on DisplayMessageActivity.java I been following it and i am stuck on 3 textview errors
tutorial:http://developer.android.com/training/basics/firstapp/starting-activity.html
I get 2 error saying textView cannot be resolved and one saying textView cannot be resolved as a variable. help!
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the message from the intent
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Create the text view
    TextView textview = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);

    // Set the text view as the activity layout
    setContentView(textView);

    setContentView(R.layout.activity_display_message);
    // Show the Up button in the action bar.
    setupActionBar();

`

A: You've declared it as textview (lowercase "v") but are referencing it as textView (uppercase "v"). Pick one!
TextView textView = new TextView(this); // Change the "v" to uppercase
textView.setTextSize(40);
textView.setText(message);

A: Variables in Java are case sensitive, so textView and textview are different. Change your code to this:
TextView textview = new TextView(this);
textview.setTextSize(40);
textview.setText(message);

// Set the text view as the activity layout
setContentView(textview);


text:
Q: Aggregate associatations to JSON only if they exist in Postgres SQL I'm trying to return a "complete" user object via JSON from an API that is backed by a Postgres SQL database. users can belong to teams, which are stored as memberships in a table.
My tables are setup like this:
Users
   id   |        email         | password |   name   | created_at
--------+----------------------+----------+----------+------------
 user_1 | user-one@example.com | password | User One | 2015-09-17
 user_2 | user-two@example.com | password | User Two | 2015-09-17

Teams
   id   |        email         |   name   | created_at
--------+----------------------+----------+------------
 team_1 | team-one@example.com | Team One | 2015-09-17
 team_2 | team-two@example.com | Team Two | 2015-09-17

Memberships
   id   | team_id | user_id | created_at
--------+---------+---------+------------
 memb_1 | team_1  | user_1  | 2015-09-17
 memb_2 | team_1  | user_2  | 2015-09-17

With my current query:
SELECT
  users.id,
  users.email,
  users.name,
  users.created_at,
  json_agg(teams.*) AS teams
FROM users, teams, memberships
WHERE users.id=$[id]
AND users.id=memberships.user_id
AND teams.id=memberships.team_id
GROUP BY
  users.id,
  users.email,
  users.name,
  users.created_at

For user_1 that ends up returning:
{
  "id": "user_1",
  "email": "user-one@example.com",
  "name": "User One",
  "created_at": "2015-09-17T07:00:00.000Z",
  "teams": [
    {
      "id": "team_1",
      "email": "team-one@example.com",
      "name": "Team One",
      "created_at": "2015-09-17"
    },
    {
      "id": "team_2",
      "email": "team-two@example.com",
      "name": "Team Two",
      "created_at": "2015-09-17"
    }
  ]
}

But the problem is, if I add a new user_3, they don't have any memberships yet, so the query ends up returning nothing, since there's nothing to AND users.id = memberships.user_id join on.
How can I fix this query so that when a user doesn't have any memberships it ends up with just an empty "teams": [] array?
Thanks for the help!

A: Use LEFT JOIN instead, You will get null if not matching on the other tables.
SELECT
  users.id,
  users.email,
  users.name,
  users.created_at,
  json_agg(teams.*) AS teams
FROM users
LEFT JOIN memberships
 ON users.id=memberships.user_id
LEFT JOIN teams
 ON teams.id=memberships.team_id
WHERE users.id=$[id]
GROUP BY
  users.id,
  users.email,
  users.name,
  users.created_at


text:
Q: After WordPress updated to 4.8.1, RSS feed stopped enclosing audio files? We are using the automatic RSS feeds created by WordPress to convert a page into a podcast. After WordPress updated to 4.8.1, RSS stopped enclosing the audio files and I can't figure out why.
Page in question: www.faithandvictory.com/sermons/
Feed: www.faithandvictory.com/sermons/feed/
Anybody know why it would stop and/or how to fix it?


text:
Q: How to remove specific object from an array using service in angular 9 Trying to remove one object which name is Test1 from the array object. I do not know how to remove that.If i did anything wrong in my code you can correct it. I have used service to update the array value.  you can understand If you check my stackblitz.
If i click the Remove Name  button i want to remove the object which name is Test1 from the array object.
So, Please help to find the solution.
dashboard.component.html:
<button (click)="callFun('Test1')">Remove Name</button>
 {{ deleteItemName }}
<app-optymodel></app-optymodel>

dashboard.component.ts:
callFun(name: any) {
    this.commonService.modifyDeleteItem(name);
    this.commonService.modifyNameList(name);
    this.commonService.modifyDeleteItem('');
  }

common.service.ts:
 modifyNameList(name: string) {
 const nameList = this.nameList.getValue();
 const result = nameList.filter((x) => x.name != name);
 this.nameList.next(result);
 }

 modifyDeleteItem(name: string) {
 this.deletedItem.next(name);
 }

After cliked Remove Name button result it should be like

const result = nameList.filter((x) => x != name);
console.log(result);
[
{ name: 'Test2', id: '2' },
{ name: 'Test3', id: '3' },
{ name: 'Test4', id: '4' },
{ name: 'Test5', id: '5' },
];

Demo: https://stackblitz.com/edit/angular-pass-table-data-to-input-property-zn22go?file=src%2Fapp%2Fservices%2Fcommon.service.ts

A: The code in your stackblitz is actually different than the one you showed here. The line
const result = nameList.filter((x) => x != name);

should be
const result = nameList.filter((x) => x.name !== name);

Then you will get an lint warning/compile error that the type is wrong because you have the name list defined as Array<string> while it actually should be Array<{name: string, id: string}>. I would recommend using a type or an interface for your content of the array.
And instead of Array.filter you could also use Array.splice if you just want to remove one item (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice?retiredLocale=de#remove_1_element_at_index_3)


text:
Q: Angular 6 adding change event on drop down list is giving an error of undefined value I am having a drop list generated at each row of data:
<ng-container matColumnDef="status_change">
  <th mat-header-cell *matHeaderCellDef mat-sort-header>Change Status</th>
  <td mat-header *matCellDef="let row">
    <mat-form-field>
      <form [formGroup]="sitStatus">
        <mat-select (click)="updateUnitSituationStatus()" formControlName="sitStatusControl" placeholder="Change Status To">
          <!-- <mat-option [value]="row.unit_sprotection_status">{{row.unit_sprotection_status}}</mat-option> -->
          <mat-option *ngIf="row.unit_sprotection_status!='Active'" value="Active">Active</mat-option>
          <mat-option *ngIf="row.unit_sprotection_status!='Inactive'" value="Inactive">Inactive</mat-option>
        </mat-select>
      </form>
    </mat-form-field>
  </td>
</ng-container>

I added an event to get the value of the changed drop list. In other words, if I changed the value of drop list at row id 4, I need to get the value changed, and the id of the row, so I can update my database.
I used (click) event, but an error appeared:

ERROR TypeError: Cannot read property 'value' of undefined
      at UnitEditComponent.push

Here is the method:
updateUnitSituationStatus(){
    console.log(this.formGroup.controls['sitStatusControl'].value);
}

I tried to use (change) event but nothing happened too.

A: Since you are using sitStatus form group here <form [formGroup]="sitStatus"> you should lookup control in that group as well
this.sitStatus.controls['sitStatusControl'].value

A: I havent tried on Material UI but I believe it works the same as normal select
<select (change)="onChangeEvent($event)">
    <option value="option1">My Options</option>
</select>

Then in your .ts
onChangeEvent(ev) {
    console.log(ev.target.value); // should print option1
}


text:
Q: How to prove log n! = Ω(nlog n)? I saw this proof but i didn't understand the bold part
log(n!) = log(1) + log(2) + log(3) + ... + log(n)
Deleting the first half of the terms gives
log(n!) >= log(n/2) + log(n/2+1) + log(n/2+2) + ... + log(n)
could any one explain to me this part?

A: Well, for any $k \ge 1$ we have $\log ( k) \ge 0$.
And as a sum of positive elements is positive, we have $\sum_{k=1}^{\left\lfloor\frac{n}{2}\right\rfloor -1} \log (k) \ge 0 $.
So we have $$ \log( n!) = \sum_{k=1}^n \log(k) = \sum_{k=1}^{\left\lfloor\frac{n}{2}\right\rfloor-1} \log(k) + \sum_{k = \left\lfloor\frac{n}{2}\right\rfloor}^n \log (k) \ge  \sum_{k = \left\lfloor\frac{n}{2}\right\rfloor}^n \log (k) = \sum_{k=0}^{\left\lceil \frac{n}{2} \right\rceil } \log (\left\lfloor \frac{n}{2} \right\rfloor +k)$$

A: For example when $n=6$:
$$\begin{aligned}\log(6!)&=\log(1)+\log(2)+\log(3)+\log(4)+\log(5)+\log(6)\\
&\ge\log(3)+\log(4)+\log(5)+\log(6)\\
&=\log\frac{6}{2}+\log\left(\frac{6}{2}+1\right)+\log\left(\frac{6}{2}+2\right)+\log\left(\frac{6}{2}+3\right).
\end{aligned}$$