No keyboard input in Qt Creator after update to Qt5

Question: I have this strange situation that after updating Qt from 4.8 to 5.3, Qt Creator (v.3.2.1) will not take any keyboard input. The keyboard is working normally in other applications.
I'm on Debian Wheezy (7.7) with XFCE, but installed the Qt5 set of packages from wheezy-backports.
Does anyone have an idea what can be done about this?
Update:
As requested, here's the Terminal output:
libEGL warning: DRI2: failed to authenticate
xkbcommon:ERROR: failed to add default include path auto
Qt: Failed to create XKB context!
Use QT_XKB_CONFIG_ROOT environmental variable to provide an addtional search path,
add ':' as separator to provide several search paths and/or make sure that XKB
configurationdata directory contains recent enough contents, to update please see
http://cgit.freedesktop.org/xkeyboard-config/ .

Comment: Can you open a console, type `qtcreator` and update your question with the messages you obtain?
Comment: @prajmus No, shortcuts don't work either.
Answer: It is apparently a known bug, some messages and posts talks about this issue on the Internet.
Maybe try this, from https://lists.debian.org/debian-backports/2014/10/msg00061.html

Opening Qt5 applications from backports (or self compiled against backported
  Qt5) have some trouble finding XCB data:
$ /usr/lib/x86_64-linux-gnu/qt5/examples/quick/d
  ialogs/systemdialogs/systemdialogs
  xkbcommon: ERROR: failed to add default include path auto
  Qt: Failed to create XKB context!
  Use QT_XKB_CONFIG_ROOT environmental variable to provide an additional search
  path, add ':' as separator to provide several search paths and/or make sure
  that XKB configuration data directory contains recent enough contents, to
  update please see http://cgit.freedesktop.org/xkeyboard-config/ .
Applications run fine, but can't get input from the keyboard.
As the warning points out, setting the environment variable fixes it:
export QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb

So, try to run qtcreator with the folowing command:
export QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb && qtcreator

Comment: If you are logging in from a SSH client and get the error message requesting the QT_XKB_CONFIG_ROOT variable. Then go to your home directory of the user you are logging in and insert the line export QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb at the end of the file .bashrc
Comment: I had to do the export and qtcreator start in two steps, but now it's working again. Thanks a lot to everyone!
Comment: The reason @virt had to separate the commands is probably due to the race condition resulting from the start of the first command in background (`&`). Use `&&` to separate the two commands, to start them in sequence.
Comment: Recently I upgraded my pyqt and this error accrued for me and I want to say to those who have same problem in spyder that this solution is worked for me too!!Thanks
Comment: I am getting this error while using cv2.imshow(), any workaround?
Comment: QT_XKB_CONFIG_ROOT=/usr/share/X11/xkb at the end of the file .bashrc worked for me.
Answer: ~]$ /usr/local/bin/xca
xkbcommon: ERROR: failed to add default include path /usr/share/X11/xkb
Qt: Failed to create XKB context!
Use QT_XKB_CONFIG_ROOT environmental variable to provide an additional search path, add ':' as separator to provide several search paths and/or make sure that XKB configuration data directory contains recent enough contents, to update please see http://cgit.freedesktop.org/xkeyboard-config/ .
sudo apt-get install xkb-data (xkeyboard-config)
has solved my problem (no input from keyboard)
Comment: Please add an explaination, how this willl solve the issue in the question.
Comment: Thanks for sharing. Adding `apt-get install xkb-data` to my docker file solved the problem of having no keyboard inputs with a Dockerized Qt application.
Comment: On CentOS this is `yum install -y xkeyboard-config`.

My use case: I'm creating a Docker container for development purposes to run on my local machine a PyQt app that is usually run in a RHEL environment.


Angular Column is not Displayed when Toggle is Open

Question: In my code, I have a grid list where the user can add a column by sliding a toggle button. The code works fine but when I refresh the page, the column is not there even though the toggle is open. I have to close the toggle and re-open it in order to see the column. Here is my code what should I fix?

HTML:
<code><mat-slide-toggle [(ngModel)]="this._materialPlan.IncludeAdditionalProduction"
    (change)="toggleAdditionalProduction()" class="mr-8">Ek Üretim</mat-slide-toggle>
</code>
TS:
<code>  constructor() {
    this.initializeGridColumns();
  }

  initializeGridColumns() {

    this.displayedColumns = [
      'Sequence',
      'StockIntegrationCode',
      'ReceiptName',
      'PackagingTheoricYieldQuantity',
      'GeoType',
    ];

    let itemIndex = 0;

    if (this._materialPlan.IncludeAdditionalProduction == true) {
      this.displayedColumns.push("AdditionalProductionQuantity");

    }
    else {
      itemIndex = this.displayedColumns.indexOf("AdditionalProductionQuantity");
      if (itemIndex > 0) {
        this.displayedColumns.splice(itemIndex, 1);
      }
    }

    this.displayedColumns.push("Actions");

  }

 toggleAdditionalProduction() {

    if (this._materialPlan.IncludeAdditionalProduction == true) {
      this.form.controls["AdditionalProductionQuantity"].clearValidators();
      this.form.controls["AdditionalProductionQuantity"].updateValueAndValidity();
    } else {
      this.form.controls["AdditionalProductionQuantity"].setValidators(Validators.required);
      this.form.controls["AdditionalProductionQuantity"].updateValueAndValidity();
    }

    this.initializeGridColumns();
  }
</code>
Answer: After toggle happens, you need to call " initializeGridColumns() " to initialize the columns again.
This is based on the explanation you had on your question. Also you dont really show what is the function does upon toggle.
Comment: I edited my code, I actually do call initializeGridColumns()
Comment: have you tried "(ngModelChange)" rather than (change) its more reliable for the use of model. @RocketMonkey
Comment: I tried it now but nothing changed
Comment: just noticed remove the this from the "this._materialPlan.IncludeAdditionalProduction". After that if still no good make sure your variable actually updating. You can achieve that by setting break points or console.log the value. Let me know how it goes. I am out of ideas after that @RocketMonkey
Comment: Thanks, but that didn't work as well :/


How to use a modal for associative actions with in place search?

Question: I'm designing an application that presents a list of bus stops to the user in a list (html table). Every bus stop belongs to a city somewhere in the world. Once the user finds the stop he wants, he can see the city that the stop is associated with through a modal dialog like the one below.

download bmml source – Wireframes created with Balsamiq Mockups
In cases where this association should be changed or a new bus stop is created, besides the details of the bus stop, I need to let him search our database for the city that the stop belongs to.

How bad is it to put the search right below (or above) the bus stop details so he can find the one he wants?
What about paging, it seems weird to add all of this on top of a modal.

By using it I can see that it is not optimal, but no other way comes to mind.

download bmml source
What do you guys think?
Thanks a lot!
Answer: Working with a few assumptions ...

The number of fields you want to display is few (city/state/country).
The user already knows what city/state/country they want, they are using the search to locate the record for it. Therefore they will be able to add more characters to the search box until the item they are looking for appears in the list.

I would create an inline-edit state for the modal, allowing the user to make the change without leaving the screen at all. The 3 fields seem so natural to digest as a single string, I am not seeing much value in having the columns in a grid. Depending on how large the data set is, you may want to wait until the user enters enough characters before returning a list.

Additionally, if you had Lat/Long data, you could provide a method for limiting the search results to a radius around the current city or add it to the search results ...

San Diego, CA, USA (428 mi away)
San Francisco, CA, USA (Current Location)
Sandy Point, NV, USA (999 mi away)
Santiago, Chile (2,000 mi away)
Answer: A thought, Why does the user needs to know when was the buss stop created? you can make more space by dropping this detail and lessen the time user reading time.
Comment: It was just a sample field. Thanks by the suggestions, though


How do I get rid of corpses that don't despawn on their own?

Question: In Whiterun there are two dead bodies that never seem to despawn. They are the cultists from the start of the Dragonborn DLC. I know I could just move them out of sight, but I have some weird feeling knowing that they are still there. Is there anyway to force the corpses to despawn permanently? I'm on PC, so I do have access to the console.
Comment: [Corpses will eventually despawn on their own, but it does take a while.](http://gaming.stackexchange.com/questions/35321/do-corpses-disappear-after-a-while). I'm not sure if there is anyway to expedite the process.
Comment: @Wipqozn Those corpses are actually bugged and will not despawn on their own.
Answer: This error, and many more, are fixed up in the Unofficial Patch series for the Dragonborn DLC:

UDBP Fixes
  Dragonborn (DLC2MQ01) lost a property for cleaning up the cultist bodies after the ambush is over. DLC2WE09 also needed to be added for shutdown. (Bug #14121)

For a complete list of the change logs you can go to the change log. This patch is available through many sites like Nexus but is not available any longer through the Steam Workshop (this is due to restrictions in the Content Creator). I -highly- recommend getting comfortable installing the mod via the Nexus Mod Manager (simple easy to use interface that handles installing and uninstalling the files for you) as the Unofficial Patches are almost a requirement to play Skyrim bug free.
Comment: What about console versions?
Comment: @GnomeSlice There are no mods for Console versions of Skyrim so the only hope is that Bethesda patches the bugs. I do not think this is likely given their track record though. Also the original question stated this was on PC. I am unsure if this bug even exists on the console.
Answer: James' answer is correct for the OP's specific situation, but with the following command you can completely (not only visually) get rid of anything in-game:
Use the MarkForDelete command

[MarkForDelete] marks an object for actual deletion: when the
  system does its normal clean up, the object will be deleted, and its
  script will no longer be active.

To do so,

get the unwanted object directly in view;
go into the in-game console (using the key above the Tab key, usually ~ on QWERTY keyboards);
select the body or other unwanted object,
type in the disable command,
immediately followed by markfordelete.

This will get rid of the object completely, once the cell it's in unloads.

MarkForDelete allows a script to set the delete flag on a disabled
  reference, which places the reference in a queue for deletion a few
  frames later. It will not work on enabled references.

Whereas the disable command merely hides it from view, without unloading it:

When an object is disabled, it remains in memory and continues to
  process scripts.

Quotations from Creationkit.com
Answer: You can remove any unwanted object with the console.

Make a backup save
Open the console (the default key is the key left of the 1 key).
Click on the body (or any object you want to be removed) so the ID is shown in the console.
Type disable

This removes the object permanently. Be careful not to use it on anything, that is still needed.
Comment: will try this when i get home, this is a lot simpler than @James answer.
Comment: @freebol96 I recommend clicking on the Change Log link in my question to see all of the other bugs that patch also fixes with the Dragonborn DLC.
Answer: Put them in deep water. Eventually they will disappear with the changing of the days. If not out of sight out of mind


Java MongoTemplate exclude child relations in query

Question: Background:
I'm using Spring-boot and MongoDB.
public class User {
   @DBRef
   private List<Contact> contacts;
   ...

public class Contact {

   @DBRef
   private List<Booking> bookings;
   ...

   public Contact(){}

   public Contact(Booking booking){
       this.bookings = new ArrayList<Booking>();
       this.bookings.add(booking);
       ...
   }

@Override
public List<Contact> findAllContactsForUser(String id) {
    Query query = new Query().addCriteria(Criteria
            .where("_id").is(id));
    query.fields().include("contacts");
    User user = mongoTemplate.findOne(query, User.class);
    return user.getContacts();
}

Output from findAllContactsForUser:
[
   {
     "field":"value",
     "bookings": [
                   "field":"value"
                 ]
   }
]

Problem:
The result I want:
[
   {
     "field":"value",
     "bookings": null
   }
]

How do I exclude the bookings relationship from my query in findAllContactsForUser?
Comment: I see the new ArrayList in your Contact's constructor. I see no evidence it is being called yet, but I suspect it is. Can you add the code for User too (setContacts, getContacts +  constructors) + Contact 's setBookings, getBookings
Answer: You just need to exclude the field contacts.bookings in your query:
@Override
public List<Contact> findAllContactsForUser(String id) {
    Query query = new Query().addCriteria(Criteria.where("_id").is(id));
    query.fields().exclude("contacts.bookings");
    User user = mongoTemplate.findOne(query, User.class);
    return user.getContacts();
}

By the way, no need for the .include(contacts), fields are included by default.
Comment: That just gives me an empty array = [ ].
Comment: I tested with your model and it works for me. Can you post the complete code for your Contact class ?
Comment: Do you have anywhere in your code where you do "new ArrayList()" for bookings ?
Comment: Just updated my question with som code from Contact.class


length: argument cannot be a symbol

Question: I have following code:
configuration(s)  := makelist(i, i, 0, length(s) - 1)$
active_agents(s)  := s . configuration(s)$
prob_exp[k](l, s) := 1 - exp(- l[k] * active_agents(s))$

When I try to call prob_exp with some concrete value of s, for example:
prob_exp[k](l, [0.25, 0.25, 0.25, 0.25]);

I get following error message:
length: argument cannot be a symbol; found s
#0: configuration(s=s)
#1: active_agents(s=s)
#2: lambda([k],lambda([l,s],1-exp((-l[k])*active_agents(s))))(k=k)
-- an error. To debug this try: debugmode(true);

Is there a way to force passing s as a value?
Answer: Here's the explanation for what you've observed: Maxima first evaluates prob_exp[k], which yields a lambda expression with two arguments, which is then applied to [l, [0.25, 0.25, 0.25, 0.25]]. Evaluating prob_exp[k] causes the error since s is not bound to the actual list.
To resolve the problem, you need prob_exp[k] to evaluate to something which can have s as a symbol. Here is one way to do that. I'll define active_agents as a simplifying function (i.e., a function which is evaluated via a simplification rule).
configuration(s)  := makelist(i, i, 0, length(s) - 1);
matchdeclare (aa, listp);
tellsimp (active_agents (aa), aa . configuration (aa));
prob_exp[k](l, s) := 1 - exp(- l[k] * active_agents(s));

Then I get:
prob_exp[k];
 => lambda([l,s],1-%e^-(l[k]*active_agents(s)))
prob_exp[k](l, [0.25, 0.25, 0.25, 0.25]);
 => 1-%e^-(1.5*l[k])

Note that Maxima prefers exact fractions to floating point numbers; I recommend using [1/4, 1/4, 1/4, 1/4] instead of [0.25, 0.25, 0.25, 0.25].
Answer: The simpler would be to write:
prob_exp(k, l, s) := 1 - exp(- l[k] * active_agents(s))$

The problem is function configuration is evaluated when you call p[k] (I don't know really why). Take a simpler example:
show(x):=block(disp('run),x);
q[k](x,y):=x+k*show(y);
q[k];

yields:
run
lambda([x,y],k*y+x)

That is, q[k] is a lambda but its contents got evaluated in the process, and it prints "run". It does not throw an error though. Why ?
Simply, you can't evaluate makelist with symbolic bounds, and length(s) is symbolic, because at this stage s has no value yet.
When you define prob_exp(k, l, s) instead of prob_exp[k](l, s), the whole expression is a lambda, and will be evaluated when all variables have a value.
Likewise, this does not evaluate show:
lambda([x,y],y+k*show(x));

Also, note with the preceding definition of q, that when calling several times q[k], run will be printed only once, because q is a hashed array. Thus, Maxima prepares the function (and somehow evaluates the body) on the first call, then it is stored.
Comment: More explanations on this behaviour in the old Macsyma reference, p.17 ([link]http://bitsavers.informatik.uni-stuttgart.de/pdf/mit/macsyma/MACSYMA_RefMan_V9_Dec77.pdf)
Answer: Maybe postponing the evaluation can help?  I am not 100% sure why this works and putting e.g. the ev(..., nouns) into prob_exp does not, but this is at least a bit closer to what you need, I think.
kill(all);
configuration(s)  := 'makelist(i, i, 0, 'length(s) - 1)$
active_agents(s)  := s . configuration(s)$
prob_exp[k](l, s) := 1 - exp(- l[k] * active_agents(s))$

prob_exp[k](l, [0.25, 0.25, 0.25, 0.25]);
ev(%, nouns);

length: argument cannot be a symbol


powershell variable won't be used in second part of script

Question: I'm learning power shell and I have problem with this code. when I parse it, it all works, but not together. what could be the problem? Thank you for answer.
$hotfix = read-host "Enter hotfixID"

Start-Process firefox.exe (get-hotfix |
Where-Object -filter {$_.hotfixID -eq $hotfix} |
Select-Object -ExpandProperty Caption)

Comment: What is it that doesn't work?
Answer: Your script works correctly here. Note that I don't have Firefox installed, but it works fine with iexplore. What issue are you experiencing?
Also, as @Colyn1337 stated, you do not need to use Where-Object; you can simplify this script as follows:
$Hotfix = Read-Host "Enter Hotfix ID"

Start-Process firefox.exe
(
    Get-HotFix -Id "$Hotfix" |
        Select-Object -ExpandProperty Caption
)

EDIT: As discussed in the below comments, the issue was that the arguments do not work when called via powershell.exe -command scriptname. The solution would be to pass the arguments implicitly via ArgumentList:
$Hotfix = Read-Host "Enter Hotfix ID"

Start-Process firefox.exe -ArgumentList `
(
    Get-HotFix -Id "$Hotfix" |
        Select-Object -ExpandProperty Caption
)

Comment: Thank you. Script looks nice this short. Find out, that problem isn't in code, but in how I start it. I want executable script like batch file. So I created shortcut "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "C:\Users\Isis\Desktop\hotfix.ps1" and it won't open adress, only firefox.
Comment: Yes, it looks like the argument isn't passed when called this way. I'll edit the fix into my answer for visibility.
Comment: Great, glad to hear you got it sorted. Please remember to accept this answer if it solved your problem. (Click the check mark.)
Answer: To get a specific hotfix, you'd want to try something lik this:
$hotFix = Read-Host "Enter hotfixID"
Get-Hotfix -Id $hotFix

If I understand what you're trying to do, creating a browser process is not necessary.
Comment: I want open URL stored in caption property, that's why I start firefox. I found out, that problem is in starting script through shortcut: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "C:\Users\Isis\Desktop\hotfix.ps1" adress won't open, but firefox does.


Is it possible to build object that respond to the [] operator

Question: I was loading with a library called D3 some CSV file, and doing a console.log of the data it returned after it loaded the file, it gave me this result:
d3.csv(..., function(data) {
    console.log(data)
    // this returns the following:
    //"(6) [{…}, {…}, {…}, {…}, {…}, {…}, columns: Array(8)]"
})

Now this part is what is weird to me:
(6) [{…}, {…}, {…}, {…}, {…}, {…}, columns: Array(8)]

This looks like a mixture of an array (because I can do something like var a = data[2]) but it also looks like an object (because I can do somehting like var a = data.columns.
When I do typeof(data) I get that it is an object, but I have no idea how to build an object that also responds to the [] syntax. (Or an array, that responds to object attributes)
How does such an structure get built?
Comment: `yourArray.yourProp = "xyz";` Arrays are regular Objects.
Answer: Arrays are just a type of object. They can do anything an object can do.

var data = ["a", "b", "c"];
data.arbitaryProperty = "Hello, world";
console.log(typeof data);
console.log(data[0]);
console.log(data.arbitaryProperty);
Comment: I didnt know that I could set attributes for arrays, wow. Simple and clear explanation, thank you!

PS: can I do it the other way around? Start with an object and then give it array items?
Answer: The data returned by d3.csv() is, indeed, an array. Not getting into the technical discussion that in JavaScript arrays are objects, what you're seeing is simply an array's property.
For instance, let's see this simple array:
var arr = [1, 2, 3, 4];

If I do:
arr.foo = "bar";

It sets a property to that array. Let's see:

var arr = [1, 2, 3, 4];
arr.foo = "bar";
console.log(arr.foo)

The 'columns' property
In D3 v4, the d3.csv() function adds a new property to the array, called columns. According to the API:

The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).

So, let's load a very small sample CSV which I found online:

d3.csv("https://www.ibm.com/support/knowledgecenter/SVU13_7.2.1/com.ibm.ismsaas.doc/reference/AssetsImportMinimumSample.csv?view=kc", function(data) {
  console.log(data);
})

If I use data.columns I'll get the array property containing the first row (headers) in that CSV. Let's see the headers:

d3.csv("https://www.ibm.com/support/knowledgecenter/SVU13_7.2.1/com.ibm.ismsaas.doc/reference/AssetsImportMinimumSample.csv?view=kc", function(data) {
  console.log(data.columns);
})


How to convert an Option[String]to List [Int]in Scala

Question: I'm able to convert Option[String] to List[String] with the following code :
 def convertOptionToListString(a: Option[String]): List[String] = {
    return a.toList.flatMap(_.split(",")) // ex : ("value1", "value2", "value3", etc)
  }

But how can i convert Option[String] to List[Int] so at the end i can have list with integers : (1,3,5). My Option[String] will looks like this : Some("1,3,5")
Note that the values 1,3,5 comes from params.get("ids") sent from an url and params.get is an Option[String]
val params = request.queryString.map { case (k, v) => k -> v(0) }

Thanks
Comment: `Some("1","3","5")` isn't a `Option[String]`.  It's a `Option(String,String,String)`.  Which do you mean?
Comment: Yes it is : The values 1,3,5 comes from params.get("ids") sent from an url and params.get is an Option[String]
Comment: `scala> Some("1","3","5")`
`res40: Some[(String, String, String)] = Some((1,3,5))`
Comment: Maybe you mean `Some("1,3,5")` ? Or are the quotes around each number actually part of the String?
Comment: Yes Dylan i meant Some("1,3,5"). Sorry
Comment: One note, using `return` here is unnecessary and it is generally discouraged - see https://tpolecat.github.io/2014/05/09/return.html for a good explanation of why.
Answer: Scala 2.13 introduced String::toIntOption.
Combined with a flatMap, we can safely cast Strings into Ints and eliminate malformed inputs:
List("1", "2", "abc").flatMap(_.toIntOption)
// List[Int] = List(1, 2)

Answer: If you want to convert List[String] to List[Int], skipping unparseable values, then you can use Try:
import scala.util.Try

List("1", "2", "3").flatMap(x => Try(x.toInt).toOption)
res0: List[Int] = List(1, 2, 3)

List("1", "2", "abc").flatMap(x => Try(x.toInt).toOption)
res1: List[Int] = List(1, 2)

Comment: A regex and `collect` would give you similar behavior: `val IntRe = "(\\d+)"; xs.collect { case Re(n) => n.toInt }`
Answer: val a: Option[String] = Some("1,3,5")
val l = a.toList.flatMap(_.split(",")).map(_.toInt)

Comment: Thank you dhg. I'm learning scala and this trick will help me a lot :)
Comment: This will not work for non numeric characters
_.toInt will throw NumberFormatException
Comment: @franki3xe, It also won't work if the input comes in pipe-delimited instead of comma-delimited, and it won't work if the input comes written in roman numerals, or in a secret code where integers are replaced by letters.  If you know what the input looks like, why would you add unnecessary complexity to guard against something that's not going to happen?
Comment: Hey dhg, i wanted to up vote again but i'm not allowed for now !!! It's weird cause i already up voted yesteray and now it came to 0 !!!
Answer: From where you are, you just need to map toInt over it.  But your order of operations is kind of weird.  It's like you're using toList just to satisfy the type.  toList is one of those smelly functions where if you're using it you're probably abusing something.
The logic that reads the best is that if you have a Some, then process it, otherwise you just default to the empty list (I'm guessing):
option match {
  case Some(str) => str.split(",").map(_.toInt)
  case None => List()
}

Or:
option.map(_.split(",").map(_.toInt)).getOrElse(List())


How to create dynamic material-ui elements in a react app?

Question: I am trying to create a dynamic mui grid element when a button is pressed in a react component. When I tried to create let newGrid = document.createElement('Grid') it does not work as a normal div creation.
Any suggestions?
Current code snippet:
return (
    <>
        <button onClick={addRow}>Add Row</button>
        <Grid container className='v-timeline-container'>
            <Grid xs={12} item className="v-timeline-item v-center v-border">
                <TextItems />
            </Grid>
        </Grid>

    </>

)

What I am trying to achieve dynamically:
return (
    <>
        <button onClick={addRow}>Add Row</button>
        <Grid container className='v-timeline-container'>
            <Grid xs={12} item className="v-timeline-item v-center v-border">
                <TextItems />
            </Grid>
            <Grid xs={12} item className="v-timeline-item v-center v-border">
                <TextItems />
            </Grid>
        </Grid>

    </>

)

Answer: React uses a VDOM to keep track of stuff internally, you manipulating the DOM directly using DOM APIs is considered dangerous. What you should do this something like this.
function App(){
 // you probably want to track the text items in each row,
 // so use an array of objects
 const [gridItems, setGridItems] = useState([]);

 // this function adds a new grid item
 const onClick = () => {
  setGridItems([...gridItems, {text: "new row", id: gridItems.length + 1}]);
 };

 return (
    <>
         <button onClick={onClick}>Add Row</button>
         <Grid container className='v-timeline-container'>
          {
            gridItems.map(item => (
             <Grid xs={12} item className="v-timeline-item v-center v-border">
                <TextItems>{item.text}</TextItems>
             </Grid>
            ))
          }
         </Grid>
    </>
 );
}

Answer: Using setState is a solution.
It increments a number in state to create an array from it.
In your case you will certainly push new data to an array when you click on the button. But you get the idea.

import React, { useState } from 'react';
import { Grid } from '@mui/material'

const ListItems = () => {
  const [items, setItems] = useState(1);

  const addRow = () => {
    setItems((prev) => prev + 1)
  }

  return (
    <>
        <button onClick={addRow}>Add Row</button>
        <Grid container className='v-timeline-container'>
            {
              [...Array(items).keys()].map((key) => (
                <Grid xs={12} item className="v-timeline-item v-center v-border">

{key + 1} row

                </Grid>
              ))
            }
        </Grid>

    </>
  )
 }

export default ListItems


How to accept programmatically a ringing call in Android 8.0?

Question: Is it possible to answer a ringing call programmatically on Android 8.0 (without human interaction) ? I used some methods from older releases, but they didn't work (for example the ITelephony Interface solution)...
Answer: Have you tried looking it up? What code do you already have?
This method worked for me:
<code>if (VERSION.SDK_INT >= 26) {
   IncomingActivity incomingActivity = IncomingActivity.this;
   new Thread(new C1736O(incomingActivity)).start();
} else if (VERSION.SDK_INT >= 21) {
   IncomingActivity incomingActivity2 = IncomingActivity.this;
   new Thread(new C1735LN(incomingActivity2)).start();
} else {
   Intent i= new Intent("android.intent.action.MEDIA_BUTTON");
   i.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(0, 79));

   IncomingActivity.this.sendOrderedBroadcast(i, "android.permission.CALL_PRIVILEGED");
   Intent i2= new Intent("android.intent.action.MEDIA_BUTTON");
   i2.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(1, 79));

   IncomingActivity.this.sendOrderedBroadcast(i2, "android.permission.CALL_PRIVILEGED");
}
</code>
Comment: I tried these methods too https://inneka.com/programming/android/end-call-in-android-programmatically/


What did halfnorm() go?

Question: I would like to generate a half normal distribution in R (just the values above my specified mean).
I have tried rhalfnorm() but R doesn't recognise this as a function, was this function only available in earlier versions of R? what function could I use instead?
Comment: `rhalfnorm` isn't is base R (and never was). I'd encourage you to use your favorite search engine for something like "r rhalfnorm". The first hit I got [was this](http://svitsrv25.epfl.ch/R-doc/library/fdrtool/html/halfnorm.html), which tells you (when you know what to look for) that it is in the `fdrtool` package, which you can load with `library(fdrtool)`. (See the "{fdrtool}" in the upper left of the link, or the "/library/fdrtool/" in the URL.
Answer: You can do that with the dtnorm, rtnorm,ptnorm,qtnorm functions in base  R described here. You will need to supply the cutoff values both lower and upper (in this case the mean for the lower) to get what you want.
Here is a link to the vignette:
tnorm vignette
Comment: Link-only answers (and I'd argue that this is more of a metaphor than an answer) , are deprecated in SO. There are further ironies that there is no vignette linked from that package Index and further that it's not a link to a "base R" package and even further it's a link to a severely outdated version of that package.
Comment: Thanks for the Strunk and White analysis....how would I give a solution when the asker did not give data? I gave what she asked for...a replacement to the defunct tool, which I tested (because it has been awhile since I used it) and it works. If you are just trolling to comment on language use, you can find better examples than vignette (and I would argue that you used the word metaphor wrong) I was trying to get Brooke headed in a direction...it is called help, what was asked for!
Comment: thanks bethany, that function looks like it would do the job perfectly. trouble is R doesn't seem to recognise it. I'm getting "Error: could not find function "rtnorm" "
Comment: @bethanyP; I didn't make the rules. In this case where you seem compelled to answer a low-quality question then you should provide some code that creates an example. Shouldn't be that hard. I would expect the requested  random number generation function to just take a single number, so supply one. The number 5 would be my choice.
Comment: Brooke...I was wrong about the base R. `install.packages('msm')` and it should be good to go.I have tested it and it works. Give it a try

What did halfnorm() go?


creating simple html page with typo3

Question: i have just installed typo3 but i'm not able to create a simple html page. I create a new page with the "page" tool but i cannot see it with the "view" tool. I only can see "not found" in the navigator. ¿where are saved the html pages that you create with typo3?
regards.
Answer: at first a warm welcome to the TYPO3 community!
TYPO3 does not create HTML files, but save the rendered pages in a cache system.
To get a well installed TYPO3 producing frontend output you need a few steps:

A root page in the page tree (your entry point to the page tree)
A site created with the sites module for the root page (handles domains, languages etc.)
A TypoScript template record at the root page (rendering definition for your page tree below the root page)

You will find documentation for this here:
TYPO3 page tree:

https://docs.typo3.org/m/typo3/tutorial-editors/master/en-us/Pages/Index.html

TYPO3 site handling:

https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/SiteHandling/Index.html

TYPO3 template record:

https://docs.typo3.org/m/typo3/tutorial-templating/7.6/en-us/Tasks/WorkingTypoScript/TypoScriptTemplate/Index.html

TypoScript quick overview:

https://docs.typo3.org/m/typo3/tutorial-typoscript-in-45-minutes/master/en-us/TypoScriptOverview/Index.html

TypoScript FLUIDTEMPLATE (Fluid is the TYPO3 template engine):

https://docs.typo3.org/m/typo3/tutorial-templating/master/en-us/Index.html
https://docs.typo3.org/m/typo3/reference-typoscript/master/en-us/ContentObjects/Fluidtemplate/Index.html

May be it could be interesting for you to install a distribution first, where everything is working already, so you will get a quick result:

https://docs.typo3.org/m/typo3/guide-installation/master/en-us/In-depth/Distributions/Index.html

If you have problems with your installation have a look there:

https://docs.typo3.org/m/typo3/guide-installation/master/en-us/Index.html

I hope this will help you.
Comment: @dostoyevski For some reason stackoverflow cuts my first line. So there should be a "Hi dostoyevski" :-D
Comment: i have read all those links, but i'm usable to show not even a hello world, i cannot see where is the mistake: (here's a image of what i get):https://postimg.cc/mcZGkY6x
Comment: i have read all those links but i'm unable to show a hello world: this is what i get:https://postimg.cc/mcZGkY6x
Comment: Ok, so the normal frontend works, but only the view module in BE gives you this error?
Comment: is only the vew mode.
Comment: any opinion about what could be the problem? thanks!

creating simple html page with typo3


Predator missile hack in MW2

Question: I was recently playing a team deathmatch game where I got the predator missile, called it in and when I hit the boost button it instantly exploded.  Instead of exploding on impact, it teleported...like commando predator...:)
How did someone manage to do this?  I was playing on PS3.
Answer: I think you were in a hacked lobby, not the lose all your stats hacked lobby hopefully.
MW 2 hacked on PS3

Predator missile hack in MW2


invalid add-on error while installing gmail addons

Question: I am trying to install my gmail addons on another gmail account and getting "Invalid addons" error message.

I have selected "Enable developer add-ons for my account" checkbox and provided id.
It is already working on my main gmail account on which i have written appscript code.
Does anyone have this kind of issue?
Comment: You should ask this question on the Google community:  [Developing add-ons for G Suite](https://plus.google.com/communities/117193953428311185494)
Comment: Thanks sandy for addressing google community.
Answer: we need to give read access to add-on's script project in order to install an add-on for @gmail.com.
It is already provided in the doc.
Comment: where document says like that "in order to install an add-ons for @gmail.com." me too got same problem
Answer: I cannot comment so answering, you need to share the Project folder from Google drive with the email who's trying to install your add-on.
This wouldn't restrict the user from accessing your code, as far as I can tell.


Insulation type to use on a hinged metal attic door

Question: In this question, I asked about the best type of insulation to use on a hinged metal attic door, when one is also concerned about heat entering around the edges of the door when closed.
The answer I received is a good one (and provides an answer to that question as it was asked), but adds an extra step to entering the attic.  If I may, I would also like to ask the separate question of when one is not concerned about the edges of the door, but just concerned about the lack of insulation of the door itself.  So...
What is the best type of insulation to use on a hinged metal attic door (no integrated ladder)?
Only concerned about heat entry through the door when closed.
Would like something that does not cause a mess when the door is opened, and does not add extra steps to entering the attic.  I'm thinking along the lines of something added to the metal door itself.  There are a number of choices, and I'm wondering what type of product is best.
Comment: Why not edit the original question instead of asking a new one? I would just use rigid foam and some caulk/liquid nails/silicone to attach it.
Comment: @user20127 Because someone already spent their time answering that question, and changing the question after the fact would not be respectful to the time they spent.  Also, I'm not sure which direction is best, so I am interested in learning answers to both questions.
Comment: @user20127... post your comment as an answer and I'll up-vote it, because that's what I would use.
Comment: @JimmyFix-it Can rigid foam insulation be cut with hand tools?  Is any safety gear needed?
Comment: Can be easily cut to size using a common utility knife, flooring/carpet knife. I have even seen craftsmen use a long blade kitchen knife to cut the thicker varieties. Sheets are often 4' x 8' from 1/2" to 2" thick. Use a dust mask, safety glasses, and gloves.
Answer: One recommendation is to use rigid foam insulation attached with caulking, liquid nails, or silicone.
Answer: Use rigid foam. You can cut it with a circular saw, or with a utility knife. Buy a 2 inch sheet that's R13, you an always double it up to get R26. Measure the size you need and cut with a circular saw, it cuts like butter. Make 2 and then attach to each other and the door with silicone.
You will still possibly have issues with air leakage around the door, but that's the best you can do attached to the door itself.
Answer: Dense Packed Denim With Breathable  Reflective Insulation On Both Sides Of The Denim. I'm not referring to a radiant barrier.


Challenges in writing wrappers for C++ functions so that they can be used from C code

Question: I am now writing wrappers for C++ functions, such that they can be used from C code.
The idea is to compile the cpp files using g++ and the c files using gcc, then link them together (!), but exposing ONLY those functions that are needed, to the C programs, by making them available in a header file 'test.h' (or maybe test.hpp?), like so:
(Note how I do not expose function 'vector Tokenize(const string& str,const string& delimiters)')

test.h:

/* Header can be read by both C+ and C compilers, just the way we want! */
#ifndef TEST_H
#define TEST_H

#ifdef __cplusplus
extern "C" {
#endif

#if defined(__STDC__) || defined(__cplusplus)
 extern int TokenizeC(const char* text, const char* delim, char ***output);   /* ANSI C prototypes */
 extern void reclaim2D(char ***store, unsigned int itemCount);
#endif

#ifdef __cplusplus
}
#endif

#endif /* TEST_H */

test.cpp:

#include <string>
#include <iostream>
#include <vector>

#include <assert.h>

#include "test.h"

using namespace std;

vector<string> Tokenize(const string& str,const string& delimiters)
{
 vector<string> tokens;

 string::size_type delimPos = 0, tokenPos = 0, pos = 0;

 if(str.length() < 1)  return tokens;

 while(1)
 {
   delimPos = str.find_first_of(delimiters, pos);
   tokenPos = str.find_first_not_of(delimiters, pos);

   if(string::npos != delimPos)
   {
     if(string::npos != tokenPos)
     {
       if(tokenPos < delimPos) tokens.push_back(str.substr(pos,delimPos-pos));
       else tokens.push_back("");
     }
     else tokens.push_back("");

     pos = delimPos + 1;
   }
   else
   {
     if(string::npos != tokenPos) tokens.push_back(str.substr(pos));
     else tokens.push_back("");
     break;
   }
 }

 return tokens;
}

int TokenizeC(const char* text, const char* delim, char ***output)
{
    if((*output) != NULL) return -1; /* I will allocate my own storage, and no one tells me how much. Free using reclaim2D */

    vector<string> s = Tokenize(text, delim);

    // There will always be a trailing element, that will be blank as we keep a trailing delimiter (correcting this issue would not be worth the time, so this is a quick workaround)
    assert(s.back().length() == 0); // This will be nop'ed in release build
    s.pop_back();

    (*output) = (char **)malloc(s.size() * sizeof(char *));

    for(vector <string>::size_type x = 0; x < s.size(); x++)
    {
        (*output)[x] = strdup(s[x].c_str());

        if(NULL == (*output)[x])
        {
            // Woops! Undo all
            // TODO : HOW to test this scenario?

            for(--x; x >= 0; --x)
            {
                free((*output)[x]);
                (*output)[x] = NULL;
            }

            return -2;
        }
    }

    return x; /* Return the number of tokens if sucessful */
}

void reclaim2D(char ***store, unsigned int itemCount)
{
    for (int x = 0; itemCount < itemCount; ++x)
    {
        free((*store)[x]);
        (*store)[x] = NULL;
    }

    free((*store));
    (*store) = NULL;
}

poc.c:

#include <stdio.h>
#include "test.h"

int main()
{
    const char *text = "-2--4--6-7-8-9-10-11-", *delim = "-";

    char **output = NULL;

    int c = TokenizeC(text, delim, &output);

    printf("[*]%d\n", c);

    for (int x = 0; x < c; ++x)
    {
        printf("[*]%s\n", output[x]);
    }

    reclaim2D(&output, c);

    return 0;
}

Do you notice something wrong?
For starters, when I ran this program, I got "Unsatisfied code symbol '__gxx_personality_v0'"
Thankfully, there is something here : What is __gxx_personality_v0 for?
Once I ran g++ with options " -fno-exceptions -fno-rtti", the output now fails with "Unsatisfied data symbol '_ZNSs4_Rep20_S_empty_rep_storageE'"
Ofcourse, the two environments (the one to compile - HP-UX B.11.23 ia64 and the one to run the binary on - HP-UX B.11.31 ia64) have different library versions (but same architecture), and this should not be a reason for the errors.
I would also like to test out the case marked by "// TODO : HOW to test this scenario?", but that can wait for now.
Any pointers?
Answer: The easiest way to avoid undefined symbols while linking is to link with g++ (not gcc). You can still compile your .c file with gcc, though.
Also please use system at a time. The link error may go away if you run all your gcc and g++ commands on the same system (no matter the old or the new one).
Comment: This is what I did:

g++ -c -fPIC -Wall -Wuninitialized -fno-exceptions -fno-rtti -O -D__hpuxita -mlp64 -I$(INCLUDEPATH) $< ;

gcc -c -fPIC -Wall -Wstrict-prototypes -Wuninitialized -O -D__hpuxita -mlp64 -I$(INCLUDEPATH) $< ;

gcc -AA -Aa -mlp64 -shared -L$(LIBPATH)  $(OBJS) -o $(APP)
Comment: +1, the problem is the last line there, you should link with g++ not gcc which will include all the neccessary c++ stuff by default.
Comment: Evan, yes, but then would not the resulting binary be a C++ binary with mangled names etc? I would want the resulting binary to be a C one. I want to use C++ only in specific instances where using the STL would be extremely beneficial, but the resulting binary needs to be C compatible.
Comment: The message 'Unable to find library 'libstdc++.so' is stopping all the fun now - maybe if I can locate the lib myself, the executable will now finally run?
Comment: Funny thing is even if I set SHLIB_PATH, LD_LIBRARY_PATH_64, LD_LIBRARY_PATH and, hell, even PATH to point to the .so file, I STILL get the error message!
Answer: To call a C++ function from C, you can't have mangled names. Remove the conditional test for __cplusplus where you do the extern "C". Even though your functions will be compiled by a C++ compiler, using extern "C" will cause it to avoid name-mangling.
Here is an example:
The C file.
/* a.c */
#include "test.h"

void call_cpp(void)
{
  cpp_func();
}

int main(void)
{
  call_cpp();
  return 0;
}

The header file.
/* test.h */
#ifndef TEST_H
#define TEST_H
extern "C" void cpp_func(void);
#endif

The CPP file.
// test.cpp
#include <iostream>
#include "test.h"

extern "C" void cpp_func(void)
{
  std::cout << "cpp_func" << std::endl;
}

The compiler command line.
g++ a.c test.cpp

Comment: and I should use gcc instead of g++ to link - unlike what Evan told above?
Comment: removing the conditional test to get no name mangling seems to mess with the prototype declaration in the header file because gcc barks at me "warning: implicit declaration of function 'TokenizeC'"
Comment: The conditional works only for C++, where it SHOULD work... I believe that is not the issue.
Comment: Why do I need to have the extern at both places - the source and the header? Is not having it in the header enough?
Comment: The declaration and definition must match. That's the reason you got the: "warning: implicit declaration of function 'TokenizeC'".
Answer: Is there a reason why you haven't considered modifying Swig to do just this?  I seem to remember that there is a developmental branch of Swig to do just this...
Comment: It's hard to find...  I think most people just end up using C++ for the glue code, however I have managed to find the following link, and I think that is the same link that I remembered in the past, although I suspect that there has been little interest: http://swig.svn.sourceforge.net/viewvc/swig/branches/gsoc2008-maciekd/Doc/Manual/C.html
Comment: I was, when I asked the question, under the belief that using Swig to interface C++ code with C be too much of a workaround. I would be interested in looking at the path though - if you had some links.
Comment: Yes, I use C/C++ in production code, and I prefer rewriting code to have least dependencies in such cases. +1 for the link though.


Lua/ Torch - Error while creating train.t7 and test.t7 files using custom data set

Question: I am trying to feed my own dataset to the CNN model I created. The code to create the training and testing .t7 files is uploaded here.
I tested this code by creating a train_set.t7 of 5000 images and test_set.t7 of 500 images. Everything went well and I was able to load the images to the CNN model. Then I tried creating another set of .t7 files from a larger dataset. I would like to explain a bit about the organization of the dataset. There is a ROOT folder called data (in the code, look for ROOT). There are two sub folders in it: train and test. Each of these sub folders are divided into 5 different folders named: 1, 2, 3, 4 and 5. Each of these folders have around 70,000 images in the case of train.
The problem is that my code throws the following error after adding all the files from data/train/1:
 /home/ubuntu/torch/install/bin/luajit: ...e/ubuntu/torch/install/share/lua/5.1/torchx/indexdir.lua:53: attempt to perform arithmetic on a nil value
stack traceback:
    ...e/ubuntu/torch/install/share/lua/5.1/torchx/indexdir.lua:53: in function 'indexdir'
    create_t7.lua:25: in main chunk
    [C]: in function 'dofile'
    ...untu/torch/install/lib/luarocks/rocks/trepl/scm-1/bin/th:150: in main chunk
    [C]: at 0x0000cff9

I tried changing the order of folders, but it didn't help. What does this error indicate? Thanks in advance.
Answer: The error means that that either findFile variable or shell command wc -L 'findFile' | cut -f1 -d on line 53 in indexdir.lua results in nil.
local maxPathLength = tonumber(sys.fexecute(wc .. " -L '"
                                            .. findFile .. "' |"
                                            .. cut .. " -f1 -d' '")) + 1

So, basically lua attempts to perform nil +1 operation which is an error.
Check carefully your path_local paths.
Comment: My `path_local` are right. I recently tried using this code in a machine with larger RAM and it worked. I am trying to see if there are better alternatives.
Comment: This might not be the "not enough" RAM issue but the `wc` shell command which results in `nil`. Do both machines run linux?
Comment: Yes. But the machine which throws the error is a Jetson TX1. The second machine is a Lenovo laptop.


Proof of "Extension" for Rice's Theorem

Question: We define:
F as the set of all computable functions.
P is a subgroup of F.
And we say P is trivial if P = emptyset or P=F.
prove: 1-if P is trivial the language L={(M) | M is a TM that computes a function that belongs to P} is recursive.
2- if P is non trivial then L is not in R.
Im having a hard time proving the case when P=F. any suggestions ?
Answer: In order for the problem to make sense, $F$ has to be the set of all partial computable functions. Then when $P=F$, the language $L$ is by definition the set of all possible $\langle M\rangle$.
The result is false if $P$ is the set of all total computable functions. In that case $L$, far from being recursive, is the $\Pi_2$-complete set known as $\it Tot$.

Proof of "Extension" for Rice's Theorem


Get ip and subnetmask using command sed

Question: So I want to get my ip adress and subnetmask. The output of ifconfig should be "pasted" to sed. So sed should modify the output in order to get only the ip and subnet mask.
Like:
ifconfig | sed -n -e s/:127\.0\.0\.1 //g -e s/ *inet addr:\([0-9.]\+\).*/\1/gp

Edit:
ifconfig | sed -rn '/((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])/p'

With this I got the subnet mask and the ip BUT I also got Bcast. How can I change the regex to get only subnet mask and ip?
Output of edit:
inet Adresse:192.168.142.191
 Bcast:192.168.255.255
 Maske:255.255.0.0
 inet Adresse:127.0.0.1
 Maske:255.0.0.0

I want this output:
inet Adresse:192.168.142.191
Maske:255.255.0.0

Comment: ipconfig or ifconfig? would be useful if you add output before using sed as well your final expected output
Comment: @Sundeep see edit
Answer: Try this:
ifconfig | grep -v 127.0.0.1 | awk '/inet / {gsub("addr:", "", $2); print $2}; /netmask / {gsub("netmask", "", $2); print $4};'

It's output exclude loopback interface "lo 127.0.0.1". And gives to you and output like this:
10.0.0.1
255.255.0.0
192.168.1.46
255.255.255.0

One line per ip or mask. Or you can specify only one interface doing ifconfig eth0 instead of ifconfig. In this way you print only desired interface.
If you want the exact format with the "inet", "Adresse", etc. You can add it to awk:
ifconfig | grep -v 127.0.0.1 | awk '/inet / {gsub("addr:", "", $2); print "inet Adresse:"$2}; /netmask / {gsub("netmask", "", $2); print "Maske:"$4};'

Its output is:
inet Adresse:10.0.0.1
Maske:255.255.0.0
inet Adresse:192.168.1.46
Maske:255.255.255.0

Answer: Why did not use like this:
ifconfig |sed -n 's/inet addr:\(.*\)Bcast:.*Mask:\(.*\)/\1 \2/p'

But you need more concrete regex for ip. You can find it in google.
Answer: Consider combining the -n option and the search and replace command s/regexp/replacement/. Make it match the whole line and replace it with only the bits you need:
ifconfig | sed -rn 's/^.*(inet[0-9. ]+netmask[0-9. ]+).*$/\1/p'

Your ifconfig output seems to be different from mine so you might need to change the inet and netmask parts for it to work on your system.

Get ip and subnetmask using command sed


Default Route for every http request

Question: I need to set a default function for my web app that return for every http request a maintenance view.
I did it:
Route::group(['prefix' => '/'], function() {
     return view('maintenance');
});

but when I go for example to http://www.mypage.com/profile
it works.
How should I set my routes?
Thank you.
Comment: Why not setup a middleware group and run an if statement?
Comment: @Roland, I think it's more to the point of if the page is having work done to it, it'll show its under maintenance rather than not found.
Comment: Can you paste me the code please? @Option
Comment: laravel has a maintenance mode feature https://laravel.com/docs/5.5/configuration#maintenance-mode
Comment: How are your pages stored firstly, via DB or just hardcoded in?
Comment: I want just a maintenance page for every http request
Comment: @Fran, is this to throw the entire website into maintenance mode or just some pages? Once you answer this i'll be able to assist further..
Answer: To make this the easiest way possible to take the entire website into maintenance mode (as I am unsure if this is every page at once or separately).
You could do the following via using the database:
php artisan make:migration create_maintenance_mode_table --create=maintenance_mode
Within this file add a simple:
$table->integer('enabled')->default(0);
Then run php artisan migrate
Then setup the Model:
php artisan make:model Maintenance
within this file add:
protected $table = 'maintenance_mode';

protected $fillable = [ 'enabled' ];

After this we need to set up the middleware:
php artisan make:middleware CheckMaintenanceMode
Within this files handle function you need to add:
$maintenance = Maintenance::select('enabled')->get()->first();

        if ($maintenance->enabled == 1)
        {
            return view('maintenance');
        }

        return $next($request);

Within the kernel.php file add within $routeMiddleware
'maintenance' => \App\Http\Middleware\CheckMaintenanceMode::class,
You now need to setup the views file: maintenance.blade.php
Now within the routes file you need to add the following around all of your other route requests:
Route::group(['middleware' => ['maintenance']], function () {
    // Other Routes
});

Seems fairly long winded and you can do it other ways but this is something I'd use on my own projects.
Answer: why dont u use the integrated maintenance mode ?
php artisan down

to disable maintenance mode use
php artisan up

to exclude your IP to continue development you can try this middleware
class CheckForMaintenanceMode {
protected $app;

public function __construct(Application $app)
{
    $this->app = $app;
}

public function handle($request, Closure $next)
{
    $white = $_ENV['MAINTENANCE_WHITELIST'];        // Get WhiteListed IP from .ENV
    $ip = $request->ip();                           // Get Visior IP with no Proxy (like Cloudflare)
    // $ip = $_SERVER["HTTP_CF_CONNECTING_IP"];         // Get Real Visitor IP with CloudFlare enabled
    if ($this->app->isDownForMaintenance() &&
        !in_array($ip, [$white]))
    {
      $maintenanceMode = new MaintenanceMode($this->app);
      return $maintenanceMode->handle($request, $next);
    }
    return $next($request);
}}

dont forget to add the middleware to /app/http/kernel.php
protected $middleware = [
   ...
   \App\Http\Middleware\CheckForMaintenanceMode::class,
   ...
];

Answer: Laravel has maintenance mode support without

Execute php artisan down in the command line for enable maintenance mode (you can use php artisan up, for disable maintenance)
If you dont want use artisan. You can create 'down' file manually in storage/framework/down for enable maintenance or remove it for disable

Also, you can create maintenance view in resources/views/errors/503.blade.php
MORE INFO: https://laravel.com/docs/5.5/configuration#maintenance-mode

Default Route for every http request


convert unknown file type readable by notepad to .csv files

Question: I have 300 files with extension .EMA (never seen before) that I would like to convert to .csv files. The files are perfectly readable in Notepad. However, I need to convert them to .csv files as I want to read them with Python.
Does anyone know how to convert the files in a quick way?
Thanks.
Comment: Where did the files come from?  Do you have a spec of their format?
Comment: Without knowing anything about what's in those files or what their format is like, we can't tell you how to put the data into a different format.
Answer: The file extension doesn't determine the file contents. Both  .csv and your file can be opened in notepad because they are text files. You don't have to do anything in this case - just use the file with .EMEA extension and it will work same thing as .csv
EDIT:
New information from comments seems to indicate the file is a csv-like file but using | as separator instead of the comma; if you're using pandas, try using
pd.read_csv('file.EMEA', delimiter='|')

Comment: Assuming there's actually CSV-formatted data in those files, anyway. The question says it's "perfectly readable" in Notepad, but that doesn't mean it's CSV.
Comment: @user2357112 I mean that python can open any file, regardless of the extension. Python can open non-csv files too.
Comment: Certainly true, but processing the data will have to be done differently for CSV or non-CSV. You can't just pass it to `csv.reader` or `pandas.read_csv` or whatever you would have used with a CSV file. Opening the file and getting raw bytes or characters out is only a small part of the story.
Comment: @user2357112 maybe it is a csv file, who knows - the OP seems confused about the extension, and I am clarifying that the extension is unrelated
Comment: The problem with Notepad is that it tends to ignore characters it can't understand, just because it is "perfectly readable" doesn't mean it is all ASCII text.
Comment: I tried this. It gives the same result as without the file conversion (so this answer is consistent). I can read the file as a DataFrame but the object does not clearly contain the data. I am able to read the number of records (5536) but I cannot access entries.

Possibly the file is wrecked ... I understand this is hard to answer for you guys.
Comment: Perhaps you can provide an excerpt with some lines from the file so we can take a look
Comment: Typically one line is as follows:

CD.FW.003121|CF|USD|FO|OBROTFB|20170929|SEP17|20170102|171500|515.239644335|515.239644335|515.239644335|Source|Passed
Comment: It seems a csv file using `|` as separator instead of the comma `,`; try using `read_csv('file.EMEA', delimiter='|')`
Comment: Thanks, that was a bit stupid. I forgot the delimiter ....


bash: /path/.bash_aliases: Permission denied

Question: I don't know why this line appears first when I open my gnome-terminal.
bash: /home/username/.bash_aliases: Permission denied
laptop-dell:-$

I tried this but still the problem remains there.
chmod +x ~/.base_aliases
chmod: cannot access `/home/username/.base_aliases': No such file or directory

What should be the default permission of 'bash_aliases' ?
How to fix this ?
Comment: I suppose it doesn't *literally* say `/path/`, and that you made it up for the question, i.e. that the path is not the problem?
Comment: Default permission should be `-rw-r--r--` same as `.bash_profile` or `.bashrc`.
Comment: @jos doubt it. ... Vipul: please provide the actual commands and errors. If these are it ... "path/" ...  ?
Comment: @Jos, Yes, you are right, I just made it for the question. that's not the real problem.
Comment: @VipulBhatt Please just change the username if you don't want to show your real username, otherwise it ends up being rather misleading for people reading the question.
Answer: Using the right command and file names ;), in your second command is a typo: ~/.bash_aliases and not ~/.base_aliases
sudo chown $USER:$USER ~/.bash_aliases

and so I can sleep peacefully (thank you @ByteCommander)
chmod 644 ~/.bash_aliases

And maybe it's time to correct the permissions for the whole folder:
sudo chown -R $USER:$USER $HOME

Comment: Maybe you should not just `chown` it but also set the correct permissions, depending on what got messed up... `chmod 644 ~/.bash_aliases`
Comment: @ByteCommander Yes, you're right.
Comment: Hello @A.B.,  My terminal is not opening after performing these commands !!!
Comment: Switch to TTY1 via Ctrl-Alt-F1  and login. What is the output of `echo $USER` (Back to your GUI via Ctrl-Alt-F7)
Comment: My username, @A.B.
Comment: why aren't the perms 755?
Comment: @chicks executable rights are not necessary.
Comment: @VipulBhatt this has nothing to do with the command in my answer. Start the last command again in tty1
Comment: As in my case i was using the wrong "command", as i was having `$Editor` instead of `$EDITOR`
Answer: I do a similar thing in my .bashrc file.  I use this compound statement and it works:
if [ -f ~/.bash_aliases ]; then
   source ~/.bash_aliases
fi

The key is the source command.  I don't know if this is "bad form," but it works.


unable to create logs in aws S3 bucket using 'winston' and 's3-streamlogger'

Question: const winston = require('winston');
var S3StreamLogger = require('s3-streamlogger').S3StreamLogger;

var s3_stream = new S3StreamLogger({
    bucket: "bucket_name",
    access_key_id: "access_key_id",
    secret_access_key: "secret_access_key"
});

var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.File)({
            stream: s3_stream
        })
    ]
});

exports.handler = function (event, context) {
    winston.info('Hello Winston!');
    console.log("This is logging demo");
    logger.info('Logging is in progress');
    console.log("Consol Starting Lambda function");

    var responseCode = 200;
    var responseBody = {
        message: "Hello !",
        input: event
    };
    var response = {
        statusCode: responseCode,
        headers: {
            "x-custom-header": "my custom header value"
        },
        body: JSON.stringify(responseBody)
    };
    console.log("response: " + JSON.stringify(response));
    context.succeed(response);
};

On executing above code(successfully) on aws lambda. I am getting cloudwatch logs but there is nothing generated inside my S3 bucket.
I was hoping for a log file to be created over there but nothing created.
Am i lacking something in the code ?
My aim is to generate log file in amazon S3 bucket so that i can download the file for analysis.
Answer: s3-streamlogger buffers content before uploading it to s3. By default it will buffer for 20 seconds, or 10kB of content (whichever is less) – so if your lambda function doesn't execute for at least 20 second, or write 10KB of logs nothing will be written before your function is suspended.
You could either specify smaller thresholds for the buffering via the upload_every and buffer_size options (see https://github.com/coggle/s3-streamlogger#upload_every), or manually flush the file after each request by calling flushFile on the stream.


Leo's passive skill

Question: Today I got a Leo, but haven't had the opportunity to deal with him very often.
His 3rd skill (passive) lacks description, so I have a few questions about it.

Eye of the Storm (Passive)
  The attack speed of all enemies and allies
  is limited to your attack speed.  (...)

What happens if you buff your own team with Speed (e.g. using Bernard) and Leo (on Violent Runes) used up his charges before the rest of my team?
Does everyone fall back to Leo's now lower Speed instantly or on his next turn?
Example:

Also, if Leo dies the skill will no longer affect anyone and all monsters will regain their original Speed (if higher than Leo's). But since it's a passive skill, can you disable it (unlike Theomars' Elemental King, which can be put on cool down) with skills other than Tesarion's passive, which explicitly does that?
Answer: With his passive, the speed of all monsters, both enemies and allies, is capped at Leo's speed value and leo moves first.
For example if all monsters have 200 total speed and leo has 120 speed, then all monster will have 120 speed, but Leo will move first. The speed of all monsters immediately change.
And no, there is no way to, in my knowledge, turn off a passive skill.
Comment: Does this also count for getting and losing speed buffs? That's what the question primarily is about. I know the effect of Leo's passive, but I want to know if it's instantly updated if Leo's speed changes during the fight (e.g. getting or losing a speed buff).
Comment: Yes if his speed changes the rest will immediately change to match

Leo's passive skill


How to use App::before() Laravel 5.0

Question: i did a migration from Laravel 4.2 to 5.0, and reading another questions, i created a new Middleware on my app\http\middleware but, i don't know how implement this to my RouteServiceProvider.php
This is my BeforeMiddleware:
<?php namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware {

 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
    return $next($request);
 }

}

And on my RouteServiceProvider i got this
App::before(function($request)
{
    //I think here need to be my code...
});

Answer: You need to register your middleware in the app/Http/Kernel.php file.
Here you will find 3 options:
protected $middleware = [..] <-- run on EVERY request

protected $middlewareGroups = ['web'=>...] <-- run on all web routes

protected $routeMiddleware = ['auth'...] <-- run on routes when defined

Comment: It was declared on the  _app/Http/Kernel.php_.
Only with that options will work? or i need just something else?
Comment: Yes - these are your options now. The `before` filter was replaced by middleware in Laravel 5.0. You'll probably want to register your middleware for every request, as that's how `before` would have worked for you previously.
Answer: I had to deal with this same situation some time ago for a CRM, and the ideal approach is to migrate what you had within App::before() in Laravel 4.2 to a service provider in Laravel 5.0.
At first you can just use the boot() method located in the AppServiceProvider, in a way that you can test the waters.
From there you can opt to have a dedicated service provider just to hold this part, such as AppBeforeServiceProvider.
You have mentioned a migration to middleware, but that is actually for filters coming from Laravel 4.2.

How to use App::before() Laravel 5.0


Not able to find asp.net 3.0 in IIS

Question: I have installed VS 2008 on my win2k3 server and when i am try to create a new site in iis, but not able to find asp.net 3.0 version in dropdown list of asp.net version
Answer: .NET 3 and 2.5 are .NET 2 plus extra assemblies.
Just select 2.0.x.

Not able to find asp.net 3.0 in IIS


What is this pipe? It leaks when the sink runs

Question: I have a pipe that is halfway under a door jamb and inside the concrete floor which when I run a the sink water is now coming out of it. This pipe is next to our AC blower unit inside the basement. I suspect this is somehow connected on the other end to our sewer septic tank and was never capped correctly when they made   changes to this 40 year old house.
Does anyone know why there would be a line near the AC unit?
(Could it have been an original condensation drip line into the septic tank?)
Any suggestions on how to uncover more of the line to cap it?
I am guessing this also means the septic is nearly full and needs to be pumped. Original owners didn't know where it was located to tell us at time of sale a year or so ago.
Any ideas on how to find it?
Comment: The wooden box is part of what the air handler sits on and is connected to an air return vent.
Comment: The pipe appears to be crushed near the end. I'd guess that was someone's attempt at "capping" the pipe. Obviously that crush has failed, so it's up to you to do it right.
Comment: "septic is nearly full and needs to be pumped" - yes, post haste. I'd bust up the floor and expect to find a hole bashed with a hammed in the drain pipe that this just sticks into. ABS would need a barbed fitting, cast iron and clay don't have those. It might all be PVC and done 'right' but I doubt it. - Either way the concrete's gotta go, or all you can do is a stop gap (stuff it with something and let cement fill it when you patch the floor).
Comment: As far as finding the septic, when I bought a house with a septic system, knowing only that it was somewhere in the front yard, the septic company guy started stabbing down with a long spike in various areas of the grass until he hit it, then dug it up.  If you don't know which part of the yard it's in, you can start with tracing where the drain pipe leaves your home.
Comment: Do not listen to Mazura @Roberts2600. This house was built in 2007, as OP states. Cast Iron and clay are out of the question. Concrete doesn't "gotta go" until last case scenario... Does OP smell human waste constantly? Is slab wet from underneath in that area with no idea why? No, that was not stated. This is directed toward an AC unit, you don't say but It's likely there from new construction, and pipe could very likely be a defunct condensate line. As for barbed nonsense... ABS gets an ABS cap (under $10 at the box stores), and ABS glue.
Comment: @Roberts2600... This looks like smashed ABS, but if it's poly (ABS is rigid, poly is more noticeably flexible but in a short run like this it is still fairly rigid) you can cap same as above, I would not use rubber... rubber fittings are more expensive. A pipe cap and glue is a permanent fix, rubber "can" be a permanent fix but a rubber cap from the hardware store shelf isn't designed for that (though you wouldn't be the first one to use them that way)
Answer: Poly is flexible, I haven't seen it used as a drain like abs that is rigid.
With a septic system in winter it could be your field is flooded (standing water where the field is?).
Another cause is a partial plug up below this point it's not always a failed system heavy rain fall and a flooded drainage field the water takes longer to dissipate into the ground.
That could have been a condensate drain for the AC system but not well done. I would cap it using a rubber cap. Fernco makes them.
Cut off pipe square slide cap on and tighten the hose clamp 5$ fix for now.
There may be other ways but a fernco end cap would be my choice in this case.
Answer: It's tough to say what the cause is because it might just be that the end of that pipe intersects the sink drain line and the pressure alone siphons some liquid out, like maybe it's sub par plumbing and there was an old wash sink where the AC unit now lives... you could just cap it yourself.
Now incidentally, you might be right that your septic is due for replacement. You mention a pretty common indication that it could be full: the septic tank is at least one owner's tenancy old... maintenance should be around every 7 years. Now, if that pipe is flowing any time you use a drain, then yeah, that's a very strong sign but still could just be a bad plumbing problem like a low spot that some knucklehead tied into and if that were the case you could just cap it.
A good test would be, cap that mystery pipe, and run the sink to see if it backs up. It still may not mean your septic needs to be replaced, but it could tell you if that pipe is showing signs from some other blockage.
As for how to find it, the company you hire to replace it will snake/probe/cam the lateral with a probe and use a locator... basically same as locating a buried utility.
Comment: Thanks Jon. It seems this pipe is black ABS, black poly tubing or something similar.  I have added another photo for clarity. I also think you are right on the sub-par work. I'll get it capped and hopefully I won't have any further issues. Again thanks!


Vertical & Horizontal Scrollable UI

Question: I am creating a UI that will allow users to search. The search results are displayed in a section that is scrollable both horizontally and vertically. This is weird because the web page will end up with 2 scrolls:

one of the section
one of the webpage

Please share your thoughts on how I can handle this.
Comment: Are you saying that the results section scrolls both vertically and horizontally, and the webpage itself also scrolls vertically?
Comment: Thanks for your response. Yes Charles. The search results can be very extensive and so needs to be scrollable vertically and horizontally. It is also to provide a visual cue to the user that they can scroll through the results. Relying only on the webpage's scrollbar for the cue may not be sufficient.
Answer: Horizontal scrollbars should be enough, but try to redesign the search results not to require them.
Most users can use other means for scrolling a page other than just the scorllbars:

mouse wheel,
page up / page down
right side of a laptop pad

These usually do not exist for horizontal scrolling — you will force the user into a suboptimal experience.
If Google can do without horizontal scrolling, maybe so can you? :)
Comment: I tend to agree with you, Boris, but I have seen plenty of search results, especially in business web applications, where the search results show a lot of columns. For example, an app where you manage product data and the search shows 10-15 columns to help identify (and potentially even edit inline) products or groups of products. A search like that is likely going to need scrolling horizontally.
Comment: I agree with Boris and Charles. However, if your user has to horizontally scroll back and forth (e.g. to compare tabular data or read prose) this is generally a Bad Thing. As well as being inefficient it is tedious as well. There are many situations when horizontal scrolling is appropriate, but I would recommend checking and rechecking that it is actually needed.
Answer: Whenever I have been approached with this sort of interface, my response has always been the same - let the browser control the scrolling. Users understand what browser scrollbars are and how they work (both horizontally and vertically). My research and testing has shown that when you have the main content section of a page (the search results in this case) scroll independently of the rest of the content, it confuses more users than it helps.
Contrary to your comment, I believe that the web page's scrollbars are more than enough of a cue that the page scrolls. It is a common interface element that any average web user is going to understand.
EDIT:
To make horizontal scrolling more obvious, you can follow the design paradigm that Microsoft has chosen with Windows Phone 7. If it looks like the content is being cut off, the user will understand that there is more to the right and will know to scroll that way to see it. In a typical website design, if your content is wider than the viewing window, you probably don't even have to do anything extra. If you've got a grid of results, with borders and/or alternating row colors, as long as those identifying characteristics go all the way to the edge of the browser window, even if the content happens to cut off (e.g. the current column happens to end right before the edge of the screen), that visual cue will help the user understand that there is more to see.
Comment: @Tara - While not as common, users in general still understand horizontal scrolling in a browser. I'll update my answer with a little more on how to make sure it's obvious.
Comment: The browser's scrollbars are enough. I also find it very hard to use a website that has both scrollbars on the browser and on some inner DIV. Scrolling DIVs also don't look scrollable on phones and tablets (iOS and Android). You'll confuse those mobile users.
Comment: True, vertical scroll is intuitive for a web user. How about horizontal scroll?
Answer: I think the horizontal scroll is much easier to apply than the vertical one, as the vertical scroll is a user experience weakness point for any site, i suggest you create a grid to guarantee your page width and stick with it, then scroll horizontally as much as you want.

Vertical & Horizontal Scrollable UI


How to properly read touch events and get position on a QWidget Qt

Question: I'm trying to develop a game controller for an android app in qt and am having some issues. The controller works perfectly fine when I just use QMouseEvents instead of QTouchEvents, but the problem is that it doesn't support multiple points of contact. There doesn't seem to be an equivalent for QWidget::mousePressEvent for touch events. I was told to use QWidget::event instead as such.
bool GameController::event(QEvent* event)
{
    switch(event->type())
    {
    case QEvent::TouchBegin:
         //Do something...
         break;
    case QEvent::TouchEnd:
         //Do something else...
         break;
    case QEvent::TouchUpdate:
         //Do something else...
         break;
    }
    return QWidget::event(event);
}

The problem with this is that I'm unable to use event->touchPoints() to get the position of the touches because it doesn't know that its a touch event. How can I properly read touch events?
Answer: The compiler may not know it's a touch event, but as long as you know it, you can downcast:
case QEvent::TouchBegin:
{
   QTouchEvent * te = static_cast<QTouchEvent *>(event);
   // now you can call te->touchPoints(), etc here
}

Note that the above code will invoke undefined behavior if event isn't actually pointing to a QTouchEvent (or a subclass thereof), so only use static_cast when you can 100% guarantee that event is actually a QTouchEvent (which AFAIK you can in this scenario).
For cases where you can't guarantee the downcast will be valid, you can use dynamic_cast instead, which is smart enough to check the pointed-to-object and return NULL if it isn't actually valid to downcast to that type:
case QEvent::TouchBegin:
{
   QTouchEvent * te = dynamic_cast<QTouchEvent *>(event);
   if (te)
   {
      // now you can call te->touchPoints(), etc here
   }
}

Of course that runtime check costs a few CPU cycles, so don't use dynamic_cast unless you need to.
Answer: All of the protected functions/event handlers for various types of events for QWidget (e.g. QWidget::showEvent(QShowEvent*), QWidget::hideEvent(QHideEvent*)) are specializations of the general QWidget::event() method for your convenience.
And QWidget::event() itself is implemented through the QObject::eventFilter() virtual method. You can read more about it here - https://doc.qt.io/qt-5/qobject.html#eventFilter. Through the help of  bool eventFilter(QObject *obj, QEvent *ev) override, you can get notified about all QEvents that are sent to your QObect as well as to other objects through the use of QObject::installEventFilter().
In the body of your implementation of QObject::eventFilter() you check the type of the event as well as its receiver and then after that do either static_cast or dynamic_cast as described by @Jeremy Friesner to access the methods specific to that event. Using this powerful mechanism you can implement your own specialized event functions, as well as custom signals, if you want your sub-classed QObject to emit a signal in case of an event.


Inputs for difficult form

Question: We have a difficult form in our application.
There are all sorts of inputs: start date, end date, full name, phone and e-mail address, and a section for count of people in rooms (adult/child...).
The basic requirement is that the form can be filled very quickly.
My question is: which inputs choose for this form - especially for table with counts?
Comment: We'll need some more details, I suppose ... Why do you judge the form "difficult"? Can you show us a sketch of it, and why you aren't satisfied with it? Is it a website, mobile app or desktop application? Etc.
Comment: And can you expand on the rooms aspect - is it that you need to say there are x adults and y children in each of z rooms? i.e. How many variables?
Comment: Thanks for the reply. Form is difficult becouse contains too much information and it's core of our project.

User selects rooms (it is possible to select multiple rooms), date on calendar and then form shows up. Then user have to fill personal information and count of adult/children on every selected room.

x = room count
y = person type count (adult/child/...)

You have to set x*y variables.

For example: If you select 4 rooms (and you have 3 person type), you have to set 12 variables.
Comment: Can you add a screenshot/mockup of what you already have? I *think* I kind of understand what the form is about but am not sure.
Comment: Another question: how often is this form used? It may be very quick to fill in, but difficult. But a user using it the first time will prefer the contrary: easy choices, even if it takes a little longer.
Comment: This is mockup of our form [link](http://img153.imageshack.us/img153/8042/mockw.png). User have to set numbers in table.
Comment: @giraff Users use this form every day several times.
Comment: When there are these huge forms to be filled I found that many users where glad if we could pre-fill the form with the data we already knew.
Try to see if there is a way you can pre-populate some of the input fields, perhaps try also to highlight them and let the user clearly distinguish those pre-filled from those they filled manually.
Answer: There are a few general tactics for maximizing speed of completion, keeping in mind that time to completion includes both the mechanical motion necessary to make entries and any time spent thinking or preparing to make an entry. How you apply these tactics depends on the task (mostly the form and patterns in the data to be inputted) and the amount of knowledge, skill, experience, and training your users will have. Proper optimization will require user research.
Defaults
Most important is to default fields to the most common value. If rooms are typically needed on the current date, then default the Start Date to the current date (or at least default the year to the current year). If rooms are typically only needed overnight, then default the End Date to one day after the Start Date. If there are typically zero children, then default the Children fields to 0. Determine your defaults through user research, possibly through archival records for the current system they use.
Even if the default value is only correct a fraction of the time, it still means less typing. This assumes your users are experienced enough to realize that when they enter a field and the default value is highlighted, they can simply type an alternative value, not backspace or delete the existing value first. That's a something you can determine through some brief user observation.
Free-form Fields
Generally, users are faster at typing familiar text if it all goes in one text box. This saves field navigation time and maintains the user's train of thought. Dates, name, phone number, and email should each be a single text box. Do not have a separate field for the phone number area code. Avoid having separate first and last name fields.
All fields, including the date fields, should be especially tolerant of a wide range of formats to prevent time-consuming validation errors. For example, the phone number field should accept any special character as delimiters –and accept no delimiters. Users familiar with the number pad should not have to move their hands to type a parenthesis around the area code.
While date fields should accept typed dates, each should also have a dropdown to select from a calendar. Otherwise, some users will be slower as they refer to an external calendar before entering their dates.
Minimize keyboard-mouse transitions
At least some of your fields must be completed by the keyboard, so try to make all your fields completable without the fingers leaving the keyboard. Allow users to tab between fields, and make sure your tab order is consistent with how they work. For example, I would guess that they tend to complete input of each room before moving to the next room, but user research will confirm this. If your users are trained or appropriately skilled, consider a means to make input with only the number pad for all rooms, which can be done faster than input via the numbers on the alphanumeric keyboard. The plus and minus key can substitute for tab and shift-tab. The enter key may skip to the next room (row) accepting defaults for all remaining fields for the current room. To avoid time-consuming errors, such special key use should be consistent with how they are used elsewhere in the app.
Alternatively, you may want to make it possible to complete nearly all fields with the mouse alone after the user enters name, phone, and email. If your defaults are usually correct or close to correct you may want to use spinner controls for your room and date data, where the users usually only need to give a few clicks to up or down arrows to adjust the dates and amounts, and they're done.
Make Input Consistent with Source
Minimize backtracking and mental manipulations by having the input be consistent with the format in its source. If the user is transcribing a paper form, make sure the electronic form is laid out the same way. If the user it taking data from a customer on the phone, the fields should have the same order and data type as the customers tend to speak. If the input is from the user's memory, make sure the data form and units fit with that mental representation.
For example, maybe the user doesn't think in terms of start and end dates, but rather in terms of a start date and a duration of days. If so, replace your end date field with Number of Days. Typing a one- or two-digit duration is faster than typing a four to eight digit date anyway.
Perhaps users are visually imagining a block of dates on a calendar. If so, instead or in addition to date text fields, maybe you want a single calendar when the user can drag-and-drop the start and end dates (assuming your users are familiar with drag and drop and are trained that it exists in the app –more user research to do).
Provide Aggregates and Other Feedback on Input
Make it fast and easy for the users to check their work on the fly. For example, after they enter a date as text, show the day of the week in a read-only field. Likewise, show duration of days and the total number of people in each room, along with totals of each person type, and the grand total. This may save the user from performing mental arithmetic. While you should allow the user to enter their phone number without any delimiters, you should automatically display the number with delimiters so it's easy for the user to cross-check the number. Use 12-point font so values are clearly visible.
At same time, don't clutter the form with data that is of no use to the users. They'll waste precious milliseconds glancing at it while looking for the field they really want to use.
Provide Tools to Exploit Data Patterns
In addition to defaults, provide a set of commands that allow the users to apply common input patterns. If rooms often have the same input, then even relatively inexperienced users may be able to efficiently use a Same As Above button placed by the second through last room. Research may show that reservations for business travelers is almost always one adult and no children per room. You could have a single button populate all rooms with those values, if that isn't your default (e.g., usually you're reserving rooms for family reunions, but occasionally you do business retreats).
If you have more complex patterns and more practiced or trained users, you may want to provide controls to copy and paste data from/to one or more entire rooms at a time (like one can with a spreadsheet), preferably with keyboard accelerators and context menus. Support multi-selection (by dragging, Ctrl-clicking, and shift-clicking) to save time. Consider shortcuts to common room configurations the user can call up from a menu then modify as necessary. Maybe even allow the user to retrieve old configurations from previous sessions and re-edit them for a new one.
No Second Email Field for Verification?
In web apps, it's common to make the user enter the email address twice to verify it's typed correctly. In your case, maybe you should dispense with it for the sake of a shorter and faster form. If an email doesn't work, then you have the phone number to fall back on.
Analysis and Testing
A usability test between two or three designs will settle which one is fastest. Prior to that, you can analytically get a pretty good estimate of relative form completion times by applying GOMS. GOMS-KLM is relatively easy and accurate for experienced users entering familiar data, and is useful for comparing trade-offs between mouse versus keyboard input.
Comment: repeat email field. gah.
Answer: Have you considered using some rich graphics to divide the form into understandable chunks?  For instance, when your user has selected the number of rooms and the form is drawn, the fields about each separate room could be contained within a graphic that looks like a floor plan of a room, providing some context for the user, and also a natural grouping of the fields so that they are dealing with the rooms one at a time.  Graphics aside, using clear sections could help simplify the process - remember that a form being filled in very quickly does not necessarily equate to the form being very small or short.  Providing a clear and natural flow may let a user fill it in quickly even is they need to scroll quite far, as long as they are very clear on what to do at each step.

Inputs for difficult form


Matching Multiple Columns Excel

Question: I would like to match 3 columns in a different sheet in excel and if all match then return a result. The data needs to search for the results (i.e not specific rows)
Example:
Sheet1
A   B   C   D   E   F   G
11  22  33  44  55  66  (Blank)
22  11  33  55  44  66  (Blank)

Sheet2
A   B   C   D   E   F   G
22  11  33  55  44  66  Yes
11  22  33  44  55  66  Yes
33  44  55  66  11  22  No
11  22  33  44  55  66  No
22  11  33  55  44  66  No

If Column C, D (both) matches C and D in Sheet2 AND G is yes then display yes in Sheet1, otherwise no
It cannot be a partial match, both columns C and D need to match and G be yes
Answer: sheet1.C11 --> gives you C11 for sheet 1
sheet2.C11 --> gives you C11 for sheet 2
after you can match their value as you want :-D
Answer: in Excell, you can use functions.
For example : IF( condition, [value_if_true], [value_if_false] )
into a empty cell (where you want to write the result) you can write
=IF(AND( sheet1.C1=sheet2.C1, Sheet1.D1=Sheet2.D2, Sheet2.G1="yes"), "yes", "NO MATCH" )

Comment: The data can be random, i think i need to index it first. how would i do that

Matching Multiple Columns Excel


Let R be the following relation on the set of pairs of integers:

Question: Let $R = \left\{\bigl((a, b), (c, d)\bigr) \in \mathbb{Z}^2 \times \mathbb{Z}^2; a + d = b + c\right\}$.

Prove that $R$ is an equivalence relation.
Find the equivalence class of the pair $(0, 0)$.
Answer: The relation $R$ is

reflexive. For all $(a,b)\in\mathbb{Z}^2$, we have $(a,b) R (a,b)$ because $a+b = a+b$.
symetric. Let $(a,b)\in\mathbb{Z}^2$ and $(c,d)\in\mathbb{Z}^2$ such that $(a,b) R (c,d)$. We have $a + d = b + c$ or equivalently $c + b = d + a$, that is $(c,d) R (a,b)$.
transitive. Let $(a,b)\in\mathbb{Z}^2$, $(c,d)\in\mathbb{Z}^2$ and $(e,f)\in\mathbb{Z}^2$ such that
$$
  (a,b) R (c,d) \quad\text{and}\quad (c,d) R (e,f),
$$
then
$$
\begin{align*}
  a + d &= b + c && (1) \\
  c + f &= d + e. && (2)
\end{align*}
$$
We add $(1)$ and $(2)$:
$$
  a + d + c + f = b + c + d + e,
$$
and now we substract $c + d$ from each side of the above equality. We get
$$
  a + f = b + e,
$$
that is
$$
  (a,b) R (e,f).
$$

The equivalence class of $(0,0)$ is the set
$$
  \left\{ (a,b)\in\mathbb{Z}^2 : a + 0 = b + 0 \right\}
  = \left\{ (a,a) : a\in\mathbb{Z}\right\}.
$$
Answer: To show that something is an equivalence relation, we need to show 3 properties:

$R$ is reflexive: $aRa$ for all $a$.
$R$ is symmetric: $aRb\implies bRa$ for all $a,b$.
$R$ is transitive: $aRb,bRc\implies aRc$ for all $a,b,c$.

For reflexive: $$a+b=a+b\implies(a,b)R(a,b)$$
For symmetric: $$(a,b)R(c,d)\implies a+d=b+c\implies c+b=d+a\implies (c,d)R(a,b)$$
For transitive: $$(a,b)R(c,d),(c,d)R(e,f)\implies a+d=b+c,c+f=d+e\implies a+d+c+f=b+c+d+e\implies a+f=b+e\implies(a,b)R(e,f)$$
Notice that $(a,b)R(0,0)\implies a+0=b+0\implies a=b$. Hence the equivalence class is $\{(k,k)\mid k\in\mathbb Z\}$.


Disable Software Updater pop-up after 14.04 to 16.04 upgrade

Question: When I did a clean install of 16.04 with Unity on my home desktop computer, the Software Updater GUI from earlier releases seems to be gone and replaced with a discreet reminder in the upper right corner. However, when I upgraded my work desktop from 14.04 to 16.04, the Software Updater still pops up whenever there are new updates. Is there a way to disable this pop-up? I prefer to just use the terminal for updates, but the reminder in the upper right corner was pretty nice.
Software Updater GUI from earlier releases:

Discreet reminder in the upper right corner:
Comment: please see if there is a left-over package in this output: `dpkg -l | grep update-notifier` - at my system there are two packages: update-notifier & update-notifier-common
Comment: Yeah, I've got the same ones.
Answer: lots of people recommend simply removing the update notifier:
sudo apt-get remove update-notifier

But that also removes the ubuntu-desktop package, so it wouldn't work in a secure way. I came up with the simplest and most brutal workaround, which is just not having that program as part of your system startup. For this, open your bashrc file
gedit ~/.bashrc

and add at the end
killall update-notifier

It has worked so far. This file executes those commands everytime you start a new session, so it should kill the notifier as soon as you login.
Comment: Thanks, I'll try that! But shouldn't the line be in ~/.profile for it to be executed upon login?


Java: Collection sorting, returning changed indexes

Question: In Java, I currently have my PriorityQueue set up to add the objects where they are needed in the list, ideally, I'd want to call a method on all of the moved items, for example:
List = {0,10,20,30,40,50,60,70,80,90,100}.
Add 55
List = {0,10,20,30,40,50,55,60,70,80,90,100}
Objects that would have moved down:
{0,10,20,30,40,50} (indexes: 7,8,9,10,11,12)
I only need to worry about the highest 8 items in this list, so, ideally it would only call the method on:
{40,50} (indexes: 7,8)
if anything below that index is changed, I don't need to bother checking it.
I've tried doing it by creating a LinkedList, using Collections.sort and cloning the top 8 elements before the next sort. but I continually run into null pointer or and Index out of bounds exception.
Could anyone provide a more generic approach to this problem?
My current iteration method:
Hit[] sorted = hitList.toArray(new Hit[hitList.size()]);
    for (int i = sorted.length - 1; i > 0; i--) {
        if (sorted[i] != clone[i]) { // Nullpointer, arrays are not of equal length
            System.out.print("CHANGE AT " + i);
        }
        System.out.println("");
    }

My point is, surely there's a method that avoids this entire conundrum, such as extending a Priority List and overriding add... Which isn't an option because all the useful methods are private.
Comment: PriorityQueue keeps track only of the top element. The order of remaining elements is unspecified. You have to use `SortedSet` or manually sorted collection.
Answer: I would do it like this:
TreeSet<T> set = new TreeSet<>();

public void add(T t) {
    List<T> oldHead = new ArrayList<>(set).subList(0, Math.min(set.size(), 8));
    set.add(t);
    List<T> newHead = new ArrayList<>(set).subList(0, Math.min(set.size(), 8));
    for (T e : oldHead) {
        int oldIndex = oldHead.indexOf(e);
        int newIndex = newHead.indexOf(e);
        if (oldIndex != newIndex) {
            System.out.println(e + ": " + oldIndex + "->" + newIndex);
        }
    }
}

Make sure duplicated entries are handled as expected.
Comment: After a little tweaking, this method is absolutely perfect. +1 for actually understanding what I meant :P
Answer: In Java, indexes start from 0 (first element has index 0, second has 1 etc.). In your case 12th element (the last one) has index 11 (not 12 as you wrote), so asking for element with index 12 (i.e. 13th element) causes Null pointer or Index out of bounds exception.
Here's the code after edit:
Hit[] sorted = hitList.toArray(new Hit[hitList.size()]);
for (int i = clone.length - 1; i > 0; i--) {
    if (sorted[i + sorted.length - clone.length] != clone[i]) {
        System.out.print("CHANGE AT " + i);
    }
    System.out.println("");
}

Comment: Yeah I know, the issue is really when I'm checking against a cloned array that is not of equal length, What's a simple way to check that? I'll add my current method of iteration.
Comment: You can't ask for index 11 of both 12 and 8 elements array. I'll try to figure the solution
Comment: Exactly. But again, this is horrible, I'm having to clone an entire array when the pushing is CLEARLY happening on add.
Comment: I just edited my answer, try the code (it works only if sorted is larger or equal to clone in array length, otherwise split the operands)
Comment: I have no doubt this would work but it seems counter-intuitive to need to clone an array when the order of the list is changing...
Comment: Hold on, what are you trying to do with the arrays? I guess I misunderstood
Comment: You understood me correctly, it just dawned on me while writing the above edits to my post that in fact: when an element is added to the list, the order of the list changes. Perhaps I need to create a custom sorting algorithm. Which changes the question entirely. Thanks for this though! More questions to solve!


Is it possible to restrict url access from application only in Django REST

Question: I have Web application with angular as frontend and Django REST as backend.
My web application does the request like
/api/options/user?filter={}
Now is it possible that if those requests are made from application then they go through but they type that in broswer directly and edit some filters then they don't work
Although the data is not sensitive and they can still see it via console but i just don't want them to play with it or at least make it hard
Comment: I do not think you can completely restrict access to public API. If you want to make it harder, you can add an authentication header. Something like `X-API-Token`.
Answer: You can't rely on the URL to distinguish between the two cases.  You could have your application provide information in the headers of the request, which a browser would not know, but someone writing their own application could mimic your technique.