Does anyone know what this pipe is in an HVAC system?

Question:
In a new rental (one story, approx 1400 sq ft), one of the bedrooms was not as cool as the other two. I noticed air flowing from the attic door in the ceiling, so went to investigate. The pipe (thin plastic, not PVC) circled had air flowing out of it. It has a flap on the end, so the more air that flows the flap would open. It was strong enough of a flow to blow the insulation around it away. The A/C was running at the time. I went and looked a couple hours later and the flap was closed, so air was not flowing thru it, but A/C was still running. This isn't a dampener, as it is just an open pipe and you do not set the flap to a certain position. This is just an open pipe that seems to have air flowing out of it at certain times. Does anyone know what this pipe is? I don't have any specs on the HVAC system, as I'm just renting.
Answer: This looks like a vent pipe that would be hooked up to a ventilation fan in the bathroom.  If the bathroom door was closed, you might get quite a bit of air loss out of that pipe, but when the door is open, there wouldn't be as much pressure to push the A/C out of that room.
Those ventilation fans are not supposed to vent into the attic because their supposed purpose is to remove humid air, but incorrect installations are pretty common.
Comment: Our builder did just that, and when the house A/C is running, the attic tubing behaves in a similar manner. Dampers are not going to be placed in an attic, as such devices are engineered to be easily accessible. If the pipe is left open and you run your bathroom (or other room fan) to cause moist air to enter your attic, it will become the dampener and reduce the effectiveness of your insulation. Note: damper restricts airflow, dampener causes things to become damp (wet).
Comment: This makes sense after hearing these two explanations. The room that wasn't cooling had the ceiling fan on full blast to try to keep the room cooler. This room has a 1/2 bath and this tube could have been in this bathroom coming from the vent. I will double check to see if this is the case. Thanks!
Comment: @kricca, At this point its just an educated guess.  You will have to verify.  Check it out with the fan on and off, etc.


glew build $PATH issue

Question: I am trying to build glew2.1.0 on Ubuntu 18.04 using these instructions.  My first error suggests PATH is setup incorrectly, regardless of what $SYSTEM is set as.
$ export GLEW_DEST=/usr
$ export SYSTEM=linux
$ make all
cc -DGLEW_NO_GLU -DGLEW_BUILD -O2 -Wall -W -Iinclude -fPIC -Wcast-qual -ansi -pedantic -fno-stack-protector  -o tmp/linux/default/shared/glew.o -c src/glew.c
In file included from src/glew.c:55:
include/GL/glxew.h:98:22: error: X11/Xlib.h: No such file or directory

As you can see, Xlib.h is in /usr/include/X11/.  And PATH includes both /usr and /usr/include.
$ echo $PATH
/usr:/usr/include
/usr$ find -name Xlib.h
./include/X11/Xlib.h

It's my understanding that gcc will attempt to locate files in the directories in PATH.  I briefly browsed Makefile and the corresponding Makefile.linux in the config directory to see if anything weird is going on here (like overwriting PATH).  I would prefer not to modify the source as that can be long, daunting rabbit hole in itself.
Also, I have verified all the header files have read permissions for all users.
Is there something I'm forgetting?
Comment: *"It's my understanding that gcc will attempt to locate files in the directories in PATH"* - no, see [What are the GCC default include directories?](https://stackoverflow.com/questions/4980819/what-are-the-gcc-default-include-directories)
Answer: Ask the packaging system!
walt@bat:~(0)$ dpkg -S /usr/include/X11/Xlib.h
libx11-dev:amd64: /usr/include/X11/Xlib.h
walt@bat:~(0)$

and install the libx11-dev package.

glew build $PATH issue


What anchor type should I use for mounting a pull-up bar installation into concrete?

Question: So yesterday I got a pull up bar at a really good price. Now the only thing I got to do is to mount it to a solid concrete wall. Since a nearby shop offers only a few different anchors, I bought two types that would fit best.
Sleeve anchor - 1/4'' (5/16'' drill) width x 4'' length,
Wedge anchor 5/16'' width x 2.5'' length
Pull up bar thickness is 4/5'' (2cm) and there are 8 holes

But here is the problem... I know that the sleeve anchors holding values are less in terms of shear and pullout than those of wedge type. On the other hand the wedge type anchors are really short and the pull up bar itself is thicker than the maximum value allowed for this length of the anchor.
The question is : Should I look for longer wedge type anchors? I live far from the city and would have to order some.
Or are the sleeve type anchors sufficient for the strain that's typical for a workout? Would also like to exercise using a TRX. (Not just me, flatmates too) so safety is a priority.
Comment: Can you confirm the wall is absolutely solid concrete?  Your pic is of tile.
Comment: How thick is the wall? Can you get to the other side? Could you put coach bolts through from the other side?
Comment: The floor at the picture is unrelated. Excuse me for the confusing pic. The destined wall is solid concrete for sure. The wall is at least 7''. But since it's the outer wall of my flat, I have no access to the other side.
Comment: Ok I'm pretty sure that the BIG concern is going to be shear strength, not length.
Comment: I suppose shear strength is related to width? I tried 3/8'' ones but they couldn't fit through the holes. That would solve the problem but unfortunately they are just a little bit too wide. You can see one at the picture, I can't pull it out. Since the wedge anchors are wider and generally have better shear strength, do you suggest buying longer wedge type than going with the current ones?
Comment: Is the actual grab bar missing from your picture? If what the picture shows is the wall bracket only, and the bar will sit out on the end of those square tube arms, there **will** be "pull out" forces; a lot, all along the top of the bracket. In fact, that is much more of a concern than shear strength. You should get longer wedge anchors so they are set to the proper depth or they could pull out.
Answer: Tapcon makes a heavy duty masonry screw designed for applications like ledger boards. They come in the longer lengths as well. You'll have to drill holes with a masonry bit first (you can buy bits for a standard drill if you don't have a hammer drill), but they bite really well.
I have a pull-up bar mounted on wood studs (had to cleat it with 2x4s since the holes didn't line up). Just to be sure the cleat can't move I have 2 4" lag bolts driven in the top with 3" screws driven in the bottom. I would want a minimum of 3" on this to make sure it doesn't move.
Answer: The wedge anchors you've shown are fairly standard. I'd go that route. Sleeve anchors of the type you have here are more for hollow wall applications, I think. They need room to expand sufficiently.
Anyway, if you install the wedge anchors to adequate depth they should work well. I'd want the gripping portion inserted at least an inch to reduce the chance of surface blowout. The deeper you go the wider the force is distributed in the concrete. You may need to find some longer ones.
I would install six anchors, forgoing one at each top corner. Drilling holes in concrete that close together often results in collapse. Six should be plenty (with four being at the top).


Recursively update values based on rows parent id SQL Server

Question: I have the following table structure
| id | parentID | count1 |

  2      -1         1
  3       2         1
  4       2         0
  5       3         1
  6       5         0

I increase count values from my source code, but i also need the increase in value to bubble up to each parent id row until the parent id is -1.
eg. If I were to increase count1 on row ID #6 by 1, row ID #5 would increase by 1, ID #3 would increase by 1, and ID #2 would increase by 1.
Rows also get deleted, and the opposite would need to happen, basically subtracting the row to be deleted' value from each parent.
Thanks in advance for your insight.
I'm using SQL Server 2008, and C# asp.net.
Comment: Are you using Linq-to-SQL?
Comment: I am not no, just using SQLCommands
Comment: I would suggest using a CTE to handle this.
Answer: You want to use a recursive CTE for this:
with cte as (
      select id, id as parentid, 1 as level
      from t
      union all
      select cte.id, t.parentid, cte.level + 1
      from t join
           cte
           on t.id = cte.parentid
      where cte.parentid <> -1
    ) --select parentid from cte where id = 6
update t
    set count1 = count1 + 1
    where id in (select parentid from cte where id = 6);

Here is the SQL Fiddle.
Answer: If you really want to just update counts, you could want to write stored procedure to do so:
create procedure usp_temp_update
(
  @id int,
  @value int = 1
)
as
begin
    with cte as (
        -- Take record
        select t.id, t.parentid from temp as t where t.id = @id
        union all
        -- And all parents recursively
        select t.id, t.parentid
        from cte as c
            inner join temp as t on t.id = c.parentid
    )
    update temp set
        cnt = cnt + @value
    where id in (select id from cte)
end

SQL FIDDLE EXAMPLE
So you could call it after you insert and delete rows. But if your count field are depends just on your table, I would suggest to make a triggers which will recalculate your values


Android Camera OnActivityResult resets photo path to null

Question: I'm having a problem while testing my app on a friends Galaxy S4 (GT i9505, Android 5.1). When giving a file URI to camera intent, OnActivityResult gives result Activity.RESULT_OK and and the path is null. It is working on most of other devices I tested (LG G3, nexus 5...). This is my code:
GetOutputMediaFile
public File getOutputMediaFile(int type){
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), MediaChooserConstants.folderName);
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MediaChooserConstants.MEDIA_TYPE_IMAGE){
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    } else if(type == MediaChooserConstants.MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }
    return mediaFile;
}

OnActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        String picturePath = null;
        if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            picturePath = fileUri.getPath(); // <--- fileURI is null
        }
    }
}

DispatchTakePhotoIntent
private void dispatchTakePictureIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File file = Utils.getInstance().getOutputMediaFile(MediaChooserConstants.MEDIA_TYPE_IMAGE);

    fileUri = Uri.fromFile(file); // create a file to save the image
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

    //fileUri is not null here while debugging (../DCIM/.../IMG_XXX.jpg)
    startActivityForResult(intent, MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

}

Comment: There is no requirement for `ACTION_IMAGE_CAPTURE` to hand back a `Uri`.
Answer: you need to save the file path to the bundle in onSaveInstanceState and then get it again in onRestoreInstanceState from the bundle
Answer: Save path of image like this :
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {

    if(mImageCaptureUri!=null)
        savedInstanceState.putString("camera_image", mImageCaptureUri.toString());

    super.onSaveInstanceState(savedInstanceState);
}

And Retrieve image path from this :
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {

    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey("camera_image")) {
            mImageCaptureUri = Uri.parse(savedInstanceState.getString("camera_image"));
        }
    }

    super.onRestoreInstanceState(savedInstanceState);
}

This problem happens, Only when user goes to camera intent and by the time he captures the image the activity on which camera intent was hosted gets destroyed or recreated when user comes back from the camera intent.
Comment: I'll try it out, but you made a bad copy/paste in `onRestoreInstanceState` by putting the `URI` to InstanceState again. And just a reminder to anyone else, since I'm doing this in a fragment (didn't mention it before), fragments have `onActivityCreated` instead of `onRestoreInstanceState`.
Comment: i have edited my answer according to Activity. And as you said you didn't mentioned "Fragments" earlier and also you are right fragments `onActivityCreated` instead of `onRestoreInstanceState`.
Comment: BTW, i can't test on my friends device at the moment, but on my device (which is working without resetting the uri to null), `savedInstanceState` is called, but `onActivityCreated` is not called. Is it a normal behaviour?
Comment: yeah sometimes its normal, as recreation of activity depends on the phone performance. If you test this thing with Nexus 6 it will work fine without recreation but if you test it on Moto G2. it will call `onRestoreInstanceState` or as in your case `onActivityCreated` because of memory and performance issues.


Removing input() text from console Python3

Question: I want to clear the line of text created after the input() function. I've tried \033[a, \r, end='' but either I'm doing it wrong or it doesn't work. Is there a better way:
Code is:
rawguess = input('Enter a 5 letter word: ')
print('words go here')

I've tried:
rawguess = input('\033[A' + 'Enter a 5 letter word: ' + '\033[A')
print('words go here')

rawguess = input('Enter a 5 letter word: ')
print('\rwords go here')

rawguess = input('Enter a 5 letter word: ')
print('\r', end='')
print('words go here')

And other variations of these three but nothing's worked so far.
Comment: Hello @spuddo, and welcome to StackOverflow! I think, because `input` prints a newline, you need to move the cursor up 1 line _after_ `input`, instead of in the `input` prompt text.
Comment: Does this (https://stackoverflow.com/questions/517970/how-to-clear-the-interpreter-console) or this (https://stackoverflow.com/questions/44565704/how-to-clear-only-last-one-line-in-python-output-console) answer your question? It clears everything in the console though.
Comment: What operating system are you using?
Comment: @JoboFernandez Tried a bunch of those, they either cleared the whole console or didn't do anything :/ Thanks for the reply though
Comment: @Bharel Windows 10
Comment: @David Thanks for the reply! Do you know what method would do that in Python 3.9?
Comment: I don't know how to move the cursor up in Windows. In most \*nix systems you can do `print('\x1b[1A')` but that's not supported by Windows.
Answer: I didn't know this before, but apparently Windows now supports Console Virtual Terminal Sequences, which include using ESC [ <n> A to move the cursor up (like on *nix). So we can call the Win32 API with ctypes.windll and enable Virtual Terminal Sequences, which will allow us to use '\x1b[1A'.
import sys

# Only do this on Windows, so that *nix users
# can also run the program without errors
if sys.platform.startswith('win'):
    import ctypes
    from ctypes.wintypes import *

    STD_OUTPUT_HANDLE = -11
    ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4

    kernel32 = ctypes.windll.kernel32

    h = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
    m = DWORD()
    kernel32.GetConsoleMode(h, ctypes.pointer(m))
    m.value |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
    kernel32.SetConsoleMode(h, m)

rawguess = input('Enter a 5 letter word: ')
print('\x1b[1A' + 'words go here')

Answer: Well I just found a piece of dark magic allowing you to enable terminal controls in Python:
import subprocess
subprocess.run("", shell=True)
input('Enter a 5 letter word: ')
print('\x1b[1A' + 'words go here       ')

Comment: Thanks for the trick! However, I would not rely on this feature because AFAIK it's not documented anywhere... The Win32 API _is_ documented and should work with all implementations of Python.


Aggregating data based on unique triads in R

Question: I was referred here Counting existing permutations in R
for previous related question but I can't apply it to my problem. Here is the data I have
One <- c(rep("X",6),rep("Y",3),rep("Z",2))
Two <- c(rep("A",4),rep("B",6),rep("C",1))
Three <- c(rep("J",5),rep("K",2),rep("L",4))
Number <- runif(11)

df <- data.frame(One,Two,Three,Number)

   One Two Three     Number
1    X   A     J 0.10511669
2    X   A     J 0.62467760
3    X   A     J 0.24232663
4    X   A     J 0.38358854
5    X   B     J 0.04658226
6    X   B     K 0.26789844
7    Y   B     K 0.07685341
8    Y   B     L 0.21372276
9    Y   B     L 0.13620971
10   Z   B     L 0.49073692
11   Z   C     L 0.52968279

I tried
aggregate(df, df[,c(1:3)],FUN = c(length,mean))

received
Error in match.fun(FUN) :
'c(length, mean)' is not a function, character or symbol

I am trying to aggregate by creating a new data frame that gives me the frequency of each unique triad (One, Two, Three) and another column that contains the median of Number for each unique triad. So for the (X,A,J) triad, I want Count = 4 and Median to be the median of the first four numbers under Number.
Answer: You could use dplyr
 library(dplyr)
 res <- df%>%
 group_by(One,Two,Three) %>%
 summarize(length=n(), Mean=mean(Number)) #change `mean` to `median` if you want `median`

 str(res)
#Classes 'grouped_df', 'tbl_df', 'tbl' and 'data.frame':    7 obs. of  5 variables:
 ----------
  str(as.data.frame(res))
#'data.frame':  7 obs. of  5 variables:
# $ One   : Factor w/ 3 levels "X","Y","Z": 1 1 1 2 2 3 3
# $ Two   : Factor w/ 3 levels "A","B","C": 1 2 2 2 2 2 3
# $ Three : Factor w/ 3 levels "J","K","L": 1 1 2 2 3 3 3
# $ length: int  4 1 1 1 2 1 1
# $ Mean  : num  0.689 0.989 0.524 0.181 0.345 ...

or
library(data.table)
setDT(df)[,list(length=.N, Mean=mean(Number)),by=list(One,Two,Three)]
#      One Two Three length      Mean
# 1:   X   A     J      4 0.3660189
# 2:   X   B     J      1 0.8389641
# 3:   X   B     K      1 0.2815004
# 4:   Y   B     K      1 0.4990414
# 5:   Y   B     L      2 0.3814621
# 6:   Z   B     L      1 0.1144003
# 7:   Z   C     L      1 0.9508751

Answer: OTT <- paste(One,Two,Three)
ott.mean <- tapply(Number,OTT,mean)
ott.count <- tapply(OTT,OTT,length)
cbind(ott.mean,ott.count)

Answer: Seems pretty straightforward:
aggregate( df$Number, df[ , c(1:3)],
                    FUN = function(x) { c( len=length(x), mn=mean(x) ) } )

@latemail. Not sure what you mean by a 'borked' data.frame. The fourth element is a matrix. Matrices are legitimate components of dataframes:
> d2[[4]]

     len        mn
[1,]   4 0.7531795
[2,]   1 0.8777003
[3,]   1 0.8003510
[4,]   1 0.6113566
[5,]   2 0.2470044
[6,]   1 0.3444656
[7,]   1 0.7517357

And the matrix can be accessed in the usual way:
> d2[ , 'x'][ , "mn"]
[1] 0.7531795 0.8777003 0.8003510 0.6113566 0.2470044 0.3444656 0.7517357

Comment: Beware that this gives a borked data.frame with a matrix inside it called `x` with columns named `len` and `mn` that need fixing with `do.call(data.frame,result)`


How do you unlock Poppi's Final Form?

Question: I'm in Chapter 9 and still don't have Poppi's Final Form? How do I get it?
Answer: To get Poppi's Final Form (qt pi), you'll have to travel to the Leftherian Archipelago (specifically Fonsett Village Arch) and walk to a Heart-to-Heart. You can find it by going down the stairs and to the right, across a bridge and onto the next landmass.
Afterwards, you can find the Heart-to-Heart by around the left side of that particular island. It's located here:

After viewing this, head back to Tora's House, and you'll get the "Powered up Poppi" quest, which requires you to get 10 Golden Cogs by salvaging in Temperantia.
Afterwards you'll need to get 5 Cubic Diamonds from Mor Ardain (gathered), 12 Ambler Stigmas from Land of Morytha (gathered), and a Genbu-Weave Cloth from Tantal (purchased).
You'll then need to talk with an npc in Argentum. This will require Forestry 5, Ancient Wisdom 3. You'll also fight a level 50 monster.
For the final stretch you need to either do a Merc Mission a few times or get a lot of materials.
Comment: I don't really remember doing any H2H aside of one about Poppi upgrade.
Comment: @lentinant well, as far as I can tell, it's required. So if you have this form of poppi, you've probably seen it.
Comment: Do you know what chapter is required to be on to do this?
Comment: @ellsedil I do not, I think I did it during chapter 10 or before the final boss

How do you unlock Poppi's Final Form?


Generic method to read from json resource and return object

Question: I have an extension method which loads a resource from an assembly as text, this contains json
I then get this and deserialize it into my required type
var json = ResourceAssembly.GetResourceAsText("MyResourceFileName");
var list = JsonConvert.DeserializeObject<List<MyObject>>(json);

Ideally I would like to do this in one single method GetFromResourceJson which takes the type that I want to serialize into and the filename, using generics
So the example above would simply be
var list = ResourceAssembly.GetFromResource<List<MyObject>>("MyResourceFilename");

How can I do this?
My current implementation for GetResourceAsText is below
 public static string GetResourceAsText(this Assembly assembly, string resourceToLoad)
 {
    var resourceName = GetFullResourceName(assembly, resourceToLoad);
    using var stream = assembly.GetManifestResourceStream(resourceName);
    var streamReader = new StreamReader(stream!);
    var result = streamReader.ReadToEnd();
    return result;
 }

Could someone help please?
Paul
Answer: Am I missing something here?
public static T GetResource<T>(this Assembly assembly, string resourceToLoad)
{
    var resourceName = GetFullResourceName(assembly, resourceToLoad);
    using var stream = assembly.GetManifestResourceStream(resourceName);
    using var streamReader = new StreamReader(stream!);
    return JsonConvert.DeserializeObject<T>(streamReader.ReadToEnd());
}

You might even want to make it more generic by injecting the deserializer as a Func<string, T>, like this:
public static T GetResource<T>(this Assembly assembly, string resourceToLoad, Func<string, T> deserializer)
{
    var resourceName = GetFullResourceName(assembly, resourceToLoad);
    using var stream = assembly.GetManifestResourceStream(resourceName);
    using var streamReader = new StreamReader(stream!);
    return deserializer(streamReader.ReadToEnd());
}

and call it like this:
var list = ResourceAssembly
    .GetResource<List<MyObject>>("MyResourceFilename", JsonConvert.DeserializeObject);

This way you can use it to also deserialize xml (or any other string format, for that matter)
Comment: at least I am not the only one who though "What? Just do it."
Comment: @Paul - So basically your question was how to declare a generic method?


For linearly independent vectors {u, v}, {$ au+bv, cu+dv$} is linearly independent iff $\begin{pmatrix}a & b\\\ c & d\end{pmatrix}$ is invertible.

Question: Given $\{u, v\}$ is linearly independent vectors, I want to prove that $\{au+bv, cu+dv\}$ is linearly independent if and only if  $M = \begin{pmatrix}a & b\\\ c & d\end{pmatrix}$ is invertible.
I started from assuming the two linear combinations are linearly independent, however I do not know how to show that $\det(M) > 0$. Should I use other theorem to show it is invertible?
Comment: Why do you want $\det(M)>0$? $M$ is invertible iff $\det(M)\neq 0$.
Answer: Consider the equation $t(au+bv)+s(cu+dv)=0$. By linear independence of $u$ and $v$ this is equivalent to the system of equations
$ta+sc=0$
$tb+sd=0$
This system has  a non-trivial solution iff the coefficient matrix is non -singular which means $\det(A) = 0$.
Hence $det(A) = 0$ iff there exist $t$ and $s$ not both $0$ satisfying these equations iff $au+bv$  and  $cu+dv$ are linearly dependent.


Why do some factions refuse to trade?

Question: Some factions really like me and a trade route is possible but they still and repeatedly refuse to trade with me – and other factions are neutral towards me but happily agree to a trade agreement. Can anybody explain the game mechanics the AI uses to determine if they accept or decline an offered trade agreement?
Comment: Possibly a bug. If it were alliance, it'd make sense if they didn't want to ally with you for strategic reasons (you're too far away and they're too close to a powerful enemy of yours). Trading agreements shouldn't be a problem though. In Shogun 2, everybody accepted my trade requests, even if they were unfriendly towards me...
Comment: @Nolonar Yeah, but in Rome 2 the factions are kinda a dickish, they just plain out refuse because there is nothing you can give them that they want. Just take more resource spots and soon the trades will be flowing in.
Comment: Most factions require money, a lot of money normally to trade even on normal mode, if you are not offering money this could be why
Comment: According to the patch notes for [Patch 4](http://wiki.totalwar.com/w/Total_War_ROME_II:_Patch_4) and my personal experience, the AI seems to respond better to trade agreement requests.
Answer: Possibly the most important factor that the AI uses is an unfortunate one: game difficulty. If the difficulty is above normal, the AI will only trade with you on the most favorable terms, and will deny trade relations for no particular reason. If you are playing on a harder difficulty, this might be your problem.
Comment: I'm playing at normal difficulty – but even for hard difficulty I'd expect the AI to refuse according to their relation towards me

Why do some factions refuse to trade?


Working with a ListBox from an SQL database

Question: I'm new to CS.  I have a ListBox control that I populate from an SQL table called Category.  I have a class called Category to match the fields from the DB.  I want all my fields available to edit and save.  The ListBox has a single field, CategoryDesc.  When I select an item in the ListBox I want two textboxes and a check box to update with the CategoryID (string), CategoryDesc (string), and IsActive (bool).  I have it working but it seems cumbersome and like I'm taking a lot of steps.  I want to learn efficient coding so I'm submitting the following for suggestions on how to clean it up and make it more efficient.  Any positive comments will be greatly appreciated.
id ListControl()
    {
        this.LstCategory.SelectedIndexChanged -= new System.EventHandler(this.LstCategory_SelectedIndexChanged);
        DataTable categoryDt = new DataTable();
        categoryDt = GetDataTable("GetListCategory");
        for (int i = 0; i < categoryDt.Rows.Count; i++)
        {
            category.Add(new Category()
            {
                CategoryID = (int)(categoryDt.Rows[i]["CategoryId"]),
                CategoryDesc = (string)(categoryDt.Rows[i]["CategoryDesc"]),
                ShortCode = (string)(categoryDt.Rows[i]["ShortCode"]),
                IsActive = (bool)(categoryDt.Rows[i]["IsActive"]),
                CanDelete = (bool)(categoryDt.Rows[i]["CanDelete"])
            });
            LstCategory.Items.Add((string)(categoryDt.Rows[i]["CategoryDesc"]));
        }

        this.LstCategory.SelectedIndexChanged += new System.EventHandler(this.LstCategory_SelectedIndexChanged);
    }

    private void LstCategory_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (LstCategory.SelectedIndex >= 0)
        {
            string desc = LstCategory.SelectedItem.ToString();
            foreach (var c in category)
            {
                if (c.CategoryDesc == desc)
                {
                    TxtDescription.Text = c.CategoryDesc;
                    TxtShortCode.Text = c.ShortCode;
                    ChkIsActive.Checked = c.IsActive;
                }
            }
        }
        else
        {
            TxtDescription.Text = string.Empty;
            TxtShortCode.Text = string.Empty;
            ChkIsActive.Checked = false;
        }
    }

Thanks.
Answer: Learn to use Linq
This
    categoryDt = GetDataTable("GetListCategory");
    for (int i = 0; i < categoryDt.Rows.Count; i++)
    {
        category.Add(new Category()
        {
            CategoryID = (int)(categoryDt.Rows[i]["CategoryId"]),
            CategoryDesc = (string)(categoryDt.Rows[i]["CategoryDesc"]),
            ShortCode = (string)(categoryDt.Rows[i]["ShortCode"]),
            IsActive = (bool)(categoryDt.Rows[i]["IsActive"]),
            CanDelete = (bool)(categoryDt.Rows[i]["CanDelete"])
        });
        LstCategory.Items.Add((string)(categoryDt.Rows[i]["CategoryDesc"]));
    }

can be replaced by
   category = categoryDt.Select(cd => new Category{
            CategoryID = (int)(cd["CategoryId"]),
            CategoryDesc = (string)(cd[i]["CategoryDesc"]),
            ShortCode = (string)(cd["ShortCode"]),
            IsActive = (bool)(cd[i]["IsActive"]),
            CanDelete = (bool)(cd[i]["CanDelete"])}).ToList();
   LstCategory.Items.AddRange(category.Select(c=>c.Desc));

and
       string desc = LstCategory.SelectedItem.ToString();
        foreach (var c in category)
        {
            if (c.CategoryDesc == desc)
            {
                TxtDescription.Text = c.CategoryDesc;
                TxtShortCode.Text = c.ShortCode;
                ChkIsActive.Checked = c.IsActive;
            }
        }

can be replaced by
        var c = category.FirstOrDefault(c=>c ==desc);
        TxtDescription.Text = c.CategoryDesc;
        TxtShortCode.Text = c.ShortCode;
        ChkIsActive.Checked = c.IsActive;

There might be a few typos here and there becuase I dont have yur data structures to try it out on.
But LINQ is incredibly useful for performing operations on collections.

'select' is used to transform 'project' (its not a filter)
'where' is used to filter
'FindFirstOrDefault' will retunr the first match (or null)
'Count' counts
'ToList' converts to list

The nice thing is you can chain then together
mylist.Where(...).Select(..) etc

Comment: A better option would be to add the `Category` objects directly and use `DisplayMember` to choose what to display
Comment: Thanks.  I write a lot of SQL code so for the most part I understand LINQ, just not when to use it.  Thanks again for the insight.  You have been very helpful.
Comment: Oops! Now I get the nebulous error message. "CS1660: cannot convert lambda expression to type 'string' because it is not a delegate type" on the category = categorryDt... expression.
Comment: I have using System.Data;   using System.Linq;   I tried to add using System.Data.Entity; but that created an error.


ASP.NET MVC controller method input parameter - how does it get populated?

Question: I am trying to understand an ASP.NET MVC JQGrid sample. The grid makes an AJAX request to get its data:
http://[thesiteurl]/[ControllerName]/GetGridData?_search=false&nd=14&rows=10&page=1&sidx=Id&sord=asc

The controller method is:
public ActionResult GetGridData(GridSettings gridSettings)

How do the GET params get transformed into a GridSettings object, and how can it be changed with a different type?
Answer: The ASP.NET MVC framework has a built-in model binder which performs this task.  (You can write custom model binders as well.)  Essentially what it does at its simplest is examine the key/value pairs of incoming data and match it with the method parameters of the routed action method.
Examining the request, it looks like you have the following:
_search: false
nd: 14
rows: 10
page: 1
sidx: Id
sord: asc

So, for example, if the Gridsettings object is defined like this:
class GridSettings
{
    public string _search { get; set; }
    public int nd { get; set; }
    public int rows { get; set; }
    public int page { get; set; }
    public string sidx { get; set; }
    public string sord { get; set; }
}

Then the model binder would be able to map the incoming parameters to the model's properties accordingly.
If you were to define another type with the same properties then you could use that type in place of GridSettings.  With that type you could add more properties to match any client-supplied values you want to add, you could add more logic internal to the model, etc.


MySQL if row is duplicated prefer which matches field value

Question: I have the following select query. I want to avoid getting the duplicated "EN" row when "ES" row is present. Like prefer ES over EN.
SELECT s.soft_id,s.groupby,s.packageid,s.name,s.area,l.min,GROUP_CONCAT(DISTINCT JSON_ARRAY(s.version,s.detailid,s.filesize,s.updatetime)) versions
FROM software s
INNER JOIN langs l ON s.lang_id=l.lang_id
INNER JOIN devices_type t ON (s.familylock_id=t.familylock_id OR (s.familylock_id=0 AND s.devicelock_id=t.device_type_id))
INNER JOIN devices d ON t.device_type_id=d.device_type_id
INNER JOIN users u ON d.user_id=u.user_id
WHERE s.groupby IN(1,2,3)
AND u.token="abc"
AND d.serialno="123456789"
AND l.min IN("ES","EN")
GROUP BY s.soft_id,s.groupby,s.packageid,s.name,s.area,l.min ORDER BY s.name ASC

This is the example result:
image
You can test your query here: http://188.8.131.52/login.php?2=epiz_26706010wejghelqwdtg3e54gVGtSRk1VMUVRVE5QVkdzeFRWaDNhRWxUUldoSldIZzRaa2g0T0daSWVEaG1TSGhvVjIxc1JGb3lkRk5rV0U1cFZsRTlQUT09wejghelqwdtg3e54gsql102.epizy.comwejghelqwdtg3e54gepiz_26706010_test&db=epiz_26706010_test
Answer: I'd do it in two steps, count how many duplicate rows you have. And by duplicate, I mean identical on one column but differ in ES vs EN. have the table sorted
select the last among the duplicates
Get top first record from duplicate records having no unique identity
Comment: is there any chance you cant try to apply your idea to my query? because i dont know how to do it
Answer: Outer join the table twice, looking for a single specific value with each join, and then coalesce the fields in the order you prefer:
SELECT s.soft_id, coalesce(les.min, len.min) As min, ...
FROM software s
LEFT JOIN langs les ON s.lang_id=les.lang_id AND les.min = 'ES'
LEFT JOIN langs len ON s.lang_id=len.lang_id AND len.min = 'EN'
...
WHERE s.groupby IN(1,2,3)
   AND coalesce(les.lang_id, len.lang_id) IS NOT NULL
...

Windowing functions can do it more efficiently, but they're still not support on lots of MySql servers in the wild. If you're using 8.0 or later, you should look into that option.
Comment: i have tried but i dont know how to apply your solution to my query :( also i can run mysql 8
Answer: You can use window functions as:
with q as (
      <your query here>
     )
select q.*
from (select q.*,
             row_number() over (partition by soft_id order by field(l.min, 'ES', 'EN')) as seqnum
      from q
     ) q
where seqnum = 1;


Exception in thread "main" java.lang.ClassCastException: class com.sun.proxy.$Proxy0 cannot be cast to class crewcut

Question: As per stated in the title,
as I were to continue to next supposed section in the coding. The RMI system did not the display the action based on my input. I want it to display the next part of the coding when the system recognized the input as Customer / Barbershop.
How do i make it show the next case statement?
Client
import java.rmi.*;
import java.net.*;
import java.io.*;
import java.util.*;

public class crewcut_client {

public static void main(String[] args) {

    try{
        Scanner sc = new Scanner(System.in);

        System.out.println("Welcome to CrewCut Service");
        System.out.println("Are you a 'CUSTOMER' | 'BARBER' ? Type in below");
        String resp = sc.next();

        crewcut cc = (crewcut) Naming.lookup("rmi://localhost/CrewCut");
        switch (resp){
            case "CUSTOMER":
            case "customer":
            case "Customer":
            {
                System.out.println("Hello Customer !");
                System.out.println("Welcome to our system");
                System.out.println("Please enter your name :");
                String name = sc.nextLine();
                System.out.println("Please enter your contact num :");
                String num = sc.next();
                System.out.println("Here are our services :");
                System.out.println("Hair Cut RM15");
                System.out.println("Hair Wash RM20");
                System.out.println("Hair Dye RM25");
                System.out.println("Press '1' for Hair Cut");
                System.out.println("Press '2' for Hair Wash");
                System.out.println("Press '3' for Hair Dye");
                String service = sc.next();
                System.out.println("Your day of booking ? Monday | Tuesday | Wednesday | Thursday | Friday |Saturday | Sunday");
                String day = sc.next();
                //impl code
                System.out.println(cc.check_client(name,num,service,day));
            break;
            }
            case "BARBER":
            case "barber":
            case "Barber":
            {
                System.out.println("Hello Barber !");
                System.out.println("Are you in for work today? Enter 'Y' for YES or 'N' for NO" );
                String attend = sc.nextLine();
                if (attend.equals("Y")){
                    System.out.println("Welcome to work ! ");
                    System.out.println("The shop shall be closed in 9pm");
                }else if (attend.equals("N")){
                    System.out.println("Hope to see you soon !");
                }else{
                    System.out.println("Invalid input");
                }
            }
        }
    }catch (RemoteException re){
        re.printStackTrace();
    }catch (NotBoundException nbe){
        nbe.printStackTrace();
    }catch(MalformedURLException mfe){
        mfe.printStackTrace();
    }
}}

Server
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;

public class crewcut_server {
public static void main(String[] args) {
    try{
        crewcutimpl ccl = new crewcutimpl();
        Naming.rebind("rmi://localhost/CrewCut",ccl);
    }catch (RemoteException re){
        re.printStackTrace();
    }catch (MalformedURLException mfe){
        mfe.printStackTrace();
    }
}
}

Implementation
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;

public class crewcutimpl extends UnicastRemoteObject implements crewcut{
public  crewcutimpl() throws RemoteException{
    super();
}
public String check_client (String name, String num, String service, String day){
    String display;
    int price = 0;
    switch (service){
        case "1":
            price = 15;
            break;
        case "2" :
            price = 20;
            break;
        case "3":
            price = 25;
            break;
    }display =" Your booking has been entered into the system Mr/Mrs " + name + "\n We shall contact
     you through this num : " + num + "\n Service wanted : "+ service + "Total price :" + price +"Day
     of appointment :" + day;
    return display;

    }
    }

Interface
import java.rmi.RemoteException;

 public interface crewcut {

public String check_client(String name, String num, String service, String day) throws
RemoteException;
}

Comment: Why don't you follow the Java naming conventions when defining classes?
Comment: can you further explain this?
Comment: Class and interface names should start with a capital letter, underscores are rarely used.
Comment: Ohh okay, thank you for pointing that out. Here is a new problem :
Comment: Exception in thread "main" java.lang.ClassCastException: class com.sun.proxy.$Proxy0 cannot be cast to class Crewcut (com.sun.proxy.$Proxy0 and Crewcut are in unnamed module of loader
'app')

it said the problem lays in the Naming.lookup in the client class
Comment: `public interface crewcut` must extend `Remote`. I'm surprised you didn't get an error when exporting, or that if you did you didn't mention it here.
Answer: Interface must have "extends Remote" that should solve your 2nd problem
"Exception in thread "main" java.lang.ClassCastException: class com.sun.proxy.$Proxy0 cannot be cast to class..."


Can I assume that a biologist will know what "lhs" and "rhs" mean? Or what are some other ways of indicating the left/right hand sides of an equation?

Question: I am writing a scientific article with a few mathematical equations. Can I assume that my audience will know what lhs and rhs mean?
Comment: This question is not about mathematics at all.
Comment: This is relevant. It is about how mathematics is discussed. I agree with PEV's comment it should be LHS and RHS. But the first time you use it, just mention left hand side(LHS).
Comment: Well David, the fact that they suggested you to ask it in here does not imply that it is appropriate for this site.
Comment: Agree with Adrián. Voted to close as off-topic.
Comment: The answer to the question as stated depends on your audience. I agree that this is not a mathematical question.
Comment: @Adrian two commenters at english.stackexchange.com suggested that I ask the question here within a few minutes of asking... although I have usually had good experience asking technical questions on that site
Comment: @adrian, fair enough. I just wanted to point out that I had already tried what I also thought was a more appropriate site.
Answer: If you even have to think if your audience knows what a particular abbreviation means, then you must explain it.
In any case, writing LHS/RHS in anything but very informal contexts seems simply unacceptable to me.
Answer: I like to define acronyms like:
"The left hand side (LHS) of Equation 1..."
And then use LHS throughout the rest of the paper if it is used frequently. If you only use "left hand side" a few times, it's best to just spell it out.
Answer: I think abbreviations like that rarely pay.
Comment: Ironic answer from someone with your name!
Comment: Agreed. I would never use those abbreviations without explanation even when writing for mathematicians!
Answer: I think it should be pretty obvious. Or you can simply say that LHS means "left hand side" and RHS means "right hand side." But many biologists have probably studied some probability or statistics. So they might have seen this notation before.
Comment: good point; is more proper to use capitalization?
Comment: @David: I think it is proper to use capitalization.


Convention regarding zero vector

Question: My Calculus text says that the zero vector is considered parallel to all vectors in the same space, because it's a scalar multiple of any other vector, and scalar multiples are parallel. I can see that certain other results benefit from this convention, such as saying that two vectors are parallel if and only if their cross-product is $0$. On the other hand, we sacrifice other results, such as "vectors parallel to the same vector are parallel to each other."
My question: is the convention taking the zero vector as parallel to all other vectors a universal one? It seems arbitrary to me, and that if we take it as parallel to none, we preserve a more intuitive idea of "parallel", and we can always salvage facts relying on the other convention by throwing in the word "non-zero" as necessary.
If everyone agrees that the zero vector is parallel to all the others, what is it that makes this so useful?
Thanks in advance.
Answer: In terms of parallel vectors in calculus, most people would assume that zero vector is parallel to everything.  You are really looking at the span of a vector and identifying all those vectors, and zero is always in the span:  Two vectors are parallel if their spans are equal.  In three dimensions this also has a short and beautiful definition: $u$ and $v$ are parallel if and only if $u \times v = 0$.  If you pick a convention, you usually pick the one that gives the nicest definition.
One place the word parallel comes up in for geometry is in "parallel transport" where you move vectors to their parallel counterparts at a different point, and you really want to be able to move the zero vector too.
Of course it depends on the context, in the traditional greek Euclidean geometry context, you only talk about parallel lines, and a zero vector does not define a line.  But the ancient greeks also did not talk about vectors at all.
Comment: I just noticed: "two vectors are parallel if their spans are equal" doesn't actually indicate that the zero vector should be parallel to any non-zero vector, because its span is not the same as the span of any non-zero vector. This is still a good answer, but I thought that was worth mentioning. The zero vector is *in* the span of any non-zero vector, but not vice-versa.

Convention regarding zero vector


android - create a virtual camera or overwrite the real cam stream? (/dev/msm_camera/frame0, v4l2loopback)?

Question: I'm currently working on a project about latencies in image and video transmission.
Do I have the ability (assuming root) to create a virtual camera or overwrite the real cam framebuffer with the same picture or raw video stream?
I want to use this cam in skype for example.
I through about something like v4l2loopback to manipulate the picture...
i tested things like that, but this dosn´t work...
<code>ln -s /sdcard/image.jpg /dev/msm_camera/msm_camera0
dd if=/dev/graphics/fb0 of=/dev/msm_camera/frame0
cat /dev/graphics/fb0 > /dev/msm_camera/frame0
</code>
Is this possible?
I´am using a HTC Desire HD with ICS
thanks in advance
Answer: I'll start by saying i can only give you a leading start.
You can use introspy to investigate how the operation system is using the camera.
Than you can exploit it, and make a hook, possibly replacing the original stream.
Link to introspy:
https://github.com/iSECPartners/Introspy-Android/blob/master/README.md


Average matrix values after interpolation

Question: I have a matrix that is 1x24. Within each cell is another matrix that is a single column. However, the column length changes from one matrix to another. Is there a way to average the first row from each matrix, and output into a new matrix where the first cell is the average of all the matrix first cells? Then second and third all the way to the end?
Here is my script so far. You can see that I create a matrix. Now I would like to average them (after I interpolate them).
close all
clear
clc

k = cell(1,24);
for k=1:24
   data{k} = xlsread('C:\data.xlsx',['PKA', num2str(k)]);
end

for i=1:24
xfinal{i}=data{1,i}(end,1);
xi{i}=0:0.001:xfinal{i};
xi{i}=transpose(xi{i});

x{i}=data{1,i}(:,1);
y{i}=data{1,i}(:,4);

yi{i} = interp1(x{i},y{i},xi{i});

xf{i}=xi{i};
xf{i}=(1:10001);

yi{i} = interp1(x{i},y{i},xi{i});

yf{i}=yi{i};
yf{i}=(1:10001);
end

If I click on the yi variable, I see a single row. In each cell, there is another matrix. The first matrix is 10014x1, the second is 10084x1. I only care about the first 10,001 elements, despite the fact that the matrices are different lengths. I just want the first 10,000 elements averaged from each matrix. So row 1 is averaged, row 2, from each matrix, etc. , all in a single matrix that is 10001x1
EDIT: Code working with rayreng
close all
clear
clc

k = cell(1,24);
for k=1:24
   data{k} = xlsread('C:data.xlsx',['PKA', num2str(k)]);
end

for i=1:24
xfinal{i}=data{1,i}(end,1);
xi{i}=0:0.001:xfinal{i};
xi{i}=transpose(xi{i});

x{i}=data{1,i}(:,1);
y{i}=data{1,i}(:,4);

yi{i} = interp1(x{i},y{i},xi{i});

end

Y = zeros(10001, numel(data));
for ii = 1 : numel(data)
    Y(:, ii) = yi{ii}(1 : 10001);
end

Y2 = mean(Y, 2);

Y3 = std(Y2, [], 2); errorbar(0 : 0.1 : 10, Y2(1: 100 : 10001), Y3(1 : 100 : 10001));
grid on

Comment: Suppose you have a cell array that's three elements, and the elements are defined as column vectors with size `5 x 1`, `3 x 1` and `2 x 1`.  What do you do when you are in the third row, when you've exhausted the elements from the third matrix of `2 x 1`?  I can't seem to figure that out with your code as I don't know what the current structure is with your variables.
Comment: @rayryeng If I click on the yi variable, I see a single row. In each cell, there is another matrix. The first matrix is 10014x1, the second is 10084x1. I only care about the first 10,001 elements, despite the fact that the matrices are different lengths. I just want the first 10,000 elements averaged from each matrix. So row 1 is averaged, row 2, from each matrix, etc. , all in a single matrix that is 10001x1
Comment: What if you have a matrix that is less than 10000 elements?  Will that ever happen?  Your problem statement is still very ill-posed.  In addition, your desired output and the code you have posted do not correspond to each other.
Comment: @rayryeng None are less than 10000 elements. The code I posted has not yet attempted to calculate it. It just shows what I did to get to this current point to help the reader understand how my problem is setup. I have tried to do it myself but I can't seem to get it work.
Comment: Ah I see. OK.  Let me see what I can cook up.
Comment: @rayreng Probably a new variable could be created instead of yi so that they are all the same length. Just append every matrix in yi to stop at 10,001 elements.
Comment: @rayryeng I edited my code so they are all the same length. Now the values are under yf
Comment: You don't need to do that.  I'll handle it for the original problem.  BTW, `yf` isn't necessary.
Answer: Unfortunately because you have a cell array of data where each cell has different row lengths, you have no choice but to loop through each cell.  What's even more intricate is that you want to find the average of each position i over all cell arrays to be stored in an output array such that Y(i) contains the desired average.  Naively, you'd have to use a double for loop for that, but what I can recommend since you are guaranteed to have 10001 elements and that's relatively cheap in memory is to simply use a single for loop and create a new matrix that is 10001 elements long with the total number of columns being the total number of your cells.  You would then extract out the first 10001 elements of each column in your cell array and place it in its corresponding column in the output matrix.  Once you do that, just average along each row individually:
Y = zeros(10001, numel(data));
for ii = 1 : numel(data)
    Y(:, ii) = yi{ii}(1 : 10001);
end

Ymean = mean(Y, 2);

Y will contain a matrix of size 10001 x 24, and we thus call mean along each row individually and transform Y to a 10001 x 1 column vector storing the mean of each position i for all cell arrays stored in Ymean.
Finally, you desire to draw an error bar graph where you wish to compute the standard deviation for each column of the matrix Y as well.  You will thus need to find the standard deviation of each row, then use it with the [errorbar](http://www.mathworks.com/help/matlab/ref/errorbar.html) function.  Specifically, given your x coordinates which you defined to be from 0 to 10 in steps of 0.001, the y coordinates would be the mean of each row of Y, the error bars would be the standard deviation of each row of Y, and so the error bars drawn would be twice the standard deviation centered at each mean point.
Therefore:
Y = zeros(10001, numel(data));
for ii = 1 : numel(data)
    Y(:, ii) = yi{ii}(1 : 10001);
end

Ymean = mean(Y, 2);
Ystd = std(Y, [], 2);

errorbar(0 : 0.001 : 10, Ymean, Ystd);

This figure will be rather clustered as you have 10000 points to deal with.  Instead, try subsampling and perhaps show 101 points instead to get a feel of what you're visualizing:
errorbar(0 : 0.1 : 10, Ymean(1 : 100 : 10001), Ystd(1 : 100 : 10001));

In general, you can set a variable for the desired spacing in between each point, then subsample the x and y axes, as well as the lengths of each of the error bars to complete everything.
sampling_interval = 200;
pts = 1 : sampling_interval : 10001;
x = 0 : 0.001 : 10;
x = x(pts);
errorbar(x, Ymean(pts), Ystd(pts));

The first line of code defines the sampling interval, and we then define a vector from 1 up to 10001 increasing linearly by sampling_interval amount.  We then create the equivalent values for the x axis, and we finally plot everything.
Comment: Right.  Well you can do that in two lines of code.  The `errorbar` function is your friend: `Y3 = std(Y, [], 2); errorbar((0 : 0.001 : 9.999).', Y2, Y3);`.  First line finds the standard deviation of each row in the stacked `Y` matrix we created, then we plot an error bar graph whose error lines are the size of the twice the standard deviation: `mean - std` to `mean + std`.
 More documentation about it here: http://www.mathworks.com/help/matlab/ref/errorbar.html
Comment: @Jack I've just edited my post to put in exactly what you want.  This will minimize the conversation we have here.... and I have to get back to work.
Comment: By default `errorbar` always provides vertical error bars... meaning that at each point, you draw a vertical error line.  There are small horizontal markers at the end of the line that are simply indicators that help you determine which values on the `y` axis they roughly stop at.
Comment: You said that Y will contain a matrix of size 10,000x24 but I only see a single column. I understand you overwrote it with Y = mean(Y,2), but is there a way to see the matrix that was created?
Comment: Just change it to a different variable: `Y2 = mean(Y, 2);`.  `Y` will contain the original matrix.  I overwrote it because I didn't think you actually needed to see the matrix.  It was a means to an end.
Comment: I did that.  It still just shows that Y is 10,000x1
Comment: @Jack You need to run the code again from the beginning of the section.  You are just running the last command, and `Y` was already overwritten at that point.  Just run it from the `Y = zeros(...)` part, and make sure you change `Y = mean(Y, 2);` to `Y2 = mean(Y, 2);`.  Once you do this, `Y2` will contain your desired single column and `Y` will contain the first 10000 elements of each cell array - one per column.
Comment: Actually, it appears that Y=mean(Y,2) just gives me the exact first matrix values, not the mean. I did rerun it. The variable Y that is created is just the first matrix in yi
Comment: @Jack That's a problem with your inputs - nothing to do with the code I wrote.  You may want to recheck your interpolation code before you run the code I provided again.
Comment: All of my yi matrices are different. I am telling you that Y is just the first matrix. I don't think it has anything to do with interpolation. I have 24 unique matrices and the matrix that is created in your for loop is just the first matrix.
Comment: That is not what I mean. When I just get rid of the Y=mean command, I should have a matrix that is 10,000x24, but I dont. I just have a matrix that is 10,000x1.
Comment: Ah, that's because you overwrote `k` as a `for` loop index.  I've changed the code.  Try it again.  It tripped me out because I saw at the very beginning that you defined `k` as a cell array, but then you stored the data in `data` instead.  Serves me right that I didn't read the entire code... but again, that isn't my job.
Comment: Now I get a matrix that is 10,000x24 but only the first column has nonzero numbers. The values in columns 2-24 are all 0, despite the fact that each matrix in yi is nonzero
Comment: @Jack sorry. Forgot to change the `for` loop. Try it again.
Comment: @Jack You're welcome!  Glad we finally got it to work.
Comment: I hate to ask for more, maybe I should create a new question? Is there a quick way to plot it with the stdev of all the values? Should that be a new question? Thanks again for your help!
Comment: Are you talking about a plot where you're plotting the bars of standard deviation combined with the mean... something like this? http://support.sas.com/kb/42/addl/fusion_42515_1_g42515.gif.  For that, you'd need to know the `x` axis values.  The `y` axis values would be the mean, and the error bars would simply be the standard deviation of each column in `Y`,  but what's important is the `x` axis.  Would this just be `1 : 10000`?
Comment: Right. I have my y values. My x values are just 10,000 elements from 0 to 10.
Comment: Is this assuming that we are using Y instead of Y2? Also the error bars are horizontal but they should be vertical since the y variable is what is dfiferent between each matrix
Comment: The error bars are by default vertical.  Not sure why you're seeing them horizontal.  Also, we should be using `Y2`, sorry not `Y`.
Comment: Yeah that is strange. Also, I want it to be to 10,000 not 9.999. But when I change the other variables to 10,001 and that to 10,000, i get that they are not the same length
Comment: @Jack Change the `for` loop so that it captures 10001 elements.  I'll change this in my code.
Comment: Also... you are plotting 10001 error lines, so it's definitely going to look messy.  That may be way you're confused.  Try plotting at an interval instead of all 10000... so perhaps try plotting only 101 of them: `errorbar(0 : 0.1 : 10, Y2(1: 100 : 10001), Y3(1 : 100 : 10001));`  This assumes you have 10001 elements now, instead of 10000.
Comment: Yeah, I thought about that..I can change the number of elements once I get a feel for the code. Currently though, I keep getting errors. The error I get is this: Error using errorbar>checkSingleInput (line 264)
XData must be the same size as YData.

Error in errorbar (line 94)
x = checkSingleInput(x, sz, 'XData');

Error in interpolate (line 35)
Y3 = std(Y, [], 2); errorbar((0 : 0.001 : 10).', Y, Y3);
Comment: Replace `Y` with `Y2`.
Comment: But dont I need the stdev from Y? Y2 just has the already averaged values
Comment: That's stored in `Y3`.  The `x` coordinates are from 0 to 10, the `y` coordinates are the **averaged** values... that's in `Y2`.... and the length of the error bars are the standard deviations... that's in `Y3`.
Comment: How is that stored in Y3? Y3 only makes reference to Y2, never Y?
Comment: I thought you changed your code so that `Y2` stores the actual average.... that's where we keep messing up.  If you want the standard deviation, you'll need to remember the 24 column matrix you made.  I'll have to edit my post again.
Comment: Thanks for the help, seems to be working. Error bars are correct now. must have been an error in my code.
Comment: YOu had a good idea every 100 points. If I want to change it to every 200 points, do I just change the two 100 to 200? And then 0.1 to 0.2. seems like it works. thanks!
Comment: Yes, you'd also have to change the resolution of the `x` axis to go every 0.05 instead of 0.1.  I'll make my post more robust to this.
Comment: 0.2, not 0.05 i beleive
Comment: @Jack Ah I thought you wanted 200 points, not sample every 200 points.  Yes you're right.  I've added some more code in to make this adaptable to whatever spacing you want.


Extract a Folder from Duplicity Archive

Question: Using the duplicity command, I need to specify the following:

a specific folder to restore
indicate time and date from which to restore
indicate the destination to restore to

How can I specify these 3 things using the duplicity command?
Answer: That's correct, even if it tells "--file-to-restore", you can enter any file or folder path (without the "/" sign at the beginning of it, for example "temp/logs") at "foldername" and any "destination folder" (with the "/"sign at the beginning of it, for example "/temp/logs") to the command.
Sample: I want to restore my /temp/logs which is backed-up 3 days ago into the same folder:
duplicity -t 3D --file-to-restore temp/logs file:///backup/location /temp/logs

Sample2: I want to restore my file /temp/logs/app-error.log which is backed-up 3 days ago into the same folder:
duplicity -t 3D --file-to-restore temp/logs/app-error.log file:///backup/location /temp/logs/app-error.log

Note that you have to give a full destination path for the file.
Sample3: My backup stays at an ftp server=my.ftp.server with user=root at the location=my_backup, the same scenario with #1:
duplicity -t 3D --file-to-restore temp/logs sftp://email@example.com/my_backup /temp/logs

Comment: Actually, when using the parameter `--file-to-restore` in duplicity 0.8.12 and specifying a file or directory to restore, I had to use the *absolute* path instead of a relative one. This is opposed to that the documentation states. Otherwise I always got an error message that the indicated file/path cannot be found in the backup.
Answer: duplicity -t 3D --file-to-restore <foldername> file:///backup/location <destination folder>

Duplicity enters restore mode because the URL comes before the local directory.
-t 3D 3 days ago
If you want to check more information, here are useful links depending on the version:

http://duplicity.nongnu.org/vers7/duplicity.1.html
http://duplicity.nongnu.org/docs.html
https://duplicity.readthedocs.io/en/latest/

Extract a Folder from Duplicity Archive


Find Moment Generating Function from a non linear function

Question: Let $X$ be a r.v which has the following $mgf$ $$M_{x}(t) = (1-2t)^{-2}$$
If $Y = (100)(1.1)^{X}$ then calculate $E[Y]$
I know that $X \sim \chi^{2}_{(4)}$ but I am supposed to answer it only with $M_{x}(t)$
I think I have to start like this $E[e^{tY}] = E[e^{t(100)(1.1)^{X}}]$ but since the relation between Y and X is not linear I really don't know how to proceed.
Can anyone give me any hint? Or is it possible I can't solve it only with $M_{x}(t)$
Comment: I can compute it manually, just that I am supposed no to answer it manually.
Comment: $\mathbb E[Y] = 100 \mathbb E[(1.1)^X] = 100 \mathbb E[e^{X\ln(1.1)}]$. Can you finish from there?
Answer: We want to find $E[Y]$ using only the moment generating function provided for X.
Step 1
We use the definition $Y = (100)(1.1)^X$, and substitute this into the above so that we are now looking to find the value $E[Y] = E[(100)(1.1)^X]$.
Step 2
We know that we can always factor out constants from the expectation and so we are able to rewrite the desired quantity as $100E[(1.1)^X]$
Step 3
You correctly observed that the function of X in the expectation is not linear, and so we are able to use a trick that is often useful in mathematics (particularly when it comes to probability and statistics), that $a^b=e^{ln(a^b)}=e^{(b)(ln(a))}$.
And so when we apply this trick to the desired quantity, we note that $100E[(1.1)^X] = 100E[e^{(X)(ln(1.1))}]$
Step 4
We notice that this is now in the form of the moment generating function which are given in the question: $M_x(t)=E[e^{tX}]=(1-2t)^{-2}$.
Therefore, $100E[e^{(X)(ln(1.1))}]=100M_x(ln(1.1))=100(1-2ln(1.1))^{-2}=152.65$.
And so we conclude that $E[Y] = 152.65$ using only the moment generating function provided for X.


USB doesn't mount

Question: I have a problem. I have had Ubuntu 12.04 on my laptop for 2 years and up until now no problems with the USB. But since this evening the pc doesn't mount the USB. I read some discussions but the problem persists.
with
sudo fdisk -l

shows
    Disk /dev/sdb: 2003 MB, 2003828736 bytes
43 heads, 42 sectors/track, 2167 cylinders, total 3913728 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00095b2e

My USB  has got fat32 filesystem:

And with a USB with ext4 filesystem,shows:
    Disk /dev/sdb: 31.5 GB, 31457280000 bytes
255 heads, 63 sectors/track, 3824 cylinders, total 61440000 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000eecfd

So the Pc sees that the USB is connected but I don't see it in file directory.

Where data is a partition of my SSD.
whitsudo lsusb command:
Bus 001 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 8644:8003

Where the last line is the 2GB USB
I have Arduino and it works without problems.
with the other pc in my house, with ubuntu too the USB are read perfectly. How can I solve my problem?
Comment: Maybe the output of dmesg just after you try to connect the USB might help
Answer: Mount device/partition manually.

Try:
# mount -t ntfs /dev/sdb1

If problem persists:
# mkdir /media/$USER/USB1
# mount -t ntfs /dev/sdb1 /media/$USER/USB1

You can try to mount a device/partition using UUID/LABEL of device/partition. Double-click on given device/partition in GParted to retrieve <uuid>. Then:
# mount -t ntfs UUID=<uuid>

or
# mount -t ntfs /dev/disk/by-uuid/<uuid>

or
# mount -t ntfs LABEL=

or
# mount -t ntfs /dev/disk/by-label/

3a. You can define mountpoint:
# mount -t ntfs /dev/disk/by-uuid/<uuid> <mountpoint>

If none doesn't lead to supposed result, use usb ammeter to check whether usb port is powered properly.

Further reading:
A. $ man mount
B. mount on ArchWiki.
C. mount(8) on die.net.
Comment: Hi, thank you for the reply. With second command (with the mount point I can mount the USB, but I able to use it only with root permissions (I created a mountpoint in/media/USB_mount (where I have other mountpoint)).
But my question is: why from a day to an other my PC doesn't mount USB automatically?
Comment: I don't know why (maybe kernel problems). But I have found additional solution:
`sudo apt-get install usbmount`.

This thread on [help.ubuntu.com](https://help.ubuntu.com/community/Mount/USB) might be also helpful for you.
Comment: with Disk application I see the USB and I can mount it without root access. Thanks for your help. Waiting for the answer  about why not automatically mount.
Answer: The Mount Helper was disabled (I don't know why)

Once abilitated, all works fine.

USB doesn't mount


Cannot calculate antiderivative using undefined coefficients

Question: Using a simple substitute, I have simplified the function whose antiderivative needs to be calculated to the following form:
$$I=\int{\frac{2x^4-x^3}{x^5+1}dx}$$
Using the method of undefined coefficients, I tried to break this function as following:
$$\frac{2x^4-x^3}{x^5+1} = \frac{A}{x+1} + \frac{Bx+C}{x^4-x^3+x^2-x+1}$$
$$= \frac{A\cdot(x^4-x^3+x^2-x+1) + (Bx+C)\cdot(x+1)} {(x+1)(x^4-x^3+x^2-x+1)}$$
This is equivalent to:
$$\begin{align}2x^4-x^3 &= A\cdot(x^4-x^3+x^2-x+1) + (Bx+C)\cdot(x+1)\\
&= Ax^4 -Ax^3+Ax^2-Ax+A+Bx^2+Bx+Cx+C\\
&= Ax^4 -Ax^3 +x^2(A+B) + x(-A+B+C) + (A+C)\\
\end{align}$$
whis is equivalent to the following system:
$$\begin{cases}
A=2 \\
-A = -1 \implies A=1 \\
A+B=0 \\
-A+B+C=0\\
A+C=0
\end{cases}
$$
Clearly the problem is with the coefficient A. This method worked for me so far and I am not sure as to where did I go wrong.
Comment: You have to decompose $\;x^5+1\;$ in a product of linear and/or quadratic factors. It is a horrible outcome and several questions close to this with that quintic in the denominator have been asked lately. Either there's no simplifying trick to deal with that or else nobody has shown it.
Answer: You need more coefficients. In general, when doing partial fractions (or what you are calling undefined coefficients), what you put in the numerator needs to be a polynomial of 1 degree less than the denominator. So for you, you need $$\frac{2x^4 - x^3}{(x+1)(x^4 -x^3 + x^2 -x + 1)} = \frac{A}{x+1} + \frac{Bx^3 + Cx^2 + Dx + E}{x^4 -x^3 + x^2 -x + 1}.$$ That is, on top of the 4th degree polynomial, you need a 3rd degree polynomial. Then it will work.
Edit: grammar
Comment: @Joanpemo Yes I agree. This gives no hint as to how to actually find the antiderivative and that much is indeed a nightmare.

Original poster: I'm not quite sure what you mean. You need a 3rd degree polynomial because on top of the 4th degree polynomial. This way, when you cross multiply, you end up with a 4th degree polynomial on top of a fifth degree polynomial which is exactly what you started with. If you didn't get back exactly what you started with, you wouldn't be able to solve the resulting equations (which is what happened when you tried with only $Bx + C$).
Comment: For the decomposition of the rational function this works, for solving the integral I doubt it: the solutions is almost a nightmare.
Comment: But this way the second partial fraction is of the same sort as the one I started with: the numenator is of 1 degree less than the denominator, which this time can't be factored over the real numbers.
Comment: My mistake, I understood everything.
Answer: $$\frac{x^3}{x^5+1}=x^3\prod_{k=0}^4\frac1{x-\omega_k}=\sum_{k=0}^4\frac{A_k}{x-\omega_k}$$ where $\omega_k=e^{i\theta_k}=\cos\theta_k+i\sin\theta_k$ and $\theta_k=\frac{2\pi(2k+1)}{10}$. Then
$$\lim_{x\rightarrow\omega_k}\frac{x^3(x-\omega_k)}{x^5+1}=\frac00=\lim_{x\rightarrow\omega_k}\frac{x^3+3x^2(x-\omega_k)}{5x^4}=\frac{\omega_k^3}{5\omega_k^4}=-\frac15\omega_k^4=\lim_{x\rightarrow\omega_k}\sum_{j=0}^4\frac{A_k(x-\omega_k)}{x-\omega_j}=\sum_{j=0}^4A_k\delta_{jk}=A_k$$
So now we have $$\int\frac{2x^4-x^3}{x^5+1} dx=\frac25\ln(x^5+1)+\frac15\sum_{k=0}^4\int\frac{\omega_k^4}{x-\omega_k} dx$$ Now,
$$\int\frac{\omega_0^4}{x-\omega_0}dx=\omega_0^4\ln(x-\omega_0)+C_0=\omega_0^4\ln(x-\cos\theta_0-i\sin\theta_0)+C_0=\omega_0^4\ln\left(\sqrt{x^2-2x\cos\theta_0+1}e^{i\text{atan2}(-\sin\theta_0,x-\cos\theta_0)}\right)+C_0=\omega_0^4\ln\left(\sqrt{x^2-2x\cos\theta_0+1}e^{i\tan^{-1}(x-\cos\theta_0)/\sin\theta_0-i\pi/2}\right)+C_0$$ With a little more work,
$$\int\frac{\omega_0^4}{x-\omega_0}dx+\int\frac{\omega_4^4}{x-\omega_4}dx=\cos(4\theta_0)\ln\left(x^2-2x\cos\theta_0+1\right)-2\sin(4\theta_0)\tan^{-1}\left(\frac{x-\cos\theta_0}{\sin\theta_0}\right)+C_{04}=\frac{-\sqrt5-1}4\ln\left(x^2-\frac{\sqrt5+1}2x+1\right)-\frac{\sqrt{10-2\sqrt5}}2\tan^{-1}\left(\frac{4x-\sqrt5-1}{\sqrt{10-2\sqrt5}}\right)+C_{04}$$ and
$$\int\frac{\omega_1^4}{x-\omega_1}dx+\int\frac{\omega_3^4}{x-\omega_3}dx=\cos(4\theta_1)\ln\left(x^2-2x\cos\theta_1+1\right)-2\sin(4\theta_1)\tan^{-1}\left(\frac{x-\cos\theta_1}{\sin\theta_1}\right)+C_{13}=\frac{\sqrt5-1}4\ln\left(x^2+\frac{\sqrt5-1}2x+1\right)-\frac{\sqrt{10+2\sqrt5}}2\tan^{-1}\left(\frac{4x+\sqrt5-1}{\sqrt{10+2\sqrt5}}\right)+C_{13}$$ and of course
$$\int\frac{\omega_2^4}{x-\omega_2}dx=\int\frac1{x+1}dx=\ln(x+1)+C_2$$ so overall we have
$$\int\frac{2x^4-x^3}{x^5+1}dx=\frac25\ln(x^5+1)+\frac15\ln(x+1)+\frac{-\sqrt5-1}{20}\ln\left(x^2-\frac{\sqrt5+1}2x+1\right)-\frac{\sqrt{10-2\sqrt5}}{10}\tan^{-1}\left(\frac{4x-\sqrt5-1}{\sqrt{10-2\sqrt5}}\right)+\frac{\sqrt5-1}{20}\ln\left(x^2+\frac{\sqrt5-1}2x+1\right)-\frac{\sqrt{10+2\sqrt5}}{10}\tan^{-1}\left(\frac{4x+\sqrt5-1}{\sqrt{10+2\sqrt5}}\right)+C$$ I'm too tired to continue. Hopefully others will edit my errors.
Answer: As said in comments, the antiderivative is not the most pleasant to find.
However, writing $$x^5+1=(x-1)(x-a)(x-b)(x-c)(x-d)$$ a complete full partial fraction decomposition would lead to $$\frac{2x^4-x^3}{x^5+1}=\frac{1}{(a-1) (b-1) (c-1) (d-1) (x-1)}+\frac{2 a^4-a^3}{(a-1) (a-b) (a-c) (a-d) (x-a)}+\frac{2 b^4-b^3}{(b-1) (b-a) (b-c)
   (b-d) (x-b)}+\frac{2 c^4-c^3}{(c-1) (c-a) (c-b) (c-d) (x-c)}+\frac{2
   d^4-d^3}{(d-1) (d-a) (d-b) (d-c) (x-d)}$$ which is simple to integrate. For sure the problem would be to simplify (by recombination) the logarithms which contains complex numbers as well as the coefficients.
What I suspect is that, by to reals, the result contains three logarithms and two $\tan^{-1}(.)$
However the problem can be a little simplified wrting $$I=\int{\frac{2x^4-x^3}{x^5+1}dx}=\frac 25\int\frac{5x^4}{x^5+1}dx-\int\frac{x^3}{x^5+1}dx$$ $$I=\frac 25 \log(x^5+1)-\int\frac{x^3}{x^5+1}dx$$ and doing the same as before $$\frac{x^3}{x^5+1}=\frac{1}{(a-1) (b-1) (c-1) (d-1) (x-1)}+\frac{a^3}{(a-1) (a-b) (a-c) (a-d) (x-a)}+\frac{b^3}{(b-1) (b-a) (b-c) (b-d)
   (x-b)}+\frac{c^3}{(c-1) (c-a) (c-b) (c-d) (x-c)}+\frac{d^3}{(d-1) (d-a) (d-b)
   (d-c) (x-d)}$$


Halfspaces in $\mathbb{R}^d$

Question: On page 28 of Ziegler's "Lectures on Polytopes", we are told that an $H-poyhedron$ is an intersection of closed halfspaces. He then defines a halfspace as a set $P \subset \mathbb{R}^d$ presented in the form $P = P(A, z) = \{x \in \mathbb{R}^d: Ax \leq z\}$ for some $A \in \mathbb{R}^{m \times d}, z \in \mathbb{R}^m$. (Here $Ax \leq z$ is the usual shorthand for a system of inequalities, namely $a_1x \leq z_1, ..., a_mx \leq z_m$, where $a_1, ..., a_m$ are the rows of $A$ and $z_1, ..., z_m$ are the components of $z$.)
Can anyone please explain to me why halfspaces are defined this way? Also, why is $z$ an $m-$dimensional vector? I tried thinking about lower dimensions and in $\mathbb{R}^2$, I still don't understand why a halfspace is defined as $ax+by + c \leq 0$. I get that $ax+by + c = 0$ is a hyperplane in $\mathbb{R}^2$, but why making it into an inequality turns it into a halfspace? How do we know that all the points satisfying $ax+by + c \leq 0$ necessarily lie below this line?
Thanks a lot in advance. I would really appreciate any help. Thanks again.
Comment: I think you misread something and $P$ is already the polyhedron and indeed the intersection of $m$ half-spaces. Can you re-read the section and then clarify the question?
Comment: The halfspace should be defined by one inequality: $\{x \in \mathbb R^d\; : \; a \cdot x \le c\}$ where $a \in \mathbb R^d$ and $c \in \mathbb R$.  Thus the hyperplane $\{x \in \mathbb R^d\; : \; a \cdot x = c\}$ divides $\mathbb R^d$ into two halfspaces, one where $a \cdot x \le c$ and the other where $a \cdot x \ge c$.
Answer:
Can anyone please explain to me why halfspaces are defined this way?  Why is $\vec{z}$ an $m$-dimensional vector?

A hyperplane is defined by its normal vector $\vec{n}$ and signed distance $d$ from origin in units of the normal vector length.  Point $\vec{p}$ is on the hyperplane if and only if
$$\vec{n} \cdot \vec{p} = d$$
Note that this is the definition for the signed distance $d$ when $\vec{p}$ is on the plane itself.  If the plane passes through origin, then $d = 0$.  If the plane is on the same side from origin the normal points towards, then $d \gt 0$.  If the plane is on the opposite side from origin the normal points towards, then $d \lt 0$.
The hyperplane splits the space into two: the side where the normal vector points to, and the other one (opposite to where the normal vector points),
$$\vec{n} \cdot \vec{p} \lt d \label{1}\tag{1}$$
which is the definition of a single halfspace.
(The comparison direction varies, since it is just an arbitrary choice.  It can also include or exclude the hyperplane.  Thus, all of $\lt$, $\le$, $\ge$, and $\gt$ are acceptable in $\eqref{1}$ above.)
In $\mathbb{R}^n$, we can express this relationship using a matrix $\mathbf{A}$ with $m$ row vectors (each representing a single $\vec{n}$), and a result column vector $\vec{z}$, whose $m$ components are the signed distances from origin in units of the corresponding normal vector (each representing the corresponding $d$).  Then, the comparison $\lt$ in
$$\mathbf{A}\vec{p} \lt \vec{z} \tag{2a}\label{2a}$$
refers to component-wise comparison; it is true if and only if each component of $\mathbf{A}\vec{p}$ is less than the corresponding component of $\vec{z}$.
So, it is a very simple shorthand compared to something like
$$\vec{n}_i \cdot \vec{p} \lt d_i \quad \forall ~ 0 \le i \lt m \in \mathbb{N} \tag{2b}\label{2b}$$
which you can see in texts using basic vector algebra notation instead of linear algebra notation.  The two ($\eqref{2a}$ and $\eqref{2b}$) do describe the exact same thing, assuming $\mathbf{A}$ has $m$ rows, and $\vec{z}$ is a column vector with $m$ components.  The convex polytope is then defined by $m$ halfspaces.
In this definition, the normal vectors point outwards from the polytope, and strictly speaking, the surface of the polytope is not included in its volume.  (It does not change the volume at all, of course, but it will affect computer programs that implement the algorithm, since they work with limited precision numbers.)

How do we know that in 2D, points satisfying $a x + b y \lt c$ (i.e., $a x + b y - c \lt 0$) necessarily lie below this line?

In vector notation, if we use $\vec{n} = (a, b)$ and $\vec{p} = (x, y)$, this is again
$$\vec{n} \cdot \vec{p} \lt c$$
where $\vec{n}$ is the normal vector of the hyperplane, perpendicular to the 2D line $a x + b y = c$.  If we pick any point $\vec{p}_0$ on the line itself, then
$$\vec{n} \cdot (\vec{p} - \vec{p}_0) = \vec{n} \cdot \vec{p} - c$$
because by definition, $c = \vec{n} \cdot \vec{p}_0$.  In vector algebra terms, $\vec{n} \cdot \vec{p}$ is also the length of $\vec{p}$ projected to vector $\vec{n}$: if $\vec{p}$ is in the same halfspace as $\vec{n}$, the dot product increases as $\vec{p}$'s magnitude increases; if the two are perpendicular, the dot product is zero; and if $\vec{p}$ is in the other halfspace as $\vec{n}$, the dot product decreases.
A practical example.  Let's choose line $y = 1$, with the normal pointing towards negative $y$ axis, so we choose the half-space above $y = 1$.  Then, $\vec{n} = (0, -1)$, i.e. $a = 0$, $b = -1$, $c = -1$ (negative, because $y = 1$ is in the opposite direction to $\vec{n}$), and we have
$$a x + b y - c = 0 x - 1 y - (-1) = 1 - y \lt 0 \quad \forall y \gt 1$$
Another practical example.  Let's choose line $x = 0$, with the normal pointing towards positive $x$ axis, so we choose the negative $x$ halfspace.  Now, $\vec{n} = (1, 0)$, $a = 1$, $b = 0$, $c = 0$, and
$$a x + b y - c = 1 x - 0 y - 0 = x \lt 0 \quad \forall x \lt 0$$
So, OP's definition of "below" must be understood in relation to the normal vector, as in "the halfspace in the opposite direction of the hyperplane than the normal vector points towards".

Halfspaces in $\mathbb{R}^d$


how to add jfxrt.jar in openjdk8

Question: I am using OpenJDK 8 and want to add jfxrt.jar in my MS project. I am getting NoClassDefFoundError for FXCollection.class. My MS project is deployed on a Kubernetes pod. Is there any way to add jfxrt.jar there and to resolve given error.
I tried to add a COPY command in the Docker file, but it is giving error like file not found.
I didn't got any compatible dependency version of it from Maven Central.
Comment: Please provide some code which makes it easier to answer your question
Answer: JDK8 and JavaFX are obsolete. You can find info on modern JDK and JavaFX distributions (currently 21), at openjfx.io. BellSoft and Azul also provide JDKs that include JavaFX.
BellSoft offer JDK 8 distributions (select "JDK 8 LTS" + "Full JDK") that include JavaFX, you could try one of those if you wish. The JavaFX Media and Webkit components in BellSoft Liberica JDK 8 do not work.
Regarding jfxrt.jar. It does not exist in recent versions of JavaFX. It also does not exist in most OpenJDK distributions. It does exist in archived Oracle JDK 8 versions. You can't just copy the jfxrt.jar that you may find somewhere into an Open JDK distribution and expect it to work. JavaFX requires native components matching the Java runtime versions in order for it to work and those native components (e.g. DLLs or .so libraries) are not included in jfxrt.jar.
JavaFX also may not function within a kubernetes pod as you are trying to run it.

how to add jfxrt.jar in openjdk8


Reconstructing D3 Animated Choropleth with a new Map and Data

Question: I am trying to recreate the D3.js example: "Yet another animated choropleth map":
http://bl.ocks.org/rgdonohue/9280446
Only, I am attempting to use a different map with different data. The map I am using is of US counties and the data is 2 years worth of median household values by county. I am running into an error in displaying my map. The error:
TypeError: counties[i].properties is undefined
Arises in the following function (see link above for original function):
function processData(error, us, countyData) {
  var counties = us.objects.counties.geometries;  // store the path in variable for ease
  for (var i in counties) {    // for each geometry object
    for (var j in countyData) {  // for each row in the CSV
      if(counties[i].properties.id == countyData[j].id) {   // if they match
        for(var k in countyData[i]) {   // for each column in the a row within the CSV
          if(k != 'name' && k != 'id') {  // let's not add the name or id as props since we already have them
            if(attributeArray.indexOf(k) == -1) {
               attributeArray.push(k);  // add new column headings to our array for later
            }
            counties[i].properties[k] = Number(countyData[j][k])  // add each CSV column key/value to geometry object
          }
        }
        break;  // stop looking through the CSV since we made our match
      }
    }
  }
  d3.select('#clock').html(attributeArray[currentAttribute]);  // populate the clock initially with the current year
  drawMap(us);  // let's mug the map now with our newly populated data object
}

I believe what is happening is that 'us' is undefined for some reason. The original example uses the map world-topo.json which I haven't been able to find the source for.  My map is http://d3js.org/us-10m.v1.json.
Original code:
world.objects.countries.geometries

which I changed to:
us.objects.counties.geometries

In Bostock's original Choropleth example he uses the same US map that I am using and references it as 'us', but it doesn't seem to be working for me:
svg.append("g")
.data(topojson.feature(us, us.objects.counties).features)

I realize I don't have a very  good understanding of D3 - I'm more of a code hacker and not a developer. I'm just trying to experiment with some visualizations and have little experience with javascript/d3. Any help would be appreciated.
My entire program:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>d3 choropleth map</title>

      <button id="play">play</button>
      year

Example data from countiesRandom.csv:
id,2010,2015
01001,141300,133900

Answer: In regards to:

I am running into an error in displaying my map. The error: TypeError:
  counties[i].properties is undefined

We need to examine both the referenced world topojson and US topojson.
In the world topojson, the geometries are defined like this:
"geometries":[
{"type":"Polygon","id":1,"arcs":[[0,1,2,3,4,5,6,7]],"properties":{"admin":"Afghanistan","id":"AFG"}},
{"type":"Polygon","id":4,"arcs":[[16,17,18,19,20]],"properties":{"admin":"Albania","id":"ALB"}},

There is a properties attribute to each geometry.
In the US topojson you reference, the geometries are defined like this:
"geometries":[
{"type":"Polygon","arcs":[[0,1,2,3,4]],"id":"05089"},
{"type":"Polygon","arcs":[[5,6,7,8,9]],"id":"06079"},
{"type":"Polygon","arcs":[[10,11,12,13,14,15,16]],"id":"17111"},

There is no properties attribute assigned to each geometry. So, when you call for the properties of a geometry, it'll return undefined.
So instead of using counties[i].properties.id, you might find more success with counties[i].id.

It may also be worth noting, if you are comparing examples, that the conversion from topojson to geojson (topojson.feature(us, us.objects.counties).features) will modify the structure of the data as well:

d3.json("//d3js.org/us-10m.v1.json",function(error,us) {
  console.log("Number of county geometries:");
  console.log(us.objects.counties.geometries.length);
  console.log("Example county id:");
  console.log(us.objects.counties.geometries[0].id);
});

d3.json("//d3js.org/us-10m.v1.json",function(error,us) {
  var geojson = topojson.feature(us, us.objects.counties).features;
  console.log("Number of features");
  console.log(geojson.length);
  console.log("Example county ID");
  console.log(geojson[0].id);

});

Comment: Thanks for the reply! Providing the source topojson is very helpful. I think with a little more work I can figure this out.


Ember: Passing localisation key to component template

Question: I have a modal-dialog component template, which contains the following

    {{t title}}

So, I am using the ember-i18n [1] library to add localisation to ember. Now I am calling that component template from the actual modal dialog template:
{{#modal-dialog title="dialog.title"}}

I am a modal dialog

  <button {{action "close"}}>Done</button>
{{/modal-dialog}}

What I am trying to do here is, defining a key that is used for localisation in the dialog template, which is passed to the component template and translated there. However, this leads to the following error: Missing translation: title. So the variable title just seems to actually be treated as a string and not as a variable.
Alternatively I could translate the title in the dialog template and pass it to the component template:
dialog:
{{#modal-dialog title={{t "dialog.title"}} action="close"}}

That leads to a compiler error:
Error: Parse error on line 1:
...#modal-dialog title={{t "dialog.title"}}
-----------------------^
Expecting 'STRING', 'INTEGER', 'BOOLEAN', 'OPEN_SEXPR', 'ID', 'DATA', got 'OPEN'

Is there any way to make this happen?
[1] https://github.com/jamesarosen/ember-i18n
Answer: mitchlloyd presented a great solution here: http://discuss.emberjs.com/t/need-to-pass-a-value-from-component-template-to-component/5792/6
Use the Translation suffix in the template (I was just passing a title property):
{{#modal-dialog action="close" titleTranslation="modal.title"}}

Name Change Modal

{{/modal-dialog}}

The component uses the Mixin from ember-i18n:
export default Ember.Component.extend(Em.I18n.TranslateableProperties, {
});

And finally in the template, just reference the translated title property:

 {{title}}

Answer: The explanations above are not working with the latest version of ember-i18n where TranslateableProperties has been removed:
Here is how I made it work with ember-i18n 4.x and ember-cli 1.13.1:
1 - Make sure that the service i18n is injected in your component:
//initializers/i18n.js
export default {
  name: 'i18n',

  after: 'ember-i18n',

  initialize: function(_, app) {
      app.inject('controller', 'i18n', 'service:i18n');
      app.inject('component', 'i18n', 'service:i18n');
  }
};

2 - The component's template references a {{title}} property:
//templates/components/pick-card.hbs
!-- Selection of the card -->

{{title}}

...

3 - The template where I call my component:
//templates/security/forgot-username.hbs
{{#pick-card title-i18n="page.forgot_username"}}
{{/pick-card}}

4 - The component's controller where the magic is:
    import Ember from 'ember';
    import {translationMacro as t} from "ember-i18n";

    export default Ember.Component.extend({
      title: Ember.computed('i18n.locale', function() {
          return this.get('i18n').t(this.get('title-i18n'));
      })
    });

As described in ember-i18n doc the use of
i18n.locale is crucial to make sure that the property {{title}} is translated automatically as soon as the user changes the locale.
Have fun :)
Answer: Better way is to use the Handlebars Subexpressions:
You would use some this like this:
{{#modal-dialog title=(tv "dialog.title") action="close"}}

Here tv is the helper i have used:
And You need to register a helper for this:
Ember.Handlebars.registerHelper('tv', function (key) {
  return Em.I18n.t(key);
});

Hope this helps
Answer: You can compute that title property within the controller or model. So:
{{#modal-dialog title={{t "dialog.title"}} action="close"}}

Would be:
{{#modal-dialog title="dialog.translateTitle" action="close"}}

And then you could have a computed property like so:
translateTitle: function () {
  return this.translateLibraryMethodYouUse(this.get('title'));
}.property('title')

That is obviously psuedo code, but it should work if you can get your localization into the translateTitle property. you can put that in your dialog model, or you can put it into your item controller or whatever you are using for that context.
UPDATE::
Okay, so took a look at that library. You can also try updating your controller or model with the Em.I18n.TranslateableProperties mixin to allow you to bind a translated property:
App.DialogController = Ember.ObjectController.extend(Em.I18n.TranslateableProperties, {
  titleTranslation: 'dialog.title'
});

Good luck, and hope that helps!
Comment: Thanks, I tried to get that going using what you described, however everything broke when I was trying to either access the value I have  in the component-template from the component, or when I was trying to access the value that is set in a controller from the component-template. I have written more about these issues here: http://discuss.emberjs.com/t/need-to-pass-a-value-from-component-template-to-component/5792
Answer: Just to update the responses here to be a little more up to date! As mentioned by @mohamedjahabersadiq, you can use Subexpressions. These also work fine in HTMLBars (>= Ember 1.10.0). However, you don't have to register a new helper, you can use the existing t helper from ember-i18n.
{{#modal-dialog title=(t "dialog.title")}}
    Hello
{{/modal-dialog}}


parse PHP array depending on values

Question: --- AIM ---
I have an array like this
$codes = array(
            array('type'=>1,'id'=>'qcdv'),
            array('type'=>2,'id'=>'thcd'),
            array('type'=>2,'id'=>'ngjd'),
            array('type'=>1,'id'=>'mhkx'),
            array('type'=>3,'id'=>'tnfr') /* many more elements*/
          );

and desired output is
Array(
    [0] => Array ()
    [1] => Array (
        [0] => qcdv
        [1] => mhkx )
    [2] => Array(
            [0] => thcd
            [1] => ngjd
        )
    [3] => Array (
        [0] => tnfr
    )
)

that is differentiate by type key.
-- WHAT I TRIED TILL NOW --
$codes = array(
    array('type'=>1,'id'=>'qcdv'),
    array('type'=>2,'id'=>'thcd'),
    array('type'=>2,'id'=>'ngjd'),
    array('type'=>1,'id'=>'mhkx'),
    array('type'=>3,'id'=>'tnfr')
);
$by_type=array(array(),array(),array(),array()); /* unable to digest this line */
foreach($codes as $code) {
    array_push($by_type[$code['type']],$code['id']);
}
print_r($by_type);

It is giving correct output but type key range is not fixed so I can't use
$by_type=array(array(),array(),array(),array());

is there any other efficient way ?
Answer: <?php

$codes = array(
            array('type'=>1,'id'=>'qcdv'),
            array('type'=>2,'id'=>'thcd'),
            array('type'=>2,'id'=>'ngjd'),
            array('type'=>1,'id'=>'mhkx'),
            array('type'=>3,'id'=>'tnfr')
          );

$array = array();
foreach( $codes as $v) {
$array[$v['type']][] = $v['id'];
}

print_r($array);

Answer: this code does the trick:
$output = array();
foreach ($codes as $idx1 => $array2)
{
    $k = $array2['type'];
    $v = $array2['id'];
    if (!isset($output[$k])) $output[$k] = array();
    $output[$k][] = $v;
}

Answer:  <?php

$codes = array(
            array('type'=>1,'id'=>'qcdv'),
            array('type'=>2,'id'=>'thcd'),
            array('type'=>2,'id'=>'ngjd'),
            array('type'=>1,'id'=>'mhkx'),
            array('type'=>3,'id'=>'tnfr') /* many more elements*/
          );

          $result = array();
          foreach($codes as $code)
          {
            $result[$code['type']][] = $code['id'];
          }

          print_r($result);

parse PHP array depending on values


Mapping RDF/XML data to java objects

Question: i have set up a web crawler that collects data and stores it in rdf/xml file,now i want to map that data to my java objects...how can i do that?
i have found this piece of code that might be usefull for me,but i cant seem to use it properly...it collects subjects,predicates and objects from my rdf/xml file but i can represent this data with my java specified objects,i dont know how...i googled a lot but there arent much usefull things about this so help guys!:D
StmtIterator iter = rdfGraph.listStatements();
     while (iter.hasNext()) {

            Statement stmt      = iter.nextStatement();  // get next statement
            Resource  subject   = stmt.getSubject();
            //System.out.print(subject.getNameSpace(  ) + subject.getLocalName(  ));// get the subject
            Property  predicate = stmt.getPredicate();
            //System.out.print(" " + predicate.getNameSpace(  ) + predicate.getLocalName(  ));// get the predicate
            RDFNode   object    = stmt.getObject();      // get the object
            //System.out.println(" " + object.toString(  ) + "\n");
            System.out.println(subject + " | "+predicate + " | " + object);

         }

this is a part of my rdf file...
<rdf:Description rdf:nodeID="A12">
<schema:reviewRating rdf:nodeID="A13"/>
<schema:description>descriptiooooon</schema:description>
<schema:datePublished>2012-02-22</schema:datePublished>
<schema:author>Nick M.</schema:author>
<rdf:type rdf:resource="http://schema.org/Review"/>
</rdf:Description>

and i want to represent it with this java object..here is my class...
@Namespace(Constants.SCHEMA)
@RdfType("Review")
public class Review extends Thing{

@RdfProperty(Constants.SCHEMA + "author")
private String author;

@RdfProperty(Constants.SCHEMA + "reviewRating")
private Rating reviewRating;

@RdfProperty(Constants.SCHEMA + "datePublished")
private Date datePublished;

@RdfProperty(Constants.SCHEMA + "description")
private String description;

    }

Answer: Maybe this api could be useful for you:
XMappr API
Answer: Well, you haven't told us what

i can represent this data with my java specified objects,

actually means, since you haven't described your Java objects.
Taking a guess, the problem, I think, is that you are accessing the contents of the RDF model one triple (Statement) at a time. This is rather a low-level access pattern.  The first thing you need to recognize is that groups of triples with the same subject URI denote information about the same RDF resource. So, one thing you could do is iterate over the subjects of the model, and then list their properties:
ResourceIterator i = rdfGraph.listSubjects();
while (i.hasNext()) {
  Resource s = i.next();
  System.out.println( "Graph contains subject " + s );
  for (StmtIterator j = s.listProperties(); j.hasNext(); ) {
    Statement t = j.next();
    System.out.println( "   with property " + t.getPredicate() +
                        " ---> " + t.getObject() );
  }
}

That will give you a sense of the basic level of grouping of statements in your graph. You probably, in fact, only want to start with resources of a certain rdf:type which is easy enough to do.
This would be a more common basic pattern for working with RDF data. If you really, really do need a mapping of resources in the graph to Java objects, have a look at projects like JenaBean. Be aware though, that that code is quite old, and may need to be adapted to work with current versions of Jena.
Comment: ian can you help me more with this?i added a piece of my rdf/xml and java class...
Comment: Hi Andrej, sorry not to respond sooner, I've been busy. It looks like the code you've shared is some JenaBean code - I put the link in my original answer. As I said then, JenaBean is not an actively maintained project, so it may not work with current versions of Jena. My advice would be to forget about making your resources into Java beans, and just work with the RDF model API using the code sample I suggested. If you're not sure how to do that, I'd advise sending a more complete code sample to the Jena users list. See http://jena.apache.org/help_and_support/index.html for how to do that.

Mapping RDF/XML data to java objects


Water Heater - Electrical Fire - Safe to replace thermostat to try to fix?

Question: I replaced my water heater elements and thermostats about a week ago. Everything was fine and dandy for about a week. Then this afternoon I noticed no hot water so I took a look at the insides and it looked like the wires caught on fire.
Two questions: 1. What could cause this? It worked fine and then bam no more. 2. Would I be able to just replace the thermostat and it work again? It looks like the black wire is kinda burnt. Is it safe to replace myself or should I call in a plumber?

Thank you.
Comment: This is really beyond the skills of someone who does not have extensive electrical knowledge. Please call a plumber to avoid further risk to yourself and your family.
Comment: We can't possibly troubleshoot this in a safe manner with the limited information given and from the other side of the internet. Get some local help or you risk a more serious fire.
Answer: A loose connection can cause the wire to overheat. Now with the terminal appearing to be damaged it would require a new wire and possibly a new thermostat. If you can clean the terminal and it is not pitted you may be able to re use the thermostat but the wire needs to be replaced. These connections are high current draw and your wire was not wrapped around the screw even if tight the point of contact is two small and not code compliant without being wrapped. Exhibit 110.4 in 2014 NEC hand book 2/3 minimum not over lapping.


Configuring aluminium Mac Japanese keyboard on 15.04

Question: I have an aluminium Mac keyboard with Japanese layout. Using System Settings -> Text Entry, I can configure it easily as a regular Mac keyboard. However a lot of the non-alphabetic keys are mapped incorrectly. I have tried the Japanese (Macintosh) keyboard but it only gives me Japanese text - at present, getting all the English mappings is what I need. Is there a mapping somewhere or some way I can at least change the key-mappings?
Answer: To type the alphanumeric symbols as they appear on a Japanese keyboard:

Open Language Support
Check that Japanese is installed
Under Keyboard Input Method System, select fcitx
Log out and back in
Open Text Entry
Click the + button
Scroll down and select Mozc (Fcitx)
Click Add
An orange あ should appear in the system tray. (If it doesn't--it might
be a JP or EN icon, for example--click the language icon and select
Mozc.)
Switch to alphanumeric (i.e., romaji) input by toggling the
全角 key or by clicking on the あ, selecting Input Method, then Direct
Input.

If, on the other hand, you want to type all the alphanumeric symbols as they would appear on an English (e.g., US) keyboard by memory, you can just install that keyboard and type regardless of what symbols are printed on the keys of the Japanese keyboard.
Comment: Same problem. Following @tyknkd instructions and after installing Japanese in the language support, there is no fcitx in step 3. only iBus, XIM and none are listed in the Keyboard Input Method System.
I have a 2017 macbook with Japanese keyboard layout using Ubuntu 22.04
Comment: Finally added fcitx 4 by installing fcitx-mozc, the orangeicon appeared but that does not work because no alphanumeric is listed there.
Comment: This question and answer are for earlier versions of Ubuntu. For 22.04, the following post will probably be more helpful:
https://askubuntu.com/questions/1459992/on-ubuntu-22-04-lts-how-to-set-a-keyboard-layout-that-matches-a-japanese-keyboar