text:
Q: How can i use a Gridview efficiently in asp.net by using only the keyboard? i need to use my gridview by using only the keyboard.My clients prefer keyboard rather than using mouse.How can i use my gridview like that?What all events should i use?

A: Are you permitted to use Javascript libraries (with or without Ajax)?
If your answer is yes then I suggest you don't reinvent the wheel on something this complex and go for something like ExtJS, even though all you'll need is a GridPanel. It has all keyboard support in it, you can use paging, sorting, filtering etc. And it also provides a very nice look and feel (even though you'll have to change it to your customer's needs).
If you won't use Ajax (XHR) calls to the server, you can still load your data into your page into JavascriptBlocks and use it on the client side to provide data for the GridPanel.
But if you are still at the very beginning of development and can still change bits of technologies used I suggest you take embrace ExtJS. Your client will love it, and you won't have to develop something that's been developed long ago.
BTW: I don't work for Ext llc even though you may thought so. I just had a routine client that used keyboard extensively.


text:
Q: Share annotated PDF from iOS When I annotate a PDF file, the annotations are correctly saved and can be seen using iOS "files" when saved there.
But, when I upload the annotated PDF on the web, or by email, the annotations aren't there anymore.
But, when saved again in "files", the annotations appears again.
How can I annotate a PDF using iOS preview, and share them by email to anyone who has or hasn't iOS ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Z3Py how to use Pi and e Is it possible to use pi, e and other non-algebraic real numbers in Z3Py?
I wouldn't want to run any C program, but directly from the Z3 Python API

A: Non-algebraic numbers are usually not supported by SMT solvers. Having said that, you can get pi in z3 indirectly via trigonometric functions, (sin, cos etc.); but the support is incomplete. (Meaning that the solver is most likely to return unknown for most inputs.)
See this answer for a related question: Support of trigonometric functions ( e.g.: cos, tan) in Z3


text:
Q: perfs manager in Ubuntu 14.04 When I was under Ubuntu 14.04, I had in the title bar a menu that allowed me to choosee between high performances or energy saving for the processor.
I want to know what app it was, I can't remember... Thermald? Conky? Perf? Something else?
And btw can it run under Kubuntu or Lubuntu?


text:
Q: Is this a valid proof of eigenvectors/values of nonzeroilty? Let $A$ be a square real matrix such that it is symmetric, show that if $Ax = \lambda x$ for some nonzero vector in $\mathbb{C}^n$, then in fact, $\operatorname{Re}(x)$ is an eigenvector of $A$ if it is nonzero given that $\lambda$ is real.
I thought that to prove that the real part of $x$ is real, I would do a contrapositive and a contradiction that is, "If $\mathbf{x}$ is non-zero, then \operatorname{Re}(x) is nonzero" will turn to "If $\operatorname{Re}(x)$ is zero, then $x$ is zero".
Proof
Fact: Eigenvectors are by definition not zero vectors
Assume that $\operatorname{Re}(x)$ is zero, then $\mathbf{x}$ is zero.
So we have $\mathbf{x} = \operatorname{Re}(x) + \operatorname{Im}(x)i = 0 + \operatorname{Im}(x) = \operatorname{Im}(x)i$
and we arrive at $\mathbf{x} = \operatorname{Im}(x)i$, however $\mathbf{x} \neq 0$, so $\operatorname{IM}(x) \neq  0$, therefore this is a contradiction and $\operatorname{Re}(x)$ is nonzero.
Q.E.D

A: Since $A$ is real $\overline{Ax}=A\bar x$ and by the properties of inner product $\lambda$ has to be a real number. So $A\bar x=\overline{Ax}=\overline{\lambda x}=\lambda\bar x$ and so $$A(\operatorname{Re}x)=A\left(\frac{x+\bar x}2\right)=\frac 12(Ax+A\bar x)=\frac 12(\lambda x+\lambda \bar x)=\lambda\operatorname{Re} x,$$
hence if $\operatorname{Re}\neq 0$ it's an eigenvector for $\lambda$.
But $\operatorname{Re}x$ can be $0$, for example taking $A=Id$, $\lambda=1$ and $x=i(1,0)$, then $Ax=x$ but of course $\operatorname{Re} x=0$.


text:
Q: R: ggmap: containing missing values (geom_point) when plottinng but no NAs values/values in range of map I'm plotting some points over a map using ggmap. This is the error message:
Removed 10 rows containing missing values (geom_point).
This is my code:
    library(ggmaps)
    library(maps)
    library(DataComputing)
    map <- get_map(location='san francisco', zoom=12, maptype = 'terrain', source = 'google', color = 'color')
    ggmap(map) %>%
    + geom_point(aes(x=longitude, y=latitude, colour = as.numeric(total)), data=district_crimes) %>%
    + scale_color_gradient(low='beige', high='blue')

Data frame
Proof that longitude and latitude are numeric.
How do get the points to plot? Thanks.

A: The suggestion of @timfaber is right. Longitude is placed on the x axis and latitude on the y axis, as you can see from the axes labels of the following plot:
ggmap(map)

Hence, the right way to plot points on your map is:
ggmap(map) +
 geom_point(aes(x=latitude, y=longitude, colour = as.numeric(total)),
   size=4, data=district_crimes) +
scale_color_gradient(low='blue', high='red')


text:
Q: Bindings doesn't work on nested template loaded by JSON in KnockoutJS Yesterday I make this question:
How can I refresh or load JSON to my viewModel on Knockout JS with complex models
Everything works OK with the fixes but when I try to use a complex json to load in the viewModel some of the buttons (specifically on Groups) doesn't work.
To resume the problem. I have a json with the previous serialized data. I use that json to fill the viewModel, this works, load correctly the data but the problem are in the "group" template, because the data is loaded but the buttons doesn't work, the only button which is working is the "remove group".
(Please refer to the image)
Any idea to fix this? Thanks.
Jsfiddle example with the problem
http://jsfiddle.net/y98dvy56/26/
!Check this picture.
The red circles indicates the buttons with problems.
The green circles indicates the buttons without problems.
Here is the body html

Knockout.js Query Builder

      Example Output

    <input type="submit" value="Save" data-bind="click: Save"/>

Condition.js:
window.QueryBuilder = (function(exports, ko){

  function Condition(){
    var self = this;

    self.templateName = 'condition-template';

    self.fields = ko.observableArray(['Points', 'Goals', 'Assists', 'Shots', 'Shot%', 'PPG', 'SHG', 'Penalty Mins']);
    self.selectedField = ko.observable('Points');

    self.comparisons = ko.observableArray(['=', '<>', '<', '<=', '>', '>=']);

    self.selectedComparison = ko.observable('=');

    self.value = ko.observable(0);
  }

  exports.Condition = Condition;
  return exports;

})(window.QueryBuilder || {}, window.ko);

Group.js
window.QueryBuilder = (function(exports, ko){

  var Condition = exports.Condition;

  function Group(){
    var self = this;

    self.templateName = 'group-template';
    self.children = ko.observableArray();
    self.logicalOperators = ko.observableArray(['AND', 'OR']);
    self.selectedLogicalOperator = ko.observable('AND');

    // give the group a single default condition
    self.children.push(new Condition());

    self.addCondition = function(){
        self.children.push(new Condition());
    };

    self.addGroup = function(){
        self.children.push(new Group());
    };

    self.removeChild = function(child){
        self.children.remove(child);
    };
  }

  exports.Group = Group;
  return exports;

})(window.QueryBuilder || {}, window.ko);

ViewModel.js
window.QueryBuilder = (function(exports, ko){

  var Group = exports.Group;

  function ViewModel() {
    var self = this;
    self.group = ko.observable(new Group());

    self.load = function (data) {
        ko.mapping.fromJS(data, self);
    }

    self.Save = function () {
        console.log(ko.toJSON(self));
    }
  }

  exports.ViewModel = ViewModel;
  return exports;

})(window.QueryBuilder || {}, window.ko);

A: Your issue is caused by the fact that the mapping plugin makes your data observable, but doesn't augment your data with the functions in your model such as the add, remove, etc... functions. If you do a console log for the json data when it's inserted into the view model you will notice that the data is observable but the functions are missing. You need to provide a mapping to customize your Group, Condition, etc.. constructors. Because the children array in your case is of mixed types (condition or group) Here is a custom mapping to take care of that:
var childrenMapping = {
    'children': {
        create: function(options) {
            var data = options.data;
            console.log(data);
            var object;
            switch(data.templateName) {
                case 'condition-template':
                    object = new QueryBuilder.Condition(data);
                    break;
                case 'group-template':
                    object = new QueryBuilder.Group(data);
                    break;
            }
            return object;
        }
    }
};

Then you simply need to provide this mapping in your initial mapping
ko.mapping.fromJS(json.group, childrenMapping, vm.group);

Then inside the constructor of the Group object:
 function Group(data){

   var self = this;

   self.templateName = 'group-template';
   ...

   ko.mapping.fromJS(data, childrenMapping, this);
}

You also need to update the Condition constructor to accept the data provided by the mapping, but since conditions don't have children you do not need to provide the childrenMapping here:
 function Condition(data){

     var self = this;

     self.templateName = 'condition-template';

     ...

     ko.mapping.fromJS(data, {}, this);
 }

I've the mapping at the end of both function so that the mapped values override you initial value.
The updated jsfiddle here:
http://jsfiddle.net/omerio/y98dvy56/32/
This answer is related:
knockout recursive mapping issue


text:
Q: How to Implement Interface with Enum Specific to Derived Class in C#? I'm trying to write an interface such as...
interface MyInterface
{
    MyObject Set(REGISTER register, PIN pin);
}

Both REGISTER and PIN are enums.  The problem I'm running into is that REGISTER is defined in my MyBaseClass and PIN is defined in MyDerivedClass.  I can live with using something like MyBaseClass.REGISTER in the interface, but that won't work for PIN.  Every derivation of MyBaseClass will have a different enumeration for PIN.  I found this other answer on SO, which seems to partially solve the problem, but it's not clear how I should then implement the function in MyDerivedClass.  Does anyone have a solution for this?

A: Try using generics:
interface MyInterface<TPin>
{
    MyObject Set(Register register, TPin pin);
}

When you implement it in each derived class, you have to tell it what the type of the pin enum is:
class MyImplementation : MyInterface<MyPin>
{
    MyObject Set(Register register, MyPin pin)
    {
        // ...
    }
}

This means that you can't have a list of MyInterface objects, but you can have a list of MyInterface<SomePin> objects. And that makes sense - if the enum is different for each implementation, then given a MyInterface, how would you know what values to pass it?


text:
Q: Update of the not immediate state in Example Counter - BloC Flutter My pubspec.yml:
  bloc: ^4.0.0
  flutter_bloc: ^4.0.0
  equatable: ^1.2.5

I created my CounterBloc:
class CounterBloc extends Bloc<CounterEvent, int> {
  @override
  int get initialState => 0;

  @override
  Stream<int> mapEventToState(event) async* {
    if (event.status == EventStatus.INCREMENT) {
      yield state + event.value;
    } else if (event.status == EventStatus.DECREMENT) {
      yield state - event.value;
    }
  }
}

enum EventStatus { INCREMENT, DECREMENT }

class CounterEvent {
  final int value;
  final EventStatus status;

  const CounterEvent({this.value, this.status});
}

void main() => runApp(CounterApp());

class CounterApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'BLoC Demo',
      home: BlocProvider<CounterBloc>(
        create: (context) => CounterBloc(),
        lazy: false,
        child: TestBlocWidget(),
      ),
    );
  }
}

class TestBlocWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counterBloc = BlocProvider.of<CounterBloc>(context);
    return Scaffold(
      body: Center(
        child: BlocBuilder<CounterBloc, int>(
          builder: (ctx, state) {
            return Text(
              'count: $state',
              style: TextStyle(fontSize: 28),
            );
          },
        ),
      ),
      floatingActionButton: Align(
        alignment: Alignment.bottomRight,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            FloatingActionButton(
              onPressed: () async {
                print("test 0 = " + counterBloc.state.toString());
                counterBloc.add(CounterEvent(value: 1, status: EventStatus.INCREMENT));
                print("test 1 = " + counterBloc.state.toString());
              },
              child: Icon(Icons.add_circle),
            ),
            FloatingActionButton(
              onPressed: () {
                print("test 2 = " + counterBloc.state.toString());
                counterBloc
                    .add(CounterEvent(value: 1, status: EventStatus.DECREMENT));
                print("test 3 = " + counterBloc.state.toString());
              },
              child: Icon(Icons.remove_circle),
            ),
          ],
        ),
      ),
    );
  }
}

Then my question is:
Inside FloatingActionButton, I increment value to my state;
But I print before increment and after increment and the state is the same value;
test 0 = 0;
test 1 = 0;
Why?
In the screen reflect my value, but not immediately in my prints inside FloatingActionButton;
After I tested this:
            FloatingActionButton(
              onPressed: () async {
                print("test 0 = " + counterBloc.state.toString());
                counterBloc
                    .add(CounterEvent(value: 1, status: EventStatus.INCREMENT));
                await Future.delayed(Duration(milliseconds: 0));
                print("test 1 = " + counterBloc.state.toString());
              },
              child: Icon(Icons.add_circle),
            ),
    ```

Note: I put "await Future.delayed", after my CounterBloc, with value 0 in my FloatingActionButton;
Works;
test 0 = 0;
test 1 = 1;

A: That is because of how the scheduler works. Dart code is executed on a single event loop. The order in which instructions are executed is influenced by await.
Without the Future.delayed (you could have used Future.delayed(Duration.zero) by the way) when code in the onPressed lambda is executed entirely sequentially. The add method calls mapEventToState which is an async method (generator really). When Dart encounters such a method it will schedule it for later execution and progress to the next instruction. Therefor you will see 0 twice.
This changes when you add an await call like your Future.delayed. Dart will then stop and see what else it can run. In this case the mapEventToState. It will run that one and after it will continue on with the remainder of the onPressed lambda. That is why you see 1 with the awaited Future.delayed.


text:
Q: Random selection of a committee Hello and thanks for looking at my questions.
I'm sure this is a very simple question but I just cant seem to understand it
A committee of three is selected from a pool of five individuals : two females (A and B) and three males (C,D,E)
If the committee is selected at random, what is the probability that contains both females?
(i figured for this one it would be P=(2/5)*(1/4) because the first one selected has a 2/5 chance of being a women, and the second one has a 1/4 chance but I was told that was not correct)
and
If instead, the committee is selected by randomly selecting one of the two females, one of the three males, and then one of the remaining three individuals, what is the probability it contains both females

A: This was wrong because you implicitly assumed that the two females will be choosen in the first two places. As, you point in the last three lines, this can be done also in a different order.
Using combinations (or even the hypergeometric distribution if you are familiar with it) you can approach it as follows

*

*The possible ways to choose the 3-person committee are $$\dbinom{5}{3}$$

*The favourable ways to choose the 3-person committee, i.e. the ways in which 2 females and 1 male are choosen are $$\dbinom{2}{2}\dbinom{3}{1}$$ Thus, by the classical definition (favourable over possible) we have that the requested probability is equal to $$\frac{\dbinom{2}{2}\dbinom{3}{1}}{\dbinom{5}{3}}=\large\frac{\frac{2!}{2!0!}\cdot\frac{3!}{2!1!}}{\frac{5!}{3!2!}}=\frac {3}{10}$$

Using the hypergeometric distribution (by denoting with $X$ the number of females in the committee), your paramaters would be $N=5$, $K=2$, $n=3$ (following Wikipedia notation) and you would be asking the probability $P(X=2)$.

A: For your first question the answer of Stefanos is excellent. For your second question:
If one female and one male have been chosen then there are $3$ persons left and exactly one of them is female. So the chance that a female will be chosen is $\frac{1}{3}$, and choosing a female in this situation is the 'same thing' as ending up with a committee that contains both females.


text:
Q: Testing location services on device I am trying to test background location changing using startMonitoringSignificantLocationChanges
In the simulator, I can enable Freeway Drive mode and I get regular calls to locationManager:didUpdateLocations: which is great.=, the problem is debugging when the app is terminated and it's meant to be woken up.
I have changed the RUN scheme to "Wait for my.app to launch" and again this works good as the debugger waits for the app to become active. The downside is, I can't view any NSLogs and the simulator doesn't have a way to view the Device Logs.
So I moved over to device as I thought at least I can view the Device Logs, however the device doesn't have a Freeway Drive mode.
I've created a .gpx file like this:
<?xml version="1.0"?>
<gpx version="1.1" creator="Xcode">
    <wpt lat="37.331705" lon="-122.030237"></wpt>
    <wpt lat="37.331705" lon="-122.030337"></wpt>
    <wpt lat="37.331705" lon="-122.030437"></wpt>
    <wpt lat="37.331705" lon="-122.030537"></wpt>
    <wpt lat="37.331705" lon="-122.031437"></wpt>
    <wpt lat="37.331705" lon="-122.031537"></wpt>
    <wpt lat="37.331705" lon="-122.031437"></wpt>
    <wpt lat="37.331705" lon="-122.032537"></wpt>
    <wpt lat="37.331705" lon="-122.032437"></wpt>
    <wpt lat="37.331705" lon="-122.032537"></wpt>
    <wpt lat="36.331705" lon="-122.030437"></wpt>
    <wpt lat="36.331705" lon="-122.030537"></wpt>
</gpx>

And in the RUN scheme set it as the default location.
I can see that the coordinates of the device are changing as I fly through the default maps app, however none of the locationManager delegate methods are being called like they where in the simulator.
Any help appreciated on how I can test this.
Thanks

A: You can use something like this https://github.com/futuretap/FTLocationSimulator. Or modify it to better fill your needs(my answer from here)
Edit
(I'm one of the authors) https://github.com/Azoft/FakeGPSUtility - can be helpful too.


text:
Q: mock implementation for feign client would not be autowire i want to test my spring project. i need to mock a feign client in a test class but normal implementation would be autowired instead of mock implementation. here is top of my codes. plz help.
@Profile("test")
@Primary
@Component
public class PushDevClientMock implements PushDevClient {

//apiKey is needed for comminucating with GCM
private static final String apiKey = "AIzaSyC7nH1yMgfGnEHbOHCgAeOrspMReaj0hCg";
@Override
public ResponseEntity<PushInstanceResponse> getPushInstance(@PathVariable("instanceId") String instanceId) {

    ResponseEntity<PushInstanceResponse> response;
    if (instanceId == null) {
        response = new ResponseEntity<PushInstanceResponse>(HttpStatus.BAD_REQUEST);
    }
    else {
        PushInstanceResponse body = new PushInstanceResponse();
        body.setApiKey(apiKey);
        response = new ResponseEntity<PushInstanceResponse>(body,HttpStatus.ACCEPTED);
    }

    return response;
}

}
here is my test class:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest({"server.port:0", "spring.profiles.active:test"})
public class RegistrationControllerTest {

@Autowired
WebApplicationContext wac;

@Autowired
TokenRepository tokenRepository;

private static MockMvc mockMvc;
private static ObjectMapper mapper = new ObjectMapper();
//    token and sender id are required for communicating with google
private static String senderId = "553921561995";
private static String token =
"ecdNq6_jeTM:APA91bEgWsJeIS5cXFwWrj_83EKeLWRFf1" +
        "-     lNQGXA1uWdzrfHLpd7fAY7ur6Pplc4TQuKmEDiSUhUBhDdQLwG2a_fxdgoGbDrKNLjPm2E7JOMJFjk65jtFGHrjJ39NkgABtfn6MDVUCQ";

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(springSecurity()).build();
    tokenRepository.deleteAll();
}

A: Annotate RegistrationControllerTest with @ActiveProfiles("test").

A: *

*I removed @EnableFeignClients  from Application.java

*Add empty configuration class like this :
@Configuration
@Profile("!test")
@EnableFeignClients(basePackages = "ir.pegahtech.backtory.push_api") //this is my project root
public class FeignClientConfiguration {
}

Now everything works fine


text:
Q: How to automatically capture respondent's email ID in Google Sheet? I am sending a survey sheet to participants to their email ids. I am able to capture and see the responses to each question asked. However, I am not able to see the corresponding Respondent's email id.
Is there any way to auto capture the respondent's email address automatically in the response sheet?

A: Go to your form and click on 'Settings' icon. There you will find a checkbox to collect email address of the respondent and save it. You can now see a column in the response sheet which contains email addresses.

A: I use the Google Forms Pre-Filled Answers feature. This allows you to pre-fill a form value when you send it out to someone. This is described here:
Follow the steps here: https://support.google.com/docs/answer/2839588?hl=en
You will get a form URL with an email query string parameter like this which you can then modify by changing the email address for each user:
https://docs.google.com/forms/d/e/111122223333/viewform?usp=pp_url&entry.1731330325=me@example.com
Here are some high level steps to accomplish this:

*

*Open a form in Google Forms

*In the menu bar, click Responses > Get pre-filled URL

*Click the email field and enter a test value

*Click submit

*Choose Get pre-filled link and identify the parameter name associated with the email address you entered

*Create a program that does a "mail merge" with the URL adding the recipient's email address to the parameter in question for each recipient email


text:
Q: NegativeColors in Highcharts with R I'm trying to plot a graph with two colors according if it is positive or negative values, using highchart in R. I simplify a code in the next way:
x <- c(-3, -4, 1, 4, 8)

dt <- seq(as.Date("2018-01-01"), as.Date("2018-01-05"), by = "days")

ts <- xts(x, dt )
names(ts)="serie"
print(ts)

highchart(type="stock") %>%
  hc_add_series(ts$"serie",
                type = "lollipop",
                color="black")

I'm trying to plot the graph with black color for positive values and green color for negative ones. I checked that we can use negativeColor in JS, ¿is there a way to use this on R? For example in JS: https://jsfiddle.net/BlackLabel/9ay8vezd/

A: You could simply add negativeColor = 'green' as an argument to hc_add_series:
library(highcharter)

x <- c(-3, -4, 1, 4, 8)

dt <- seq(as.Date("2018-01-01"), as.Date("2018-01-05"), by = "days")

ts <- xts::xts(x, dt )
names(ts)="serie"

highchart(type="stock") %>%
  hc_add_series(ts$"serie",
                type = "lollipop",
                color =  'black',
                negativeColor = 'green')


text:
Q: Set Duplicate Row as One Row AND one Different Column Value Merge I have ONE table like this
in this table orderID column is repeat but its CollectDate is different
So i want to SET MY table AS means IF OrderID Same then concatenate Collect Date

MY query is following and its work
            SELECT distinct df.OrderId as OrderId,df.FileName as FileName, df.RandomKey as RandomKey,
            df.ClientId as ClientId, df.ProjectId as ProjectId, df.Status as Status,df.UserId as UserId,
            df.emailTo as emailTo,df.PackageType as PackageType,df.RequestedDatetime as RequestedDatetime,
            STUFF(
            (SELECT '  |  ' +  convert(varchar(10),ord.CollectDate, 101)

            FROM SMXPSU.OrderDetails ord
            WHERE df.OrderId =ord.OrderId --and ord.OrderId in(getdate()-30)
            FOR XML PATH('')),1,1,'') AS CollectDate
            FROM SMXPSU.downloadfiles  AS df
            INNER Join
              SMXPSU.OrderDetails ord (NOLOCK)
            ON df.OrderId=ord.OrderId
            WHERE df.ClientId='shaw22'  and df.PackageType='Hard Copy' and df.RequestedDatetime>=getdate()-30
            GROUP BY df.OrderId,FileName,PackageType,RequestedDatetime,RandomKey,ClientId,ProjectId,Status,UserId,emailTo,PackageType,RequestedDatetime,CollectDate

            order by df.OrderId desc ![enter image description here][3]

But Output give me like this

Means if CollectDate same then cumming multiple time but i want only one time if same

A: SELECT OrderId, RandomKey, PackageType, RequestedDate,
CASE
WHEN COUNT(*)=1 THEN CAST(MIN(CollectDate) AS VARCHAR(20))
ELSE CAST(MIN(CollectDate) AS VARCHAR(20)) + '-' + CAST(MAX(CollectDate) AS VARCHAR    (20)) AS CollectDate
FROM
Table
GROUP BY OrderId, RandomKey, PackageType, RequestedDate

A: You can try the following query
;WITH order_cte
AS
(
    SELECT OrderId,RandomKey,PackageType,RequestedDate,
    (
        SELECT CAST(CAST(orders.CollectedData AS DATE) AS VARCHAR)  + '-' AS 'text()'
        FROM Orders WHERE Orders.OrderId=o.OrderId
        FOR XML Path('')
    ) [CollectDate]
    FROM Orders o
    GROUP BY OrderId,RandomKey,PackageType,RequestedDate
)
SELECT OrderId,RandomKey,PackageType,RequestedDate,LEFT([CollectDate],LEN([CollectDate])-1) AS [CollectDate]
FROM order_cte;


text:
Q: Why Flask does not traceback when it recognizes bad DB connection? Could not find any answer to this, I try to create two separated objects for different configurations to separate development environment from production.
So I came up with this config.py file

class BaseConfig:
    SECRET_KEY = 'MYSECRET'

class DevConfig(BaseConfig):
    SQLALCHEMY_DATABASE_URI = 'sqlite:///market.db'
    DEBUG = True

class ProdConfig(BaseConfig):
    DEBUG = False
    pg_user = 'admin'
    pg_password = 'admin'
    pg_db = 'mytable'
    pg_host = 'localhost'
    pg_port = '5432'
    SQLALCHEMY_DATABASE_URI = f"postgresql://{pg_user}:{pg_password}@{pg_host}:{pg_port}/{pg_db}"

Now I have this config file, I want to test out and see failure by purpose when I create a Flask instance and read from ProdConfig object (Note: I still don't have Postgres instance running on localhost), but I expect for a connection failure when I start my app. But why it lets me to even run the application?
Project has one package, so here is __init__.py of one of my packages:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from market.config import DevConfig, ProdConfig

app = Flask(__name__)
app.config.from_object(ProdConfig) # Note this one!

db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = "login_page"
login_manager.login_message_category = "info"

And I have a run.py outside of the package that imports this package, so:
from market import app
#Checks if the run.py file has executed directly and not imported
if __name__ == '__main__':
    app.run()

I would expect Flask to fail immediately when the connection could not be established against the DB.


text:
Q: Android Swipe Tabs without Action Bar By Using Vertical Layout On Screen Here is my code in onCreate() function;
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);

The problem is that, When I write and compiler this code, I cannot get the result which I wanna see on the screen. I just want to see the swipe tabs without action bar.
Here is the result by image;
enter image description here

A: Remove your ActionBar and use TabLayout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="fixed"
    app:tabGravity="fill" />

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="net.voidynullness.android.tabitytabs.TabLayoutActivity">

</android.support.v4.view.ViewPager>

A: Edit your styles.xml under res - > values - > styles.xml and set parent to parent="Theme.AppCompat.Light.NoActionBar"
<resources xmlns:tools="http://schemas.android.com/tools">

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->

</style>

</resources>

and remove
getSupportActionBar().setDisplayShowHomeEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);

from onCreate() of Activity


text:
Q: TaskTimer not working in a game loop I want to make a simple pause function that is within a game loop that uses TaskTimer, but it's not functioning. Is there something wrong with the task timer? Should I be using another util? I've been stuck on this for a while now.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;

public class test extends JFrame implements KeyListener, Runnable {
    public boolean pause = false;

    public test() {
        new JFrame();
        addKeyListener(this);
        setVisible(true);
    }

@Override
public void run() {
    // TODO Auto-generated method stub

    while (true) {
        if (pause) {
            System.out.println("Paused");
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    System.out.println("Some Pause Related Task");
                    pause = false;
                }
            }, (long) 3000);
        }
    }
}

@Override
public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent e) {
    char c = e.getKeyChar();
    if (c == KeyEvent.VK_SPACE) {
        System.out.println("typed space");
        pause = true;
    }
}

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

A: *

*JFrame isn't focusable JComponents, won't react to KeyEvent, then (never) KeyListener doesn't works, is required to use focusable JComponent (put there JPanel and to with setFocusable()), but not proper of possible ways

*Swing JComponents are designated to use KeyBindings instead of lowlevel KeyListener (with another side effect in compare with KeyBindings)

*use KeyListener only in the case that there are three or more Keys pressed e.i.

*use Swing Timer instead of util.Timer, output from Swing Timer notified EDT, otherwise you have to calculating with Concurency in Swing

A: I recommend you use a swing timer instead of a utility timer. It is tailored for swing apps that need a periodic callback. The callbacks go to an ActionListener and occur in the EDT. I am also puzzled by the line new JFrame() in your constructor. It, quite frankly, is useless.

A: You never call run() to start the timer. I also recommend following tbodt's advice to use swing Timers instead of the general purpose timers in swing programs.
public void main() {
    // Swing components should be modified only in the event dispatch thread.
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            test t = new test(); // test class should really be renamed to Test to follow java naming conventions
            t.run();
        }
    });
}

Furthermore, remove the while loop. Otherwise you create new timers until you run out of memory - you need only one. The timer will take care of the repeats. Just call timer.stop() when you want to pause.

A: Yeah use the correct Timmer. This one is for regular Tasks not intended to controll the main game loop. Better switch now, to avoid problems with TimerTask in later development. Why you dont like the truth?


text:
Q: Design event view using swift i want to make a view for event details, using swift, something like this one:

what do you suggest me to use? tableview? collectionview? every events has a different numbers of rows and every row can have a different height, example based on text.
Is there some example on the web?
Thanks!

A: I suggest a tableView and everything row should be in section.

*

*Sections:

*

*image section

*action section

*date section

and so for forward. For the sections you can use and enum so you don't use directly ints. Then every section has one row usually. The final design should result pretty clean.


text:
Q: Cakephp's beforeSave() not retaining new data using $model::save() When i do debug($this->data) on SalasController reservar() method, $data from json is ok, but when i do this->Sala->save($this->data), and try debug($data) on beforeSave() return that:
Notice (8): Undefined property: FormataDataBehavior::$data [APP\Model\Behavior\FormataDataBehavior.php, line 52]
\app\Model\Behavior\FormataDataBehavior.php (line 52)
null

SalasController.php
App::uses('AppController', 'Controller');

class SalasController extends AppController {

public $components = array('RequestHandler');

public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('listar', 'reservar');
    $this->RequestHandler->addInputType('json', array('json_decode', true));
}
    public function reservar() {
    $this->Sala->save($this->data); //no conditions just for debugging.
}

Model Sala.php
class Sala extends AppModel {

public $useTable = 'agenda';
public $actsAs = array(
    'FormataData' => array('dia')
);

Behavior
class FormataDataBehavior extends ModelBehavior {

// Armazena os campos do model a serem formatados.
public $campos;

//Inicializa o behavior
public function setup(Model $model, $settings = array()) {
    if (!empty($settings)) {
        $this->campos[$model->name] = $settings;
    } else {
        throw new MethodNotAllowedException('Campos data não informados na declaração do behavior');
    }
}

public function beforeSave(Model $model, $options = array()) {
    parent::beforeSave($model, $options);
    debug($this->data); //trying show data, but is !isset... =/
    die();
}

MyJs
function adicionarReserva() {
var dadosForm = {Sala: {}};
$.each($("#form-reservas").serializeArray(), function(index, value) {
    dadosForm.Sala[value.name] = value.value;
});
$.post("/intracake/Salas/reservar.json", dadosForm)
        .done(function(data) {
            sysMsg(data.html);
            atualizaTabelas();
        });
}

A: My beforeSave after @Holt tips;
public function beforeSave(Model $model, $options = array()) {
    parent::beforeSave($model, $options);
    $this->formataBeforeSave($model);
    return true;
}

public function formataBeforeSave(Model &$model, $padrao = 'Y-m-d') {
    foreach ($this->campos[$model->name] as $campo) {
        if (isset($model->data[$model->name][$campo]) && !empty($model->data[$model->name][$campo])) {
            $model->data[$model->name][$campo] = $this->converte($model, $model->data[$model->name][$campo], $padrao);
        }
    }
}


text:
Q: I have validation error for graphql query My query
query MyQuery($resourceId: ID) {
  resource(id: resourceId) { name }
}

I have an error: Field "resourceId" argument "id requires type ID found ID.

A: trying
query MyQuery($resourceId: ID) {
  resource(id: $resourceId) { name }
}


text:
Q: Sending Email with an Attachment Good day. I'm trying to make an application that allows you to select an image (from the gallery in any place where there are images) and send it by email. Search on all sides but you can not manage to send the image, sending only text is simple ... but with the image becomes complicated. I attach a code that I think is the most likely to walk. It is not my property, then I leave the link of the creator.
https://www.javacodegeeks.com/2013/10/send-email-with-attachment-in-android.html
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {

   EditText editTextEmail, editTextSubject, editTextMessage;
   Button btnSend, btnAttachment;
   String email, subject, message, attachmentFile;
   Uri URI = null;
   private static final int PICK_FROM_GALLERY = 101;
   int columnIndex;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          editTextEmail = (EditText) findViewById(R.id.editTextTo);
          editTextSubject = (EditText) findViewById(R.id.editTextSubject);
          editTextMessage = (EditText) findViewById(R.id.editTextMessage);
          btnAttachment = (Button) findViewById(R.id.buttonAttachment);
          btnSend = (Button) findViewById(R.id.buttonSend);

          btnSend.setOnClickListener(this);
          btnAttachment.setOnClickListener(this);
   }

   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
                 /**
                  * Get Path
                  */
                 Uri selectedImage = data.getData();
                 String[] filePathColumn = { MediaStore.Images.Media.DATA };

                 Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
                 cursor.moveToFirst();
                 columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                 attachmentFile = cursor.getString(columnIndex);
                 Log.e("Attachment Path:", attachmentFile);
                 URI = Uri.parse("file://" + attachmentFile);
                 cursor.close();
          }
   }

   @Override
   public void onClick(View v) {

          if (v == btnAttachment) {
                 openGallery();

          }
          if (v == btnSend) {
                 try {
                       email = editTextEmail.getText().toString();
                       subject = editTextSubject.getText().toString();
                       message = editTextMessage.getText().toString();

                       final Intent emailIntent = new Intent(
                                     android.content.Intent.ACTION_SEND);
                       emailIntent.setType("plain/text");
                       emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                     new String[] { email });
                       emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                     subject);
                       if (URI != null) {
                              emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
                       }
                       emailIntent
                                     .putExtra(android.content.Intent.EXTRA_TEXT, message);
                       this.startActivity(Intent.createChooser(emailIntent,
                                     "Sending email..."));

                 } catch (Throwable t) {
                       Toast.makeText(this,
                                     "Request failed try again: " + t.toString(),
                                     Toast.LENGTH_LONG).show();
                 }
          }

   }

   public void openGallery() {
          Intent intent = new Intent();
          intent.setType("image/*");
          intent.setAction(Intent.ACTION_GET_CONTENT);
          intent.putExtra("return-data", true);
          startActivityForResult(
                       Intent.createChooser(intent, "Complete action using"),
                       PICK_FROM_GALLERY);

   }}

activity_main.xml
 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
tools:context=".MainActivity" >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    android:padding="5dp" >

    <EditText
        android:id="@+id/editTextTo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="5dp"
        android:hint="Email Address!"
        android:inputType="textEmailAddress"
        android:singleLine="true" />

    <EditText
        android:id="@+id/editTextSubject"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextTo"
        android:layout_margin="5dp"
        android:hint="Subject"
        android:singleLine="true" />

    <EditText
        android:id="@+id/editTextMessage"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@id/editTextSubject"
        android:layout_margin="5dp"
        android:gravity="top|left"
        android:hint="type message here!"
        android:inputType="textMultiLine" />

    <Button
        android:id="@+id/buttonSend"
        android:layout_width="80dp"
        android:layout_height="50dp"
        android:layout_below="@id/editTextMessage"
        android:layout_margin="5dp"
        android:text="Send" />

    <Button
        android:id="@+id/buttonAttachment"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="attachment" />
</RelativeLayout>

AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

I think the error arises when you try to get the address of the file.
In this part:
 Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
        cursor.moveToFirst();
        columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        attachmentFile = cursor.getString(columnIndex);
        Log.e("Attachment Path:", attachmentFile);
        URI = Uri.parse("file://" + attachmentFile);
        cursor.close();

I hope you can help me with this problem, or guide me in the creation of another code. What I need is for the user to choose the image that he wants to send and this was sent by email.
Sorry if there is something wrong written. English is not my native language.


text:
Q: R Plotly Tornado Chart with Non-zero Center Can someone help to edit the code below so that the center of the tornado chart moves from zero to a positive number:
library("plotly")
x <- c(1,2,3,4)
name <- c("x1", "x2", "x3", "x4")
plot_ly() %>%
    add_trace(p, type = "bar",
              x = -x, y=name,
              orientation = 'h', name = "P10") %>%

    add_trace(p, type = "bar",
              x = x, y=name,
              orientation = 'h', name = "P90") %>%

    layout(p, title = "", barmode = "overlay",
           autosize = TRUE,
           showlegend = TRUE)


text:
Q: Rewrite URL from plural to singular How can all URLs that are plural and followed by /<integer> be redirected to the singular name along with the integer as a parameter.  See below for examples. Ideally "users" need not be hardcoded, and "vendors" would redirect to "vendor" the same way.  Note that I am not using any server code (i.e. PHP, etc).
users.html (not that this page is plural)
John Doe
Jan Doe
Baby Doe

Current configuration is as follows.
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName admin.facdocs.example.net
        DocumentRoot /var/www/facdocs/frontends/admin/public
        <Directory "/var/www/facdocs/frontends/admin/public">
            #Options Indexes FollowSymLinks MultiViews
            Options Indexes FollowSymLinks
            AllowOverride All
            Order allow,deny
            allow from all
            RewriteEngine On
            LogLevel info rewrite:trace3
            RewriteBase /

            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteRule ^([A-Za-z]+)s/(\d+)/?$ $1.html?id=$2 [L]
            RewriteBase /

            RewriteCond %{REQUEST_URI} !^.*\.html$
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteRule ^(.*)$ %{REQUEST_FILENAME}.html
        </Directory>
        Include /etc/letsencrypt/options-ssl-apache.conf
        SSLCertificateFile /etc/letsencrypt/live/api.example.net/cert.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/api.example.net/privkey.pem
        SSLCertificateChainFile /etc/letsencrypt/live/api.example.net/chain.pem
    </VirtualHost>
</IfModule>

A: To handle plurals only as words ending in s and only if a corresponding .html exists, you may match as:
RewriteEngine On
# The actual file does not exist already as a file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Alpha excluding final `s` captures in $1
# Numeric value in $2 with optional trailing slash
RewriteRule ^([A-Za-z]+)s/(\d+)/?$ $1.html?id=$2 [L]

A plural word (ending in s) without a corresponding singular .html will resutl in a 404.
Note: The above assumes a <Directory> or .htaccess context. If you put this in a server-level or <Location>, use a leading slash
RewriteRule ^/([A-Za-z]+)s...

And this also assumes case-sensitivity between the input plural and corresponding .html.


text:
Q: Confused about the warning "Cannot resolve variable" In login.java I am using req.setAttribute("username", req.getParameter("username")); and in welcome.jsp I am using Hello ${username} but Intellij gives me the warning:

Cannot resolve variable 'username'

The variable works. Why do I get this warning?
login.java
package ch.yourclick.zt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("username", req.getParameter("username"));
        req.setAttribute("password", req.getParameter("password"));
        req.getRequestDispatcher("/welcome.jsp").forward(req, resp);
    }
}

A: May be your login.java you use sendRedirect to welcome.jsp page and it lost request scope variable.
response.sendRedirect("welcome.jsp");

In login.java you need change to this to keep username variable
RequestDispatcher requestDispatcher = request.getRequestDispatcher("welcome.jsp");
requestDispatcher.forward(request, response);

For prevent warning you can update setting for Intellij > Setting > Code Inspection
https://www.jetbrains.com/help/idea/code-inspection.html

A: You have 2 options:
Option 1
<% String username = (String) request.getAttribute("username"); %>
<%= username %>

Option 2
${requestScope.username}


text:
Q: Count concurrent Calls from Calllog there is a list of Calls, with starttime, stoptime, duration, caller and some other Attributes. Now I try to visualize the concurrent Calls from this list, but I don't know how to start with this task. I want realize this task in .net C#.
First idea was to take each call, and count it to an Array for each second, then I have an array which counts the call for every second, but it is not so nice I think.
 class CallConcurrentCounterController
{
    static void Main(string[] args)
    {
        var Calls = new ImportDataFromCSV();
        DataTable dataTable = Calls.GetDataTable(Path,Seperator);

        DateTime startTime = new DateTime(2011,07,01);
        callsBucket(dataTable,startTime);
    }
    public void callsBucket(DataTable Calls, DateTime startTime)
    {
        var callsBuckets =
            from time in Enumerable.Range(0, (60 * 24))
                .Select(i => startTime.AddMinutes(i)) // Create the times base on start time and current minute.
            select new // Create an anonymous type
            {
                // Create a property called Time, that stores the time checked
                Time = time,
                // Another property that stores the number of calls happening at that time.
                //CallCount = Calls.Rows.Count(Call => Call.start <= time && Call.stop >= time)
                CallCount = Calls.AsEnumerable().Count
                    (Call => DateTime.Parse(Call.ItemArray[0].ToString() + " " + Call.ItemArray[1].ToString()) <= time &&
                             DateTime.Parse(Call.ItemArray[0].ToString() + " " + Call.ItemArray[2].ToString()) >= time)
            };
    }
}

From the function who is calling this function is given a DataTable with n Rows each Row is a Call with the Attributes start ItemArray[1] (for start-Time), stop ItemArray[2] (for stop-Time), Date ItemArray[0] and some other Attributes such Caller-Number...
Now I get a bucket which counts the calls by minute. But how I can convert the Type of callsBuckets to an type like Enumerable<dateTime,int>?

A: Something like the following should get you started.
This creates minute windows (covering the whole day, 60 mins per hour, 24 hours per day) from a given start time.
It then counts all calls that start before, and finish after that time. You could change the Count call to a Where, to keep the details of the individual calls that were occurring during each time.
var startTime = new DateTime.Today().AddDays(-1); //When to start the minute interval buckets
var callsBuckets =
    from time in Enumerable.Range(0, (60 * 24) // Minutes in a day
                           .Select(i => new DateTime(startTime).AddMinutes(i) // Create the times base on start time and current minute.
    select new // Create an anonymous type
    {
        // Create a property called Time, that stores the time checked
        Time = time,
        // Another property that stores the number of calls happening at that time.
        CallCount = Calls.Count(Call => Call.StartTime <= time && Call.StopTime >= time)
    };

Now that you've shown you're using a DataTable, see the accepted answer to this question: LINQ query on a DataTable.

A: You need to start by writing a method which determines whether two DateTime ranges overlap. Once that method is working, simply look for a call in your list that has the most number of overlaps. Alternatively, if you need to determine the number of calls at a particular time, simply write a method that checks whether the range covers this time value, and do a Count() on your list of calls.


text:
Q: EditText.getText().toString() is not returning current value I´m trying to get the text that was inserted into a EditText in the UI.
The UI looks like this. In a fragment the EditText for name has a default value "Hello".

After the user has entered a new value (for example "Hello2") I´d like to get the new value when the user clicks the Add Button.

But what I recive is still the default value "Hello".
My Code looks like this:
XML
<TextView
    android:id="@+id/textView_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:backgroundTint="@color/backgroundtint_color"
    android:text="Name"
    android:textColor="@color/ntext_foreground"
    android:textSize="@dimen/ntext_fontsize"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.075"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/textview_addingredient"
    app:layout_constraintVertical_bias="0.050" />

JAVA Code in Fragment
public class AddIngredient extends Fragment{

//Controls
public EditText etN;
public EditText etK;
public EditText etF;
public EditText etC;
public EditText etP;
public TextView tv1;

//ViewModel
AddIngredientViewModel model;

@Override
public View onCreateView(
        LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState
) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_addingredient, container, false);

    // Get the values
    tv1 = rootView.findViewById(R.id.textview_addingredient);
    etN = rootView.findViewById(R.id.editText_name);
    etK = rootView.findViewById(R.id.editText_kcal);
    etF = rootView.findViewById(R.id.editText_fat);
    etC = rootView.findViewById(R.id.editText_carbs);
    etP = rootView.findViewById(R.id.editText_protein);

    // Inflate the layout for this fragment
    return rootView;
}

public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    view.findViewById(R.id.fragmentbutton_addingredient).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //Get current values
            String name = etN.getText().toString();
            int kcal = Integer.parseInt(etK.getText().toString().trim());
            int fat = Integer.parseInt(etF.getText().toString().trim());
            int carbs = Integer.parseInt(etC.getText().toString().trim());
            int protein = Integer.parseInt(etP.getText().toString().trim());

            model = new ViewModelProvider(requireActivity()).get(AddIngredientViewModel .class);

            Ingredient ingredient = new Ingredient(name, kcal, fat, carbs, protein){};
            model.SaveIngredient(ingredient);
        }
    });
}

}
So has anyone an idea, what I have tho change to recive the current value? Thanks!
-- EDIT --
Entire XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/screen_background"
    tools:context=".fragments.AddIngredient">

    <TextView
        android:id="@+id/textview_addingredient"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text="Add Ingredient"
        android:textColor="@color/headercolor"
        android:textSize="@dimen/header_fontsize"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.126"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <!-- Name -->
    <TextView
        android:id="@+id/textView_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:text="Name"
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.075"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textview_addingredient"
        app:layout_constraintVertical_bias="0.050" />

    <EditText
        android:id="@+id/editText_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:ems="10"
        android:inputType="textPersonName"
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        android:text="Hello"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.157"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textView_name"
        app:layout_constraintVertical_bias="0.0" />

    <!-- Kcal -->
    <TextView
        android:id="@+id/textView_kcal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:text="Kcal"
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.075"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/editText_name"
        app:layout_constraintVertical_bias="0.050" />

    <EditText
        android:id="@+id/editText_kcal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:ems="10"
        android:inputType="number"
        android:text=""
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.157"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textView_kcal"
        app:layout_constraintVertical_bias="0.0" />

    <!-- Fat -->
    <TextView
        android:id="@+id/textView_fat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:text="Fat"
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.075"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/editText_kcal"
        app:layout_constraintVertical_bias="0.050" />

    <EditText
        android:id="@+id/editText_fat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:ems="10"
        android:inputType="number"
        android:text=""
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.157"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textView_fat"
        app:layout_constraintVertical_bias="0.0" />

    <!-- Carbs -->
    <TextView
        android:id="@+id/textView_carbs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:text="Carbs"
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.075"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/editText_fat"
        app:layout_constraintVertical_bias="0.050" />

    <EditText
        android:id="@+id/editText_carbs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:ems="10"
        android:inputType="number"
        android:text=""
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.157"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textView_carbs"
        app:layout_constraintVertical_bias="0.0" />

    <!-- Protein -->
    <TextView
        android:id="@+id/textView_protein"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:text="Protein"
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.078"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/editText_carbs"
        app:layout_constraintVertical_bias="0.052" />

    <EditText
        android:id="@+id/editText_protein"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/backgroundtint_color"
        android:ems="10"
        android:inputType="number"
        android:text=""
        android:textColor="@color/ntext_foreground"
        android:textSize="@dimen/ntext_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.157"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/textView_protein"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/fragmentbutton_addingredient"
        android:layout_width="@dimen/button_width"
        android:layout_height="@dimen/button_height"
        android:background="@color/button_background"
        android:gravity="left|center_vertical"
        android:padding="20dp"
        android:text="Add"
        android:textColor="@color/button_foreground"
        android:textSize="@dimen/button_fontsize"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.243"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/editText_protein"
        app:layout_constraintVertical_bias="0.250" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: Remove the default static text set to the editTextName field in your xml layout file. Due to this, the value is always getting stored as Hello. You shouldnt set text in EditTextview.
  <EditText
         android:id="@+id/editText_name"
         android:layout_width="wrap_content"
        android:layout_height="wrap_content"

  android:backgroundTint="@color/backgroundtint_color"
          android:ems="10"
         android:inputType="textPersonName"
         android:textColor="@color/ntext_foreground"
         android:textSize="@dimen/ntext_fontsize"
         android:text="Hello"  //Remove this line.


text:
Q: Jupyter Anaconda: error while loading text file into python as u can cleary see in this picture

i have my txt file 'sunplots' in the same ordner as my python file 'test'.
If i open the python file 'test' and enter the following code:
from pylab import *
from numpy import *

data = loadtxt("sunspots.txt")

i always get an error

The error states there is no sunplots.txt file but how can this be? Both files are in the same folder, therefore i dont need to write the exact path and i did not write the txt file names wrong...


text:
Q: addvaluechangedHandler fires twice in gwt..what alternate method shall i use? I am using following code.
But addvaluechangedHandler fires twice in gwt.
what other method should i use so that it will occur only once?
calendar.addValueChangeHandler(new ValueChangeHandler<Date>() {
    @Override
    public void onValueChange(ValueChangeEvent<Date> event) {

        Date newDate = calendar.getValue();
        newDate.setDate(newDate.getDate()+1);
        if ((newDate.before(todaysDate))) {
            Window.alert("You can not choose past dates before " +todaysDate);
            calendar.setValue(null);
        }
    }
});

A: See http://code.google.com/p/google-web-toolkit/issues/detail?id=4785
The workaround seems to be:

public class DateBoxOneEvent extends DateBox {
  @Override
  public void setValue(Date date, boolean fireEvents) {
    if (date != null) {
      date.setHours(0);
      date.setMinutes(0);
      date.setSeconds(0);
    }
    super.setValue(date, fireEvents);
  }
}


text:
Q: How to match ZLib stream between VBA 6/VBA 7and Java 8? We are being able to do the following.
In VBA 6/ VBA 7:

*

*Refer a 32 bit zlibwapi.dll (VBA 6) or 64 bit zlibwapi.dll (VBA 7).

*Invoke compress() or compress2() methods to generate compressed
streams

*Invoke uncompress() and uncompress2() methods to decompress
compressed streams

In Java 8 (JDK 1.8 on Tomcat 8)

*

*Have a simple java program that compresses data using the new
Deflater() instance

*Have a simple Java program that decompresses using Inflater()
instance

We are failing when VBA sends out the compressed stream for Java Servlet to uncompress or when Java Servlet sends out compressed response data for VBA to decompress.
We are aware of following facts.

*

*there are 3 formats provided by ZLib (raw, zlib and gzip).

*The methods in zlibwapi.dll namely compress() and compress2()
generates compressed bytes in zlib format. This has been mentioned
in a similar thread at
Java decompressing array of bytes

*Inflater() instance on Java side allows to uncompress zlib format
data as per a code sample posted at
Compression / Decompression of Strings using the deflater

*Java 8 has zlib version 1.2.5 integrated as part of java.utils.zip
package.

*We have ensured that we are using zlibwapi.dll version
    1.2.5 on VBA side as well.

We have tried to use Hex editors to compare byte streams of compressed data independently generated by VBA and Java as well. We notice some difference in the generated compressed data. We think it is this difference that is causing both the environments to misunderstand each other.
Additionally, we think that when communication occurs, there has to be some common charset that governs the encoding/decoding scheme between both the endpoints. We have even tried to compare the hex code of byte stream generated by VBA and communicated across to Java Servlet.

*

*The bytes seem to be getting some additional 0 bytes inserted in
between the actual set of compressed bytes while communication
occurs. This happens on VBA side. May be because of some unicode interpretation.

*Whatever bytes get communicated across to Java appear entirely
different in their representation.

We need to fix our independently working code to communicate with one another and compress and decompress peacefully. We think there are 2 things to address - Getting format to match and using a charset that sends bytes as is. We are looking for any assistance from experts on this front that can help us find correct path to the possible solution. We need answers for

*

*Does compress2() or compress() really generate zlib format?

*Which charset will allow us to send bytes as is (if there are 10
bytes, we want to send 10 bytes. Not 20). If its unicode, 0 bytes
get inserted in between (10 bytes become 20 bytes because of this).

A: *

*Yes.

*Don't send characters. Send bytes.


text:
Q: How to obtain paths to all the child nodes in a tree that only have leaves using clojure zippers? Say I have a tree like this.  I would like to obtain the paths to child nodes that only contain leaves and not non-leaf child nodes.
So for this tree
root
├──leaf123
├──level_a_node1
│   ├──leaf456
├──level_a_node2
│  ├──level_b_node1
│  │  └──leaf987
│  └──level_b_node2
│     └──level_c_node1
|        └── leaf654
├──leaf789
└──level_a_node3
   └──leaf432

The result would be
[["root"  "level_a_node1"]
["root"  "level_a_node2" "level_b_node1"]
["root"  "level_a_node2" "level_b_node2" "level_c_node1"]
["root"  "level_a_node3"]]

I've attempted to go down to the bottom nodes and check if the (lefts) and the (rights) are not branches, but that that doesn't quite work.
(z/vector-zip ["root"
               ["level_a_node3" ["leaf432"]]
               ["level_a_node2" ["level_b_node2" ["level_c_node1" ["leaf654"]]] ["level_b_node1" ["leaf987"]] ["leaf789"]]
               ["level_a_node1" ["leaf456"]]
               ["leaf123"]])

edit:  my data is actually coming in as a list of paths and I'm converting that into a tree.  But maybe that is an overcomplication?
[["root" "leaf"]
["root"  "level_a_node1" "leaf"]
["root"  "level_a_node2" "leaf"]
["root"  "level_a_node2" "level_b_node1" "leaf"]
["root"  "level_a_node2" "level_b_node2" "level_c_node1" "leaf"]
["root"  "level_a_node3" "leaf"]]

A: Hiccup-style structures are a nice place to visit, but I wouldn't want to live there. That is, they're very succinct to write, but a giant pain to manipulate programmatically, because the semantic nesting structure is not reflected in the physical structure of the nodes. So, the first thing I would do is convert to Enlive-style tree representation (or, ideally, generate Enlive to begin with):
(def hiccup
  ["root"
   ["level_a_node3" ["leaf432"]]
   ["level_a_node2"
    ["level_b_node2"
     ["level_c_node1"
      ["leaf654"]]]
    ["level_b_node1"
     ["leaf987"]]
    ["leaf789"]]
   ["level_a_node1"
    ["leaf456"]]
   ["leaf123"]])
(defn hiccup->enlive [x]
  (when (vector? x)
    {:tag (first x)
     :content (map hiccup->enlive (rest x))}))
(def enlive (hiccup->enlive hiccup))

;; Yielding...
{:tag "root",
 :content
 ({:tag "level_a_node3", :content ({:tag "leaf432", :content ()})}
  {:tag "level_a_node2",
   :content
   ({:tag "level_b_node2",
     :content
     ({:tag "level_c_node1",
       :content ({:tag "leaf654", :content ()})})}
    {:tag "level_b_node1", :content ({:tag "leaf987", :content ()})}
    {:tag "leaf789", :content ()})}
  {:tag "level_a_node1", :content ({:tag "leaf456", :content ()})}
  {:tag "leaf123", :content ()})}

Having done this, the last thing getting in your way is your desire to use zippers. They are a good tool for targeted traversals, where you care a lot about the structure near the node you are working on. But if all you care about is the node and its children, it is much easier to just write a simple recursive function to traverse the tree:
(defn paths-to-leaves [{:keys [tag content] :as root}]
  (when (seq content)
    (if (every? #(empty? (:content %)) content)
      [(list tag)]
      (for [child content
            path (paths-to-leaves child)]
        (cons tag path)))))

The ability to write recursive traversals like this is a skill that will serve you many times throughout your Clojure career (for example, a similar question I recently answered on Code Review). It turns out that a huge number of functions on trees are just: call yourself recursively on each child, and somehow combine the results, usually in a possibly-nested for loop. The hard part is just figuring out what your base case needs to be, and the correct sequence of maps/mapcats to combine the results without introducing undesired levels of nesting.
If you insist on sticking with Hiccup, you can de-mangle it at the use site without too much pain:
(defn hiccup-paths-to-leaves [node]
  (when (vector? node)
    (let [tag (first node), content (next node)]
      (if (and content (every? #(= 1 (count %)) content))
        [(list tag)]
        (for [child content
              path (hiccup-paths-to-leaves child)]
          (cons tag path))))))

But it's noticeably messier, and is work you'll have to repeat every time you work with a tree. Again I encourage you to use Enlive-style trees for your internal data representation.

A: You can definitely use the file api to navigate the directory. If using zipper, you can do this:
(loop [loc (vector-zip ["root"
                        ["level_a_node3"
                         ["leaf432"]]
                        ["level_a_node2"
                         ["level_b_node2"
                          ["level_c_node1"
                           ["leaf654"]]]
                         ["level_b_node1"
                          ["leaf987"]]
                         ["leaf789"]]
                        ["level_a_node1"
                         ["leaf456" "leaf456b"]]
                        ["leaf123"]])
       ans nil]
  (if (end? loc)
    ans
    (recur (next loc)
           (cond->> ans
             (contains-leaves-only? loc)
             (cons (->> loc down path (map node)))))))

which will output this:
(("root" "level_a_node1")
 ("root" "level_a_node2" "level_b_node1")
 ("root" "level_a_node2" "level_b_node2" "level_c_node1")
 ("root" "level_a_node3"))

with the way you define the tree, helper functions can be implemented
 as:
(def is-leaf? #(-> % down nil?))

(defn contains-leaves-only?
  [loc]
  (some->> loc
           down            ;; branch name
           right           ;; children list
           down            ;; first child
           (iterate right) ;; with other sibiling
           (take-while identity)
           (every? is-leaf?)))

UPDATE - add a lazy sequence version
(->> ["root"
      ["level_a_node3"
      ["leaf432"]]
      ["level_a_node2"
      ["level_b_node2"
        ["level_c_node1"
        ["leaf654"]]]
      ["level_b_node1"
        ["leaf987"]]
      ["leaf789"]]
      ["level_a_node1"
      ["leaf456" "leaf456b"]]
      ["leaf123"]]
     vector-zip
     (iterate next)
     (take-while (complement end?))
     (filter contains-leaves-only?)
     (map #(->> % down path (map node))))

A: It is because zippers have so many limitations that I created the Tupelo Forest library for processing tree-like data structures.  Your problem then has a simple solution:
(ns tst.tupelo.forest-examples
  (:use tupelo.core tupelo.forest tupelo.test))

  (with-forest (new-forest)
    (let [data          ["root"
                         ["level_a_node3" ["leaf"]]
                         ["level_a_node2"
                          ["level_b_node2"
                           ["level_c_node1"
                            ["leaf"]]]
                          ["level_b_node1" ["leaf"]]]
                         ["level_a_node1" ["leaf"]]
                         ["leaf"]]
          root-hid      (add-tree-hiccup data)
          leaf-paths    (find-paths-with root-hid [:** :*] leaf-path?)]

with a tree that looks like:
(hid->bush root-hid) =>
    [{:tag "root"}
     [{:tag "level_a_node3"}
      [{:tag "leaf"}]]
     [{:tag "level_a_node2"}
      [{:tag "level_b_node2"}
       [{:tag "level_c_node1"}
        [{:tag "leaf"}]]]
      [{:tag "level_b_node1"}
       [{:tag "leaf"}]]]
     [{:tag "level_a_node1"}
      [{:tag "leaf"}]]
     [{:tag "leaf"}]])

and a result like:
(format-paths leaf-paths) =>
    [[{:tag "root"} [{:tag "level_a_node3"} [{:tag "leaf"}]]]
     [{:tag "root"} [{:tag "level_a_node2"} [{:tag "level_b_node2"} [{:tag "level_c_node1"} [{:tag "leaf"}]]]]]
     [{:tag "root"} [{:tag "level_a_node2"} [{:tag "level_b_node1"} [{:tag "leaf"}]]]]
     [{:tag "root"} [{:tag "level_a_node1"} [{:tag "leaf"}]]]
     [{:tag "root"} [{:tag "leaf"}]]]))))

There are many choices after this depending on the next steps in the processing chain.


text:
Q: How can i pass the variable in the anchor to the next page? I have two pages where one links one to the other. How can i pass the value of the variable(region_name) in my anchor(select.php) to the next page(display.php)? i used the following codes and im getting Notice: Undefined variable: region_name.how do i fix it?
select.php

                    Greater Accra Region

display.php
<?php
ob_start();
session_start();
if(isset($_POST['region_name'])){
    $region_name = $_POST['region_name'];
}

$con=mysqli_connect("localhost","root","root","findings");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM approved_reservation WHERE region_name = '$region_name'";

$records=mysqli_query($con,$sql);

?>

A: We pass the variable $myVar through the URL and use $_GET in the next page to use it. We use htmlspecialchars(); to clean user input.
We use the if (isset($_GET['myVar'])) so it doesn't throw Notice: Undefined index error.
pageOne.php
<?php
$myVar = "My variable one.";

echo "Page Two"
?>

pageTwo.php
<?php
if (isset($_GET['myVar'])) {
    $myVar = htmlspecialchars($_GET['myVar'], ENT_QUOTES);

    // Now you can use $myVar.
}
?>

Now I'm not sure what variable you want to pass through so I used a simple skeleton which I made yesterday to show you how it is done. If you supply more code, I'll edit it to suit your scenario.
Edit 1
Your code below is incorrect because you're declaring your variable $region_name inside the scope of the if statement your queries and other code which is dependent on the variable has to be in that if statement.
Another solution would be to define an empty variable $region_name outside of the if statement then after the if statement you won't get the error Undefined Index.
if(isset($_POST['region_name'])){
    $region_name = $_POST['region_name'];
}

Edit 2
That error is being thrown for two reasons,

*

*Your not actually passing the region name through the URL - though even if you were it wouldn't work as you're using $_POST instead of $_GET.

*I outlined reason 2 in the above edit. You're using a variable which isn't in the scope of the queries.

A: The simplest form of passing along the data to display.php would be to add the region_name to the URL like so:
href="displayApprovedReservation.php?region_name=<?php echo $region_name; ?>"
In the display.php, you would then use $_GET['region_name'] to retrieve the data from the URL. Doing it this way, you would need to make sure you sanitize the input as it can be changed very easily from the URL by a user.
The reason you are getting the error Notice: Undefined variable: region_name is because the data is not being posted to the page, therefore $_POST['region_name'] is not set, thus not setting $region_name in the process -- yet you are still calling it in the SQL query regardless of the variable being set:
$sql="SELECT * FROM approved_reservation WHERE region_name = '$region_name'";

A: You're getting an undefined variable because of the following:
href does not use methods, nor values, nor type, <form>...</form> does.
Forms use inputs with name attributes set for its method.
Your code is expecting it to be passed via a form and using a POST method.

*

*More on forms here http://php.net/manual/en/tutorial.forms.php
What you want to use here is a GET in your conditional statement:
if(isset($_GET['region_name']) && !empty($_GET['region_name']) ){
    $region_name = $_GET['region_name'];
    echo $region_name;
}

Sidenote: I used !empty() should someone want to modify the URL as ?region_name=
and using a ? parameter after the filename and a = followed by the "value" you wish it to be:
Greater Accra Region

which in turn will echo "your_value".
You will need to modify its value respectively.
In your case, that would read as:
Greater Accra Region

You can also add to the above and inside the conditional statement:
if($_GET['region_name'] == "Greater Accra Region"){
   echo "Region is Greater Accra Region";
}

Which can be modified as:
Sidenote: The following example checks if a region equals to something, and if the value was modified in the URL such as ?region_name=.
if(isset($_GET['region_name'])){
    $region_name = $_GET['region_name'];
    echo $region_name;

if($_GET['region_name'] == "Greater Accra Region"){
    echo "Region is Greater Accra Region"; }

if(empty($_GET['region_name'])){
    echo "EMPTY"; }

}

Now, seeing your query, that is unknown as to what the ultimate goal is.

*

*Only you know and goes beyond the scope of your original question.

If you have a form (with a POST method) that you haven't posted, then you can use an input:
I.e.:
Greater Accra Region:
<input name="region_name" value="Greater Accra Region" type="submit">

and using your present POST arrays.

Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.

A: There are several ways to do what you're trying to do. The method that you're trying to achieve would require a form like:
<form name="selection" method="POST" action="display.php">
    <input name="region" type="radio" value="Greater Accra Region">
</form>

But it doesn't look great and don't work the way you want to.
Another method would be just to use a get variable like this
Greater Accra Region

Then on your display file you can use the variable $_GET['selection']; to use your selection :)


text:
Q: MacLane's CWM Exercise Categories for the Working Mathematician, S. Mac Lane, 3.2, ex. 1:

Let functors $K, K'\colon D\to \mathbf{Set}$ have representations $\left<r,\psi\right>$ and $\left<r', \psi'\right>$, respectively. Prove that to each natural transformation $\tau\colon K\stackrel{*}{\rightarrow} K'$, there is a unique morphism $h\colon r' \to r$ of $D$ such that
  $$
\tau\circ\psi = \psi' \circ D\,(h, -)\colon D\,(r,-)\stackrel{*}\longrightarrow K'
$$

Here's my attempt:

Since $\psi'$ is a representation, it's an isomorphism, hence there exists an inverse natural transformation $\psi'^{-1}$, obtained by reversing the arrows. Consider composition
  $$
\psi^{\prime-1}\circ\tau\circ\psi\colon D\,(r,-)\to D\,(r',-)
$$
  It's a natural transformation between covariant hom-functors. It follows from Yoneda lemma there exists unique $h\colon r'\to r$ such that $\psi^{\prime-1}\circ\tau\circ\psi = D\,(h,-)$. Composing with $\psi'$ on the left yields the thesis.

Now, what seems disturbing is that the above argument does not rely on the fact $\psi$ is isomorphic. Am I being paranoid? Or have I missed something?

A: Your proof is correct. It is an immediate consequence of the Yoneda Lemma. One only needs that $\psi : D(r,-) \to K$ is some natural transformation.


text:
Q: MessageSource always returns the default message I'm trying to inject text message using MessageSource in Spring. The program I wrote compiles fine, but it always printing out the default message instead of fetching the right values from .properties file. I have no clues at all.
Here's the Circle class that tries to inject the text:
 @Component
    public class Circle implements Shape {

        @Resource
        private Point center;
        @Autowired
        private MessageSource messageSource;

        public MessageSource getMessageSource() {
            return messageSource;
        }

        public void setMessageSource(MessageSource messageSource) {
            this.messageSource = messageSource;
        }

        public Point getCenter() {
            return center;
        }

        public void setCenter(Point center) {
            this.center = center;
        }

        @Override
        public void draw() {
            System.out.println(this.messageSource.getMessage("greeting", null, "Default Greeting", null));
            System.out.println(this.messageSource.getMessage("draw.circle", new Object[] {center.getX(), center.getY()}, "Required Drawing", null));

        }

And here's part of the bean configuration file:
...
    <bean id="center" class="java.awt.Point">
        <constructor-arg value="0" />
        <constructor-arg value="-20" />
    </bean>

    <bean id="messageSourse" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
                <value>messages</value>
        </property>
    </bean>

    <context:component-scan base-package="com.myproject.spring"/>

    <context:annotation-config/>

And I store the greeting and draw.circle in messages.properties file and wrote a main class. But the outputs are always:
Default Greeting
Required Drawing

Does anybody know what can possibly go wrong in my case?
Update
Thanks for the advice. I was debugging and seems like something went wrong in here:
public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
        if (this.parentMessageSource != null) {
            return this.parentMessageSource.getMessage(code, args, defaultMessage, locale);
        }
        else {
            return renderDefaultMessage(defaultMessage, args, locale);
        }
    }

this.parentMessageSource is null so it decided to render default message. But I still don't quite understand what is parentMesssageSource and how it can be (not) null?

A: You have to use id="messageSource" instead id="messageSourse".
For all  that use Java configurations, you have to have "messageSource()" as a method name
    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource resourceBundleMessageSource =
                new ResourceBundleMessageSource();
        resourceBundleMessageSource.setBasename(I18_PATH_TEMPLATE + "email_welcome");
        resourceBundleMessageSource.setDefaultEncoding("UTF-8");
        return resourceBundleMessageSource;
    }

A: Probably, the messageSource is not able to pick your messages file. ResourceBundleMessageSource has overriden toString() method to display the messageResource configuration. Try using it once. You can also inspect messageSource object just after it has been injected with the help of a debugging tool, to check whether it has loaded all the properties successfully or not.

A: You have mis-spelled the bean id
Instead of 'messageSource', you have written 'messageSourse'.
You must have an id of the Message Resource bean, and it should always be 'messageSource'.

A: The Extension of the Property file should be .properties


text:
Q: Javascript concatenate a function similar to how text can be added In javscript we can do this
var text = "the original text";

text+=";Add this on";

If a library has a function already defined (e.g)
//In the js library
library.somefunction = function() {...};

Is there a way to add something on so that I can have two functions run?
var myfunction = function() {...};

Something like:
library.somefunction += myfunction

So that both myfunction() and the original library.somefunction() are both run?

A: You can use this kind of code (leave scope empty to use default scope):
var createSequence = function(originalFn, newFn, scope) {
    if (!newFn) {
        return originalFn;
    }
    else {
        return function() {
            var result = originalFn.apply(scope || this, arguments);
            newFn.apply(scope || this, arguments);
            return result;
        };
    }
}

Then:
var sequence = createSequence(library.somefunction, myFunction);

A: I think what you want to create is a Hook (function) - you want to call library.somefunction but add a bit of your own code to run before. If that's the case, you can make your myfunction either call or return the library function after it's done with your bit of code.
var myfunction = function() {

    // your code
    // ...

    return library.somefunction();
}


text:
Q: Получение доступа к конкретному элементу Есть запрос
$query ="SELECT `head` FROM `comi`";

Который мне возвращает столбец head.
Как мне получить доступ к, например, 3 строке возвращенного массива без использования while?
Как сделать тоже самое если запрос выглядит так:
SELECT * FROM `comi`

То есть запросить все, а выдернуть одно конкретное значение из 3 строки столбца head.
$Row=mysqli_fetch_array(mysqli_query($link, $query));
echo $Row['head'];

Зачем? Надо в учебных целях.

A: Для этого существует функция mysqli_data_seek
Только надо иметь в виду, что работает она с буферизованными результатами. Т.е. с результатами возвращаемыми mysqli_query(), или, в случае подготовленных запросов, после применения mysqli_store_result().

A: Не надо использовать ересь типа mysqli_data_seek. Так никто никогда не делает.
Во-первых, потому что надо использовать PDO вместо mysqli.
Во-вторых, потому что для обращения по индексу служат массивы.
Поэтому если нам нужна только одна запись, то выбираем только её средствами SQL.
$head = $pdo->query("SELECT `head` FROM `comi` LIMIT 3,1")->fetchColumn();
echo $head;

Если же нужны все записи к которым потом обращаемся по индексу, то получаем их в массив, с которым дальше и работаем:
$data = $pdo->query("SELECT `head` FROM `comi`")->fetchAll(PDO::FETCH_COLUMN);
echo $data[2];


text:
Q: Cleaning up class path, what is the correct approach to avoid this issue in future? I am building a java 12 based project using Gradle as the build tool and all things going well until I shared code on the repo for another dev to have a look. In inadvertently it seems I have put a lot of jars in the classpath as dependencies in the project

admittedly this is going to look awful I'm sure to some more competent developers out there but I have not done this before so hence my likely rookie mistake here. What I'm looking to understand most is how this came to be, i.e. I don't recall adding these dependencies in to the classpath myself so I assume gradle did it for me.
So some questions I have around this are

*

*Did I do this the right way? Should I be lettinggradle handle my classpath updates like that? (I am assuming it was gradle because the folder paths are gradle based mostly)

*Confirm it was not actually eclipse that did this somehow and I'm misleading myself to believe it was gradle

*How do I correctly avoid this issue in the future to stop other people taking the code having issues like this again? Do I put better clarifications in the gradle script somewhere, or do I not ship with all the dependencies listed so the next user pulls them all down themselves?

*Is this actually an issue? I'm presuming it is an issue because of my own personal drive folder structure being put in place but was there some checkbox I missed maybe that would've set this up the right way without picking up the personal folder structure? Like perhaps a reference to a system environment variable for the first component to get to '.gradle'

*When I build my application to ship it, will these references or jars be compiled into the final jar that I produce thus when it's on another machine this folder setup etc won't be an issue?

Am fully willing to admit there are some components running here that I don't understand but this one sneaked up on me so I've likely long missed where I made that mistake thus identifying how I did it kind've hard for me
EDIT: gradle build script
    plugins {
    id 'java'
    id 'application'
    id 'org.openjfx.javafxplugin' version '0.0.7'
    id 'org.beryx.jlink' version '2.9.4'
    id 'idea'
}

group 'com.bisit'
version '0.1.1'

repositories {
    mavenCentral()
}

sourceCompatibility = 12

javafx {
    version = "12"
    modules = [ 'javafx.controls', 'javafx.fxml' ]
}

mainClassName = 'com.bisit.App'

dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter:5.5.2')
    testImplementation('org.junit.jupiter:junit-jupiter-api:5.5.2')
    testImplementation('org.junit.jupiter:junit-jupiter-params:5.5.2')

    // https://mvnrepository.com/artifact/commons-validator/commons-validator
    compile group: 'commons-validator', name: 'commons-validator', version: '1.4.0'

    // https://mvnrepository.com/artifact/com.google.code.gson/gson
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.0'

    // https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core
    compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.12.1'

    // https://mvnrepository.com/artifact/org.jetbrains/annotations
    compile group: 'org.jetbrains', name: 'annotations', version: '17.0.0'

    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'

    // https://mvnrepository.com/artifact/org.clojure/java.jdbc
    compile group: 'org.clojure', name: 'java.jdbc', version: '0.7.10'

    // https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc
    compile group: 'org.xerial', name: 'sqlite-jdbc', version: '3.28.0'

    // https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc
    compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '7.4.1.jre12'

    // https://mvnrepository.com/artifact/mysql/mysql-connector-java
    compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.17'

    // https://mvnrepository.com/artifact/org.freemarker/freemarker
    compile group: 'org.freemarker', name: 'freemarker', version: '2.3.29'

    // https://mvnrepository.com/artifact/com.openhtmltopdf/openhtmltopdf-core
    compile group: 'com.openhtmltopdf', name: 'openhtmltopdf-core', version: '1.0.0'

    // https://mvnrepository.com/artifact/com.openhtmltopdf/openhtmltopdf-pdfbox
    compile group: 'com.openhtmltopdf', name: 'openhtmltopdf-pdfbox', version: '1.0.0'

    // https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core
    compile group: 'org.hibernate.orm', name: 'hibernate-core', version: '6.0.0.Alpha2'

    // https://mvnrepository.com/artifact/com.h2database/h2
    runtimeOnly group: 'com.h2database', name: 'h2', version: '1.4.199'

    // https://mvnrepository.com/artifact/org.apache.poi/poi
    compile group: 'org.apache.poi', name: 'poi', version: '4.1.0'

    // https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml
    compile group: 'org.apache.poi', name: 'poi-ooxml', version: '4.1.0'
}

jar {
    manifest {
        attributes 'Main-Class': 'com.bisit.Launcher'
    }
    from {
        configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
    }
}

jlink {
    options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages']
    launcher {
        name = 'xmlanalyser'
    }
}

test {
    useJUnitPlatform()
}

tasks.withType(JavaExec) {
    if (System.getProperty('DEBUG', 'false') == 'true') {
        jvmArgs '-Xdebug', '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9099'
    }
}


text:
Q: Execute an action without opening application in Android I have an application in Android that has a button in the MAIN activity that performs an action.
Is there a way to execute that action without opening the application?
I don't know if I can say it is like a widget, because it does not wait for updates.
The user should be able to execute that action just clicking on the icon of the application without opening.
Is it possible?

A: Yes and no. What I had to do for a similar problem was have a transparent view in my main activity, and then self-terminate:
In your activity...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
            // Do whatever you need here...
    finish();
}

And in AndroidManifest.xml:
        <activity android:name=".whatever" android:theme="@android:
style/Theme.NoDisplay">

Hope this helps,
Phil Lello

A: Try this question Android - How to execute main functionality of project only by clicking on the icon of application?


text:
Q: How to move references just one cell if I drag the formula six rows? I have a formula that references to $K4. When I copypaste this formula six rows below, I want to get $K5, instead of $K10. How can I do this?

A: Good Day,
This should work for you.
1. In the formula bar highlight the formula
2. Press Control C
3. Click on the cell you want the formula in
4. Click on the formula bar and press Ctrl & V
You might need to change 4 to 5. You could drag the formula to the cell below to get $K5 first, the do all the above from there, but it is likely more work.
Hope this helps,
Brad

A: *

*At the location of the 1st $K4 formula.. =INT(ROW()/6) || What answer did you get? say x .

*use indirect to build "replacement" formula : so replace the $K4 with =INDIRECT("K"&((INT(ROW()/6)-x)+4),TRUE) .. where x is number you get from step 1.

*do this for every different formula that use $K4.

*Then you may drag the 'new' formula as usual.
Have a try. (and share if it works/or not) (: