Probability that a number falls in a range

Question:
Suppose that $X$ and $Y$ are exponential r.v.'s with parameters $\lambda$ and $\mu$. Given the condition that $X$ is bounded by $Y$ (i.e., $X<Y$), how do I find the probability that a number $t$ falls between $X$ and $Y$?

Can I interpret this question as $P(X<t<Y\mid X<Y)$? If correct, how to compute it?

A follow-up question. Given the condition that $X<Y$ and $t<Y$, how do I compute the probability that $X<t$?
Answer: Your interpretation seems fine to me. See that:
$$
P(X<Y\mid X<t<Y)=1.
$$
Hence:
$$
P(X<Y,X<t<Y)=P(X<t<Y)=P(X<t)P(Y>t)=(1-e^{-\lambda t})e^{-\mu t}.
$$

Regarding  your second question. Again remember that:
$$
P(Y>X\mid Y>t)=1-\frac{\mu}{\lambda+\mu}e^{-\lambda x}.
$$
So:
$$
P(X<t\mid t<Y,X<Y)=\frac{P(X<Y,X<t<Y)}{P(X<Y,Y>t)}=\frac{e^{-\mu t}(1-e^{-\lambda t})}{e^{-\mu t}(1-\frac{\mu}{\lambda+\mu}e^{-\lambda t})}\\
=\frac{ (1-e^{-\lambda t})}{ (1-\frac{\mu}{\lambda+\mu}e^{-\lambda t})}.
$$


FileNotFoundException when try to generate PDF in android

Question: In here i'm try to generate a pdf file in android, but in the run time i get  this execption
       ioException:java.io.FileNotFoundException: /storage/sdcard/PDF/Demo.pdf: openfailed: ENOENT (No such file or directory)

this is my code
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
     import java.io.IOException;
    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Font;
    import com.lowagie.text.HeaderFooter;
    import com.lowagie.text.Image;
    import com.lowagie.text.Paragraph;
    import com.lowagie.text.Phrase;
      import com.lowagie.text.pdf.PdfWriter;

      public class MainActivity extends Activity {
    private Button createPDF , openPDF;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        createPDF = (Button)findViewById(R.id.button1);
        createPDF.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                createPDF();
            }
        });
        openPDF = (Button)findViewById(R.id.button2);
        openPDF.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                openPdf();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void createPDF(){
        Document doc  =new Document();
        try {
            String parth = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
            File dir = new File(parth);
            if(!dir.exists())
                dir.mkdir();
            Log.d("PDFCreater", "PDF PARTH "+parth);
            File file = new File(dir,"demo.pdf");
            Log.d("PDFCreater", "Create");
            FileOutputStream fOut = new FileOutputStream(file);
            Log.d("PDFCreater", "1");
            PdfWriter.getInstance(doc, fOut);
            Log.d("PDFCreater", "2");
            doc.open();
            Log.d("PDFCreater", "open");
            Paragraph p1= new Paragraph("Customer History");
            Font paraFont = new Font(Font.HELVETICA);
            paraFont.setSize(16);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);
            doc.add(p1);
            Log.d("PDFCreater", "add");
            /* Inserting Image in PDF */
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.apple);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
            Image myImg = Image.getInstance(stream.toByteArray());
            myImg.setAlignment(Image.MIDDLE);

            //add image to document
            doc.add(myImg);
            Phrase footerText = new Phrase("This is an example of a footer");
            HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
            doc.setFooter(pdfFooter);

            Toast.makeText(getApplicationContext(), "Created...", Toast.LENGTH_LONG).show();
        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        }
        finally
        {
            doc.close();
        }

    }
    void openPdf()
    {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";

    File file = new File(path, "demo.pdf");
    intent.setDataAndType( Uri.fromFile( file ), "application/pdf" );
       startActivity(intent);
    }

}

here is my xml file
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginLeft="56dp"
    android:layout_marginTop="50dp"
    android:text="Create" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/button1"
    android:layout_below="@+id/button1"
    android:layout_marginTop="38dp"
    android:text="Open" />

</RelativeLayout>

Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.isuru.mypdf"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.isuru.mypdf.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

I think that the exception throws on this line
FileOutputStream fOut = new FileOutputStream(file);

please help me , thank you !
Comment: `ENOENT (No such file or directory)` <-- the file is not where you expect it to be. I know `FileNotFoundException` sucks, but at least its message is clear enough about what happens here. And yes, you think correctly. If you are still stuck with Java 6, `file.exists()` would hopefully return `false`.
Comment: Did you give your app the permission to write to the external storage?
Comment: Where's the rest of the stacktrace? What you posted is not all the stacktrace! Like Daniel said, you'll need this `` permission added to your AndroidManifest file. See [here](http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE) for more info and read about the caveat for API 19.
Answer: Have you declared this permission in the android manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Comment: @Octopus If you don't have permissions to read files then how can you make folder in it?
Comment: So, you are saying that the expected file wouldn't have been created due to permission problem. Am i right?
Comment: yeah true that is what
Comment: thanks a lot, yes i haven't add above cording for my manifest file,now when i creating my pdf file using addroid app there are no errors, but when i open my pdf file using android app it will give me en error                                  android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/sdcard/PDF/demo.pdf typ=application/pdf }                      what was the problem, please help me thank you
Comment: @user3276345 You didn't mentioned activity in the manifest file of application tag. So you must and should add that activity in manifest other wise it will through that exception
Comment:
Comment:
Comment: @shylendra i have no experience by giving permissions on android applications i have post my android manifest file,so what should i have to modify on that, i'm  very happy that you ask manifest file try to help me.Thanks a lot ,please help me to solve this error.Thank you
Comment: Here you are trying to start an intent but there is no another activity to start from that intent. So that is why here you getting that activity not found exception, for that you need to create new activity and put code of open pdf file in that.and try
Comment: please help me to implement that part ,in the first line i give the parth and the name of the pdf file,                               File file = new File(path, "demo.pdf");      then how to open it and show that pdf file please help me , thank you
Comment: thank you , every one  now i solve the problem ,  ActivityNotFoundException come because i haven't install the wanted plugins for my emulator, now it works correctly thanks for every one who help me to solve my problem from the beginning ,
Answer: Add read and write permission in manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Check here:
Getting file from sdcard with Uri
Comment: thank you , every one  now i solve the problem ,  ActivityNotFoundException come because i haven't install the wanted plugins for my emulator, now it works correctly thanks for every one who help me to solve my problem from the beginning ,
Comment: thanks a lot yes i haven't add above cording for my manifest file,now when i creating my pdf file there are no errors, but when i open my pdf file it will give me en error                                                                    android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///storage/sdcard/PDF/demo.pdf typ=application/pdf }                                                                     what was the problem, please help me thank you
Comment: Check that http://stackoverflow.com/questions/19772856/getting-file-from-sdcard-with-uri
Comment: thank you , but i'm get an error call ActivityNotFoundException so what and where i have to modify that , thanks for helping to solve my problem
Comment: in that cord thay use some thing like this                           Uri uri = Uri.parse(fileURI);
File pdf = new File(uri.getPath()); ////////////////// but i use like this                            intent.setDataAndType( Uri.fromFile( file ), "application/pdf"  startActivity(intent); what was the different of these lines and can u please expand above cording
Comment: void openPdf(){Intent intent = new Intent(Intent.ACTION_VIEW);String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/PDF";
File file = new File(path, "demo.pdf");
intent.setDataAndType( Uri.fromFile( file ), "application/pdf" );
startActivity(intent.setDataAndType( Uri.fromFile( file ), "application/pdf" ));
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent target = Intent.createChooser(intent, "Open File");
try {startActivity(target);} catch (ActivityNotFoundException e) {
Log.e("PDFCreator", "ActivityNotFoundException:" + e);} }
Comment: Please Edit Question with Log Cat
Comment: i modify openpdf  method like above cording still the error there


Get Max(value) without grouping in SQL Server

Question: I have this grouping problem that I do not need.
Here is my SQL code to create and seed the table:
create table player
(
    playerid int identity(1,1) primary key,
    Name varchar(255)
)

create table gameplay
(
    gameplayid int identity(1,1) primary key,
    Name varchar(255),
    playerid int references player(playerid)
)

Create table room
(
    Roomid int identity(1,1) primary key,
    number int
)

Create table PC
(
    PCid int identity(1,1) primary key,
    Name varchar(255)
)

Create table playperiod
(
    PKid int identity(1,1) primary key,
    StartDate Datetime null,
    EndDate Datetime null,
    Roomid int references room(roomid),
    PCID int references PC(PCid),
    gameplayid int references gameplay(gameplayid)
)

Insert into player (name) values ('Kris')
Insert into player (name) values ('Bart')
Insert into player (name) values ('Bob')
Insert into player (name) values ('John')
Insert into player (name) values ('Iris')

insert into room (number) values (1000)
insert into room (number) values (1001)
insert into room (number) values (1002)
insert into room (number) values (1003)
insert into room (number) values (1004)
insert into room (number) values (1005)
insert into room (number) values (1006)
insert into room (number) values (1007)
insert into room (number) values (1008)
insert into room (number) values (1009)
insert into room (number) values (1010)

insert into gameplay (name, playerid) values ('WOW', 1)
insert into gameplay (name, playerid) values ('LOL', 2)
insert into gameplay (name, playerid) values ('DIablo', 3)
insert into gameplay (name, playerid) values ('Starcraft', 4)
insert into gameplay (name, playerid) values ('Borderlands', 5)

insert into PC (name) values ('Dell (1)')
insert into PC (name) values ('HP (1)')
insert into PC (name) values ('Dell (2)')
insert into PC (name) values ('HP (2)')
insert into PC (name) values ('Dell (3)')
insert into PC (name) values ('HP (3)')
insert into PC (name) values ('Dell (4)')
insert into PC (name) values ('HP (4)')
insert into PC (name) values ('Dell (5)')
insert into PC (name) values ('HP (5)')
insert into PC (name) values ('Dell (6)')
insert into PC (name) values ('HP (6)')
insert into PC (name) values ('Dell (7)')
insert into PC (name) values ('HP (7)')
insert into PC (name) values ('Dell (8)')
insert into PC (name) values ('HP (8)')
insert into PC (name) values ('Dell (9)')
insert into PC (name) values ('HP (9)')
insert into PC (name) values ('Dell (10)')
insert into PC (name) values ('HP (10)')

truncate table playperiod

insert into playperiod (StartDate, EndDate, Roomid, PCID, gameplayid)
values ('2015-01-22 10:02:00.000', '2015-01-22 11:30:00.000', 1, 1, 1)

insert into playperiod (StartDate, EndDate, Roomid, PCID, gameplayid)
values ('2015-01-22 10:02:00.000', '2015-01-22 16:02:00.000', 1, 2, 2)

insert into playperiod (StartDate, EndDate, Roomid, PCID, gameplayid)
values ('2015-01-22 10:04:00.000', '2015-01-28 10:02:00.000', 2, 3, 3)

insert into playperiod (StartDate, EndDate, Roomid, PCID, gameplayid)
values ('2015-01-20 10:02:00.000', '2015-01-22 10:02:00.000', 2, 4, 4)

insert into playperiod (StartDate, EndDate, Roomid, PCID, gameplayid)
values ('2015-01-22 22:40:00.000', '2015-01-22 22:50:00.000', 3, 5, 1)

insert into playperiod (StartDate, EndDate, Roomid, PCID, gameplayid)
values ('2015-01-22 22:55:00.000', '2015-01-22 23:50:00.000', 3, 6, 1)

insert into playperiod (StartDate, EndDate, Roomid, PCID, gameplayid)
values ('2015-01-22 11:30:00.000', '2015-01-22 13:30:00.000', 1, 1, 1)

insert into playperiod (StartDate, EndDate, Roomid, PCID, gameplayid)
values ('2015-01-22 14:30:00.000', '2015-01-22 16:30:00.000', 1, 1, 1)

insert into playperiod (StartDate, EndDate, Roomid, PCID, gameplayid)
values ('2015-01-22 19:30:00.000', '2015-01-22 22:30:00.000', 1, 1, 1)

Know these are my queries:
Step 1) get everything for 1 day (No problem so far)
Select startdate, number, pc.name, gp.Name,p.Name
from playperiod PD
left join room R on R.Roomid = PD.Roomid
left join pc on pc.PCid = PD.PCID
left join gameplay gp on GP.gameplayid = PD.gameplayid
left join player P on P.playerid = GP.playerid
where
DATEDIFF(day, pd.startdate, '2015-01-22') >= 0 and DATEDIFF(day, pd.startdate, '2015-01-22') <= 0

Step 2) Get the max date value from start date (Problem constation)
Select max(startdate) as startdate, number, pc.name, gp.Name,p.Name
from playperiod PD
left join room R on R.Roomid = PD.Roomid
left join pc on pc.PCid = PD.PCID
left join gameplay gp on GP.gameplayid = PD.gameplayid
left join player P on P.playerid = GP.playerid
where
DATEDIFF(day, pd.startdate, '2015-01-22') >= 0 and DATEDIFF(day, pd.startdate, '2015-01-22') <= 0
group by number, pc.name, gp.Name,p.Name

At the end I do group by so the behavior is correct. But here the user 'Kris' plays on 3 Pc that day in 2 rooms.
But I would like to have this situation:

Only the max startdate with that room number / pc / game / name (for that row)
I only need the latest situation. (even if he changed pc or room)

Here is the result that I need:

Can anyone help me ?
Comment: row_number partition by just search msdn
Comment: that date where looks wrong
Answer: You can read about row_number. Basically it assign number by some criteria. Here I said that make numbering for every group combination of gp.Name, P.Name and then I ordered these groups by datetime and took the latest one.
SELECT
    startdate ,
    number ,
    pc_name ,
    gp_name ,
    Name
FROM
    (
      SELECT
        startdate ,
        number ,
        pc.name pc_name ,
        gp.Name gp_name ,
        P.Name ,
        ROW_NUMBER() OVER ( PARTITION BY gp.Name, P.Name ORDER BY startdate DESC ) rn
      FROM
        playperiod PD
        LEFT JOIN room R ON R.Roomid = PD.Roomid
        LEFT JOIN pc ON pc.PCid = PD.PCID
        LEFT JOIN gameplay gp ON gp.gameplayid = PD.gameplayid
        LEFT JOIN player P ON P.playerid = gp.playerid
      WHERE
            DATEDIFF(DAY, PD.startdate, '2015-01-22') >= 0
        AND DATEDIFF(DAY, PD.startdate, '2015-01-22') <= 0
    ) a
WHERE
    rn = 1

Answer: You can do this a tiny bit more compactly with the nonstandard TOP WITH TIES clause:
SELECT TOP (1) WITH TIES
  startdate ,
  number ,
  pc.name pc_name ,
  gp.Name gp_name ,
  P.Name
FROM
  playperiod PD
  LEFT JOIN room R ON R.Roomid = PD.Roomid
  LEFT JOIN pc ON pc.PCid = PD.PCID
  LEFT JOIN gameplay gp ON gp.gameplayid = PD.gameplayid
  LEFT JOIN player P ON P.playerid = gp.playerid
WHERE PD.startdate >= '20150122'
AND PD.startdate < DATEADD(DAY,1,'20150122')
ORDER BY ROW_NUMBER() OVER (
  PARTITION BY gp.Name, P.Name
  ORDER BY startdate DESC
)

Comment: nice solution, never saw this syntax. However the performance is not very good compare to similar solutions.


An A.P. whose $(a_1 +1)^{th}$ term is prime

Question: We have to find an A.P. whose $(a_1 +1)^{th} $ term is prime & $a_1\ne 1$
I mean if first term is $4$, then $5^{th}$ term should be prime
According to me it is not true for any A.P.
because $(a_1+ 1)^{th}$ term is given by $a_1\times (1 +d)$
So it can't be a prime number
Am I right with my argument? Really?
If yes , then it is such a weird thing,
If no , please provide a counter example
Please help!!!
Comment: This is hard to follow, but looks trivial.  If the $(a+1)^{st}$ term is $a+aP$ where $P$ is the period of the progression, then of course it is divisible by $a$.
Comment: The question is not clearly stated.
Comment: for what stands $$a_1$$?
Comment: What are you talking about??
Comment: Do you mean the $(a_1+1)^{\text{th}}$ term? What is $a$?
Answer: If the arithmetic progression $a_1,a_2,\dots$ has a common difference of $d$ then the $n$th term is given by $a_1+(n-1)d$. Therefore the $(a_1+1)^{\text{th}}$ term is given by $a_1+a_1d=a_1(1+d)$, which is composite provided $a_1 \neq 1$ and $1+d\neq 1$ (i.e., $d \neq 0$). So excluding the case of a constant prime arithmetic progression (e.g., $5,5,5,\dots$), you are correct that the $(a_1+1)^{\text{th}}$ term cannot be prime provided $a_1\neq 1$.


Prove for $abc$-triples that $c\leq rad(abc)^2$

Question: Prove for $abc$-triples that $c\leq \text{rad}(abc)^2$. $\text{rad}(abc)$ and $\text{rad}(x)$ means here the product of all prime factors of $x$.
(edit 2)
The above holds for:
$16+5=21 \leq (2*5*3*7)^2$
$3^2+4^2=5^2 \leq (3*2*5)^2$
$1+99=100 \leq (2*11)^2$
I am looking for a general condition which would at least satisfy the above examples.
Comment: Is $rad(abc)$ defined as $rad(a)\cdot rad(b)\cdot rad(c)$? Or is it defined as the product of prime factors of $abc$? If $a=4,b=6,c=9$, for example, the two are different.
Comment: No, an abc-triple has to satisfy $a+b=c$, e.g., $(a,b,c)=(1,8,9)$.
Comment: If the three dots just mean rad(b) why not write rad(b)?
Comment: Okay now the question is clear, but $a=3,b=9,c=81$ would be an easy counter example.
Comment: @cr001 You're right, that expansion holds only in special cases. Corrected.
Comment: @Justpassingby Who cares, both are equivalent? Why have you written "If the three dots just mean rad(b) why not write rad(b)?" instead of "Why not replace '...' with rad(b)?"? Why would you ask questions which penetrate to someone's syntactic taste?
Comment: Oh did not know that is a specific term. Thanks for the clarification.
Comment: @DietrichBurde I am not sure what you're trying to say, still $3+9\neq 81$
Comment: Look [here](http://webusers.imj-prg.fr/~michel.waldschmidt/articles/pdf/abcLahore032013.pdf) for the term "abc-triple". Of course, $(3,9,81)$ is not an abc-triple. The numbers must be coprime, too. Only then the statement with the radical makes sense.
Comment: @DietrichBurde That's what I am trying to say. Please specify the user you're responding to by using the @ sign and the username, to avoid confusion.
Comment: @Joe The abc-conjecture has a related conjecture, namely that perhaps $c<Rad(abc)^{7/4}$ for $(a,b,c)$-triples, i.e., with $a+b=c$ and $a,b,c$ coprime.
Comment: Just if you're trying to look for which $\epsilon$ the abc-conjecture is proven, I think (maybe my knowledge is limited) that the upper bound of $c$ for the moment  is exponential, $$\log c \leq C R^{1/3}(\log R)^{3}\implies c\leq e^{(R^{1/3}\cdots)} $$ where $R=rad(abc)$ which is due to Stewart-Yu Kunrui. Anyway I don't think that you will find a counter example either because the best highest quality triple is $$
    a = 2,
    b = 310·109 = 6,436,341,
    c = 235 = 6,436,343,
    rad(abc) = 15042. $$
Comment: Continuing my comment, my last counter example gives $$c = rad(abc)^{1.62\cdots}$$ and there is no known $a,b,c$ triples such that $c\geq rad(abc)^{1.63}$
Comment: @Elaqqad Thank you guys for your comments, I appreciate those a lot. Please check out my latest edit, could you comment on it?
Comment: @Wojowu Yes I do, I'm sorry for the typo.
Answer: Currently it is unkwown whether or not there exists an $(a,b,c)$-triple, i.e., coprime numbers $a,b,c$ with $a+b=c$ and $c\ge a,b$, such that
$$
c>rad(abc)^2.
$$
So the formulation "prove that it holds" is quite unrealistic. For references on these claims see, say, here. This is closely related to the so-called "explicit" $abc$-conjecture.


Exporting two Access tables to the same excel tab

Question: I was wondering if it was possible to export two access tables to the same excel tab not just sheet. I am trying to join both tables on the same page. Does anybody know how to do this or any other solutions that could help?
Thanks!
Comment: Why not run a union query of both tables and export to worksheet? Otherwise, open tables in VBA recordsets and output to Excel range using [CopyFromRecordset](https://msdn.microsoft.com/en-us/library/office/ff839240.aspx).
Answer: If you have an relation between the tables then you can create a query in access and then export the query
Comment: They are two separate tables that do not have a relationship... I do not want them to be joined together
Comment: Then my only solution is java ; )  odbc driver and poi
Answer: Since tables are not related, use in Access VBA CopyFromRecordset to output tables to specific ranges of Excel worksheet. You will need to reference only the top left most corner cell (so be sure to account for columns and rows of tables to not overlap data):
Public Sub acToxlRecordsets()

    Dim xlApp As Object, xlwkb As Object
    Dim db As Database
    Dim frst As Recordset, srst As Recordset
    Dim strPath As String

    Set db = CurrentDb()
    Set xlApp = CreateObject("Excel.Application")

    strPath = "C:\Path\To\Excel\Workbook.xlsx"

    Set xlwkb = xlApp.Workbooks.Open(strPath)

    ' OPEN FIRST RECORDSET
    Set frst = db.OpenRecordset("FirstTable", dbOpenDynaset)
    frst.MoveFirst

    ' OUTPUT RECORDSET (SELECT TOP LEFT CORNER --CHANGE SHEET AS NEEDED)
    xlwkb.Worksheets(1).Range("A1").CopyfromRecordset frst
    frst.Close

    ' OPEN SECOND RECORDSET
    Set frst = db.OpenRecordset("SecondTable", dbOpenDynaset)
    srst.MoveFirst

    ' OUTPUT RECORDSET (SELECT TOP LEFT CORNER --CHANGE SHEET AS NEEDED)
    xlwkb.Worksheets(1).Range("J1").CopyfromRecordset srst
    srst.Close

    ' SAVE AND CLOSE EXCEL WORKBOOK
    xlwkb.Close True
    xlApp.Quit

    Set xlwkb = Nothing
    Set xlApp = Nothing
    Set frst = Nothing
    Set srst = Nothing
    Set db = Nothing

End Sub


how i can show all data from get api in flutter

Question: I have trouble displaying data, all data is received correctly from Get method, but I can not handle it to show values.
in the getDataLadder successfully received data in response.body and i can see result with print('Response Body : ${response.body}');
with this section i store data in stringResponse value , but i can't show json data in this section:
  Widget getBody() {
    var size = MediaQuery.of(context).size;
    return Container(
      width: size.width,
      height: size.height,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10)),
          color: Colors.white),
      child: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
                SizedBox(
                  width: 10,
                ),
                Text(
                  stringResponse.toString(),
                  style: TextStyle(color: Colors.black54),
                ),
                SizedBox(
                  width: 10,
                ),
                Flexible(
                  child: Container(
                    height: 1,
                    decoration:
                        BoxDecoration(color: Colors.grey.withOpacity(0.2)),
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 15,
            ),
            Column(
                children: List.generate(nardeban_data.length, (index) {
              return Column(
                children: [
                  Padding(
                      padding: const EdgeInsets.only(right: 5, left: 5),
                      child: Container(
                        decoration: new BoxDecoration(
                          image: new DecorationImage(
                            image: new AssetImage("assets/images/bg.png"),
                            fit: BoxFit.fill,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              height: 90,
                              // width: (size.width - 20) * 0.68,
                              child: Row(
                                children: [
                                  SizedBox(width: 20), // give it width
                                  Container(
                                      width: 40,
                                      decoration: BoxDecoration(
                                          color: Colors.blue,
                                          border:
                                              Border.all(color: Colors.blue),
                                          borderRadius:
                                              BorderRadius.circular(40.0)),
                                      child: Padding(
                                          padding: EdgeInsets.all(10.0),
                                          child: Text("14",
                                              style: TextStyle(
                                                  fontSize: 13.0,
                                                  fontWeight: FontWeight.bold,
                                                  color: Colors.white)))),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Container(
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          nardeban_data[index]['name'],
                                          style: TextStyle(
                                              fontSize: 14,
                                              color: Colors.black54,
                                              fontWeight: FontWeight.w400),
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Container(
                              width: (size.width - 120) * 0.32,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(10),
                                        border: Border.all(color: Colors.blue)),
                                    child: Padding(
                                      padding: const EdgeInsets.only(
                                          right: 10,
                                          bottom: 4,
                                          left: 10,
                                          top: 4),
                                      child: Row(
                                        children: [
                                          SizedBox(
                                            width: 25,
                                            height: 25,
                                            child: TextField(
                                              textAlign: TextAlign.center,
                                              keyboardType:
                                                  TextInputType.number,
                                              decoration: InputDecoration(
                                                hintText: '4%',
                                                border: InputBorder.none,
                                                contentPadding: EdgeInsets.only(
                                                  bottom: 8,
                                                  top: 3,
                                                ),
                                              ),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                  // Icon(
                                  //   Icons.notifications,
                                  //   size: 22,
                                  //   color: Colors.blue.withOpacity(0.7),
                                  // )
                                ],
                              ),
                            )
                          ],
                        ),
                      )),
                ],
              );
            })),
          ],
        ),
      ),
    );
  }

this is my json style when i get from api:
{
    "pellekan": [
        {
            "name": "1",
            "form": null,
            "to": "1000000",
            "percent": 1
        },
        {
            "name": "2",
            "form": "1000000",
            "to": 1100000,
            "percent": 2.89
        },
        {
            "name": "3",
            "form": "1000000",
            "to": 1200000,
            "percent": 4.79
        },
    ]
}

also this is my class and i difine stringResponse value out of that
 var stringResponse = [];

class ResultLadder extends StatefulWidget implements PreferredSizeWidget {
  @override
  Size get preferredSize => const Size.fromHeight(100);

  const ResultLadder({Key? key}) : super(key: key);

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

Future<String> getToken() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('login')!;
}

class _ResultLadderState extends State<ResultLadder> {
  String token = "";
  @override
  void initState() {
    // getInfo();
    getDataLadder();
    super.initState();
  }

generally, for example how i can show name in json data instead of "14" , in this below:code:
child: Text("14",
     style: TextStyle(
     fontSize: 13.0,
     fontWeight: FontWeight.bold,
     color: Colors.white))

this is getDataLadder Code :
  Future getDataLadder() async {
    print('bye');
    String token = await getToken();
    var response = await http.get(
        Uri.parse('https://mylocalapiurl.com/backend/api/v1/pellekan/main/active'),
        headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'Authorization': 'Bearer $token',
        });
    print('Token : ${token}');
    print('Response Body : ${response.body}');

    if (response.statusCode == 200) {
      setState(() {
        stringResponse = json.decode(response.body);
      });
    }

  }

nardeban ladder is one file in data folder and i add this values for show data demo (this is working):
const List nardeban_data = [
  {
    "img":
        "https://images.unsplash.com/image.jpg",
    "name": "mark wiliams",
    "takhfif": "description item"
  },
  {
    "img":
        "https://images.unsplash.com/photo-1610859923380-c8e5a13165d1?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80",
    "name": "joe mark",
    "takhfif": "description item"
  },
];```
</code>
Comment: Can you show the code inside the **getDataLadder()** method? Also show a bit of how you are populating the property called ** nardeban_data**.
Comment: @RomanJaquez i added
Answer: So now use your stringResponse since it has already been decoded into JSON, I'd create a small PODO (Plain Ol' Dart Object) to map my JSON to the data you're receiving, as in:
<code>class NardebanData {
   String? name;
   String? form;
   String? to;
   double? percent;

   NardebanData({ this.name, this.form, this.to, this.percent });

   factory NardebanData.fromJson(Map<String, dynamic> json) {
     return NardebanData(
        name: json['name'],
        form: json['form'],
        to: json['to'],
        percent: json['percent']
     );
   }
}
</code>
Inside your setState() call, then map it as such:
<code>
setState(() {

 stringResponse = json.decode(response.body);

 nardeban_data = (stringResponse['pellekan'] as List<dynamic>).map((d) => NardebanData.fromJson(d)).toList();
});
</code>
So make your nardeban_data not a const anymore, but a List of NardebanData objects:
<code>List<NardebanData> narbeban_data = [];
</code>
And when you consume it (inside of your List.generate) you could fetch the current object in the iteration, as in:
<code>children: List.generate(nardeban_data.length, (index) {
   // fetch the item in the collection by the index provided
   NardebanData dataItem = nardeban_data[index];

   // ALL YOUR WIDGET STRUCTURE HERE
   // LIKE YOUR TEXT WIDGETS AS IN:
   Text(
     dataItem.name!, // pull the data out of the dataItem using the provided properties
     style: TextStyle(
       fontSize: 14,
       color: Colors.black54,
       fontWeight: FontWeight.w400),
       overflow: TextOverflow.ellipsis,
   ),
}
</code>
Also make sure your JSON data coming from your API is consistent as far as the type of data in each field, otherwise the decoding will fail (i.e. make sure that name, form, to are Strings, and percent is a double).
See if that works for you.
Comment: You could try to cast the stringResponse into a List., as in: **(stringResponse['pellekan'] as List).map**; this is based on the sample json output you put above that there is a property called pellekan that contains the array of objects
Comment: Sure, I'll update the code; here's also a DartPad Gist so you can see how it works in real time. Just hit "Run" and see the outcome on how I'm parsing your data.

https://dartpad.dev/?c0eaeb623b66d2d7e33e9ec9920838c3
Comment: Yes that's good - but check again the values that are coming from your API - you're getting that error above because one of the properties is not the correct type - make sure they map correctly.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/242283/discussion-between-roman-jaquez-and-sara).
Comment: thank for your answer , but i have a error in setState , in this line ```nardeban_data = stringResponse['pellekan'].map((d) => NardebanData.fromJson(d))```give me a error ```nardeban_data = stringResponse['pellekan'].map((d) => NardebanData.fromJson(d))``` and ```Error: The method 'map' isn't defined for the class 'NardebanData'.``` also ```Try correcting the name to the name of an existing method, or defining a method named 'map'.```
Comment: I do not understand what you mean, can you put this in the code above?
Comment: thank you Roman , i test that but we have a issue in ```['pellekan']``` | tell me this after command flutter run : ```Error: A value of type 'String' can't be assigned to a variable of type 'int'.
        nardeban_data = (stringResponse['pellekan'] as List).map((d) => NardebanData.fromJson(d)).toList();```
Comment: by the way, i define ```stringResponse``` below ```List narbeban_data = [];``` like this , ```List stringResponse = [];``` , it's true?
Comment: mr Roman i set these class like this : ```String? name;
   String? form;
   int? to;
   double? percent```

and my last api result is like this: ```{
    "pellekan": [
        {
            "name": "first",
            "form": null,
            "to": "1000000",
            "percent": 1
        },
        {
            "name": "lastname",
            "form": "1000000",
            "to": 1100000,
            "percent": 2.899999999999954465439991
        },
        ``` but still have same error: ```unhandled Exception: type 'String' is not a subtype of type 'int?'```    :((((


Possible to resolve host name to an internal IP address from a central location?

Question: I currently have the following setup:

An internal server that has a web application running on it (ip
addresss 10.1.1.47)
Amazon Route 53 for DNS

I would like users on my internal network to be able to access the application running on the internal server using a specific url, lets call say test.admin.mysite.com
Currently I can setup the /etc/hosts file on my local OSx machine with an entry like 10.1.1.47 test.admin.mysite.com and it will work, but I would rather not have to set this on every machine on the network.  I assume that since I am using Route 53 for DNS, that I cannot direct urls to an internal IP address.
Is it possible to have test.admin.mysite.com resolve to 10.1.1.47 by configuring something in a single location?
I do very little network admin tasks, so I apologize if the answer is obvious or if I have left something out.
Comment: Do you have a router with DNS which you could use, or a spare machine?  My thoughts would be to have a DNS internally on your network to point to **test.admin.mysite.com**.
Comment: You definitely need to set this up internally in your network. While it might work in some cases if you use Amazon Route 53, the chances are better it won't.  And since the 10.x.x.x range is an internal network address there could be confusion if your clients connect to a non-office network since 10.1.1.47 cane be used by other intranets for other reasons.
Answer: You would have to set that zone test.admin.mysite.com up in whatever DNS server your internal clients use, and create an A record in it pointing to 10.1.1.47.  This will force your internal DNS server to believe it is authoritative for that zone and won't use external DNS (your Route 53 zones) to resolve it.
If you don't have an internal DNS server for your internal clients, (i.e. your clients go direct out to external DNS servers such as google's 188.8.131.52), you would need to configure some device as an internal DNS server first.  This would involve more than just setting up the DNS server, as you'd also have to set it up to forward to an external DNS server, as well as tell your clients to go to the internal server.
If you are using Active Directory a good place to create the test.admin.mysite.com zone would be on your AD DNS servers.
Answer: Go to your network administrator and ask him to add the name  "test.admin.mysite.com" and resolve it to your ip on which the application is running.
this is similar to adding an entry in your host file. But adding in the DNS home routs the requests in the network level for any computer that is trying to access this url from your internal network.


nfs partition move

Question: I have the following problem.
We have the partition /iAmAPartition mounted on ~100 client machines via NFS.
i want to move the partition somewhere else (because it's a mess) and have the files recreated automatically (the application is taking care of that).
the problem is that some of the clients are using the exported data as input in scripts.
the actual question is .... what can i do in order to make this change without breaking something ?
if i stop the nfs daemon, what will happen to the clients ? will they stall or not ?
Comment: Can you clarify your question? I don't understand what "move the partition somewhere else" means.
Answer: What will happen when you stop NFS is complicated and depends on the way the NFS partition is mounted on their machines (what options were used to mount).
It would be foolish to attempt to do this during business hours and you should schedule an outage. This give you some breathing room if something does go down or wrong due to unforeseen circumstances.
Make sure you let the users at least know you are making changes that could cause an outage.
Comment: For many reasons, the next maintenance window will be in a few months, so that's not an option :<. the exporting parameters are (ro,sync,root_squash,no_subtree_check,fsid=1)
Comment: regardless of maintenance windows, you should make sure to let your users know that you are moving the nfs share.
Comment: Also if you change the mounting point of the share you are going to break any connections to the server when the nfs service is restarted. You could alias the share to a directory then share that so it appears to be coming from the same share to the user.
Comment: Good point, but no, i don't intent to change the mounting point. if the client is constantly reading a file named "foo", in case that i delete the file probably the application will crash, but what will happen to the nfs ? will it stall ?
Comment: If the client has the nfs mounted, and you turn off the server, the nfs connection will hang. The client os will hang on any read/writes to the share and should resume when the nfs share become available. This will break something.
Comment: No. I mean to make the changes without turning off the server. Also, is there any way to make NFS "paused". By paused i mean stop sending the file updates to the client side.
Comment: What you are trying to do is going to cause outages and unexpected problems. NFS is not meant to be used in this way.
Comment: @Nikolaidis I think you should update your question with exactly what you intend to do (step by step) rather than just "move the partition somewhere else".  Do you mean you are going to move the files from /foo/whatever to /bar/whatever, then change /etc/exports to export /bar/whatever?  Do you plan to move the files from /foo/whatever to /bar/whatever, then umount /bar and remount /bar to /foo, and leave /etc/exports alone?  Also, are you using NFSv3 or v4, because what will happen will depend, especially if clients are locking files.

nfs partition move


Express $2\cos (n\theta)$ in terms of $z$

Question: How can I show that $$2\cos(n\theta)=z^n + \frac{1}{z^n}$$
if $z=\cos\theta+i\sin \theta$
Can some one help me? thx!
Comment: what you have done?
Comment: @Boris is the only one to have written a sensible comment or answer here, given the level of the question, its appearance as homework, and the lack of work shown.
Comment: How is the number $z$ related to $n$ and $\theta$? Without knowing that, it seems impossible to prove what you want to show. [One side of your desired equation has only $n,\theta$ and the other side only $z$]
Comment: what i know is that RHS is equal to the real part
Comment: I have tried to make the RHS to become 2cos(ntheta) but i dont know how to work on it
Comment: Still unclear, maybe (just a guess) $z=\cos \theta +i \sin \theta$ and the left side is the real part of the right? It still needs to be stated just what $z$ is to denote if anyone is to help here.
Comment: oh yes , i missed the part "z=cos thea+i(sin theta)"
Comment: @GillianCheung: The proof $2\cos(n\theta)=z^n+1/z^n$ will hold  if $z, n$ & $\theta$ are related as $$z+\frac{1}{z}=2\cos\theta\iff z=\cos\theta\pm i\sin\theta$$
Answer: Starting from the Euler's formula $$z=\cos\theta+i\sin \theta$$ and from De-Moivres theorem $$\color{red}{z^n=\cos(n\theta) +i\sin(n\theta)=e^{in\theta}}\tag{1}$$ therefore $$\color{blue}{\frac{1}{z^n}=(\cos (n\theta)+i\sin(n\theta))^{-1}=\cos(n\theta)-i\sin(n\theta)=e^{-in\theta}}\tag{2}$$ since $\cos(-n\theta)=\cos(n\theta)$ and $\sin(-n\theta)=-\sin(n\theta)$
Finally, add equations $(1)$ and $(2)$:
$$\require{enclose}\cos(n\theta)+\enclose{updiagonalstrike}{i\sin(n\theta)}+\cos(n\theta)\enclose{updiagonalstrike}{-i\sin(n\theta)}=2\cos(n\theta)=\frac{1}{z^n}+{z^n}$$
Answer: Since $z=e^{i\theta}$, $z^n=e^{in\theta}=\cos(n\theta)+i\sin(n\theta)$.  Similarly, $z^{-n}=e^{-in\theta}=\cos(-n\theta)+i\sin(-n\theta)=\cos(n\theta)-i\sin(n\theta)$ since $\cos$ is even and $\sin$ is odd.
Answer: setting the value of $z=\cos\theta+i\sin \theta$, one should have  $$z^n+\frac{1}{z^n}=(\cos\theta+i\sin\theta)^n+\frac{1}{(\cos\theta+i\sin\theta)^n}$$
$$=(\cos\theta+i\sin\theta)^n+(\cos\theta+i\sin\theta)^{-n}$$
using De-Moivre's theorem,
$$=\cos(n\theta)+i\sin(n\theta)+\cos(-n\theta)+i\sin(-n\theta)$$
$$=\cos(n\theta)+i\sin(n\theta)+\cos(n\theta)-i\sin(n\theta)$$
$$=2\cos(n\theta)$$ or $$2\cos(n\theta)=z^n+\frac{1}{z^n}$$
Comment: @HarishChandraRajpoot Nothing is wrong, some people just downvote answers for no reason I have upvoted your answer and Michaels answer also
Comment: could someone please explain what is wrong in the answer?


is there any way to make the webform components labels translatable?

Question: Just wondering how to make the webform components labels translatable.
I found this post with a link to a sandbox project but I don't where to download the module: Make Webform multilingual (i18n) aware through contributed modules
I also find this function to just make what I need but it doesn't work, maybe with a few change it will work: Source: work around
function module_name_form_webform_client_form_xx_alter(&$form, &$form_state) {
  foreach (element_children($form['submitted']) as $element) {
    // Pass each webform component title through the t() function.
    $form['submitted'][$element]['#title'] = t($form['submitted'][$element]['#title']);
  }
}

The function provided  by @lenni does the job but I get these error messages.

Warning: strlen() expects parameter 1 to be string, array given en
  drupal_validate_utf8() (línea 1600
  de/Applications/MAMP/htdocs/tonisacristan.com/includes/bootstrap.inc).
Notice: Array to string conversion en filter_xss() (línea 1366 de
  /Applications/MAMP/htdocs/tonisacristan.com/includes/common.inc).
Notice: Array to string conversion en format_string() (línea 1552 de
  /Applications/MAMP/htdocs/tonisacristan.com/includes/bootstrap.inc).

The source of the problem is a Markup component. This function is working fine.
function webform_extras_node_view($node, $view_mode, $langcode) {
  if($node->type == 'webform' && $view_mode == 'full') {
    // translate the webform component labels
    foreach(element_children($node->content['webform']['#form']['submitted']) as $key){
      //to skip Markup components
      if($key != 'my_markup_component'){
        $node->content['webform']['#form']['submitted'][$key]['#title'] = t($node->content['webform']['#form']['submitted'][$key]['#title']);
      }
    }
  }
}

Answer: Similar (a litte bit more generic) solution but still not a clean one:
function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'webform' && $view_mode == 'full') {
    // translate the webform component labels
    foreach(element_children($node->content['webform']['#form']['submitted']) as $key){
      $node->content['webform']['#form']['submitted'][$key]['#title'] = t($node->content['webform']['#form']['submitted'][$key]['#title']);
    }
  }
}

Comment: It does the job, but I get some error messages. I added these message at the bottom of my question. Can you help with this?
Comment: Are you sure the errors are related to this workaround?
Comment: Yes, the source of the problem is a Markup component. I added 1 more line to your function. See it at bottom of my question.
Answer: And if you actually want to translate your markup fields as well, which is often the case:
function mymodule_node_view($node, $view_mode, $langcode) {

  if ($node->type == 'webform') {
    // translate the webform component labels
    foreach(element_children($node->content['webform']['#form']['submitted']) as $key){
      if($key != 'your_markup_component' && $key != 'your_markup_component_2'){
        $node->content['webform']['#form']['submitted'][$key]['#title'] = t($node->content['webform']['#form']['submitted'][$key]['#title']);
      }
      else {
        $node->content['webform']['#form']['submitted'][$key]['#value'] = t($node->content['webform']['#form']['submitted'][$key]['#value']);
      }
    }
  }
}


Mysql query to update row if exists?

Question: I need an If, then, else query in mysql,
tried out the below,
if exists( select * from data_table where user_id =1 and link_id = 1) then update data_table set is_view = 1 where user_id = 1 else insert into data_table...

what is the correct way to do this?
Comment: possible duplicate of [SQL - IF EXISTS UPDATE ELSE INSERT INTO](http://stackoverflow.com/questions/15383852/sql-if-exists-update-else-insert-into)
Answer: if you only need to do this in mysql, then search insert on duplicate key. Or you can use a stored procedure. Check INSERT ... ON DUPLICATE KEY UPDATE Syntax
Answer: insert into data_table (user_id, link_id, other_column)
values (1, 1, 'value to insert or uodate')
on duplicate key update  other_column='value to insert or update';

Mysql query to update row if exists?


let $f, g$ be two polynomial such that : $f(0)=-24 \ \ , \ \ g(0)=30$ and $\forall x \in \mathbb{R} : \ \ f(g(x))=g(f(x))$

Question:
let $f, g$ be two polynomial such that : $f(0)=-24 \ \  , \ \  g(0)=30$
and $$\forall x \in \mathbb{R} : \ \ f(g(x))=g(f(x))$$
then fine  :
$$ (f(3),g(6))=?$$

since :
$$\forall x \in \mathbb{R} : \ \ f(g(x))=g(f(x))\\f(g(0))=g(f(0))=f(30)=g(-24)\\f(g(3))=g(f(3))\\f(g(6))=g(f(6))$$
now:
$$f(g(6))=g(f(6))\to f(g(2\cdot3))=g(f(2\cdot3))$$
now what ?
Comment: What does $( \cdot, \cdot )$ mean here?
Comment: So far I have only been able to show that there exists two polynoms $P$ and $Q$ such that $Pf-Qg+6=0$
Comment: Is there any restriction on the coefficients of $f,g$? real, rational, integer?
Answer: I shall assume that we want $f,g\in \Bbb Z[X]$ (or else $\gcd(f(3),g(6))$ make little sense).
If $g$ is constant, we need $f(30)=30$, but then $f(30)-f(0)=54$ is not a multiple of $30$, contradiction.
Similarly, if $f$ is constant, we need $g(-24)=-24$, but then $g(-24)-g(0)=-54$ is not a multiple of $-24$, contradictiom.
We conclude that neither $f$nor $g$ is constant.
Write  $f(x)=a_nx^n+a_{n-1}x^{n-1}+\ldots$ and $g(x)=b_mx^m+b_{m-1}x^{m-1}+\ldots$ with $a_n, b_m$ non-zero and $n\ge 1$, $m\ge 1$.
Then
$$f(g(x))=a_nb_m^nx^{nm}+\ldots \qquad g(f(x))=b_ma_n^mx^{nm}+\ldots. $$
Equality is possible only in the following cases:

$n=m=1$, $a_n,b_m$ arbitrary
$n=1$, $a_n=1$, $b_m,m$ arbitrary
$m=1$, $b_n=1$, $a_n,n$ arbitrary
$a_n=b_m=1$, $n,m$ arbitrary.

In the first case, $f(X)=aX+30$, $g(X)=bX-24$, $f(g(X))=abX-24a+30$, $g(f(X))=abX+30b-24$, so in this case a necessary and sufficient condition is that $5b+4a=9$.
We can parametrize this as $a=5k+1$, $b=-4k+1$.
Then $f(3)=3a+30=15k+33$, $g(6)=6b-24=-24k-18$.
From $8f(3)+5g(6)=174$, we conclude $\gcd(f(3),g(6))\mid 174=2\cdot 3\cdot 29$.
On the other hand, clearly $3\mid \gcd(f(3),g(6))$.
We have $2\mid \gcd(f(3),g(6))$ iff $k$ is odd.
We have $29\mid f(3)\iff k\equiv 21\pmod {29}$ and also $29\mid g(6)\iff k\equiv 21\pmod{29}$.
In summary, the case of linear $f,g$ allows the following values for $\gcd(f(3),g(6))$:

$3$, for example with $f(X)=X+30$, $g(X)=X-24$
$6$, for example with $f(X)=6X+30$, $g(X)=-3X-24$
$87$, for example with $f(X)=251X+30$, $g(X)=-199X-24$
$174$, for example with $f(X)=106X+30$, $g(X)=-83X-24$

In the second case, $f(X)=X+30$, so $g(X+30)=g(X)+30$; it follows that $g(X)-X$ has period $30$, hence must be constant. This takes us back to the first case.

In the third case, $g(X)=X-24$, so $f(X-24)=f(X)-24$, and again we end up in the first case.

In the fourth case, we may assume $n\ge 2$ and $m\ge 2$.
This might be treated by consideraing the intermediate coefficients of $f(g(X))=g(f(X))$. (But at least it is still clear that $3\mid f(3)-f(0)$ and $6\mid g(6)-g(0)$, so $3\mid\gcd(f(3),g(6))$).
Comment: So the bracket stands for $\gcd$?
Comment: Why can't we have the case of $a_n = 1, b_m = -1, n,m$ odd? EG $x^3, -x^3$ commute? $\quad$ In fact, the condition of $|a_n | = |b_m | = 1 $ isn't needed either, eg $ 2x^3, -2x^3$. $\quad$ From just comparing those coefficients, all that we have is $a_nb_m ^n = a_n^m b_n$, which could have numerous solutions.
Answer: $f(x) = x-24$ and $g(x) = x+30$ satisfy the conditions. These give $f(3) = -21$ and $g(6) = 36$.


C- an ADT that keeps crashing

Question: I'm trying to create an ADT ,
first of all, here is the basic information about it:
typedef struct orange_t* Orange;

typedef enum {
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC,
} Month;

struct orange_t {

short size;
Month expirationMonth;
char** foodCompanies;
int maxNumberOfFoodCompanies;
int sellingPrice;
};

now im trying to create a function that will "create" new orange like that:
Orange orangeCreate(short size,Month expirationMonth
    ,int maxNumberOfFoodCompanies,int sellingPrice)
 {
   Orange new_orange=(Orange)malloc(sizeof(struct orange_t));
   if(new_orange==NULL)
   {
        return NULL;
    }
   if((sellingPrice<0)||(size>256||size<1)||(maxNumberOfFoodCompanies<0)||(expirationMonth>12)
        ||(expirationMonth<1))
        {
        return NULL;
        }
new_orange->sellingPrice=sellingPrice;
new_orange->maxNumberOfFoodCompanies=maxNumberOfFoodCompanies;
new_orange->expirationMonth=expirationMonth;
new_orange->size=size;
for(int i=0;i<new_orange->maxNumberOfFoodCompanies;i++)
{
    new_orange->foodCompanies[i]=NULL;
}
return new_orange;
}

when I tried to check the function with the simple main():
int main()
{
Orange orange=orangeCreate(3,JAN,10,4);
printf("the size is %d\n",orange->size);
orangeDestroy(orange);
return 0;
}

the program keeps crashing, I guess I didn't change the values in orange as I should, and they might still be NULL.
where did I go wrong here?
Comment: You are not allocating `foodCompanies` anywhere, but trying to index and assign it.
Comment: in C, the returned value from `malloc()` and family of functions is type `void *`, which can be assigned to any other pointer.   Casting the return type is completely unnecessary and leads to difficulties when debugging and or maintaining the code.   The typedef name `Orange` is misleading as it is actually a pointer type.   Much better to typedef is as just `struct orange_t` with no pointer, then add the '*' as necessary in the body of the code.
Comment: an enum starts with 0 (unless specifically defined otherwise) so the check for the `expirationMonth` is not correct, unless the enum is modified so the first entry is: `JAN=1,`
Answer: JAN is 0. if expirationMonth<1 you are returning NULL from orangeCreate.
Also: you are not checking the return value of orangeCreate. And you are leaking memory in orangeCreate when you are just returning NULL without freeing the allocated new_orange.
Answer: The problem is that you are not allocating memory for char** foodCompanies;

While allocating memory here
Orange new_orange=malloc(sizeof(struct orange_t));

You have allocated space for the pointer variable char** foodCompanies;, but have not allocated space where it would point to.
Answer: You have to allocate some memory and store the address of it to new_orange->foodCompanies before accessing it.
Possible fix:
Orange orangeCreate(short size,Month expirationMonth
    ,int maxNumberOfFoodCompanies,int sellingPrice)
 {
   Orange new_orange=malloc(sizeof(struct orange_t));
   if(new_orange==NULL)
   {
        return NULL;
    }
   if((sellingPrice<0)||(size>256||size<1)||(maxNumberOfFoodCompanies<0)||(expirationMonth>12)
        ||(expirationMonth<1))
        {
        return NULL;
        }
new_orange->sellingPrice=sellingPrice;
new_orange->maxNumberOfFoodCompanies=maxNumberOfFoodCompanies;
new_orange->expirationMonth=expirationMonth;
new_orange->size=size;
new_orange->foodCompanies=malloc(sizeof(char*)*new_orange->maxNumberOfFoodCompanies); /* add this line */
for(int i=0;i<new_orange->maxNumberOfFoodCompanies;i++)
{
    new_orange->foodCompanies[i]=NULL;
}
return new_orange;
}

Note: it is discouraged to cast the result of malloc() in C.
c - Do I cast the result of malloc? - Stack Overflow

C- an ADT that keeps crashing


Why can my AutoHotkey script only type some emoji?

Question: I have set up a small AutoHotkey script that uses hotstrings to allow me to type a few emoji and other special characters:
<code>#SingleInstance force

#Hotstring * ?

::–::–
::†::†

::π::

::&shrug;::¯\_(ツ)_/¯
::&tm;::™
::&c;::©
::&r;::®
::&tableflip;::(╯°□°)╯︵ ┻━┻
::&music;::♫
::&piano;::
::&cmark;::✓
::&xmark;::✗
::&hourglass;::⌛
</code>
The script is also available on PasteBin.
It all works in my text editor:

However, some replacements don't work everywhere, for example in Telegram Desktop:

Both emoji were originally copied from Telegram Desktop, so they are definitely supported in it.
Why isn't this working as expected?
I'm running AutoHotkey Unicode 64-Bit in version 22.214.171.124 on Windows 10 (version 1511), Sublime Text 3 (3103) and Telegram Desktop 0.9.28.
Comment: @fefrei, the problem with this and some other programs is in how they process input. They don't just take keystrokes like a normal program, they process every key you press, which interferes with AHK's ability to send keys. You can try the different send modes (input, event, play, raw), and different delays, but as others have found, you might have to resort to just using the clipboard.
Comment: I'm a bit afraid that this is some Unicode problem that is lost when the code is processed by Stack Overflow, but I provided an inline copy nonetheless.
Comment: I fixed this problem by opening by script in windows notepad and saving. I normally work in notepad++ (UTF-8) but apparently something wasn't saving properly.
Comment: @jiggunjer you need to make sure the file has the Byte-Order-Mark.
Answer: I answered a similar question in the past: Autohotkey Replace 2 specific character with one
I don't really know what the problem was, but we managed to get around the problem by making use of the clipboard. Maybe the same method can be used for your scenario.
Comment: That works for me – thanks! I'd still love to know the underlying problem, though...
Comment: For that we'd have to find out what input methods both the clipboard and autohotkeys hotstrings are using.
Comment: Just an idea: Autohotkey has several ways of sending text. It's possible that your Telegram Desktop handles them differently. Try `Send`, `SendInput` and `SendPlay`, `SendEvent`. They all share the same syntax. And then there is `ControlSend`, `ControlSetText` and `PostMessage`/`SendMessage`. Those are definitely more complicated to use, but maybe they'll do the trick.
Comment: I tried the four basic methods – none of them work, but some break even in my text editor.
Comment: Can you summarize or quote your linked answer?


How do I test hypothesis of slope = 1 and intercept = 0 for observed vs. predicted regression?

Question: I have two columns of data: Observed (Obs) and Predicted (Pred), each column having 23 data. I have plotted Observed on y-axis and Predicted on x-axis (as pointed by Pineiro et al., 2008). On deriving a best fit linear model for the data, I have obtained:
$$Obs = 0.21 + 1.09 * Pred
$$
It is well known that in the ideal case, the equation should have been:
$$Obs = 0.00 + 1.00 * Pred
$$
Pineiro et al. (2008) [Link available on top], on page 4 [Eq. (9)], suggest:

We tested the hypothesis of slope = 1 and intercept = 0 to assess statistically the significance of regression
  parameters. This test can be performed easily with statistical
  computer packages with the model:

$$ Pred - Obs = a + b* Pred + \epsilon
$$
The significance of the regression parameters of this
models corresponds to the tests: b = 1 and a = 0.
Please help on how do I conduct these tests so that I can compare the slope ($b$) with 1 and intercept ($a$) with 0. Also I am not able to get the basic concept behind proposing the model shown above.
Comment: Unless I completely misunderstand its notation, that paper is so seriously and fundamentally flawed it ought to be ignored by everyone.  Consult any multiple regression textbook for better approaches.  Model (8) is merely a version of performing the same regression all over again while Model (9) strongly violates OLS assumptions (since the predictor appears as both regressor and response, the errors are strongly intercorrelated).  Performing the suggested tests "with statistical computer packages" will produce utterly worthless results.
Answer: You can attain something similar using offset in R:
a = 1; b = 0

set.seed(123)
x = rnorm(1000)
y = a*x+b+rnorm(1000)/100

fit = lm(y~1+x+offset(x))
summary(fit)

#Coefficients:
#             Estimate Std. Error t value Pr(>|t|)
#(Intercept) 0.0004105  0.0003183   1.290  0.19751
#x           0.0008805  0.0003211   2.742  0.00621 **
#---
#Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Basically we are regressing $y=A\cdot x+x+B+\epsilon=(A+1)\cdot x+B+\epsilon$, so if $H_0:A=0$ is rejected we can safely say the slope is not equal to 1. The test for the intercept remains unchanged.
But surely, it seems worthless: with enough data you will almost always reject the null hypothesis, as you get smaller and smaller standard errors, and any small deviance from zero becomes significant.

Other approach with the same result:
fit = lm(y~1+x)
library(car)
linearHypothesis(fit, "x = 1")
#  Res.Df     RSS Df  Sum of Sq    F   Pr(>F)
#1    999 0.10184
#2    998 0.10108  1 0.00076165 7.52 0.006211 **

Comment: If you add the lmtest package, your offset model can be modified to fit the proper null model y~ offset (x) - 1. Then a 2 degree of freedom Wald or likelihood ratio test can be conducted using nested models.
Comment: @AdamO I think the null hypothesis is a bit more involved than here. You'd be jointly testing both coefficients. But I've read the concern voiced by whuber, and the result is the same in my asnwer. Add an answer and let's compare :)
Comment: @AdamO you mean it like this, correct?
`fit1 = lm(y~0+offset(x));

fit2 = lm(y~x);

anova(fit1, fit2)`
Answer: This depends in part on what software you are using.  In R you can use the ellipse package to generate a confidence ellipse on the intercept and slope and see if the point 0, 1 is in the ellipse.
For a general approach (not quite as good as the ellipse approach, but will work in any software that does regression):
Compute a new column that is the difference between observed and predicted.  Use this column as the y-variable and your predicted column as the x-variable.  Now look at the individual tests of the intercept and slope, if either is significant then you should reject your null of 0,1.  You may also want to look at the correlation between the estimated intercept and slope, if that is high (in absolute value) then you may want to rerun with your predictions (x-variable) centered.
Comment: @user3024069, Friends don't let friends use Excel for Statistics (https://oit.utk.edu/research/documentation/Documents/ExcelStatProbs.pdf and http://www.burns-stat.com/documents/tutorials/spreadsheet-addiction/).  I would not even think to attempt the ellipse approach in Excel, it is worth learning R for that part alone.  But the general approach mentioned above "should" work in Excel, just create the new column that is the difference between the 2 methods to use as the y/response/dependent variable.
Comment: As I am not well-versed in this area; if possible, please give necessary equations to be used, or some suitable link. If it can be done on Excel, it would be very helpful.
Comment: Thanks for the timely advice! Could you suggest where to start for learning R?
Comment: @user3024069, https://www.r-project.org/, follow the "CRAN" link for downloading R, Then start reading under the "Documentation" links.
Comment: There are some decent intros in Udacity, Coursera, or similar.


How to show message view containing own and following activity?

Question: I have created a message view using the Message module. I want this view to show the current user activity and activity of the user he is following using the "follow" flag (user). i.e own + following.
The Message module comes with a "message subscribe" flag, but I do not want to use that. What should be the setting of my view particularly the relationship and contextual filters?
Answer: About the Message module and user activity
Even though you're question doesn't really say so, I'm assuming that:

"activity" in this question is about message instances created by the Message module, targeted to the current user.
"activity of the user he is following" is about message instances target to the current user (also), though they are about events related to any of the followed users (indicated by your follow-flag).

If these assumptions are correct, then your question is about creating a view of various flavors of messages (typically created using various Message Types), which are all targeted to the current user.
Creating a view about Messages by user
Add a new view

View name "Messages by user".
Show Message.
Type All.
Create a page (not a block)

Create a table display of this view
For this question here, you only need a single table display, of All messages.
To differentiate this "All", think of additional displays you might want to add later on, such as:

Read messages
Unread messages

Add Contextual Filters

Message: User uid, and for "When the filter value is NOT in the URL" use "Provide default value" with Type "User ID from logged in user".

Add Relationships
"Message: User uid" will result in the messages targeted to the current user, so that one you need for sure.
I suggest you create a first display only using the above relationship (to check the results you get so far). Then clone this display into another one, in which you add another relationship like "Flags: follow (by current user)" (assuming that follow corresponds to your follow-flag). By swapping between the 2 displays, you can decide which one you really want, or just keep both.
Add Fields

Message: Message ID (Msg ID)
Message: Timestamp (Created on)
Message: Render message (Get text) (Text)
(User) User: Name (User), and use "Exclude from display" for this field, which is only needed to add a "Global: Text area" to the views headers which contains something like Messages for user [name].

Add Sort criteria

Message: Timestamp (desc)

Further Refinements

Filter criteria: none
Page settings:

Path: /user/%/messages
Menu tab: Messages

Make the Messages manage-able
If you complete the above steps, you'll have a view that shows all relevant messages ... and that's really it. It won't be obvious for a user to remember which messages have been read already, and which ones are new (= unread). Try it for yourself (to experience the pain ..).
To implement a facility to mark messages as read/unread, just perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

Create a flag (using the the Flag module).
Create a view 'Messages by user' (= improved version of the view specifications described above).
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module). So that whenever a new message gets created, the user gets a notification in the format of an iOS-like (red) badge with the number of unread messages.

Fruit of your labor
If you follow the above steps, the result of it is something similar to an eMail client inbox, whereas the eMail "messages" are not real eMails, but instances of messages created by the Message module.
Comment: looks good. I will try
Comment: I tried both scenarios mentioned in "Add relationship" section above, but not working as i want. 1. The **"Message: User uid"** is showing only current user activity. 2. Then i tried **"Flags: follow (by current user)"** with **"Message: User uid"** in contextual filter, it was showing only current user activity. Then I removed it from contextual filter. The view showed activity of all users including who I am not following. Then I checked "include only flagged content" and it was showing messages from users I am following.
Comment: Both "current user activity" and "activity of user flagged" should show in a single view.
Comment: What if we can do it in rules. In the "user for which to log the message", the user who flagged the content author should only see the activity message. What do you say? I think it is better approach. It is better because if we use the approach from the answer, when someone starts following you with the follow flag, that activity is logged for you. Now the user who is following you, will also receive the message log as he is following you. Even though the message log was only concerned to you.


Checking PH assumption using scaled Schoenfeld residual tests

Question: My cox model violates the PH assumption (according to cox.zph test), and I'm trying to interpret the scaled Schoenfeld residual plot, but I've never seen a plot with points lying in such a flat manner. I'm wondering what the beta(t) means and if it's possible that almost all the points, across time, have almost the same values...
I'd appreciate any help!
Comment: What is plotted here? Is Beta(t) the df-beta for a Cox time-to-event model with one covariate (sex)? What code gave you this graph?
Comment: model<-coxph(Surv(time, status) ~ sex, data)   then
ggcoxzph(cox.zph(model)) was the code!
Answer: The Schoenfeld residuals take the difference between the scaled covariate value(s) for the i-th observed failure and what is expected by the model.
So for your model, you have a single binary covariate sex which takes values 0 or 1. Supposing there is 0 association and supposing sex is balanced in the sample, the "expected" covariate would be 0.5, that is, any given event is equally likely to have belonged to either a male or a female at any time. This amount can be offset by the number of males or females in the overall sample or whether they are right censored and entered into the sample in a staggered fashion. The lack of variability and association in the covariate is what's essentially being reflected in the plot.
For the smoothing spline that trends somewhat upward, we are clued into a possible accelerated failure time effect ($\beta(t) \ne 0$). A tried-and-true sensitivity analysis would be to inspect a Kaplan-Meier plot for binary sex and inspect whether the survival curves cross in the sample.
We can simulate this using the simple result that an exponential random variable has a constant hazard whereas a Weibull model has a linear hazard that is not flat when the shape is not 1.
Take:
<code>set.seed(123)
group <- rep(0:1, each=1000)
t1 <- rexp(1000)
t2 <- rweibull(1000, 2, 1/gamma(1+1/2))
t <- c(t1, t2)
par(mfrow=c(1,2))
plot(survfit(Surv(t) ~ group), col=1:2, xlab='Survival time', ylab='Surviving proportion')
fit <- coxph(Surv(t) ~ group)
summary(fit)
proph <- cox.zph(fit)
proph
plot(proph)
</code>
Gives:
<code>> summary(fit)
Call:
coxph(formula = Surv(t) ~ group)

  n= 2000, number of events= 2000

         coef exp(coef) se(coef)     z Pr(>|z|)
group 0.10060   1.10584  0.04675 2.152   0.0314 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

      exp(coef) exp(-coef) lower .95 upper .95
group     1.106     0.9043     1.009     1.212

Concordance= 0.465  (se = 0.007 )
Likelihood ratio test= 4.64  on 1 df,   p=0.03
Wald test            = 4.63  on 1 df,   p=0.03
Score (logrank) test = 4.63  on 1 df,   p=0.03
</code>
i.e. a marginally significant hazard ratio because the expected failure time is close to exactly equal. However, the exponential model shows more earlier failures and this tends to power Cox models.
The failure time averaged hazard ratio comes out to 1.1. It should be noted this is the correct interpretation, there's nothing wrong with the estimate it's telling us exactly what's in the data. If you use the robust=TRUE option, the 95% CI is correct and there's no reason to discredit the Cox model except that possible answers to the general question: which group survives better, may have better, more nuanced answers. Thus is the result of any sensitivity analysis, rather than "invalidating models".
As we see, the proportional hazards test is highly significant.
<code>> proph
        rho chisq        p
group 0.325   230 6.19e-52
</code>
And the plot is similar to yours. My example shows more extreme trends because I have exaggerated the accelerated failure time effect in the Weibull model. This is mostly to illustrate the reason why we see a temporal trend in the smoothing, and you also see the "parallel groups" for covariate values both high and low.
Comment: Thank you so much for the answer!!!!I'm using retrospective data in which participants were followed up about five years after the initial survey, and at that point, some people had experienced the event of interest, and they recorded (retrospectively) the month that event occurred. But I realized now that this means for those who hasn't experience the event ("survivors"), "time" variable would be how many months have passed since the last survey and would not have as much variability (the minimum being like 52 months...). I guess this isn't data I could use Cox!!  Thanks ALOT


How to mount an NFS share in a VM guest?

Question: We have a machine with Win7-x64 installed. On this machine, with VirtualBox, we're running a guest Fedora-x64. We've defined an NFS share on this Fedora instance. Here is the entry in /etc/exports:

/dvr 192.168.0.0/192.168.255.255(rw)

The ip address of the windows machine is, 192.168.1.100, the ip address of the Fedora guest is 192.168.1.110. The networking mode of the VM is set to be bridged networking.
Now, from another linux box, when we ping the Fedora guest (192.168.1.110), we get responses just fine. However, when we try to mount the nfs share, we get a "no route to host" error. The command we use is:

mount -t nfs 192.168.1.110:/dvr /mnt/test

Just to make sure there are no iptables issues, on the fedora guest, we did:

service iptables stop

and re-tried to mount, to no avail.
Any ideas what might be wrong in our setup? All these machines are connected to each other through a hub. A linksys router is configured as a DHCP server, from which all the machines grab an ip address.
Thanks.
Answer: Fedora uses firewalld as the firewall these days. Stopping iptables directly is not the correct way to stop the firewall. Try systemctl stop firewalld.service instead.
You have started the NFS service on the Fedora VM haven't you?
You'd do that by running systemctl start nfs.service on the VM.
If you've changed the /etc/exports file since starting the nfsd, then you need to either systemctl restart nfs.service or re-export filesystems with the exportfs -a command.
Answer: I know this question is a bit old, but I think it's still relevant. Setting up NFS mounts can be tricky because it consists of several components, so there's more than one port that must be opened in the firewall. Also, Fedora uses firewalld, so there's no service called "iptables".
I'm assuming you have your exports defined correctly on the NFS server (TLDP documentation), which is another Fedora box. Don't forget to run exportfs -ra after editing /etc/exports. It might as well be your vm host running VirtualBox (to set up a file share between the host and the guest without having to install and maintain the guest additions package), it doesn't make a difference.
Trying to mount an NFS share on your "client", you might encounter a timeout:
# mount -v Share/
mount.nfs: timeout set for Tue May 22 15:40:52 2018
mount.nfs: trying text-based options 'vers=3,addr=192.168.56.1'
mount.nfs: prog 100003, trying vers=3, prot=6
^C

RPC needs to work (must be able to communicate) for NFS to work. In this case, it can't connect to the NFS server (192.168.56.1 is a default ip address of the VirtualBox host system, replace it with the ip of your NFS server):
# rpcinfo -p 192.168.56.1
rpcinfo: can't contact portmapper: RPC: Remote system error - No route to host

To stop the firewall from blocking NFS on the server (vm host or separate server), you should not disable it, effectively allowing everything. You need to identify the network interface through which the client connects. If it's not assigned to a firewall zone, pick one that's appropriate (probably not "public"). Then allow NFS in that zone.
Identify the network interface (the following commands are to be run on the server):
# ip address
...
6: vboxnet0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 0a:00:27:00:00:00 brd ff:ff:ff:ff:ff:ff
    inet 192.168.56.1/24 brd 192.168.56.255 scope global vboxnet0
       valid_lft forever preferred_lft forever

In this example, the client connects to 192.168.56.1, so vboxnet0 is the correct interface on that host.
Identify the firewall zone this interface is assigned to.
# firewall-cmd --get-zone-of-interface vboxnet0

If that's "no zone", you'll need to pick one and assign it yourself. For example "internal", to make it obvious that NFS should not be allowed on external interfaces.
# firewall-cmd --add-interface=vboxnet0 --zone=internal

If you now list all the interfaces in the "internal" zone, "vboxnet0" should show up:
# firewall-cmd --list-interfaces --zone=internal
vboxnet0

Enable those "services" (i.e., open the ports) that are required by the NFS server.
# firewall-cmd --add-service nfs --zone internal
# firewall-cmd --add-service mountd  --zone internal
# firewall-cmd --add-service rpc-bind --zone internal

Double-check that those services are enabled for nics in the "internal" zone:
# firewall-cmd --list-services --zone internal
ssh mdns samba-client dhcpv6-client nfs ntp mountd rpc-bind

If this firewall on the server was blocking NFS, it should work now. Or maybe it doesn't because you have another firewall in the network. However, this is about Fedora and its firewalld.
Last but not least: All of the changes made by the commands listed above are temporary. Only the runtime configuration has been changed (because --permanent has not been used). If you've made a mistake, all your changes will be gone after restarting firewalld.
If you want to keep your changes, you need to save them to the permanent configuration (firewalld documentation):
# firewall-cmd --runtime-to-permanent

Answer: /etc/exports expects an IP address, optionally followed by a CIDR or old-style netmask.
So you need to change it to one of:
/dvr 192.168.0.0/255.255.0.0(rw)

or:
/dvr 192.168.0.0/16(rw)

(Hostnames can also be used, but that's not relevant here.)
Comment: thanks for the very fast response. We tried that as well without success. We also tried 255.255.255.0, with no success. After each change to /etc/exports, we did a "service nfs-server restart". Do we have to do anything else?
Comment: Just to be clear, it should be "/dvr 192.168.1.0/255.255.255.0(rw)", correct? This would make 192.168.1.0-192.168.1.255 to be available?
Comment: If that's the network you want to be accessible, then yes.
Comment: Hmm. still no go. Any more ideas? Just noticed that, running rpcinfo -p 192.168.1.110 on the linux machine results in "can't contact portmapper". However, on the linux guest, portmapper service seems to be running.
Comment: You have a network or firewall issue, then.
Comment: Turned off iptables on the guest linux. Turned off Windows Firewall (in case it matters, I didn't think so, but just to be safe). Could this be a problem because my nfs server is running in a VM?
Comment: No, you can run an NFS server in a VM just fine.


Returning max value of multiple related rows and incorporate data from another table (SQL Server 2005)

Question: I need to return data from two tables - one table contains records on a one-to-one level (TableB) and the other contains records on a one-to-many level (TableA). From the one-to-many table I only want to return one row for each unique CustomerAccountNumber, and I want to base the criteria on which record from the one-to-one table has the highest DollarAmount value. So even though the link between the tables is the RequestNumber, I am mainly concerned with the CustomerAccountNumber column (don't even need RequestNumber in the results).
Just having a hard time wrapping my head around the logic needed to get the desired result. I searched through some other max() function questions here but couldn't find anything that does quite what I'm looking for. This is my first post here, so I'm open to any constructive feedback about my pre-question searching and/or question structuring :)
Sample Data
TableA: one-to-many

RequestNumber    CustomerAccountNumber
12345            987456
54321            987456
32145            987456

TableB: one-to-one

RequestNumber    DollarAmount
12345            13000
54321            15000
32145            17000

Desired output after query (w/ 32145 having the highest DollarAmount value

CustomerAccountNumber    DollarAmount
987456                   17000
Answer: <code>SELECT  customerAccountNumber, dollarAmount
FROM    (
        SELECT  *,
                ROW_NUMBER() OVER (PARTITION BY customerAccountNumber ORDER BY dollarAmount DESC) rn
        FROM    tableA a
        JOIN    tableB b
        ON      b.requestNumber = a.requestNumber
        ) q
WHERE   rn = 1
</code>
Comment: Wow, I had never heard of the row_number() function, thanks so much, that did the trick!


Identification assumptions and causal relationships

Question: I'm new to econometrics and I'm having a hard time answering if the following statement is true or false:
"In regression studies, making adequate identification assumptions is sufficient for identifying causal relationships between the variables of interest"
After some reading, I've come to this answer:
-Strucutural conditional expectation allows us to draw a causal inference
-If we cannot collect data on some variables, we can use identification assumptions to recover the structural conditional expectation
-So, if we make the adequate identification assumptions, we can draw a causal inference -> the statement is true.
Could someone please shed some light on this?
Comment: Related https://stats.stackexchange.com/questions/377004/regression-and-causality-in-econometrics
Answer: "Making adequate identification assumptions is sufficient for identifying causal relationships" is either tautologically true or obviously wrong. It is true if by "adequate identification assumptions" you mean "assumptions that identify a causal effect".
If you mean "adequate" in the sense of "substantively adequate", then of course making such identification assumptions does not always guarantee that you can identify a causal effect. This is what most discussions in the social sciences are about: People question the validity of identification assumptions, state that they should be weakened, and then argue that for this reason, the effect is not identified.
To give a short definition of causal identification, it means you can write a causal parameter in terms of the probability distribution of the observable variables.
E.g., when you think the causal effect of $X$ on $Y$ is a constant $\beta$, one may identify it with $cov(X, Y)/(var(X))$, the coefficient of a linear regression of Y on X, assuming $E[\epsilon|X]=0$, where $\epsilon$ is the structural error representing all other causes of Y other than X.
Or, when you define the causal parameter in potential outcomes, for example as the ATE $E[Y^{1} - Y^{0}]$, then you sometimes can identify it as $E[Y|X = 1] - E[Y|X = 0]$, assuming $E[Y^{x}|X] = E[Y^{x}]$ for $x \in {1,2}$. The latter assumption is a generalization of the error term assumption: $X$ should be mean-independent from all variables that affect $Y$ save for $X$.


How do I show user created node in user profile page with edit mode?

Question: I have a content type 'child'. And I have give the permission to authenticated user to create child node. Its working fine.
But I need to show current user created node in user profile page with edit mode so user can easily updated own created node.
For this I have created views but I am not getting any option to show a created node as a edit form.
Answer: You have to give permission for Edit own page for that role to see "Edit link" in views or any other page.
Tha can be available from
www.example.com/people/permissions -> <Content Type>: Edit own content

You have to create a module for showing your custom link in user profile page
function <modulename>_menu() {
 $items['user/%user/<yourlink>'] = array(
    'title' => 'Your Pages',
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );
 return $items;
}

Not to mention you have to clear cache after the this.
Comment: Permission is working fine.. I need to show node on profile page with edit mode.
Comment: Update my answer please refer.
Comment: I need to show whole form in edit form with submit and delete button.And one user can create more than one link.


How to use factors (from CFA) as independent variable in Regression Analysis

Question: I calculated 4 factors as latent constructs in a Confirmatory Factor Analysis (I use AMOS). Now I am wondering if it is possible to extract some kind of a factor score like I know it from Exploratory Factor Analysis with SPSS to use those as independent variables in a multiple regression analysis.
Can I use the "Data Imputation" Function of AMOS? What are the risks?
THank you a lot in advance
Comment: See [CFA factor scores AMOS](http://stats.stackexchange.com/q/66656/32036) and [IBM's support on this topic](http://www-01.ibm.com/support/docview.wss?uid=swg21600240).
Comment: thank you. my lecturer said, there would be problems with those calculated scores, because it includes missing values. Does anyone know more about those risks?
Comment: I have the exact same problem AnnaOSophie, were you able to resolve this issue? If so, could you please share with me your solutions? Thank you!
Answer: Factor regression, as this plug-in approach is known, is subject to measurement error bias. In linear regression $y=x'\beta + \epsilon$, if $x$ is measured with error, then the OLS estimates are biased towards zero (which is sometimes called attenuation bias). See  Skrondal and Laake (2001) for a thorough study of the factor regression issue.
If you are working in AMOS, I don't see any reason why you shouldn't just expand your CFA to include regression onto your outcome of interest, making this a full structural equation model.
Imputation is out of the picture whatsoever here. I don't know why you are bringing this up.
Comment: Thank you StasK! The references are very useful! Just one more question, would the factor scores obtained from an EFA conducted in SPSS also suffer from attenuation bias as the factor scores obtained in the CFA in AMOS?


logarithmic differentiation, a function to the power of another function

Question: Let $f$, $g$ be two differentiable functions.
Using logarithmic differentiation, find a formula for the derivative of
$h(x) = f(x)^{g(x)}$.
Answer: $h(x)=e^{g(x)ln(f(x))}$ implies that $h'(x)=(g'(x)ln(f(x)+{{f'(x)}\over {f(x)}}g(x))e^{g(x)ln(f(x))}$


Non-3D View for Widgets in Dock

Question: I have the following QDockWidget:

My question is how do I get rid of the 3-D view for the QTableWidget in this case. I just want plain white background, no 3-D frames, no raised stuff... I think I have to do something with the style but I don't know what...
Answer: Since QTableWidget inherits from QFrame, you can simply set:
widget->setFrameStyle(QFrame::Panel | QFrame::Plain);

Non-3D View for Widgets in Dock


How to make POST requests to save a list of objects in the hierarchical structure in angular

Question: I have a list of objects in the hierarchical structure which are related by parentId, for example:
[
  {
    id: 10,
    name: "Parent Unit 1",
    parentId: null,
    children:
    [
      {
        id: 11,
        name: "Unit Child 1.1",
        parentId: 10,
        children:
        [
          {
            id: 15,
            name: "Unit Child 1.1.1",
            parentId: 11,
            children: []
        ]
      },
      {
        id: 12,
        name: "Unit Child 1.2",
        parentId: 10,
        children: []
      }
    ]
  },
  {
    id: 13,
    name: "Parent Unit 2",
    parentId: null,
    children:
    [
      {
        id: 14,
        name: "Unit Child 2.2",
        parentId: 13,
        children: []
      }
    ]
]

I need to save objects one by one through web service by calling POST method six times. The requirement is that I have to save them sequentially. I mean, I have to wait until Parent Unit is saved, when the web service returns new id of the parent object and then I can make another POST request to web service with modified parentId for Unit Child objects.
I use Observables for making web services in my angular app. Any ideas how can I do it?
Comment: Actually it would be better to send the whole data at once, and then let server handle it. Otherwise you will face complexity when dealing with failed requests. What should happen when one of the requests fails? Should you fire all again? How the server responds when data already exists?
Comment: Sorry that I did not point it out under the original question
Comment: Thanks for your comment! Your description makes sense. Thanks again.
Answer: You can use switchMap
Here's a basic example of how it works
Rx.Observable.of('some_url')
  .switchMap(url => this.http.get(url))

Basically, you get the first id, switchmap it to use it on the 2nd call etc...
Read more about it here: https://www.learnrxjs.io/operators/transformation/switchmap.html


parse a url, get hash value, append to and redirect URL

Question: I have a PHP foreach loop which is getting an array of data.  One particular array is a href.  In my echo statement, I'm appending the particular href onto my next page like this:
echo 'Stats'

It redirects to my next page and I can get the URL by $_GET.  Problem is I want to get the value after the # in the appended URL.  For example, the URL on the next page looks like this:
stats.php?url=basket-planet.com/ru/results/ukraine/?date=2013-03-17#game-2919

What I want to do is to be able to get the #game-2919 in javascript or jQuery on the first page, append it to the URL and go to the stats.php page.  Is this even possible?  I know I can't get the value after # in PHP because it's not sent server side.  Is there a workaround for this?
Here's what I'm thinking:
echo 'Stats';


Exchange 2010 SP3: 4.3.1 Insufficient system resources

Question: We have Office 365 with a hybrid deployment. Our on-premise server is relaying email directly out to the web (not via EOP). domain-a.com is an accepted domain on our on-premise server; domain-b.com is not.
The issue we have had was that the on-premise server was a bit low on space on the C: volume and the transport server was rejecting emails with a from address of domain-b.com, but not domain-a.com. The error message received was:
send-mailmessage : Insufficient system storage. The server response was: 4.3.1 Insufficient system resources
    At line:1 char:1
    + send-mailmessage -to firstname.lastname@example.com -Subject test -from email@example.com
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage],SmtpException
        + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

Once I had cleared down the log files in IIS, email was successfully relayed for both domains. What could be the explanation for this? I'm not sure where to start.
Comment: This article may help explain...? [http://technet.microsoft.com/en-us/library/bb201658(v=exchg.150).aspx](http://technet.microsoft.com/en-us/library/bb201658(v=exchg.150).aspx)
Answer: Backpressure is caused by low systems resources, which you know that you had. It causes SMTP sessions to be rejected or delayed.
Advice: Move all the logs (IIS, transport protocols, etc) off the system volume.
Comment: I understand what the solution was in general, but it doesn't explain why it works for one and not the other.
Comment: Perhaps they came in on different connectors that have different rules? I don't know, you need to tell us more about your environment.


Guitar self repair tutorials and forums

Question: I have a fender squire strat . It goes out of tune very frequently, even after i bend my string once and also is a bit out of tune towards the higher notes.
Are there any good blogs or sites which points someone to guitar self repair so that
i can start learning it to fix by myself?
Probably fit in a new pair of tuning heads ?
Change pickups etc?
Which sites do you suggest?
Thanks
Answer: I would suggest music.stackexchange.com
Fitting machine heads is actually incredibly easy - if you buy ones of the same type as those you already have, you will only need a screwdriver and a pair of pliers.
Before going down the route of fitting new machine heads, there are two things you can look at though:

Pre-stretch your strings
Check your nut is allowing the strings to move smoothly

The reason more modern guitars have features like locking nuts is to avoid the de-tuning problem as much as possible, but with a classic, you do what you can to minimise the issue.
Answer: The upper frets going out of tune suggest to me that the bridge might need some attention. Make sure it's flush against the body, not pulled-up by the strings. You might need to tighten the springs in the back or even add an additional spring.
Answer:
Make sure you put the string on the machine correctly. It's best to wind the string under tension. Use one hand to keep the string stretched and the other to turn the machine head.
Put at least two full windings (under tension, see #1) on the head
If you have a tremolo, remove it or bolt it down. Cheap tremolos go always out of tune
If the higher frets are out of tune, you need to adjust the string length at the bridge. It's easy to do: Use a tuner to tune the open string (or better the "first harmonic"). Then fret at the twelfth fret. Should be the same note. If it's sharp make the string longer, if it's flat, make the string shorter. Repeat until the pitches of fretted and un-fretted note match.

P.S. you play the "first harmonic" by putting your finger lightly on the string over the twelfth fret but NOT pressing down. You get a note that's exactly one octave above the open string. You may have to shift the finger a little bit up and down the string to find the right spot

Guitar self repair tutorials and forums