Questions about base under paver stones for a patio

Question: I am building a patio with paver stones, roughly 20x16. I am building it on rocky clay in New England. I have dug out my soil and plan to put geotextile fabric over the clay before I lay my crushed stone and dust. I have a few questions and am grateful for any guidance:

Is the fact that clay is rocky going to cause any problems? I have removed as many rocks as I can but it is impossible to remove them all.
Can the depth of my crushed stone base fluctuate so long as it is always at least 4" deep? After excavating and removing stones the soil bed is not a consistent depth- some areas have space for 4" of crushed stone but some areas could go as high as 8" or maybe even 12" of crushed stone. Is this ok? Does it matter if the soil bed is not perfectly even so long as it is compacted, has geotextile fabric over it, and the crushed stone is lever after installation?
My last questions are about drainage. The patio will slope down 4" away from the house over 16 feet, which I believe is a good slope?
Lastly, the water will drain right towards my detached garage (an old 2-horse carriage house that isn't nearly as nice as that may sound), which has a concrete slab floor and no foundation. There will be about 12" between the end of the patio and the garage. My plan is to dig a canal here to collect the water and move to another part of the yard to drain. Is this a good idea or am I asking for trouble having the canal so close to the garage? The setup of my yard makes it nearly impossible to have it drain in any other direction.

Thanks for reading this and many thanks for any feedback!
Comment: You may want to consider asking each question as a separate question, rather than trying to fit them all into a single post.
Answer:
~Is the fact that clay is rocky going to cause any problems? I have removed as many rocks as I can but it is impossible to remove them all.

The rocks should not pose an issue as long as the soil base is compacted.

Can the depth of my crushed stone base fluctuate so long as it is always at least 4" deep? After excavating and removing stones the soil bed is not a consistent depth- some areas have space for 4" of crushed stone but some areas could go as high as 8" or maybe even 12" of crushed stone. Is this ok? Does it matter if the soil bed is not perfectly even so long as it is compacted, has geotextile fabric over it, and the crushed stone is lever after installation?

The geotextile fabric is good to use as a base over the soil base. Being in New England, you will see cold winters with the possibility of frost heaving. Thicker crushed stone bases help prevent this. 4" is the minimum crushed stone you will see recommended. If possible, increase that to a minimum of 6" across the entire patio area. When laying thicker crushed stone bases, it is good to use a plate compactor with every couple inches (3" or so) of base. With 4" of base, the plate compactor can be used once it is all laid down. With 6" or more it should be used two or more times.
Also, extend the crushed stone base at least 6" outside of the area to be covered by pavers. This will ensure the pavers stay supported by the crushed stone even with expansion and contraction.
The fluctuating depth should be minimized as much as possible, but it will not ruin your patio as long as the base soil is compacted.

~My last questions are about drainage. The patio will slope down 4" away from the house over 16 feet, which I believe is a good slope?

Yes. That's fine. 1/4" vertical drop per horizontal linear foot is a commonly accepted slope for drainage.

~Lastly, the water will drain right towards my detached garage (an old 2-horse carriage house that isn't nearly as nice as that may sound), which has a concrete slab floor and no foundation. There will be about 12" between the end of the patio and the garage. My plan is to dig a canal here to collect the water and move to another part of the yard to drain. Is this a good idea or am I asking for trouble having the canal so close to the garage? The setup of my yard makes it nearly impossible to have it drain in any other direction.

A concern with the patio being so close to the garage is waterflow from the patio causing erosion and undercutting the garage's slab foundation. I would suggest installing a French drain to divert water down this path rather than an open canal. The French drain would use 4" perforated corrugated pipe with a sock buried at least 4" under the surface. The pipe should slope at least 1/4" vertical drop per 1 horizontal linear foot, the same as the patio. Cover the pipe with 4" of pea gravel and top it with larger rocks, such as river stones. The rocks will help to break up and slow the flow of water to prevent erosion of the surrounding soil. The French drain will help remove water quickly to keep the soil from becoming water logged.
If you don't have an appropriate place to locate the exit of the French drain, you can dig a dry well. It is essentially a large pit filled with gravel into which the French drain can deposit water to be absorbed by the surrounding soil.


How to format JSON for Google Charts from C#

Question: I'm trying to output JSON from c# for use with a google Chart.
At the moment I build it using JSON.Net:
  JArray arrB =     new JArray(
                        from c in cards
                        where c.complete
                               group c by new { date = Convert.ToDateTime(c.completed).Date } into g
                               select new JObject(
                                   new JProperty("date", g.Key.date),
                                   new JProperty("completedHours", g.Sum(x => x.estHours))
                                   )
                        );

Which outputs the following:
 { "burndown" : [ { "completedHours" : 30.0,
[ { "completedHours" : 30.0,
    "date" : "2014-03-26T00:00:00+00:00"
  },
  { "completedHours" : 3.0,
    "date" : "2014-04-03T00:00:00+01:00"
  },
  { "completedHours" : 3.0,
    "date" : "2014-03-28T00:00:00+00:00"
  },
  { "completedHours" : 1.0,
    "date" : "2014-03-27T00:00:00+00:00"
  }
]

However, google charts doesn't like this. As far as I can work out I need to format it so it has column headings in the first block of data, and then content after. I'm new to JSON so not sure how to go about this.
EDIT: Adding "correct" structure
As far as I can tell from the Google Charts documentation, the correct format should be like this:
{"cols":[{"id":"Col1","label":"","type":"date"}],
  "rows":[
    {"c":[{"v":"a"},{"v":"Date(2010,10,6)"}]},
    {"c":[{"v":"b"},{"v":"Date(2010,10,7)"}]}
  ]
}

See: https://developers.google.com/chart/interactive/docs/reference#dataparam
Comment: Could you update your question with the desired JSON structure for output?
Comment: If you get the Newtonsoft JSON package from nuGet, you can just create whatever object structure you want, and then use that library to encode it to a JSON string. That should take all of the guesswork and "I'm new to JSON" out of the equation for you.
Comment: Thanks. That's what I'm using - not sure how I change the format of the string as by default it encodes it as above. Can you point me in the right direction?
Comment: As @YuvalItzchakov said, if you have a sample of the JSON it's expecting, it'll be a lot easier to help.
Answer: According to your JSON schema, your object hierarchy needs to look like this:
public class Col
{
    public string id { get; set; }
    public string label { get; set; }
    public string type { get; set; }
}

public class C
{
    public string v { get; set; }
}

public class Row
{
    public List<C> c { get; set; }
}

public class RootObject
{
    public List<Col> cols { get; set; }
    public List<Row> rows { get; set; }
}

So, to construct your json, you would do something like this:
var rootObject = new RootObject()
{
    cols = new List<Col>
    {
        new Col {id = "1", label = "2", type = "string"}
    },
    rows = new List<Row>()
    {
        new Row
        {
           c = new List<C> {
               new C { v = "a" },
               new C { v = "b"}
           }
        }
    }
};


The Reason Behind Employing an Additional Array and Counting Smaller Elements in the Counting Sort Algorithm

Question: Is it feasible to streamline the counting sort algorithm by exclusively utilizing the counting array (C) after determining the frequency of each element in the input array? Instead of creating an additional output array, can we achieve the sorted array directly by traversing C in reverse order and placing the elements accordingly? For instance, if we have an input array A and a corresponding count array C:

Would it be valid to sort the array by placing one 5 at the end, followed by no fours, three 3s just before 5, adding two 2s, and concluding with no 1s and two 0s? This would result in the sorted array:

Additionally, in the existing counting sort implementation, we count the sum of each element in C with its previous element to determine how many elements are lower or equal to that particular element. Considering this, can we simplify the sorting process by relying solely on the cumulative counts in C and eliminating the conventional steps involving the creation of an extra output array and forward traversal of the input array? Are there reasons for retaining the existing process, apart from considerations such as stability and scenarios where input array elements represent attributes of objects (e.g., satellite data)?
Comment: I'm not sure I fully understand what you're saying, but isn't "scenarios where input array elements represent attributes of objects" another way of saying "scenarios sorting anything else than integers", ie nearly all cases? Also, you might not want to sort the (single element) array `[1,234,567,890,123,456,789,012,345]` with your approach. So overall IIUC yes you're right in that special case, which is a very special case.
Answer:
Is it feasible to streamline the counting sort algorithm by exclusively utilizing the counting array (C) after determining the frequency of each element in the input array? Instead of creating an additional output array, can we achieve the sorted array directly by traversing C in reverse order and placing the elements accordingly?

That's normal if the (integer) sort keys are the items being sorted themselves, and in that case, it works just as well (and is easier to code) to traverse the array from front to back.  Otherwise, no, it does not work, for the same reason that doing the same thing from front to back does not work: unless the objects are already in sorted order, you will overwrite and lose some of them.

Additionally, in the existing counting sort implementation, we count the sum of each element in C with its previous element to determine how many elements are lower or equal to that particular element. [...] can we simplify the sorting process by relying solely on the cumulative counts in C and eliminating the conventional steps involving the creation of an extra output array and forward traversal of the input array?

You can perform that simplification when the items themselves are the keys. Otherwise not, because again, you will overwrite and lose some of the items if you do not use additional storage.

Are there reasons for retaining the existing process, apart from considerations such as stability and scenarios where input array elements represent attributes of objects (e.g., satellite data)?

Again, Counting Sort can be simplified in the special case of sorting integers, where the items are themselves the sort keys.  Perhaps in some other special cases, too.  In general, however, you need the extra steps and storage to get the correct result.
You could also consider converting a Counting Sort into a Flash Sort, which reorders the array in-place, but that's hardly a simplification.


Split a list of tuples into sub-lists of the same tuple field

Question: I have a huge list of tuples in this format. The second field of the each tuple is the category field.
    [(1, 'A', 'foo'),
    (2, 'A', 'bar'),
    (100, 'A', 'foo-bar'),

    ('xx', 'B', 'foobar'),
    ('yy', 'B', 'foo'),

    (1000, 'C', 'py'),
    (200, 'C', 'foo'),
    ..]

What is the most efficient way to break it down into sub-lists of the same category ( A, B, C .,etc)?
Answer: Use itertools.groupby:
import itertools
import operator

data=[(1, 'A', 'foo'),
    (2, 'A', 'bar'),
    (100, 'A', 'foo-bar'),

    ('xx', 'B', 'foobar'),
    ('yy', 'B', 'foo'),

    (1000, 'C', 'py'),
    (200, 'C', 'foo'),
    ]

for key,group in itertools.groupby(data,operator.itemgetter(1)):
    print(list(group))

yields
[(1, 'A', 'foo'), (2, 'A', 'bar'), (100, 'A', 'foo-bar')]
[('xx', 'B', 'foobar'), ('yy', 'B', 'foo')]
[(1000, 'C', 'py'), (200, 'C', 'foo')]

Or, to create one list with each group as a sublist, you could use a list comprehension:
[list(group) for key,group in itertools.groupby(data,operator.itemgetter(1))]

The second argument to itertools.groupby is a function which itertools.groupby applies to each item in data (the first argument). It is expected to return a key. itertools.groupby then groups together all contiguous items with the same key.
operator.itemgetter(1) picks off the second item in a sequence.
For example, if
row=(1, 'A', 'foo')

then
operator.itemgetter(1)(row)

equals 'A'.

As @eryksun points out in the comments, if the categories of the tuples appear in some random order, then you must sort data first before applying itertools.groupby. This is because itertools.groupy only collects contiguous items with the same key into groups.
To sort the tuples by category, use:
data2=sorted(data,key=operator.itemgetter(1))

Comment: Don't forget that the data first has to be sorted: `data2 = sorted(data, key=operator.itemgetter(1))`.
Comment: Great answer, don't forget that you can use a lambda instead of the operator, for folks who are used to lambdas.
Answer: collections.defaultdict
itertools.groupby requires the input to be sorted by the key field, otherwise you will have to sort first, incurring O(n log n) cost. For guaranteed O(n) time complexity, you can use a defaultdict of lists:
from collections import defaultdict

dd = defaultdict(list)
for item in data:
    dd[item[1]].append(item)

res = list(dd.values())

print(res)

[[(1, 'A', 'foo'), (2, 'A', 'bar'), (100, 'A', 'foo-bar')],
 [('xx', 'B', 'foobar'), ('yy', 'B', 'foo')],
 [(1000, 'C', 'py'), (200, 'C', 'foo')]]

Answer: To get multiple lists of singletons from a list of tuples:
foo = ((1,2), (3, 4), (5, 6), (7,8) , (9, 10))
[[z[i] for z in foo] for i in (0,1)]

If you prefer to get multiple tuples of singletons:
zip(*[(1,4),(2,5),(3,6)])


What are the differences between Mythbuntu and MythTV?

Question: I've heard about both, however I've never been able to distinguish how they are distinct, Mythbuntu as I see it is used as a Desktop environment, whereas MythTV seems to be installed on a TV itself with an equivalent App on the Mythbuntu desktop. I may be entirely wrong in making this assumption though.
I've also heard of Mythbuntu being used as a "frontend " with MythTV as a "backend " if someone could clarify this concept I'd be quite grateful as for me I thought MythTV also qualified as a "frontend".
In short:

How are Mythbuntu and MythTV related and what are their major differences?
What are the definitions of a frontend and backend in the case of Mythbuntu and MythTV?
Is Mythbuntu required for MythTV to work?

I've already read the following questions but I've got very basic knowledge on this issue and none really explain things in an Average Joe-esque way for users with little knowledge on the subject.

How do I connect a MythTV frontend to a MythTV backend on Mythbuntu 11.10?
How do I Install MythTV on a Lenovo S12 with wireless?
Mythmote wont connect to mythbuntu 12.04, seems frontend is not listening on all interfaces
Answer:
How are Mythbuntu and MythTV related and what are their major differences?

Mythbuntu is the official operating system based on Ubuntu.
MythTV is software that acts like a PVR (personal video recording) system. It is not limited to Ubuntu but can be used on Fedora called MythDora.

What are the definitions of a frontend and backend in the case of Mythbuntu and MythTV?

The front end is the software required for the visual elements (GUI) and is used to find, play, and manipulate media files. The back end is the server where the media files, tuners, and database are actually stored.

Is Mythbuntu required for MythTV to work?

No. You can also use other Linux based systems like Fedora and also Windows or Mac OS.
Comment: It's worth noting that Mythdora no longer exists/has stopped development. Mythbuntu and LinHES (Arch) are the two that are left.
Comment: Thanks for the answer! I've added another sub-question above, also regarding the PVR system, does this mean using MythTV you could record anything being broadcast on your TV as long as MythTV can connect to the TV via wireless/wired connection?


Is it possible to transfer Pokemon from previous 3DS Pokemon games to Sun/Moon?

Question: I own three Pokemon games on 3DS: Y, OmegaRuby and Moon. I've got some nice Pokemon in first two. Is it somehow possible for me to transfer my Pokemon to Pokemon Moon?
Answer: The answer is Pokémon Bank. It's the same procedure like in Generation 6, but the Update for Pokémon Bank will release first in January, so currently the answer is actually NO.
A useful link can be found here.
Matter, that trading them back won't be possible. You also cannot trade Gen6 back into Gen5 Editions.


How to find out which WAD (textures) files are in effective use by a BSP (map) file in CounterStrike 1.6?

Question: With the following command...
HLExtract.exe -p "fy_office.bsp" -e "root\fy_office.ent"

... is possible to find out which WAD files (textures) are listed as in use by a BSP (map) file as this output example ("fy_office.ent" file content extracted in the above command)...
{
"wad" "\programme\valve\valve\thwc_hl.wad;\programme\valve\cstrike\sourcebuero.wad;\programme\valve\cstrike\villaggio.wad;"
"mapversion" "220"
"MaxRange" "4096"
"skyname" "tornsky"
"classname" "worldspawn"
"classname" "worldspawn"
}
[...]

Notice that in the item "wad" several WAD files (textures) are listed. It turns out that none of these WAD files are needed even though they are listed. This happens with many BSP (map) files.
I've already tried several utilities and haven't found any that allow me to set this information correctly. I needed a utility that can be used via command line, as I need this output in text.
Is there any utility or strategy (via the command line) that I can use to correctly define this information, ie which WAD files (textures) are actually in use by a BSP (map) file?
Answer: This is an old question and the answer is simple, NO.
WHY? Because the BSP file does not have this information.
In reality, BSP files only have the list of WAD files it uses and the names of the textures, but it does not have information to which WAD file a particular texture belongs. The names of these textures are unique within a BSP.

The way GoldSrc (CS 1.6) works gives the false impression that it "knows" which WAD files are needed. But not quite...
To understand how GoldSrc (CS 1.6) works, let's imagine the following scenario: You have loaded a BSP file, but you have not made any of the referenced WAD files available...
[...]
"wad" "\programme\valve\valve\thwc_hl.wad;\programme\valve\cstrike\sourcebuero.wad;\programme\valve\cstrike\villaggio.wad;"
[...]

... in the "cstrike" or "valve" folders.
So, still within this scenario, let's imagine some more situations to demonstrate how GoldSrc (CS 1.6) would act when trying to load each of the textures pointed at in the BSP file:

Attempts to load all referenced WAD files that are in the "cstrike" or "valve" folders. Cannot load any;
Tries to load each of the referenced textures. Can't find the first one;
Search the list of WAD files and notice that the first one is not loaded. Then it warns that this file is missing (message box);
The user makes this WAD file available in the "cstrike" folder and tries to load the BSP again;
Loads all the referenced textures that are in the available WAD file, but realizes that there are still unavailable textures;
Asks for the next WAD file in the list;
And so on...

Possible solution (a Linux approach):
The only possible solution to programmatically determine (via Bash script, for example) which WAD files are needed is to export the list of textures from a WAD file with a utility like HLExtract.exe...
Example
WINEDEBUG=-all wine "<PATH>/HLExtract.exe" -p "<PATH>\SOME_WAD.wad" -l | grep -i ".bmp" | cut -d\\ -f2 | cut -d. -f1 > "SOME_WAD_TEXTURES_LIST.txt"

... and based on the obtained list check each of the textures inside the BSP using a utility like "strings"...
Example
strings "<PATH>/SOME_BSP.bsp" | grep -iw -- "SOME_TEXTURE_NAME" >> "SOME_BSP_TEXTURES_IN_USE.txt" 2>&1

... so that if located, then this WAD file is in use by the BSP file.
Notes

The first command lists all textures in the "SOME_WAD.wad" file and outputs to the "SOME_WAD_TEXTURES_LIST.txt" file. The second command checks if the texture name is in the file "SOME_BSP.bsp" and outputs to the file "SOME_BSP_TEXTURES_IN_USE.txt" making an append if it already exists - useful for executing the same command in sequence;
A BSP file can have its textures embedded in it so that it will not need the referenced WAD files;
A WAD file can have textures that have the same name as textures in another WAD file. The precedence of loaded textures is always by the last loaded WAD - the order followed is the same as the "wad" attribute which has the list of referenced WAD files. This can give the false impression that a WAD is not needed if a previous one already has textures with the same name, however this can result in the wrong textures being loaded.


Can anyone tell my why my gif/Label wont show

Question: I've inserted the code below. My Jframes pop up, and close when they're supposed to, but nothing shows u inside of my JFrame. It should say "sending..." next to a gif of a loading bar. I've tried everything. I freatly appreciate any and all help. Thank You
package image_processor;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/*
 * To change this license header, choose License Headers in ProjectProperties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author root
*/
public class SendingGUI {
public void sending() {
JFrame frame = new JFrame("Sending Image(s)");
JFrame frame2 = new JFrame("Image(s) Sent!");

ImageIcon gifImage = new ImageIcon("/opt/med-seg-netbeans/med-seg   /senderGUI/ajax-loader.gif");

JLabel label1 = new JLabel("Sending, please wait... ",gifImage, JLabel.CENTER);
JLabel label2 = new JLabel("Images Sent. Processing...",gifImage,JLabel.CENTER);

    frame.add(label1);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setSize(350, 150);
    frame.setVisible(true);

    try{
     Thread.sleep(4000);
    }catch(InterruptedException e){
    }

    frame.setVisible(false);

    frame2.add(label2);
    frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame2.setSize(350, 150);
    frame2.setVisible(true);

    frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING,frame2));

    try{
    Thread.sleep(3000);
    }catch(InterruptedException e){
    }

    frame2.setVisible(false);
}

}
Answer: The code is correct.
I suspect your image URL is incorrect, or alternatively, the Label may not support animated.

Solution:
Try using a different image. Ideally a non-animated image.
If you're using Windows, place the image in C:\ drive so the code will read:
ImageIcon gifImage = new ImageIcon("C:/image.gif");


Does VS Code Have a Command Panel For Testing Short Chunk of Codes?

Question: I'm new to VS Code. I wonder if VS Code has any panel to test run chunk of codes instead of creating a new file? I'm so used to traditional Rstudio, PyCharm, Jupyter Notebook IDE that I could just test out short chunks of code in the output command panel. However, it seems VS Code command output is just the terminal, which does not read my python code for the test running small chunks of code. Any suggestion on how to solve this?
Thanks,
Lily
Answer: yes it does. vs code is such a great lightweight IDE.
https://code.visualstudio.com/docs/editor/debugging
You can make breakpoints or Logpoints and decide which part of the code you want to debug.
Answer: I think what you are looking for is jupyter notebook extension for vscode.
This is good guide to help you get started
Answer: You can create a jupyter notebook in the VSCode:

Or you can select Run Selection/Line in Interactive Window or Run Selection/Line in Python Terminal:


Why does one query return related entities, but not the other?

Question: I'm currently migrating existing repositories to a generic one.
The existing method to retrieve a list of all MyEntity from the database looks like:
public IList<MyEntity> GetAll()
{
    var list = _context.MyEntity.Include(_ => _.OtherEntity).ToList();
    return list;
}

This method would return a list of all MyEntity, plus load their related OtherEntites.
I've simplified the repository in to a generic one, whose method looks like this:
public IList<TEntity> GetAll(params Expression<Func<TEntity, object>>[] expressions)
        {
            var entity = _context.Set<TEntity>();
            foreach (var expression in expressions)
            {
                entity.Include(expression);
            }
            var list = entity.ToList();
            return list;
        }

And I would call the method like this:
var myEntityList = _repository.GetAll(_ => _.OtherEntity);
However this does not seem to load the related OtherEntites. I've had to include the expression parameter for scenarios where loading related entities may or may not be needed.
Could someone explain where I've gone wrong and why my related entities won't load in the new setup? Thanks
Answer: It looks like the first method returns the result of .Include() while the second method just calls the method, but ignores the result. LINQ methods usually return a new collection rather than modify the existing collection.
Try this:
public IList<TEntity> GetAll(params Expression<Func<TEntity, object>>[] expressions)
{
    IQueryable<TEntity> entity = _context.Set<TEntity>();
    foreach (var expression in expressions)
    {
        entity = entity.Include(expression);
    }
    var list = entity.ToList();
    return list;
}

Comment: @d1s use `IQueryable entity = _context.Set();`, while you're at it you should call your variable `query` not `entity` to avoid confusion.
Comment: @d1s :) you could also check `AsQueryable()`.
Comment: @joakimriedel Thanks for catching my oversight. I've edited my answer per your initial suggestion.
Comment: Thanks for your advice. I tried this but it gives an error because the type `IIncludableQueryable` is not assignable to type `DbSet`
Comment: Update: I changed the first line to be `var entity = _context.Set().AsNoTracking()` and it fixed the issue by returning an `IQueryable`, seems like a win-win as I didn't need them to be tracked for this method. I'm curious as to how to return an `IQueryable` without using a method like `AsNoTracking()` though.
Comment: @joakimriedel thanks for your tip, you've just answered my previous comment :)


Brightness key on keyboard not working

Question: So I have seen this a few times but haven't seen a solution. I also don't know if it is computer hardware related problem or not.
My brightness keys ( fn + F2 and F3) to set the brightness in Ubuntu 16.04 does nothing, I have a HP Pavillion Laptop computer. Can anyone help me fix this. I have seen a "sort of solution" downloading an application called "Brightness Controller" but that is not a real solution for me.
Please help me with this if you can.. Thanks W
When running acpi_listen command in the terminal I get the following output:
video/brightnessdown BRTDN 00000087 00000000
video/brightnessdown BRTDN 00000087 00000000
video/brightnessup BRTUP 00000086 00000000
video/brightnessup BRTUP 00000086 00000000

Comment: @Sneetsher I have found the following [link](http://askubuntu.com/questions/540911/how-to-adjust-screen-brightness-in-ubuntu-14-04) and it seems to work. It is a manual approach.
Comment: its a bit of a pain but thanks for you help..I'll stick with it for now. Thanks once again.                                                                                This script work great , I modified it slightly to fit my system`#!/bin/mksh
printf " \n Entering file to change brightness in 3 seconds\n remember - no new line after number.  ";
sleep 3;
sudo nano /sys/class/backlight/intel_backlight/brightness`
Comment: doesn't seem to do anything after installing the above
Comment: nothing happening with {xbacklight -dec 20} .. the folder got "Intel Backlight" " acpi_video0" "acpi_video1" forlders inside
Comment: I am finding it hard to change these settings.. please explain a bit more
Answer:
Run acpi_listen in the terminal, to test if the key event received by the system. Then press Fn+F2 & Fn+F3. Below an output example:
 # acpi_listen
  PNP0C14:00 000000d0 00000000
 video/brightnessup BRTUP 00000086 00000000
  PNP0C14:00 000000d0 00000000
 video/brightnessdown BRTDN 00000087 00000000

See if you can control backlight using
 sudo apt-get install xbacklight
     xbacklight -inc 20
     xbacklight -dec 20

Another try at lower level
 # ls -l /sys/class/backlight/
 lrwxrwxrwx 1 root root 0 Jun 10 13:56 /sys/class/backlight/intel_backlight -> ../../devices/pci0000:00/0000:00:02.0/drm/card0/card0-LVDS-1/intel_backlight

 # ls -l /sys/class/backlight/intel_backlight/
 total 0
 -r--r--r-- 1 root root 4096 Jun 10 14:28 actual_brightness
 -rw-r--r-- 1 root root 4096 Jun 10 14:28 bl_power
 -rw-r--r-- 1 root root 4096 Jun 10 15:19 brightness
 lrwxrwxrwx 1 root root    0 Jun 10 14:28 device -> ../../card0-LVDS-1
 -r--r--r-- 1 root root 4096 Jun 10 14:28 max_brightness
 drwxr-xr-x 2 root root    0 Jun 10 14:28 power
 lrwxrwxrwx 1 root root    0 Jun 10 14:28 subsystem -> ../../../../../../../class/backlight
 -r--r--r-- 1 root root 4096 Jun 10 14:28 type
 -rw-r--r-- 1 root root 4096 Jun 10 14:28 uevent

 # echo 3600 > /sys/class/backlight/intel_backlight/brightness

Setup an ACPI script as explained in What code is executed when headphones are disconnected?
/etc/acpi/events/intel-backlight
 event=video/brightness*
 action=/etc/acpi/intel-backlight.sh

/etc/acpi/intel-backlight.sh
 #!/bin/bash

 x=$(cat /sys/class/backlight/intel_backlight/actual_brightness)

 if [ "$2" == "BRTUP" ]
   then
     x=$(echo $x+490 | bc)
     echo $x > /sys/class/backlight/intel_backlight/brightness
 fi

 if [ "$2" == "BRTDN" ]
   then
     x=$(echo $x-490 | bc)
     echo $x > /sys/class/backlight/intel_backlight/brightness
 fi

Make the script executable with chmod +x /etc/acpi/intel-backlight.sh.

Brightness key on keyboard not working


syllogism question

Question:
I drew two euler's diagrams

and concluded that option $b.)$ is correct,
but in the book option $c.)$ is given correct.
Answer: Answer (b) is correct in the sense that conclusion II certainly follows from A and B.   It is the strongest conclusion.
However, if conclusion II, then either conclusion I or conclusion II (via Disjunctive introduction).   So answer (c) is also not wrong; although it is weaker than answer (b).
Note that answer (c) is "I or II follows", which is distinct from answer (e) "I and II follows"

PS: However, I too would have picked the strongest answer.
Comment: So is the option $b.)$ correct ?

syllogism question


Scrolling on touchpad too fast, property 'Synaptics Scrolling Distance' doesn't exist

Question: The scrolling of my touchpad is too fast, and I tried using this solution here (as there is no setting for changing the scrollspeed, for some reason)
I've installed the Synapsis driver using this command:
sudo apt install xserver-xorg-input-synaptics
and then used xinput list to list the devices. It looks like this:
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ SYNAPTICS Synaptics Touch Digitizer V04 Mouse id=9    [slave  pointer  (2)]
⎜   ↳ SYNAPTICS Synaptics Touch Digitizer V04   id=10   [slave  pointer  (2)]
⎜   ↳ Wacom ISDv4 EC Pen stylus                 id=12   [slave  pointer  (2)]
⎜   ↳ Synaptics TM3075-002                      id=15   [slave  pointer  (2)]
⎜   ↳ TPPS/2 IBM TrackPoint                     id=16   [slave  pointer  (2)]
⎜   ↳ Wacom ISDv4 EC Pen eraser                 id=17   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Power Button                              id=8    [slave  keyboard (3)]
    ↳ Integrated Camera: Integrated C           id=11   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=13   [slave  keyboard (3)]
    ↳ ThinkPad Extra Buttons                    id=14   [slave  keyboard (3)]
    ↳ L U F T H Ü L S E N (AVRCP)               id=18   [slave  keyboard (3)]

My Touchpad is the ID 9, I'm pretty sure.
Then I tried to configure the scrolling setting using this command:
xinput --set-prop 9 'Synaptics Scrolling Distance' 8 8
It returned the following errror:
property 'Synaptics Scrolling Distance' doesn't exist, you need to specify its type and format
even tho this property should exist!
I then tried something else, another user suggested:
xinput --set-prop 9 "libinput Scrolling Pixel Distance" 10
and that returned nothing, and did nothing.
When I tried inputting:
xinput --set-prop 9 "libinput Scrolling Pixel Distance" 1
it returned the following error:
X Error of failed request:  BadValue (integer parameter out of range for operation)
  Major opcode of failed request:  131 (XInputExtension)
  Minor opcode of failed request:  57 ()
  Value in failed request:  0x153
  Serial number of failed request:  21
  Current serial number in output stream:  22

I then tried writing changes to /etc/X11/xinit/xinputrc which also did not work.
Ubuntu Version: 22.04.1 LTS
I'm using Ubuntu on Xorg
Laptop: Lenovo Thinkpad Yoga 12
Anybody know how to fix this?
Comment: Ubuntu 22.04 is using `libinput`, not `synaptics`. And the `9` id is your mouse. You can check what properies are there by `xinput list-props 9`
Comment: I tried changing "libinput Scrolling Pixel Distance" to something lower, but everything is the same (way too fast). How do I fix this?
Comment: I also tried changing it to something higher, but that had no effect either.
Answer: Okay I've figured out how to do this.
you just go into the terminal and do this:
synclient VertScrollDelta=-100
and that makes it a lot better.
To make the movement act like a rusty fidget spinner, you change:
synclient CoastingFriction=35
(The lower, the more oiled)
But doing that messes up the native settings for the touchpad, and it is now way too fast. You can fix this by doing this to the terminal:
synclient MinSpeed=0.05
followed by:
synclient MaxSpeed=0.7
make sure to play around with the values to your liking!
Edit: I've realised that all the settings get reset once the computer is restarted.
Comment: No sorry, I did not attempt. I meant it as suggesting you try it.
Comment: "all the settings get reset once the computer is restarted" — I bet there is a file somewhere where these parameters could be persisted. I might even try to use `grep -r` to find which file(s) could be identified as candidates...
Comment: Did you find the location of the file?  @Levente


COUNT (*) returns outdated number of rows after INSERT INTO or TRUNCATE

Question: I have a table with an avro schema where I insert tweets periodically.
CREATE TABLE tweets
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.avro.AvroSerDe'
STORED as INPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'
OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'
TBLPROPERTIES ('avro.schema.url'='hdfs:///tweet_schema.avsc');

When I run
SELECT COUNT(*) FROM tweets;

I get only the count of the rows added by the last INSERT statement:
INSERT INTO TABLE tweets SELECT tweet FROM another_table;

Similarly, if I run
TRUNCATE TABLE tweets;

Querying for the count returns the table rows count before truncating, however, selecting everything returns nothing as expected.
Is this the expected behavior?
If it's indeed the expected behavior, what should I be doing to get the total number of rows?
I'm running Hive 0.13
Comment: It doesn't seem to be the expected behavior from `COUNT`. Are you by any chance doing an `OVERWRITE` in your `INSERT` statement?
Comment: @visakh no it doesn't overwrite, the data is there. If I run this statement `SELECT * FROM tweets;` I get all the rows expected, old and newly added but querying for the count returns only the number of the latest addition
Answer: It turned to be a bug, I reported it and got resolved in 0.14.0. You can watch the issue here HIVE-7213
A workaround is to:
set hive.compute.query.using.stats=false;


Using Jasmine in multiple JS files, avoiding db race conditions

Question: We've got a medium sized API that we're testing with Jasmine. Right now we just have one gigantic file though.
I'd love to split the tests out into individual files, but my understanding is that the tests will not necessarily run sequentially, and therefore introduce all kinds of inconsistency with the underlying database.
Is there a good model to follow for organizing tests across multiple files in a way that will ensure a predictable dataset when each test runs?
Answer: Configure Jasmine to run your tests sequentially instead of semi-randomly by setting "random": false in spec/support/jasmine.json.
See this setup doc for more info.
Comment: So can I be confident that no two tests will be running simultaneously? (For example, a test that retrieves a user's comments may fail incorrectly if being run at the same time as a test that deletes the user.)
Comment: Please see [this page](https://jasmine.github.io/tutorials/async) of the Jasmine docs for information about how Jasmine will wait for each test to complete (and if the test is an asyncfunction, for the promise to resolve) before moving on to the next


Synaptics Pointing Device Sensitivity too low

Question: I turned off mouse acceleration for my touchpad in Xubuntu on my laptop, and now the sensitivity is way too low.  I can't have acceleration because it's unusable for me that way and I also can't have the sensitivity this low.  How do I increase the sensitivity above what is allowed in the mouse settings dialogue?
Comment: What xubuntu version are you running? What are your computers specs?
Answer: try this in your terminal:
#!/bin/sh
TP=$(xinput --list --short|grep -i touchpad|cut -f 1 | cut -d" " -f 5-|sed 's/\s\+$//g')
xinput --set-prop "$TP" "Device Accel Constant Deceleration" 1.5
xinput --set-prop "$TP" "Device Accel Velocity Scaling" 10


What is the effects of using the command git checkout?

Question: I have three branches Master, Branch1 and Branch2,
I am currently working on Branch2. I have done some local changes but I want to commit these changes to a new branch (Branch3).
After doing some research I see that I should create a new command using "git checkout -b [name_of_your_new_branch]"
I am scared that if I do a checkout new branch all my local changes will be gone.
Can someone help confirm what is the safest way to commit and push to a new branch when working on branch2.
Comment: You could copy the entire folder as what you have it right now. Then paste it somewhere on your desktop or wherever. In your working directory try whatever you need to try. If you mess things up you have a copy.
Answer: You will not loose your changes if you checkout a new branch. You should:
create a new branch
git checkout -b Branch3

stage your changes
git add .

commit your changes to that branch
git commit -m "Adding current changes to my newly created branch"

push your branch up
git push --set-upstream origin Branch3

Comment: Is there any difference between push --set-upstream origin Branch3 vs push -u origin Branch3?
Comment: `-u` and `--set-upstream` are the short and long version of the same argument, so they are equivalent https://git-scm.com/docs/git-push
Answer: Git will not overwrite or destroy your changes unless you ask it to. Be careful with commands that have the flag --force or -f. If you check out another branch while having uncommitted changes, Git will "float" these changes over. If it is not possible to apply the changes cleanly, Git will refuse to check out the other branch.
Simply create and check out the new branch just as you mention and commit the changes as usual.
git checkout -b Branch3
git add <path>
git commit

As a general advice, try to keep things that you care about committed. Recovering a change that has been part of a commit is fairly trivial, but it can be hard to recover files that have never been part of a commit or added to the index.


Unpack a list by duplicating elements longer than 1

Question: I have the following list that I wish to unpack (aka expand) using only base R.
For example, I want to turn this:
b <- list(a = c(1, 2), b = 1, d = c(5, 7))
into the equivalent of:
list(a = 1, a = 2, b = 1, d = 5, d = 7)
I have this function that works if only one named element has length > 1 but not if there are multiple elements:
expand_list <- function(listx){
  long_elements <- as.numeric(which(lapply(listx, length) > 1))
  short_elements <- as.numeric(which(lapply(listx, length) == 1))

  res <- lapply(long_elements, function(x){
    as.list(setNames(listx[[x]], rep(names(listx)[x], length(listx[[x]]))))
  })

  expanded_elements <- res[[1]]
  c(listx[short_elements], expanded_elements)
}

expand_list(b)

Comment: Related discussion - https://stackoverflow.com/questions/35163648/r-unlist-changes-names
Answer: You can use stack followed by setNames to achieve that
y <- list(a = c(1, 2), b = 1, c = 2, d = c(5, 7))
x <- stack(y)
as.list(setNames(x$values, x$ind))


How to link to a specific part of a page HTML PHP

Question: I am trying to link to a specific part in my php page. I have tried all the other answers on here but none of them have helped my special problem. This is how I am trying to go to the link
<a href="<?php echo $userLoggedIn; ?>#posts_tab">
So when the user clicks the dropdown they see a list of things. One of those things being the word Profile and when the user clicks on their profile they go to their own personal profile. When they are there they have a list of items at the top that look like this:

So what I want to do is when they click the profile they are automatically on the Profile Posts tab. Like a default option. For some reason it's not working for me and I can't figure out why. Any help please ?
header.php:
<a href="<?php echo $userLoggedIn; ?>#posts_tab">

profile.php:

        Profile Posts

Answer: I believe this is what you want, you need to let your profile page know that you want to load that part of profile.php, you can do it different ways I have used php and GET as example, I've sent a parameter on the URL and received it on profile.php
header.php
<a href="<?php echo $userLoggedIn; ?>?tab=posts_tab">

profile.php
<?php
$tab = $_GET["tab"];
if ($tab == "posts_tab"){
?><?php
}
?>

        Profile Posts

Comment: check browser console for errors, you can also try this inside script tag
Comment: Console didn't show errors and that didn't help


Points on a line are colored in 2 colours. Prove that it is always possible to find three points of the same color with one being the midpoint.

Question: Points on a line are colored in 2 colours. Prove that it is always possible to find three points of the same color with one being the midpoint.
I took the 2 colours to be red and blue. I approached this problem in the following way:
I tried to prove it by contradiction by trying to make a configuration where the midpoint of two points of the same colour can never be the same colour. Take a line segment from the line such that the endpoints are both red. Then consider the midpoint to be blue as the condition would be satisfied anyway if it was red. Then from the 2 endpoints keep going closer to the midpoint and we get a pair of points in each case.
Since the midpoint is blue I have to force the pair of points to be both red or a pair of red and blue. I tried drawing this out and could not deduce anything of use from this.
I want to know how to approach this problem and what would be the thought process in this kind of case, rather than a direct solution.
Comment: You can look at longer segments as well.  Call the first two red points $0$ and $1$.  Then $2$ must be blue....
Answer: Suppose otherwise.

Assume the line is the real number line with points labeled by their values.

Let $x,y$ be distinct points with the same color, say color $A$.

Then the points $2x-y$ and $2y-x$ must both have the other color.

Now what can you say about the color of the point ${\Large{\frac{x+y}{2}}}$?
Comment: @Sujal Motagi: The insight, assuming the claim is false, is simply to start with two distinct points of the same color, and then successively find points whose colors are forced.
Comment: Ah now I get the solution. I was hoping more for insight on how to think about the problem but this was an elegant solution.


How to stop scrolling in nestedScrollView if body is empty

Question: Sometimes my body widget have data and sometimes not so i need to stop scrollig in nestedScrollView when body is empty but unable to fix it
NestedScrollView(
                //controller: model.scrollController,
                headerSliverBuilder: (context, innerScroll) {
                  return [
                    model.isShowToolbar
                        ? SliverAppBar(
                            pinned: true,
                            floating: false,
                          )
                        : SliverPadding(padding: const EdgeInsets.all(0.0)),
                    Container(
                      height: 200,
                      color: Colors.green,
                    )
                  ];
                },
                body: ErrorWidgetView(
                  lottieFile: 'assets/images/post_empty.json',
                  title: 'No Recent Post',
                  showButton: false,
                ),
              ),

Answer: NotificationListener<ScrollNotification>(
                  onNotification: (ScrollNotification scrollInfo){
                    if ( !myModel.isLoading  &&scrollInfo.metrics.pixels ==
                        scrollInfo.metrics.maxScrollExtent) {

                    }
                    return false;
                  },)

User NotificationListener


BitBucket API Call for Creating Pull Request

Question: I am having some issues assigning reviewers to a BitBucket pull request. I can create the pull request just fine, but only one of the users is being assigned as a reviewer. Only the last "user" in the attached json payload is being added. All documentation I can find on this indicates this is the way to assign multiple reviewers, however it does not surprise me as the "name" field is a duplicate key.
<code>{
       "title": "Test",
       "description": "INSERT CHANGES HERE",
       "fromRef": {
           "id": "refs/heads/THIS_IS_A_TEST",
           "repository": {
               "slug": "fpt-programs",
               "name": "None",
               "project": {"key": "MTES"}
           }
       },
       "toRef": {
           "id": "refs/heads/master",
           "repository": {
               "slug": "fpt-programs",
               "name": "None",
               "project": {"key": "MTES"}
           }
       },
       "locked": false,
       "reviewers": [
       {
           "user": {
               "name": "mattmaur"
            },
           "user": {
               "name": "robsh"
            }
        }
    ]
  }
</code>
I have attempted formatting the "reviewers" value into a list, dictionary, etc. to no avail.
Answer: This has been resolved. The following payload will create a pull request with 2 reviewers.
<code>{
"title": "Test",
"description": "INSERT CHANGES HERE",
"fromRef": {
    "id": "refs/heads/THIS_IS_A_TEST",
    "repository": {
        "slug": "fpt-programs",
        "name": "None",
        "project": {
            "key": "MTES"
        }
    }
},
"toRef": {
    "id": "refs/heads/master",
    "repository": {
        "slug": "fpt-programs",
        "name": "None",
        "project": {
            "key": "MTES"
        }
    }
},
"locked": false,
"reviewers": [{
        "user": {
            "name": "robsh",
            "emailAddress": "_EMAIL_",
            "id": 2079,
            "displayName": "_NAME_",
            "active": true,
            "slug": "robsh",
            "type": "NORMAL",
            "links": {
                "self": [{
                        "href": "https://_URL_/users/robsh"
                    }
                ]
            }
        },
        "role": "REVIEWER",
        "approved": false,
        "status": "UNAPPROVED"
    }, {
        "user": {
            "name": "mattmaur",
            "emailAddress": "_EMAIL_",
            "id": 1901,
            "displayName": "_NAME",
            "active": true,
            "slug": "mattmaur",
            "type": "NORMAL",
            "links": {
                "self": [{
                        "href": "https://_URL_/users/mattmaur"
                    }
                ]
            }
        },
        "role": "REVIEWER",
        "approved": false,
        "status": "UNAPPROVED"
    }
]
</code>
}


Light switch connected to Smoke Alarm

Question: So my light switch is connected to my smoke alarm in such a way that the smoke alarm isn't on/charging unless the light in the room is also on.
I live in the United Kingdom. This is an upstairs bedroom light. Smoke alarm in adjacent hall.
Pretty sure that black is neutral, red is live and green/green+yellow is earth.
I've a feeling I should only need to move one wire to make it so the smoke alarm is always powered, and my light switched, but not 100% sure how to identify which wire?
Any help would be appreciated.
Here's the switch:

A wiring diagram:

The alarm wiring:

The lamp wiring:
Comment: I've added more photos see [link](http://imgur.com/a/Aa2Cv)
Answer: My guess would be

I notice someone (you?) marked the switched-live wires with black dots (single and double). If you are especially lucky, whoever did this also similarly marked the wires in the light fitting and in or behind the smoke alarm.
So for example it might be something like

switched live 1 - light fitting
switched live 2 - smoke alarm
permanent live - unused?

The bottom red wire is most likely the live feed in from the fusebox/consumer-unit.
If there are two reds behind the smoke alarm, it may be that one is the upper permanent live and the other is one of the two switched lives. If so you can rearrange wiring at the alarm. Otherwise you need to move wires at the switch.
If all else fails I would turn off the breaker for that circuit, disconnect the three red wires that exit the top of the back box, open up the smoke alarm, remove the light bulb (in case the alarm piggy-backs from the light fitting) and then use a continuity tester (e.g. Cat II multimeter) to work out which wires go where.

I have a cheap DT830B digital multimeter that I've never used.

Not ideal, but here's what I would do. Take great care as 240VAC is potentially lethal.

disconnect all the red wires (R1-R4)
plug black lead into bottom socket marked "COM"
plug red lead into middle socket labelled VΩmA
Set dial to V~ 750 range
prop the meter up somewhere you can see it which is near to the switch.
hold the probes keeping your fingers at least 1" away from the metal tips.
press the black probe tip firmly into the top of the black connector where there is a brass screw clamping the wires together.
press the tip of the red probe against each of R1 to R4 in turn and make a note of which ones show 230-250 VAC.

With luck that will identify which of the red wires is the live feed in. You can then try connecting the live wire to each of the other reds one at a time to see what turns on. That will identify what the other wires go to.

Connecting R2+R3 puts the light on ...

Test results:
Connections            |switch |light  |alarm |other |conclusion
-----------------------|-------|-------|------|------|--------------------------
top=R1+R2+R4 bottom=R3 |off    |off    |ON    |-     |R3 is not live-in nor alarm
"                      |on     |ON     |ON    |-     |R3 to light
R1 + R2 + R3 + R4      |-      |ON     |ON    |-     |-
R2 + R3                |-      |ON     |-     |-     |R3 is light, R2 is live-in
R2 + R4                |-      |-      |ON    |-     |R4 is alarm, R2 is live-in
R1 not connected to R2 |-      |-      |-     |OFF   |R1 is other rooms

So in summary:

R1 is to other rooms.
R2 is live from fusebox/consumer-unit
R3 is light
R4 is alarm

Your Crabtree switch has a top connector, often this will be labelled COM, in your case at appears to be marked COMMON. I would connect R1, R2 and R4 here
It also has two lower connectors - it is a two-way switch (US nomenclature: three-way) used where you have two switches contolling one light (e.g hallway). In this case it is being used as a normal one-way switch. The two lower connections are usually labelled L1 and L2†. I would connect R3 to L1 here.
Summary
top (COMMON) = R1 + R2 + R4
bottom (L1) = R3

It doesn't matter if you swap the roles of the top COMMON and bottom L1 connectors if that makes it easier to fit the wiring in.
If the normal ON position of the switch has the lights off, just move all the wires that are in L1 over to L2.

†Other manufacturer's switches sometimes have the common position labelled as L1 and the other positions as L2 and L3.
Comment: I've added more photos [link](http://imgur.com/a/Aa2Cv).

If I connect R4 to R1+2, the alarm gets power and the light doesn't - does that help? Connecting R3 to the same place or turning on the switch then turns the light on also.

Does that sound right?
Comment: Also, the dots were me, so I could at least put it back together the same way if all else failed.
Comment: From your experiment, it seems that R3 is to the light. That suggests R1 or R2 is the live feed in. When you say "same place" it isn't clear whether you mean "same place as before" or "same place as R1+2" or some other same place. Anyway, do you have a [voltage tester](http://diy.stackexchange.com/q/90038/2815) of any sort?
Comment: I mean with R1+2+4 at the top of the switch and with R3 at the bottom. (Only moving R4). The alarm gets power, and the light only comes on when the switch is on - which is what I want. I have a cheap [DT830B digital multimeter](http://www.hobby-hour.com/electronics/dt830b-digital-multimeter.php) that I've never used.
Comment: Maybe you have solved the problem to your satisfaction then. If not ,see updated answer. Be careful. Hope that helps. Good luck.
Comment: Thanks for helping with this! I've done what you suggested with the multi-meter - I think I need a new one as it kept only showing 0 or 1. R2 is the only one showing anything > 0, and once it did flash ~230 for a second, so I think that is the only live one.
Comment: Connecting R2+R3 puts the light on. So I guess R3 is the light. Connecting R2+R4 puts the alarm on. So I guess R4 is the alarm. I think then that R1 is the connection to the rest of the upstairs rooms? As without R2+R1 connected, the other rooms lights don't go on? Does that sound right? Given that... how should they be connected to the switch? R2+R4+R3 to the top and R3 to the bottom?
Comment: Correction: Given that... how should they be connected to the switch? R1+R2+R4 to the top and R3 to the bottom?
Comment: @brightemo Yes, see updated answer.

Light switch connected to Smoke Alarm


Synchronize and Update database android application from website

Question: I have problems.
I create an application which is on starting it will synchronize the database in external storage with database on website if any data changed it will appear dialog to ask "Do u want update".
I put my database on website http://example.com/folder/mydb.db
and for android I put it on external at data/data/database/mydb
How to check any database changed?
Comment: Need more information about the server side of it.  Bottom line: you'll have to have some way for the server to give you either a timestamp of its last update or a changeset or something.
Comment: I put my database on website http://websitename/folder/mydb.db and for android I put it on external at data/data/database
Comment: This is a bad idea, for many reasons.  First, with respect to the original question, you'd have to download the whole database and open it to check for modifications.  You need a middle layer (web service or something) between your app and the database if you have any regard for things like security, performance, scalability, or maintainability.
Comment: can you give me explanation about middle layer(web service or something). For sure, my application just want to compare between database at external storage n database on website if content of database is same or not it will give dialog
Answer: Change the name of the file you upload, adding the version number so you can just compare the file name to check for modification.
If different, download and override your existing DB using the tutorial here:
http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/


Identify module name to blacklist

Question: Everybody knows that any kernel module can be blacklisted via GRUB line:
$ module_name.blacklist=yes

However, not everybody knows the exact name of module to blacklist. And that is the real problem! How to identify it?
For example, during of loading of GRUB I see:
rtlwifi firmware not available

which is quite useless of identification. Neither
rtlwifi.blacklist=yes

nor any other variants worked. How do I figure out the name?
The same thing goes with Bluetooth adapter. It throws:
 [ 9.366503] Bluethooth: hci0: Failed to load rtl_bt/rtl8821a_fw.bin

Of course, rtl_bt/rt18821a_fw.blacklist=yes didn't work.
$ lsmod | grep rtl
rtl8821ae             233472  0
btcoexist             131072  1 rtl8821ae
rtl_pci                32768  1 rtl8821ae
btrtl                  16384  1 btusb
bluetooth             548864  5 btrtl,btintel,btbcm,btusb
rtlwifi                77824  3 rtl_pci,btcoexist,rtl8821ae
mac80211              778240  3 rtl_pci,rtlwifi,rtl8821ae
cfg80211              622592  2 mac80211,rtlwifi

Any suggestions?
UPDATE: What concerns rtlwifi error lspci -v listed only following
Network controller: Realtek Semiconductor Co., Ltd. RTL8821AE 802.11ac PCIe Wireless Network Adapter
Subsystem: ASUSTeK Computer Inc. RTL8821AE 802.11ac PCIe Wireless Network Adapter
Flags: bus master, fast devsel, latency 0, IRQ 29
I/O ports at e000 [size=256]
Memory at f7d00000 (64-bit, non-prefetchable) [size=16K]
Capabilities: [40] Power Management version 3
Capabilities: [50] MSI: Enable+ Count=1/1 Maskable- 64bit+
Capabilities: [70] Express Endpoint, MSI 00
Capabilities: [100] Advanced Error Reporting
Capabilities: [140] Device Serial Number 00-e0-4c-ff-fe-87-2b-01
Capabilities: [150] Latency Tolerance Reporting
Capabilities: [158] L1 PM Substates
Kernel driver in use: rtl8821ae
Kernel modules: rtl8821ae

And name rtl8821ae already was in my blacklist without any result, so it seems to be no-go.
What concerns Bluethooth: hci0 error, lspci listed no Bluetooth modules or nothing similar to rtl_bt, maybe because Bluetooth adapter is not a PCI device.
Comment: What does `lsmod | grep rtl` tell us?
Comment: Added output to question
Comment: Something is clearly wrong with the blacklisting as rtl8821ae is still being loaded according to your `lsmod` above (but not used, as it says "0"). It's not clear what the actual problem is though, why you want to blacklist. Is it blacklisted in `/etc/modprobe.d` ? Try that, reboot, check it's not in lsmod. Are you using bluetooth?
Comment: No, I am not using bluetooth. I am trying to boot ubuntu-based Clonezilla image and exclude unnecessary modules. As I know it, it supports blacklisting only via `grub.cfg`but I will try `/etc/modprobe.d`
Comment: what device are you trying to blacklist?
Comment: rtl8821ae and rtlwifi. I suppose these are bluetooth and wifi modules. I know only the errors I see during the boot, which I given in the question body
Comment: "ubuntu-based Clonezilla image" the Clonezilla is just a copy of a disk AFAIU, so which version of Ubu is it? Did you try blacklisting in /etc/modprobe.d/?
Comment: `so which version of Ubu is it` 18.10, Artful Aadvark
Comment: I tried `modprobe.blacklist=rtl8821ae` directive of CLonezilla and it seems to work, but only for `rtlwifi`. `Bluethooth: hci0: Failed to load rtl_bt/rtl8821a_fw.bin` error is thrown anyway. Any hint?
Answer: You can boot without blacklisting the driver and then use lspci -v to display the information about the hardware and the kernel driver and module associated with it. The Kernel Modules: section should show module name you need to blacklist (most likely)
Sample output:
00:01.3 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 03)
    Subsystem: Red Hat, Inc Qemu virtual machine
    Flags: medium devsel, IRQ 9
    Kernel driver in use: piix4_smbus
    Kernel modules: i2c_piix4

Module name in above example is i2c_piix4
Let me know if that works. Source of this info is https://askubuntu.com/a/110343/142100
Comment: Tried your suggestion without any result. See the details in my update.
Comment: Does rmmod rtl8821ae do anything after you have already booted.

Identify module name to blacklist


How to create new projects in Eclipse using Maven 3 archetypes

Question: Is there some plugin for Eclipse which allow me to create new projects based on Maven 3 archetypes? I have to deal with a bunch of archetypes (including some created/used internally by our organization) and would like to have some plugin which e.g. would ask me

which archetype to use
what is the group id
what is the artifact id

and the would create a project with that information. However, this seems impossible.
So, there are two questions:

is there such a plugin? If so,
how to use it in a way analogous to the one I described below?
Answer: What about m2eclipse?
I believe it covers all your needs. Once installed you can create a new maven project and the wizard will ask you for archetype, group and artifact id.
Just go to File-> New -> Other -> Maven -> Maven Project and it will guide you.
Note: the 2 on the m2eclipse doesn't need it uses maven 2, you can configure it to use any maven installation that you may have


select tag: first option selected by default

Question: I'm stuck with that issue for almost one day...
Simple select list that looks like this:
<code>        <select id="slide_number">
            <option value="slide_1">Slide 1</option>
            <option value="slide_2">Slide 2</option>
            <option value="slide_3">Slide 3</option>
            <option value="slide_4">Slide 4</option>
        </select>
</code>
And I use this code, to remove the selected attribute, and add it again to the right option.
<code>    $('#slide_number').change( function() {
        $('#slide_number option:selected').removeAttr('selected');
        $('#slide_number :selected').each( function() { alert( $(this).find('#slide_number :selected') ) } );
        $("#slide_number option[value='slide_" + _t._current_slide + "']" ).attr( 'selected','' );
    } );
</code>
Everything would be perfect, but after slide 2 it doesn't work properly, it autoselects the first option, even that in chrome i see that the code is changing and the selected tag is being added correctly to other options.
On iPad in Safari I saw that when I choose option 3, it signs option 1 and option 3 at the same time and this is what I think is causing the issue, but I can't get rid of that autoselect of the 1 option :/
I added this alert and it shows that even after removing the selected attribute, option 1 is still selected :(
Thanks for your time and ideas...
Comment: Please explain the logic of using this code `$("#slide_number option[value='slide_" + _t._current_slide + "']" ).attr( 'selected','' );`.
Comment: and what you want to get/do inside the `change` event?
Comment: This is selecting the right slide from the list by value. When I turn right, I change the _current_slide number and I trigger $('#slide_number).trigger('change') so it updates the list.

Change event is simply changing the selected attribute in the list to the current one.

What I saw is when I add multiple='multiple' to the select tag, everything works well, just the select itself is changing to a list that I don't want
Comment: So, on change you want to set the `_t._current_slide` as selected? Btw, which version of jQuery file are you using?
Comment: it's already setted, I want to find that slide in option list and add attr selected. But I want all the others not to be, and the first slide is getting selected somehow and it's not being shown in the code....
Answer: Try this using the jQuery v1.9.1+
<code>$('#slide_number').change(function () {
    $("option[value='slide_" + _t._current_slide + "']", this).prop('selected', true);
    $(':selected', this).each(function () {
        alert($(this).text());
    });
});
</code>
Comment: **Before jQuery 1.6**, the `.attr()` method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. **As of jQuery 1.6**, the [`.prop()`](http://api.jquery.com/prop/) method provides a way to explicitly retrieve property values, while `.attr()` retrieves attributes.


Launch default camera app and start record automatically

Question: I have a button in my app. With an OnClick event to the button I launch the default camera app.
public void startrec(View v) {
    Intent intent = new Intent(MediaStore.INTENT_ACTION_VIDEO_CAMERA);
    startActivity(intent);
}

This works fine. Now is it possible that the camera starts recording automatically without I have to press the record button in the camera application? So I mean... I press my button in my app -> the camera app starts -> the record starts immediately
How can I do that?
Answer:
How can I do that?

Record the video yourself, using classes like MediaRecorder.
Your existing code is asking a third-party app to take a video on your behalf. There are hundreds, perhaps thousands, of such apps. The behavior of each of those is up to the developer of those apps. There are no documented extras for your chosen Intent action, let alone one for your desired feature. And even if it existed, not every camera app would honor it.
Comment: @user3033136 if you found answer please share


Loading dataframe from Azure Databricks into Azure Queue Storage

Question: We do have a use case where we are building some dataframe in batch load and would like to load into Azure queue so that it can be read by a REST API later.
Instead calling the API to post data we would like to save it in some message queue that can be read by the REST API to process further.
The dataframe contain 20k records with schema like(example):

Present code snippet:
df=final_df.withColumn("status_code",post_udf('ColA','ColB','ColC','ColD'))

The udf function post the data to API and return the status code.
I would like to save above transformed dataframe into azure message queue/azure event grid or any other service, from where the API can access it.
Comment: Please edit to show relevant work (code, sample data, expected vs actual behavior, etc). As written, it's unclear what you've done or what you're having issues with. FYI you can't just place a data frame into queue messages; you have to do your own transform and output (and that's the type of thing you should be sharing here)
Comment: @DavidMakogon I did not get that point!! the dataframe is already transformed and I want to keep it any message queue/azure event grid so that API can read it later.
Comment: fyi - not sure why you re-added [tag:azure-eventgrid] - as written, this question is not about event grid specifically.
Answer: You can use Azure Functions to get data from azure queue.
Follow below steps,
First, run below code for sending data into queue.
import os
import json
from azure.storage.queue import QueueServiceClient, QueueClient, QueueMessage

json_data = df.toJSON().collect()
queue_name = "Your queue name(tst in my case)"
connection_string = "Your connection string"
queue_client = QueueClient.from_connection_string(connection_string, queue_name)
for data in json_data:
    queue_client.send_message(data)

Below is the data i have.

This code sends each row of dataframe to queue.
Before sending data, it is converted to Json format and sends it.
Below is the result of my data in queue,

Here, you can see each row is updated.
Next, you need to create an azure function.

Go to Function App and click on create.
After creating function app, let's deploy function in visual code.
Open visual code, go to extensions and search for Azure Function and install it.
You will get azure symbol at bottom left as below.

Go to azure tab, there click on the option shown below to create function.

which prompts to select type of trigger. Select HTTP Trigger then name of the function and authorization level as anonymous.
After creating the function, you will get a __init__.pyand project structure as below.

Here, you can see requirements.txt there add the following package in it.
azure-storage-queue

By default, the code will be as below in `init.py.

Replace that code with the below code.
import  logging
import azure.functions as  func
import  json
from azure.storage.queue import QueueServiceClient, QueueClient, QueueMessage

def  main(req: func.HttpRequest) -> func.HttpResponse:

    logging.info('Python HTTP trigger function processed a request.')
    queue_name = "Your queue name(tst in my case)"
    connection_string = "Your connection string"
    queue_client = QueueClient.from_connection_string(connection_string, queue_name)
    retrieved_message = queue_client.receive_messages()
    res = []

    for  i  in  retrieved_message:
        res.append(json.loads(i.content))

    res = json.dumps(res)
    logging.info(res)
    return  func.HttpResponse(f"Data : {res}. This HTTP triggered function executed successfully.")

Next give your queue name and connection string.

After updating the code, click on the option shown in image to deploy the function. Again, it prompts to select subscription id,resource group and azure function  you created before in azure. Select them appropriately.
That starts the deployment.
After deployment, go to app function you created in azure, there you can find deployed functions under Function tab.
You will get details as below.

Copy the function URL and test it.
I tested using postman.
You can see the result here.


Better design to displaying a lot of data within tables

Question: This is the current design

There could be hundreds of the 'panels' with tables that expand underneath when clicked. The tables could contain thousands of rows.
What would be a better way of displaying this?
The tables contain errors which users can do multiple things with, any suggestions?
Comment: Who is the user and what is their goal?
Answer: If a panel is expanded and it has thousands of rows, then the below panel will be unreachable if you don't collapse the panel.
My suggestion is using pagination for both the panels and the rows in the panel. So you present a limited number of panels per page and a limited number of rows per panel.
You might also want to give the option to view the full panel. This should open either in a Dialog or in a different page.
Take a look at Material design - Tables within cards.
Answer: One question you have to ask yourself is "What is your user willing to do with those thousands lines of data"?
I think that is better to focus on a useful research interface than just displaying data that user won't read.
Once the number of data to display is reduced by the filter, you would be able to think more easily to a nice User Interface.
Answer: If these base cards are just titles then why have the data rows contained within a card at all?  This seems like the perfect case of running a simple data table that the user can filter with a free text search to target the types and content of the rows that will be the of the most interest to them.
Now if this base card idea was done for performance reasons then it kind of makes since as long as the card carries a count of how may rows will be displayed when opened.  This will help inform the user of the impact of their choice of opening a card.
In essence though what it seems to be is the same issue that most retailers have already tackled with a left hand filter set married with a free text search and then just displaying the results as either table line items or cards.  Either way your starting idea seems to create more surprises for the users rather than provide them with information to guide them to the work they need to do.


MySQL - How do I know what indexes to use?

Question: I'm trying to add indexes to the following query.
<code>SELECT * FROM Messages t WHERE perspective_user=? and timestamp BETWEEN ? AND ? AND
timestamp_added =
(select max(timestamp_added) from Messages t2
where
t2.author = t.author AND
t2.body = t.body AND
t2.timestamp = t.timestamp AND
t2.timestamp_added <= ?
) AND convo_id IN(SELECT convo_id FROM Conversations WHERE perspective_user=? AND identity=? AND timestamp_added=?);
</code>
My first thought was three indexes: One on perspective_user, timestamp, timestamp_added, and convo_id, a second index on author, body, timestamp, and timestamp_added, and a final index on perspective_user, identity, and timestamp_added. This doesn't work, however, and, as far as I can tell, takes the same amount of time to execute.
How do I add indexes to this query, and, more generally, how do I know how to add them properly in the future?
Comment: Execute the queries seperately with `explain select ...` to see how it performs
Comment: you add indices to the tables not the queries
Comment: Isn't this question a dup of part of http://stackoverflow.com/questions/43023274/mysql-figuring-out-what-indexes-to-use-and-not-working-as-expected ?  I have addressed the index questions there.
Answer: Indexes to use?

Indexes depends on your needs query.
Mostly of indexes used is from on your where clause.
One best thing of indexes to use is your primary key.
Avoid creating to much indexes to your tables cause it could make your data become slower to your query.

See this indexes tutorial for more details.


Selecting Persons in table and exclude wife but combine their names

Question: I have a table Person:
PersonID | FirstName | LastName
-------------------------------
1        |   John    |  Doe
2        |   Jane    |  Doe
3        |  NoSpouse | Morales
4        | Jonathan  | Brand
5        | Shiela    | Wife

And a Relationship table:
RelationshipID | PersonID | Type | RelatedPersonID
1              |    1     |  3   |     2
2              |    2     |  3   |     1
3              |    4     |  3   |     5
4              |    5     |  3   |     4

So basically, I want to combine the names of the spouse and client, but I want to exclude the spouse:
Expected Results:
1,  John and Jane Doe, 2
----------------------
3, NoSpouse Morales, null
-----------------------
4, Jonathan and Shiela Brand, 5

I've tried:
SELECT p.PersonID,
    Case when spouse.PersonID is not null
        THEN p.FirstName + ' and ' + spouse.FirstName + ' ' + p.LastName
    ELSE p.FirstName + ' ' + p.LastName END as ClientName,
    spouse.PersonID as RelatedPersonID
FROM Person p
LEFT JOIN Relationship r on p.PersonID = r.PersonID
LEFT JOIN Person spouse on r.RelatedPersonID = spouse.PersonID
WHERE r.Type = 3 OR spouse.PersonID is null

but the results are:
1,  John and Jane Doe, 2
----------------------
2,  Jane and John Doe, 1
----------------------
3, NoSpouse Morales, null
-----------------------
4, Jonathan and Shiela Brand, 5
-------------------------------
5, Shiela and Jonathan Wife, 4

Here's some mock data:
create table Person(
    PersonID int primary key,
    FirstName varchar(max),
    LastName varchar(max)
)
insert into Person values
(1, 'John', 'Doe'),
(2, 'Jane', 'Doe'),
(3, 'NoSpouse', 'Morales'),
(4, 'Jonathan', 'Brand'),
(5,'Shiela','Wife')

create table Relationship (
    RelationshipID int,
    PersonID int references Person(PersonID),
    Type int,
    RelatedPersonID int references Person(PersonID)
)
insert into Relationship values
(1, 1, 3, 2),
(2, 2, 3, 1),
(3, 4, 3, 5),
(4, 5, 3, 4)

SELECT p.PersonID,
    Case when spouse.PersonID is not null
        THEN p.FirstName + ' and ' + spouse.FirstName + ' ' + p.LastName
    ELSE p.FirstName + ' ' + p.LastName END as ClientName,
    spouse.PersonID as RelatedPersonID
FROM Person p
LEFT JOIN Relationship r on p.PersonID = r.PersonID
LEFT JOIN Person spouse on r.RelatedPersonID = spouse.PersonID
WHERE r.Type = 3 OR spouse.PersonID is null

drop table Relationship
drop table Person

thanks in advance for your help and time.
NOTE:
I've edited my mock script to include 3, NoSpouse Morales, null in the results. Also, there is no particular criteria needed to which is husband/wife. Whoever was fetched first in the list should not include the related spouse.
Comment: If you look at your data what is the criteria to detect who is the husband and who is the wife? I don't see any criteria. Without a criteria you cannot write a query.
Comment: On a purely non-programming note, I would be wary of renaming Shiela Wife without her express permission. Consider dropping the second surname only if it matches the first.
Comment: gender is not really important. if the first person is already in the results, the spouse should not be included
Comment: Werner means, how would you choose between 'Jane and Joe Doe' and 'Joe and Jane Doe'?
Comment: So a result including "2,  Jane and John Doe, 1" but not "1,  John and Jane Doe, 2" is also OK?
Comment: You don't have any logic to handle last names. If "Lou Segusi" is spousal with respect to "Carmine Dioxide", but neither chooses to change their last name, what result do you want? Pick one? Pick both? Surgical hyphenation? Anullment?
Comment: Polygamy is gonna be fun to deal with...
Comment: If they're married, or otherwise a couple, I think choosing any of their last names would be acceptable to both parties. It's just a representation anyway.
Answer: If one has to be included while the other excluded, try adding a clause
AND r.PersonID < r.RelatedPersonID

since the IDs will not be equal and this will include only either one:
 SELECT p.PersonID,
 Case when spouse.PersonID is not null
    THEN p.FirstName + ' and ' + spouse.FirstName + ' ' + p.LastName
 ELSE p.FirstName + ' ' + p.LastName END as ClientName,
 spouse.PersonID as RelatedPersonID
FROM Person p
LEFT JOIN Relationship r on p.PersonID = r.PersonID
LEFT JOIN Person spouse on r.RelatedPersonID = spouse.PersonID
WHERE (r.Type = 3 AND r.PersonID < r.RelatedPersonID)  OR spouse.PersonID is null

Answer: This might work
SELECT p.PersonID,
    Case when spouse.PersonID is not null
        THEN p.FirstName + ' and ' + spouse.FirstName + ' ' + p.LastName
    ELSE p.FirstName + ' ' + p.LastName END as ClientName,
    spouse.PersonID as RelatedPersonID
FROM Person p
LEFT JOIN Relationship r on p.PersonID = r.PersonID and r.Type = 3
LEFT JOIN Person spouse on r.RelatedPersonID = spouse.PersonID
WHERE  coalesce(r.PersonID, 1) < coalesce(r.RelatedPersonID, 2)

This way you only take into account relationship rows where PersonID is lower than RelatedPersonID, or rows that don't join with Relationships table at all (because 1 < 2 is always true)
Comment: yep.. this seems the same with @dev8080's answer. Up for the explanation though.
Comment: Yes it's basically the same... he beat me by 45 seconds :D
Answer: If I understand correctly, you can just remove the spouses in the WHERE clause:
SELECT PersonId, ClientName, RelatedPersonID
FROM (SELECT p.PersonID,
             (CASE WHEN spouse.PersonID is not null
                   THEN p.FirstName + ' and ' + spouse.FirstName + ' ' + p.LastName
                   ELSE p.FirstName + ' ' + p.LastName
              END) as ClientName,
             spouse.PersonID as RelatedPersonID,
             spouse.LastName as spouse_lastname
      FROM Person p LEFT JOIN
           Relationship r
           ON p.PersonID = r.PersonID LEFT JOIN
           Person spouse
           ON r.RelatedPersonID = spouse.PersonID
      WHERE r.Type = 3
     ) prs
WHERE spouse_LastName <> 'Wife';

Comment: this means that i have to manually supply the spouse last names, right
Comment: I think 'Wife' was just an example name.
Comment: @GeomanYabes . . . The example data has "wife" as the last name.  It is only possible to answer the question that is asked.
Comment: but i also included the expected result. ^^, thanks for the answer anyway
Answer: Try this
create table Person(
   PersonID int primary key,
   FirstName varchar(max),
   LastName varchar(max)
)
insert into Person values
(1, 'John', 'Doe'),
(2, 'Jane', 'Doe'),
(3, 'NoSpouse', 'Morales'),
(4, 'Jonathan', 'Brand'),
(5,'Shiela','Wife')

create table Relationship (
   RelationshipID int,
   PersonID int references Person(PersonID),
   Type int,
   RelatedPersonID int references Person(PersonID)
)
insert into Relationship values
(1, 1, 3, 2),
(2, 2, 3, 1),
(3, 4, 3, 5),
(4, 5, 3, 4)

SELECT p.PersonID,
   Case when spouse.PersonID is not null
      THEN p.FirstName + ' and ' + spouse.FirstName + ' ' + p.LastName
   ELSE p.FirstName + ' ' + p.LastName END as ClientName,
   spouse.PersonID as RelatedPersonID
FROM Person p
LEFT JOIN Relationship r on p.PersonID = r.PersonID AND r.Type = 3
LEFT JOIN Person spouse on r.RelatedPersonID = spouse.PersonID
WHERE r.RelationshipID IS NULL OR  r.RelationshipID < r.RelatedPersonID

drop table Relationship
drop table Person

Demo link: Rextester
Comment: You should add an explanation on what your query does to accomplish the desired results.


How to connect with external mySQL database using hibernate

Question: Instead of using a local mySQL Database i created an external database with https://remotemysql.com/. The problem I am having is that I cant connect to the database.
This is my hibernate config file:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://www.remotemysql.com:3306/oJv6mOSx3X</property>
    <property name="hibernate.connection.username">34kjldxck</property>
    <property name="hibernate.connection.password">mysecpw</property>
    <property name="show_sql">true</property>

    <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>

    <mapping class="com.jcg.hibernate.maven.User" />
</session-factory>

This is how I am trying to connect to the database:
public class AppMain {
static Session sessionObj;
static SessionFactory sessionFactoryObj;

private static SessionFactory buildSessionFactory() {
    // Creating Configuration Instance & Passing Hibernate Configuration File
    Configuration configObj = new Configuration();
    configObj.configure("hibernate.cfg.xml");

    // Since Hibernate Version 4.x, ServiceRegistry Is Being Used
    ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();

    // Creating Hibernate SessionFactory Instance
    sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
    return sessionFactoryObj;
}

public static void main(String[] args) {
    try {
        sessionObj = buildSessionFactory().openSession();
    } catch(Exception ex){
                ex.printStackTrace();
    }
 }
}

This is the error I get:
org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:122)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at com.jcg.hibernate.maven.AppMain.buildSessionFactory(AppMain.java:24)
at com.jcg.hibernate.maven.AppMain.main(AppMain.java:30)
Caused by: java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:1041)
at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3481)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2445)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
... 14 more
Caused by: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
at com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:992)
... 27 more
enter code here

Now I am guessing that the error is because of the connection url I guess. Whats strange that i get am Math exception(igInteger cannot be cast to java.lang.Long)
Comment: can you get to the database outside an application - using workbench or similar application?
Comment: @Aviza if I use plain plain jdbc I can access my database. I used MysqlDataSource and it worked but now I decided to switch to hibernate and now it doesnt work
Answer: This type of error indicates error to connect to the database
(search the exception for results).
It is hard to say what is the reason.
It could be related to the version of the connector.jar.
I would check that but first. Also would check if you are able to connect to a local database from your hibernate framework.
Answer: if you scroll down into the error, in the caused by section , I think you have a field in database of type BigInteger and it's mapped to Long class field, which cause a ClassCastException
Hope it helps


Group Checkboxes Select All / None Design's best practices

Question: What would be more inline with best practices for the select all / select none option on group checkboxes?

OR
Answer: You can treat the checkbox as part of the header. The checkbox for list selection is a fairly established control.
Since you essentially have tabular data, you can include the top level checkbox as part of the header.
The user will get immediate feedback in close proximity as they toggle the checkbox, and select/deselect any items,  so the result is right in front of them.

You see this in Material Design guidelines for checkboxes


Flickering lights, how to determine who to call

Question: I've read numerous "flickering lights posts" and the answers range from bad bulbs to bad wiring to a bad neutral.  Here's what I've determined:

They (the tenants) report it only happens when either the 3D printer or the clothes washer is running, but not the electric stove.
It's all the lights throughout the house, and not just the LEDs.
Moving the printer to a different circuit didn't fix anything.
Even an incandescent bulb on a circuit less than 10' from the breaker panel flickers.
The voltage at the panel when not flickering (measured just after the master breaker, hot to neutral): One leg 116.7v.  The other leg 124.4
The voltage at the panel when they are flickering (hot to neutral): One leg 118.8v.  The other leg 126.4
The voltage at the outlet of a flickering bulb: 118.8v.
Previously we had a problem with the lights brightening when a load kicks in.  We had an electrician out who found some iffy neutrals and other unrelated issues.  He reseated the neutrals and the problem went away.  But that's about when the flickering started.
The house was built in 1964 and is located in the U.S.

So my question is: Who do I call next, the power company or an electrician?
Comment: @manassehkatz-Moving2Codidact That's a good idea.  She has moved the printer to a different outlet, but I can't say it was on a different leg.
Comment: @manassehkatz-Moving2Codidact I agree, 5% difference seems pretty high for something coming off a transformer.
Comment: Is it an active flicker or more of a dimming situation? Does it happen the entire time the printer or washer is running or just at start-up?
Comment: Does it happen during windy or rain/snow situations? It could indicate a failing weatherhead.
Comment: It's not affected by the weather.
Comment: I see, any my other questions?
Comment: That is an awfully high difference between the two legs. Each leg is within the "normal" range, but that really seems a bit off - I normally see < 1V difference.
Comment: The lights only flicker when the printer's bed heater is on (either warm-up or during operation) but not the heaters on the extruder nozzles.  The washer only causes flickering when the mechanism is doing something (so fill and drain don't cause any problems.)
Comment: Those are just 120v appliances, right?
Comment: @MonkeyZeus Yes, 120V, and we're 60Hz in this part of the country.
Comment: Which part of which country?
Comment: @MonkeyZeus Illinois
Comment: Interesting, which part of the US doesn't use 60Hz?
Comment: A bit odd that the bed heater causes problem, but not the motors that move the nozzle.  It might come down to getting the power company and a electrician.  For a house with a single transformer, both legs should be equal, if no power is used or balanced.  The printer and washer might need checking since they seem to cause the flickering, and nothing else, so far.
Comment: Have you moved the printer to a circuit *on the other leg*?
Answer: I think you had a lost neutral all along
Each house/dwelling has a local Grounding Electrode System aka "ground rods" and the wires running out to them.  Each main panel has a Neutral-Ground Equipotental Bond (N-G bond) whose job is to keep neutral near earth potential. This works with the ground rods to keep this from happening (UK homes don't have ground rods).
So thanks to the N-G Bond, there's a party happening in your main panel where house neutrals, utility neutral, house grounds and ground rods all come together.  Got it?

So what happens in a Lost Neutral?  This, except the neutral connection actually has an alternate path (a bit byzantine but it does work).   Your neutral -> your N-G bond -> ground rods -> the dirt -> neighbor's ground rods -> neighbor's N-G bond -> neighbor's neutral.
This path has some resistance, being dirt and all, but still, it will somewhat limit how far neutral will wander away from the center. This reduces the symptoms of a Lost Neutral.
What changed is your electrician "Tuned Up" your Grounding Electrode System to get it performing better.  (it was probably broken; given the liability that creates I would have your guy make the rounds to all your properties and check it there).
Thus, all the electrician did is reduce the severity of the symptoms and that seemed like a victory - but the underlying Lost Neutral condition remains.
The power company should fix that for free in most cases.
Comment: Upvoted - have to agree, maybe the neutral isn't totally lost but it at least has problems. That's a big difference between the two legs.


Compare dates or dates with time, depending if the time is set

Question: I have a datetime field. If the user in form enters only date, the time will be set as 00:00:00 of course, that is the way it is supposed to be.
But in mysql I need to compare this field with now() or with curdate(). If the time is set and is not 00:00:00 I need to compare only dates, if the time is other value I need to compare it with now().
For example, if I use in mysql date>=now() and the user set only date like 2013/12/22 then the comparation will be false on 12/22 which I do not want. I would like that comparation would be false on 12/23 then, the entered date is still valid on the same date.
Now if use date>=curdate() then the time will be ignored if somebody set time.
One solution would be to check if time is 00:00:00 and then somehow change it to 23:59:59 for comparation.
So bottom line is, if there is 00:00:00 as time in datetime field, user had obviously set only date so I need to compare date to curdate(). If time is set to any other value I need to compare date to now().
Is that doable?
Answer: I would try this condition:
dt >= now()
OR
(
  time( dt ) = '00:00:00'
  AND
  dt >= date( now() )
);

dt >= now() ==> cheks if a datetime dt is greather than now().

time( dt ) = '00:00:00' ==> checks if a time part is 00:00:00

date( now() ) ==> truncates a time part from now(), leaves only a date part.
See a demo ==> http://www.sqlfiddle.com/#!2/8609c/6


Security schema merge with business

Question: Im doing authentication/authorization in a generic way but i have a problem, some behaviors of system are dependant of user role and one user can have more than one role.
Its not only about user can/cant do some action but action itself change for each user role, there is a lot of metadata related with each role and cant realize how keep cohesion.
If i merge security with business the coupling will be hight and all become a messy and if keep separate creating tables for each i will get some entities double and i get a messy too.
One small part of metadata is:
One employ if junior can build only basic part for one job for only one customer or get basic job abandoned started by another junior in same customer
If master can build new basic part and fix/manage building made by all juniors from one customer.
If manager can do everything for all customers and control master job.
For each job one junior need choose one master related and one master need choose one manager, when one junior get abandoned job he become owner but when master fix one job the creator junior keep ownership.
Answer: Create one table to each entity until reach a tree, each time one new role appear create a new table, then use this structure to control system. Keep users on user tables and employees on employees table, each user has one password and login and after must login with employees password and login too. Its solve your problem.
Comment: Thanks for effort but it will really messy all, im looking for something extensible and generic.

Security schema merge with business


logging into youtube from android

Question: I am trying to log into you tube using the following code
mService = new YouTubeService("Nothing", developer_key);

//Authentication
try
{
   mService.setUserCredentials(mUsername, mPassword);
}
catch (AuthenticationException e)
{
   Log.v(TAG, e.toString());
}

but I am getting:
ConnectYouTube: com.google.gdata.util.AuthenticationException: Error connecting with login URI
This code seems pretty basic to me and I can't figure out what mistake am I making here.
Comment: did you check internet permission in Android Manifest File..?
Answer: Make sure you have to following permissions:

android.permission.INTERNET
android.permission.GET_ACCOUNTS
android.permission.USE_CREDENTIALS
android.permission.MANAGE_ACCOUNTS

logging into youtube from android