Not able to get INSERT of SP to work

Question: I am not able to get the INSERT portion of the below procedure to work. Any help would be appreciated....
@currTable varchar(100),
@ID int,
@short_Text varchar(250),
@brief_Descrip varchar(250) = Null,
@needsTranslation varchar(10) = Null,
@prev_LangString varchar(250) = Null,
@lang_String varchar(250) = Null,
@original_lang_String varchar(250) = Null,
@StringID_from_Master int,
@GUID varchar(250) = Null

        AS

        BEGIN

        SET NOCOUNT ON;

        DECLARE @submitDate1 DATETIME;
        SET @submitDate1 = GETDATE()
        SET @prev_LangString = @original_lang_String

        DECLARE @sql NVARCHAR(MAX);

        SELECT @sql = N' UPDATE  ' + QUOTENAME(@currTable) + ' SET [lang_String] = ''' + REPLACE(@lang_String,'''','''''') + ''', [date_Changed] = ''' +  convert(varchar(20), @submitDate1) + ''', [prev_LangString] = ''' + @prev_LangString + ''', [needsTranslation] = ''' + @needsTranslation + ''' WHERE ID = ' + RTRIM(@ID) +  '; ';

            EXEC sp_executesql @sql;

            INSERT tblPendingDBUpdates
                (      stringMasterID,
                       databaseName,
                       databaseStringID,
                       englishText,
                       foreignLangText,
                       submitDate,
                       GUID
                )

            SELECT      @StringID_from_Master,
                        Database_Name,
                        dbKeyID_ofStringName,
                        @short_Text,
                        @lang_String,
                        @submitDate1,
                        @GUID
            FROM      tblDBUsage
            WHERE tblUniquetblStringsMaster_ID = @StringID_from_Master;

            END

I tried this code block only and no luck it did not INSERT to tblPendingDBUpdates.... Noticed something weird about GUID as field name so changed it in table also...
        AS

        BEGIN

        SET NOCOUNT ON;

        DECLARE @submitDate1 DATETIME;
        SET @submitDate1 = GETDATE()
       -- SET @prev_LangString = @original_lang_String

        DECLARE @sql NVARCHAR(MAX);

        DECLARE @currTable varchar(100);
        SET @currTable = 'tblLangenUS'
        DECLARE @ID INT;
        SET @ID = 2
        DECLARE @short_Text varchar(250);
        SET @short_Text = 'testing99'
        DECLARE @StringID_from_Master INT;
        SET @StringID_from_Master = 2

        DECLARE @lang_String varchar(250);
        SET @lang_String = 'testing9999'
        DECLARE @GUID1 varchar(250);
        SET @GUID1 = 'Null'

            INSERT tblPendingDBUpdates
                (      stringMasterID,
                       databaseName,
                       databaseStringID,
                       englishText,
                       foreignLangText,
                       submitDate,
                       GUID1
                )

            SELECT      @StringID_from_Master,
                        Database_Name,
                        dbKeyID_ofStringName,
                        @short_Text,
                        @lang_String,
                        @submitDate1,
                        @GUID1
            FROM      tblDBUsage
            WHERE tblUniquetblStringsMaster_ID = @StringID_from_Master;

            END

Comment: Do you have a row in tblDBUsage where tblUniquetblStringsMaster_ID is 2 ?
Comment: are you getting an error message?
Comment: No error at all, just does not INSERT. In Mgmt Studio says it completes. but nothing in VS. UPDATE portion works fine. SQL Express 2008
Comment: if you run the INSERT on its own does it work?
Comment: see updated code block at the top.
Comment: @marc11h why did you post this question again? http://stackoverflow.com/questions/6946434/insert-statement-not-working
Comment: Yes there is a row, many where tblUniqueStringsMaster_ID is = 2
Comment: have you tried running your INSERT on its own, not in the stored proc?
Comment: yes, as stated and displayed in code block above, it says that it completes but nothing is inserted. I am really stuck on this one.
Comment: Marc shouldn't it be `INSERT INTO ... SELECT FROM` instead what you doing `INSERT ... SELECT FROM`?
Comment: I tried INSERT INTO same failure./
Comment: 'it says that it completes but nothing is inserted' ... How do you know that your `INSERT` is at all gettign executed?
Comment: Only the message at the bottom that says 'Query executed succesfully'  Which I guess doesn't mean that the INSERT actually  executed.
Comment: Why not ... with `EXEC sp_executesql @sql;` you are actually executing a `UPDATE` query and then going for the `INSERT` ... HENCE I ASKED THE QUESTION
Comment: can you post the entire stored procedure instead of giving bits and pieces?
Comment: I have corrected code above to remove the EXEC which is the first part of the SP, that works, the INSERT is not. Sorry, for the over sight I had the UPDATE commented out originally but missed the EXEC.
Comment: You're seeing it above.  As you suggested I am working with only the INSERT.
Comment: How many rows do you expect to be inserted into tblPendingDBUpdates when @StringID_from_Master = 2 ?
Comment: there should be 6 rows returned
Comment: What is the data type for field tblUniquetblStringsMaster_ID ?
Comment: Type is INT,   Could this problem be a permissions issue in MgmtStudio, as I have been able to get parts of the procedure to work from with VS, but not from in MgmtStudio.
Comment: No, not a permission issue. Are you sure you use the same server and the same db? Does the select alone return 6 rows?
Comment: this is all on one PC. I check the select statment alone.
Answer: If your not getting an error message and inserting zero rows, than you select statement must not be returning anything.
what does this return?
select *
FROM      tblDBUsage
WHERE tblUniquetblStringsMaster_ID = @StringID_from_Master

If you're first stored proc it didn't look like @StringID_from_Master ever got set.  That could be your problem.
Answer: Well as far I understand it ... change the SP code to below and try again ... most probably will work fine
CREATE PROCEDURE <SOME NAME>
AS
BEGIN

 <ALL YOUR DECLARATION HERE>

BEGIN

EXEC sp_executesql @sql;
END

GO

BEGIN

INSERT INTO tblPendingDBUpdates
(stringMasterID,
databaseName,
databaseStringID,
englishText,
foreignLangText,
submitDate,
GUID1)
SELECT  @StringID_from_Master,
Database_Name,
dbKeyID_ofStringName,
@short_Text,
@lang_String,
@submitDate1,
@GUID1
FROM tblDBUsage
WHERE tblUniquetblStringsMaster_ID = @StringID_from_Master;
END
END
GO

Comment: Msg 102, Level 15, State 1, Procedure usp_TestProc, Line 53
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'END'.
Answer: I don't really know what you need but here is a stored proc with your declarations
CREATE PROCEDURE TestProc
    AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @submitDate1 DATETIME
        SET @submitDate1 = GETDATE()
    DECLARE @sql NVARCHAR(MAX)
    DECLARE @StringID_from_Master INT
        SET @StringID_from_Master = 2
    DECLARE @short_Text varchar(250)
        SET @short_Text = 'testing99'
    DECLARE @lang_String varchar(250)
        SET @lang_String = 'testing9999'
       DECLARE @GUID1 varchar(250)
        SET @GUID1 = 'Null'

    BEGIN
        EXEC sp_executesql @sql
    END

    BEGIN
        INSERT INTO tblPendingDBUpdates
        (
            stringMasterID,
            databaseName,
            databaseStringID,
            englishText,
            foreignLangText,
            submitDate,
            GUID1
        )
        SELECT
            @StringID_from_Master,
            Database_Name,
            dbKeyID_ofStringName,
            @short_Text,
            @lang_String,
            @submitDate1,
            @GUID1
        FROM tblDBUsage
        WHERE tblUniquetblStringsMaster_ID = @StringID_from_Master
    END
END
GO

Not able to get INSERT of SP to work


If $a \cdot a = 1$ then $a = 1$ or $a = -1$

Question: Let $F$ be a field.
And let $a \in F$ such that $a \cdot a = 1$.
Claim: $a = 1$ or $ a = -1$
Before, I begin with the proof I cannot understand what $ a = -1$ represents...
Is $a = -1$ representing the inverse of $a$?
I am capable of getting to $a = 1$ with no trouble, but how do you get the $-$ sign to show up in your proof?
Proof: This is my attempt at getting to $a=-1$.
If $a = 0$ then we have $0 \cdot 0 = 0 \neq 1$. Then this implies that $a \neq 0$ which implies that $ \exists b \in F,$ s.t. $a \cdot b = 1$, i.e. $b$ is the multiplicative inverse of $a$.
Knowing this fact prove as follows...:
$a \cdot a = 1 \implies$ $ (a \cdot a) \cdot b = 1 \cdot b \implies$ $a \cdot (a \cdot b) = 1 \cdot b \implies$ $a \cdot 1 = 1 \cdot b \implies$ $ 1 \cdot a =1 \cdot b \implies$ $a = b$.
But since $b$ is the multiplicative inverse of $a$ is this enough to say that $a = -1$?
Comment: $a=-1$ means the same thing it has done since you first learned to use letters in math. Nothing fancy going on at all. The letter $a$ represents the number $-1$. That's all it says.
Comment: @Skypanties: What on earth do you mean? The notation $a^2$ is **by definition** an abbreviation for $a \cdot a$.
Comment: The element $a$ satisfies $a^2-1=0$, or $(a-1)(a+1)=0.$ If you can show that in a field, you cannot multiply two nonzero elements and get $0,$ then you have either $a-1=0$ or $a+1=0. \qquad$
Comment: I know you are bringing the 1 to the other side of the equation, but my **main point** of the question is do we know that $-1$ is the additive inverse of $1$? Shouldn't we call it something else (maybe $b$) since we only know that $0,1 \in F$?
Comment: I think I know what my problem is; Sorry, it takes so many points for me even know what my own problem is. Isn't it technically wrong for you guys to say $a \cdot a = a^2$ because I believe none of axioms, supports that $a \cdot a = a^2$? Another question is, I read the definition of the field once again, when the definition states that $0,1 \in F$ where $0 \neq 1$, are the $0,1$ we are referring to here the actual number $0$ and $1$ or could we have replaced them with any other symbols?
Comment: @Skypanties: By the way, your argument only shows that $a$ is its own multiplicative inverse, which was obvious from the outset, since that is exactly what the equation $a \cdot a=1$ says. So you are nowhere near proving $a=\pm 1$ yet. Michael Hardy's proof is the way to go. Regarding your doubts about $-1$, it is just **notation** for the additive inverse of $1$ (which is guaranteed to exist, by the field axioms).
Answer: A field is basically an additive group together with a multiplicative group that plays nicely with the additive one. The additive group is usually denoted with operator $+$, and the inverse function of that group is usually denoted with the operator $-$, so that $-a$ is defined to be the additive inverse of $a$ in the group. It may be the case that $-a = a$ (e.g. in any field of characteristic 2, this is true for all $a$). Indeed, $-$ may not have anything at all to do with the subtraction on $\mathbb{Z}$ that you're used to.
You need to show that $a^2 = 1$ implies $a = 1$ or $a = -1$; equivalently, if you're squeamish about minus signs, that $a = 1$ or $a + 1 = 0$. Those two formulations are exactly the same.
(And, to drive this home again, it's possible for $a = 1$ and $a = -1$ to be simultaneously true! In the field $\mathbb{F}_2$ of two elements, $1 = -1$; and it's true in any field of characteristic $2$.)
Answer:
Before, I begin with the proof I cannot understand what $a=−1$ represents...

You do not have to overthink thinks.
The inverse of $a$ is $(-a)$. And $a=-1$ just means, that $a=-1$.
Calculations work in every field the same.
It does not matter if you have $\mathbb{R}$, $\mathbb{Q}$ or a finite field like $\mathbb{F}_2$, which is the field with two elements $0$ and $1$.
Finite fields can be confusing at first, there it would actually be $1=-1$ which looks odd at first.
But to make $(\mathbb{F}_2, +,\cdot)$ a field we have to calculate like this:
$0$ is the neutral element of $+$ and $1$ the neutral element of $\cdot$.
Hence $0+0=0$ and $1+0=1$ and $0\cdot 1=0$ and $1\cdot 1=1$.
What is $1+1$? It has to be $1+1=0$!
Because if we had $1+1=1$ we had $1=0$ after subtracting $1$ on both sides. But this contradicts that 0 and 1 are different, which they are by the axioms of a field. (Neutral elements of addition and multiplication are unique).
This means 1 is its own inverse and therfor $1=-1$ which is just notation at that point.
Just as a little "introduction".
To solve your question you can simply go like this:
$a^2-1=0\Leftrightarrow (a+1)(a-1)=0$
This is true in every field!
You might have shown, that $a\cdot b=0\Leftrightarrow a=0\vee b=0$ holds in a field.
Hence $a+1=0\vee a-1=0\Leftrightarrow a\in\{-1,1\}$.


How is the stack pointer used in vector_swi() in arm linux system call initialised?

Question: While reading the vector_swi() routine for arm linux system call, I found that r0-r12 registers are copied to the kernel stack(below is the code)
ENTRY(vector_swi)
#ifdef CONFIG_CPU_V7M
    v7m_exception_entry
#else
    sub sp, sp, #S_FRAME_SIZE
    stmia   sp, {r0 - r12}          @ Calling r0 - r12

As per my understanding, during system call arm enters into svc mode and jumps to vector_swi() routine and begins execution. The sp register of svc mode(sp_svc)points to kernel stack. r0-r12 registers are copied to the kernel stack.
My question is how is the sp (sp_svc) register setup?
How does it know the address of kernel stack?
Is this kernel stack same as the process's(the process that called system call) kernel stack?
Answer: On the arm32 architecture, sp (r13) is banked, which means there are physically separate registers for USR and SVC modes.
For each userspace thread, the corresponding kernel thread always exists, and has its stack allocated and the SVC mode r13 points there.  On system call entry, the software-visible r13 is switched to the one for SVC mode, and the instructions you point to are executed after that.
Comment: For arm, in copy_thread() in arch/arm/kernel/process.c

At that point, thread->cpu_context.sp is initialized for the thread being created. Physically this value gets into SVC-mode R13 when scheduler does switch to the new thread - in __switch_to() in arch/arm/kernel/entry-*.S
Comment: Thanks. It would be great if you can also show the code  where svc mode r13 is set to the kernel stack.


Definition of $b|a \implies 0|0$?

Question: The definition I'm using for $b|a$ (taken from Elementary Numbery Theory by Jones & Jones):

If $a,b \in \mathbb{Z}$ then $b$ divides $a$ if for some $q \in \mathbb{Z}$ $a = qb$.

However, I have $0 = q\cdot0$ for any $q$ I choose. So this seems to imply that $0$ divides $0$ which I know is always taken to be undefined. Should the definition be for "unique $q$" rather than for "some $q$"?
Thank-you.
Answer: The statement $0$ divides $0$ and the "quantity" $0/0$ are different things. The first is exactly the statement that there exists some $a$ such that $0a=0$ and the second is not a number
Answer: According to the definition $0$ divides $0$, but note that $\frac{0}{0}$ could be any integer, hence the quotient is undefined.
Comment: You're right. I suppose then if I were trying to define the quotient $a/b$ I would use the definition I gave with "unique $q$" for it to be well defined. Thank you.
Answer: In the theory of (unitary) commutative rings the following expressions and statements are more of less equivalent, in many cases by definition, for $a,b\in R$

$\exists c\in R: ac=b$
$b$ is a multiple of $a$
$b\in aR$
$bR\subseteq aR$
$a$ is a divisor of $b$
$a\mid b$
$a$ divides $b$

The first alternative is the defining expression, and it so simple that there are no obvious refinement or coarsening that one could associate with any of the other formulations to make them essentially different. However when talking about "divisibility" as in the last three alternatives, much of the usual type of reasoning is only valid if there is a well defined quotient $b/a$, in other words if the element $c$ in the definition not only exists but is also unique. One condition that will ensure this is when $a$ is a regular element of $R$, i.e., neither zero nor a zero divisor. Indeed is is common to restrict the mention of divisibility to the even more special case where $R$ is an integral domain (so there aren't any zero divisors at all), and both $a$ and $b$ are nonzero. (For $b$ there is no real reason to require this, but forbidding it avoids confusion between "$a$ is a divisor of $0$", which is forbidden but would otherwise be valid for all $a\in R$, and "$a$ is a zero divisor", which means something completely different.) Usually reasoning about divisibility is done only for nonzero elements of an integral domain; I guess it would rather tricky when going beyond these cases.
With this conventional restriction of terminology one shouldn't say that $0$ (or anything else) divides $0$, but one could say that $0$ is a multiple of $0$ (or anything else).
I don't think the initial defining condition but modified to "there exists a unique $c$" is much used in the general context (where the ring may have zero divisors); probably there is no much use that could be made of such a notion.

Definition of $b|a \implies 0|0$?


Images lose transparency with imagick?

Question: This is my first time fiddling with imagick/dynamic images. All of my images used for the layers to build an image are transparent PNG files. However, when compressing the images into one image via imagick for some reason the transparency is lost, resulting in a white background and white wherever it should be transparent. Is this a normal problem, and is there a way to fix it? Here is my section right after I list the images to use;
<code>$composed_image = new \Imagick($images);
$image = $composed_image->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
$image->setImageFormat('png');
header('Content-type: image/png');
echo $image->getImageBlob();
</code>
Comment: Try this before flattening... `setImageBackgroundColor('#FFFFFF');`
Comment: There is a package called [pslayers](https://github.com/darrynten/pslayers) that we use it in production on a few of our apps to handle things like this. Disclaimer: am author of package.
Answer: Figured out that I needed to go through and apply this to every image layer:
<code>$composed_image->setImageBackgroundColor('transparent'); $composed_image->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);</code>

Images lose transparency with imagick?


Internet explorer tries to download index.jsf file

Question: Hey guys I'm trying to get my application to run on Internet Explorer 8.  If I redirect IE8 to my page it just tries to download the JSF file.  Not sure what is going on here.
Comment: Are you sending the correct `Content-Type` in your response? If it's not `text/html` for HTML pages, you'll see similar problems...
Comment: It's hard to tell based on the information given as far. Install Fiddler2 and check what the HTTP response headers contain in cases of failure and success.
Comment: It must be something to do with glassfish security.  I have a filter over /*.  If I change that to something like /admin/* I can display the pages fine.  Hmm.  How do I get around that?  Don't have a problem in Chrome, Firefox, Opera, or Safari with the filer like that.
Comment: I changed my login to page to a plain html page instead of a JSF page and it fixed the issue.
Answer: Old versions of Internet Explorer don't understand mime type application/xhtml+xml:
http://www.schillmania.com/content/entries/2004/10/24/application-xhtml+xml/
Change your web.xml configuration file to map the mime type:
<code><mime-mapping>
    <extension>xhtml</extension>
    <mime-type>text/html;charset=UTF-8</mime-type>
</mime-mapping>
</code>
Answer: I changed my login to page to a plain html page instead of a JSF(xhtml) page and it fixed the issue.


Theme Settings value dissapears

Question: I am trying to create functionality where administrator can upload header image whenever he wants.
I' using hook_form_system_theme_settings_alter in theme-settings.php and altering form like this:
 $form['theme_settings']['background_file'] = array(
        '#type' => 'managed_file',
        '#title' => t('Background'),
        '#required' => TRUE,
        '#upload_location' => file_default_scheme() . '://public/backgrounds/',
        '#default_value' => theme_get_setting('background_file'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
        ),
    );

in template.php using hook_preprocess_page and doing this in it:
$fid = theme_get_setting('background_file');
$loaded = file_load($fid);
$variables['background_url'] = file_create_url($loaded->uri);

and trying to reach $variables['background_url'] from tpl.php file.
When I upload image everything works great, header image is set properly and code has no problem but after a while, I don't really know what happens, for example after 1 day file_load returns FALSE, I just reupload image and everything works fine again.
theme_get_setting('background_file'); always returns file id without problems.
I am missing something? I can't find source of problem.
Thanks.
Answer: I think it's because there is a problem in your template.php. Indeed drupal should save your file only temporarly. You have to save your file permenantly with this code
$file = file_load($form_state['values']['background_file']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

Theme Settings value dissapears


where can I have the specific OBD DTC fault code description e.g P1xxx means XXXXXX

Question: I am working on OBD project now, I wanna have list of data for DTC fault code. we can easily find the general fault code info e.g P0xxx and P2XXX. We can pay for the license. anyone know where I can buy the database?
Answer: You can find a good list of them here: https://www.outilsobdfacile.com/data-trouble-code-obd2.php
If you are working on a specific car manufacturer you can usually find all the manufacturer level error messages hidden somewhere in a file of their diagnostic software.
Answer: As long as you don't expect to find definitions for vendor-specific fault codes (which only the respective vendors own), the first place should be the SAE International, which is the actual organization committee that has defined those codes.
E.g., you might want to buy SAE J2012 or J2012DA, respectively.


Sampling from bivariate joint cumulative distribution function

Question: Given two variable $x,y$, they are subjected to a joint probability density function:
$
f(x,y) = \dfrac{1}{3}(3x^2 + 4xy + 3y^2)\\
0\leq x \leq 1;0\leq y \leq 1
$
Obviously, its corresponding cumulative distribution function (CDF) is:
$
F(x,y) = \dfrac{1}{3}(x^3y+x^2y^2+xy^3)
$
My objective is to generate random samples from this CDF using the inverse tranformation method.
As far as I know, the first step is to get the marginal CDF of $x$:
$
F_x = F(x,y=1) = \dfrac{1}{3}(x^3 + x^2 + x)
$
Then we can readily get a random value of $x$, denoted as $u_x$.
Next, for sampling $y$, we have to derive its conditional CDF $F_{y|x}$ given $x$.
My question is how to derive the $F_{y|x}$? Can the well-known conditional rule still be adapted for this problem, such that:
$
F_{y|x} = \dfrac{F(x,y)}{F_x}
$
It is worth noting that the actual CDF I encountered is much more complicated than the above example, and is very difficult to perform integration on the PDF or CDF.
Thank you very much!
Comment: @whuber: since the joint density is given, I am unsure copulas need be involved.
Comment: @Xi'an The approach taken in the question is that of sampling from a copula.
Comment: @whuber: Ah OK, sure!
Comment: "Copula" is a great search term.  We have some threads about simulating from copulas.
Answer: If$$f(x,y) = \dfrac{1}{3}(3x^2 + 4xy + 3y^2)$$
then $$f_{Y|X=x}(y)\propto f(x,y)\propto 3x^2 + 4xy + 3y^2$$
leads to$$f_{Y|X=x}(y)=\dfrac{3x^2 + 4xy + 3y^2}{\underbrace{\int_0^1 (3x^2 + 4xy + 3y^2)\,\text dy}_{3x^2+2x+1}}$$
from which the conditional cdf can be derived.


Is it really more efficient to WhenAll() on a number of tiny awaitable methods?

Question: Given an external API method signature like the following:
Task<int> ISomething.GetValueAsync(int x)
I often see code such as the following:
public async Task Go(ISomething i)
{
    int a = await i.GetValueAsync(1);
    int b = await i.GetValueAsync(2);
    int c = await i.GetValueAsync(3);
    int d = await i.GetValueAsync(4);

    Console.WriteLine($"{a} - {b} - {c} - {d}");
}

In code reviews it is sometimes suggested this is inefficient and should be rewritten:
public async Task Go(ISomething i)
{
    Task<int> ta = i.GetValueAsync(1);
    Task<int> tb = i.GetValueAsync(2);
    Task<int> tc = i.GetValueAsync(3);
    Task<int> td = i.GetValueAsync(4);

    await Task.WhenAll(ta,tb,tc,td);
    int a = ta.Result, b= tb.Result, c=tc.Result, d = td.Result;
    Console.WriteLine($"{a} - {b} - {c} - {d}");
}

I can see the logic behind allowing parallelisation but in reality is this worthwhile? It presumably adds some overhead to the scheduler and if the methods themselves are very lightweight, it seems likely that thread parallelisation would be more costly than the time saved. Further, on a busy server running many applications, it seems unlikely there would be lots of cores sitting idle.
I can't tell if this is always a good pattern to follow, or if it's an optimisation to make on a case-by-case basis? Do Microsoft (or anyone else) give good best practice advice? Should we always write Task - based code in this way as a matter of course?
Comment: `Task.WhenAll` returns a `Task` if all tasks have the same return value. You could write `var ints=await Task.WhenAll(i.Get(), i.Get(),..)`. Or `var ints=await Task.WhenAll(Enumerable.Range(1,5).Select(i.GetvalueAsync));` Does it matter though? If you call another service, can it handle concurrent calls or will this result in increased blocking?
Comment: @TheodorZoulias this is a made-up example. That's my whole question, when should(n't) I do this? Or should I always as good practice and let the runtime decide what to do?
Comment: Scheduler overhead is generally a non-issue if gains can be made from parallelization, which is the main concern. If such gains *can't* be made, then no, but that would be unusual. Keep in mind that async != parallel; it's possible that even 100 asynchronous requests could be executing on the system in parallel with no processor overhead at all (that only comes when the results need to be gathered, but that overhead is easily dwarfed by the runtime gains). For an external API you're more likely to want explicit control over the degree of parallelism, for example with `Parallel.ForEachAsync`.
Comment: What is the expected average duration of an `await GetValueAsync()` operation?
Answer:
if the methods themselves are very lightweight, it seems likely that thread parallelisation would be more costly than the time saved.

This is definitely an issue with parallel code (the parallel form of concurrency), but this is asynchronous concurrency. Presumably, GetValueAsync is a true asynchronous method, which generally implies I/O operations. And I/O operations tend to dwarf many local considerations. (Side note: the WhenAll approach actually causes fewer thread switches and less scheduling overhead, but it does increase memory overhead slightly).
So, this is a win in the general case. However, that does assume that the statements above are correct (i.e., GetValueAsync performs I/O).
As a contrary point, however, I have seen this sometimes used as a band-aid for an inadequate data access layer. If you're hitting a SQL database with four queries, then the best solution is usually to combine that data access into a single query rather than do four calls to the same SQL database concurrently.
Answer: First, what does await actually do?
public async Task M() {
    await Task.Yield();
}

If the awaitable object has already completed, then execution continues immediately. Otherwise a callback delegate is added to the awaitable object. This callback will be invoked immediately when the task result is made available.
So what about Task.WhenAll, how does that work? The current implementation adds a callback to every incomplete task. That callback will decrement a counter atomically. When the counter reaches zero, the result will be made available.
No new I/O is scheduled, no continuations added to the thread pool. Just a small counter added to the end of each tasks processing. Your continuation will resume on whichever thread executed the last task.
If you are measuring a performance problem. I wouldn't worry about the overheads of Task.WhenAll.
Comment: The `await Task.Yield()` might not be the best example, because is returns a specialized awaitable that is always incomplete. `await Task.Delay(1)` might be a better example, because there is a chance that the `awaiter.IsCompleted` is actually true.
Comment: I only needed an example of how `await` is turned into IL by the C# compiler. The type of awaitable doesn't matter for this example.


extract word before first dot from url in nginx

Question: I use nginx
Assume that url "hello.test.example.com", hello example of dynamically subdomain,
how can i get the word before the first dot in nginx config ??
the result must be "hello" ?
Answer: For example:
server {
    server_name ~^(?<subdomain>[^.]+)\.test\.example\.com$;
    ...
}

As of this configuration, the first part of subdomain name will be available as $subdomain variable value.
Comment: when nginx reload >> Job for nginx.service failed because the control process exited with error code.
Comment: Sorry, missed a semicolon after the regex.
Comment: $subdomain empty string !!
Comment: I can't help you further unless I'll see how do you use `$subdomain` variable in your configuration. There can be some caveats if you'd use it in conjunction with the `if` directive.
Comment: if (-f $file) {
        return 302 http://$subdomain.test2.example.com/;
  }
Comment: Sorry, missing another sign in regex :) Try an updated one
Comment: this condition  not working correctly
Comment: server_name ~^(?[^.]+)\.example\.com$;

        set $file /home/ubuntu/html/files/$host;
        if (-f $file) {
                rewrite ^/(.*)$ http://$subdomain.example2.com/$1;
        }
Comment: can you help me ?
Comment: What exactly is not working? What you are trying to achieve?Assuming the `Host` HTTP header in your request is `test.example.com`, you are trying to check the `/home/ubuntu/html/files/test.example.com` file existence. Using `-f` condition neither directory nor symlink would pass this check. Next, you are trying to generate an HTTP redirect to `http://test.example2.com` preserving the request URI? What type of redirect do you want to generate? A permanent `HTTP 301` or a temporary `HTTP 302`? Can your request be the `POST` request?
Comment: I have two servers, when the file already exists in this path /home/ubuntu/html/files, then any request from subdomain.example.com redirect automatically to example2, this running but not every time !
Comment: Try adding the `redirect` flag to your rewrite directive. Alternatively you can try `return 302 http://$subdomain.example2.com$request_uri` instead of `rewrite ... redirect` directive.
Comment: same result !!!
Comment: Can you help me ?


Set the Segment control unselected

Question: I have a problem, I want my UISegment controls to start all unselected when the app loads.
If someone can help on this matter I would be very thankful.
Best Regards.
Answer: Either:
[mySegmentControl setSelectedSegmentIndex:-1];

or:
[mySegmentControl setSelectedSegmentIndex:UISegmentedControlNoSegment];

It's all in the apple docs too.
Ref: http://developer.apple.com/library/ios/#documentation/uikit/reference/UISegmentedControl_Class/Reference/UISegmentedControl.html
Answer: At the start after initializing your segmentedcontrol you can use
yourSegmentControl.selectedSegmentIndex=-1;

it will erase any selected index.
I hope it helps
Answer: Just uncheck Selected checkbox from property

Set the Segment control unselected


Change the way "add content" and "node's" are displayed

Question: I was wondering how one would go about changing the layout of the nodes when you are adding content, as well as when you view the full story.
I want certain text to be bigger, some fields to be placed side by side, some vertically. I want full control over the layout. I tried editing the CSS to change fonts and colors but it all changes fonts for the enitre website and not just in the node view. any thoughts?
Answer: page--node--[content-type].tpl.php = node template for a specific content type (no square brackets)
page--node--add--[content-type].tpl.php = node/add template for specific content type.
Copy/paste the code you have in node.tpl.php and clear your server cache. Now you can add custom classes everywhere or even create a custom HTML structure to render your fields. See the node.tpl.php documentation and Drupal 7 template suggestions.
Hope this helps!
Comment: It's strange. The docs say that the template for a node type should be `node--[content-type].tpl.php` and this works for me. However, `node--add--[content-type].tpl.php` doesn't work for me, and prefixing it with `page--` _does_ make it work (sort of, anyway -- drupal recognizes it as the template for the add content page for that type, but fails to display the page). Any idea about why it's inconsistent that way? UPDATE: never mind, it's because you can set a template for any page at all starting from the `page--` root. Anyway, thanks!


Two non-decreasing sequences $a,b : \alpha \to \alpha$ such that $a$ is a subsequence of $b$ and vice versa, but they are not the same sequence.

Question:
Let $\alpha > 0$ be an ordinal. Does there exist two non-decreasing sequences $a,b : \alpha \to \alpha$ such that $a$ is a subsequence of $b$ and $b$ is a subsequence of $a$, but they are not the same sequence?

If we consider the same question for strictly increasing sequences (or more generally injective sequences), then they have to be the same sequence:
Let $a$ and $b$ be such sequences. Then, there exist strictly increasing functions $f,g : \alpha \to \alpha$, such that $a = b \circ f$ and $b = a \circ g$. Then, we have, $$b = a \circ g = (b \circ f) \circ g = b \circ (f \circ g)$$
Now, $f \circ g$ needs to be identity since; if $(f \circ g)(\beta) \neq \beta$ , then $b(\beta) = b((f \circ g)(\beta)) \neq b(\beta)$ since $b$ is injective.
Since $f$ and $g$ are strictly increasing, $\forall \gamma \ f(\gamma) \geq \gamma \ \text{and} \ g(\gamma) \geq \gamma$. So, $g(\beta) \neq \beta$ for some $\beta$ would imply, $$\beta = (f \circ g) (\beta) = f(g(\beta)) > f(\beta) \geq \beta$$ Therefore, $b = a \circ g = a$.
However, this argument depends on the injectivity of the sequences, so it cannot be used for non-decreasing sequences.
If $\alpha = \omega$, then we can use the fact that there is at most one element that is repeated infinitely many times and we can conclude that they have to be the same sequence, but I cannot solve it for general $\alpha$. Thank you.
Answer: For each ordinal $\gamma\in \alpha$, let $W_{a,\gamma}=a^{-1}(\gamma)$ and let $W_{b,\gamma}=b^{-1}(\gamma)$. Being subsets of $\alpha$, $W_{a,\gamma}$ and $W_{b,\gamma}$ are well-ordered sets. If $a$ is a subsequence of $b$, then there is a strictly increasing map $f_\gamma\colon W_{a,\gamma}\to W_{b,\gamma}$, so the order type of $W_{a,\gamma}$ is $\leq$ the order type of $W_{b,\gamma}$. Similarly, the order type of $W_{b,\gamma}$ is $\leq$ the order type of $W_{a,\gamma}$. So the order types are equal.
Now proceed by induction on $\gamma$ to show that $W_{a,\gamma} =W_{b,\gamma}$ for all $\gamma$ (this is where we use the fact that $a$ and $b$ are weakly increasing), and thus $a=b$.
Comment: Nice generalization of the "there is at most one element that is repeated infinitely many times" argument!


How to work around needing to update a dictionary

Question: I need to delete a k/v pair from a dictionary in a loop.  After getting RuntimeError: dictionary changed size during iteration I pickled the dictionary after deleting the k/v and in one of the outer loops I try to reopen the newly pickled/updated dictionary.  However, as many of you will probably know-I get the same error-I think when it reaches the top of the loop.  I do not use my dictionary in the outermost loop.
So my question is-does anyone know how to get around this problem?  I want to delete a k/V pair from a dictionary and use that resized dictionary on the next iteration of the loop.
to focus the problem and use the solution from Cygil
list=[27,29,23,30,3,5,40]
testDict={}
for x in range(25):
    tempDict={}
    tempDict['xsquared']=x*x
    tempDict['xinverse']=1.0/(x+1.0)
    testDict[(x,x+1)]=tempDict

for item in list:
    print 'the Dictionary now has',len(testDict.keys()), ' keys'
    for key in testDict.keys():
        if key[0]==item:

        del testDict[key]

I am doing this because I have to have some research assistants compare some observations from two data sets that could not be matched because of name variants.  The idea is to throw up a name from one data set (say set A) and then based on a key match find all the names attached to that key in the other dataset (set B).  One a match has been identified I don't want to show the value from B again to speed things up for them.  Because there are 6,000 observations I also don't want them to have to start at the beginning of A each time they get back to work.  However, I can fix that by letting them chose to enter the last key from A they worked with.  But I really need to reduce B once the match has been identified
Comment: Can you post the original code? That would help way more than an ambiguous description
Comment: Okay I posted the code-I have some data that needs to be matched by hand. If I can delete a k/v once I have used it then I can reduce the amount of work I have to do by hand.
Comment: Double check the code formatting.  Linef 4 is clearly off, and since python uses indenting for denoting blocks, its hard to tell if the code displayed above would actually do what you intend it to do.
Comment: @PyNEwbie You didn't post the *original* code I asked for, but your *current* using pickle. Additionally, please at least try to isolate the code that's causing the problem. See http://www.catb.org/~esr/faqs/smart-questions.html for details.
Comment: The only difference in the code are the pickle lines.  Trust me that the problem is I try to modify the dictionary.  That is my question.  You don't want to untangle my code.  I am an academic researcher and trying to process data, not a computer guy
Comment: @PyNEwbie Exactly, I don't want to untangle your code. That's why I'm neither interested in raw_input nor pickle nor the names of your keys. And I'm confused about the difference between "academic researcher" and "computer guy". The point is I want *less* application-specific code, not *more*.
Comment: Just a sidenote: The second test of len(tempDict) is never true and redundant because if len(tempDict) were 0, the code three lines above would have called break. Also, the very last break is a syntax error. If its intention was to break an outer loop, it should be written as a test at the beginning
Comment: Well I was struggling to make things work and I got lost in the loops.  The script works as intended as long as I don't delete. I keep meaning to take a programming class.
Comment: @PyNEwbie Way better :D. Just a problem, stackoverflow indentation should be done automatically (copy your code, select it, and press Ctrl+K). I tried to correct it, can you check it?
Comment: phihag- not sure what you mean here I tried to correct it, can you check it?  Thanks for your patience
Comment: @PyNEwbie I wasn't sure if the second for did belong to top-level or in the first for. As I wrote, code in stackoverflow is tricky, please check it afterwards. But, as I infer from your latest edit, I was right. I *rollbacked* it - don't want to start an edit war, but the latest addition isn't valid
Comment: I am still confused-sorry I just copied the code from IDLE-it worked in idle and the second iteration better illustrates the problem so I am going to try again. feel free to edit
Comment: Okay now I see what you were referring to.  It should work now.
Answer: Without code, I'm assuming you're writing something like:
for key in dict:
    if check_condition(dict[key]):
       del dict[key]

If so, you can write
for key in list(dict.keys()):
    if key in dict and check_condition(dict[key]):
        del dict[key]

list(dict.keys()) returns a copy of the keys, not a view, which makes it possible to delete from the dictionary (you are iterating through a copy of the keys, not the keys in the dictionary itself, in this case.)
Comment: Am I right in assuming since I need to test\review values that I can't do this because I have to access dict[key]['someValue']
Comment: for key in dict.keys() *does* return a view in py3+. Use list(dict.keys()) instead.
Comment: cygil: I made some significant edits, please rollback and complain to me if you don't like them
Comment: Hi Philhag, it's cool.  Obviously I've been lazy and need to bone up on all the new aspects of Python 3.
Answer: Delete all keys whose value is > 15:
for k in mydict.keys(): # makes a list of the keys and iterate
                        # over the list, not over the dict.
    if mydict[k] > 15:
        del mydict[k]

Comment: If you want to be absolutely sure, use `mydict.keys()[:]` to copy the list of keys.
Comment: @S.Lott: mydict.keys() already generates a list with a copy of keys on python 2.x
Answer: Change:
for ansSeries in notmatched:

To:
for ansSeries in notmatched.copy():


Why information criterion (not adjusted $R^2$) are used to select appropriate lag order in time series model?

Question: In time series models, like ARMA-GARCH, to select appropriate lag or order of the model different information criterion, like AIC, BIC, SIC etc, are used.
My question is very simple, why donot we use adjusted $R^2$ to choose appropriate model? We can select model which lead to higher value of adjusted $R^2$. Because both adjusted $R^2$ and information criterion penalize for additional number of regressors in the model, where former penalize $R^2$ and later penalize likelihood value.
Comment: I may be missing something in the answers (below) but R-squares as well as Adjusted R-squares are appropriate for the relatively limited class of OLS estimated models whereas AICs, BICs, etc., are appropriate for the broader class of generalized linear models estimated, perhaps, with ML or a variant.
Answer: I would argue that at least when discussing linear models (like AR models), adjusted $R^2$ and AIC are not that different. (This discussion is based on Hansen's Econometrics textbook, if I remember correctly.)
Consider the question of whether $X_2$ should be included in
$$
y=\underset{(n\times K_1)}{X_1}\beta_1+\underset{(n\times K_2)}{X_2}\beta_2+\epsilon
$$
This is equivalent to comparing the models
\begin{eqnarray*}
\mathcal{M}_1&:&y=X_1\beta_1+u\\
\mathcal{M}_2&:&y=X_1\beta_1+X_2\beta_2+u,
\end{eqnarray*}
where $E(u|X_1,X_2)=0$. We say that $\mathcal{M}_2$ is the true model if $\beta_2\neq0$.
Notice that $\mathcal{M}_1\subset\mathcal{M}_2$. The models are thus nested.
A model selection procedure $\widehat{\mathcal{M}}$ is a data-dependent rule that selects the most plausible of several models.
We say
$\widehat{\mathcal{M}}$ is consistent if
\begin{eqnarray*}
\lim_{n\rightarrow\infty}P\bigl(\widehat{\mathcal{M}}=\mathcal{M}_1|\mathcal{M}_1\bigr)&=&1\\
\lim_{n\rightarrow\infty}P\bigl(\widehat{\mathcal{M}}=\mathcal{M}_2|\mathcal{M}_2\bigr)&=&1
\end{eqnarray*}
Consider adjusted $R^2$. That is, choose $\mathcal{M}_1$ if $\bar{R}^2_1>\bar{R}^2_2$. As $\bar{R}^2$ is monotonically decreasing in $s^2$, this procedure is equivalent to minimizing $s^2$. In turn, this is equivalent to minimizing $\log(s^2)$. For sufficiently large $n$, the latter can be written as
\begin{eqnarray*}
\log(s^2)&=&\log\left(\widehat{\sigma}^2\frac{n}{n-K}\right) \\
&=&\log(\widehat{\sigma}^2)+\log\left(1+\frac{K}{n-K}\right) \\
&\approx&\log(\widehat{\sigma}^2)+\frac{K}{n-K} \\
&\approx&\log(\widehat{\sigma}^2)+\frac{K}{n},
\end{eqnarray*}
where $\widehat{\sigma}^2$ is the ML estimator of the error variance. Model selection based on $\bar{R}^2$ is therefore asymptotically equivalent to choosing the model with the smallest
$\log(\widehat{\sigma}^2)+K/n$.
This procedure is inconsistent.
Proposition:
$$\lim_{n\rightarrow\infty}P\bigl(\bar{R}^2_1>\bar{R}^2_2|\mathcal{M}_1\bigr)<1$$
Proof:
\begin{eqnarray*}
P\bigl(\bar{R}^2_1>\bar{R}^2_2|\mathcal{M}_1\bigr)&\approx&P\bigl(\log(s^2_1)<\log(s^2_2)|\mathcal{M}_1\bigr) \\
&=&P\bigl(n\log(s^2_1)<n\log(s^2_2)|\mathcal{M}_1\bigr) \\
&\approx&P(n\log(\widehat{\sigma}^2_1)+K_1<n\log(\widehat{\sigma}^2_2)+K_1+K_2|\mathcal{M}_1) \\
&=&P(n[\log(\widehat{\sigma}^2_1)-\log(\widehat{\sigma}^2_2)]<K_2|\mathcal{M}_1) \\
&\rightarrow&P(\chi^2_{K_2}<K_2) \\
&<&1,
\end{eqnarray*}
where the 2nd-to-last line follows because the statistic is the LR statistic in the linear regression case that follows an asymptotic $\chi^2_{K_2}$ null distribution.
QED
Now consider Akaike's criterion,
$$
AIC=\log(\widehat{\sigma}^2)+2\frac{K}{n}
$$
Thus, the AIC also trades off the reduction of the SSR implied by additional regressors against the "penalty term," which points in the opposite direction. Thus, choose $\mathcal{M}_1$ if
$AIC_1<AIC_2$, else select $\mathcal{M}_2$.
It can be seen that the $AIC$ is also inconsistent by continuing the above proof in line three with $P(n\log(\widehat{\sigma}^2_1)+2K_1<n\log(\widehat{\sigma}^2_2)+2(K_1+K_2)|\mathcal{M}_1)$. The adjusted $R^2$ and the $AIC$ thus choose the "large" model $\mathcal{M}_2$ with positive probability, even if $\mathcal{M}_1$ is the true model.
As the penalty for complexity in AIC is a little larger than for adjusted $R^2$, it may be less prone to overselect, though. And it has other nice properties (minimizing the KL divergence to the true model if that is not in the set of models considered) that are not addressed in my post.
Comment: Great answer: not too heavy but still exact! If it had been there yesterday, I would have not posted mine.
Comment: What about for the ARMA-GARCH case? How would $R^2_{adj} $ do at selecting amung MA and GARCH terms?
Comment: I wouldn't dare to say. As you explain it's not even clear what R2 means for the fit of such a model.
Answer: The penalty in $R^2_{adj}$ does not yield the nice properties in terms of model selection as posessed by the AIC or BIC. The penalty in $R^2_{adj}$ is enough to make $R^2_{adj}$ an unbiased estimator of the population $R^2$ when none of the regressors actually belongs to the model (as per Dave Giles' blog posts "In What Sense is the "Adjusted" R-Squared Unbiased?" and "More on the Properties of the "Adjusted" Coefficient of Determination"); however, $R^2_{adj}$ is not an optimal model selector.
(There could be a proof by contradiction: if AIC is optimal in one sense and BIC is optimal in another, and $R^2_{adj}$ is not equivalent to either of them, then $R^2_{adj}$ is not optimal in either of these two senses.)
Comment: How many GARCH parameters do I have to add before the $R^2$ increases? :)....I believe a similar argument could be made for the assumption of correlated errors (as in an MA model), A GLS model does not reduce the sum of squared residuals over ordinary least squares.  In both MA and GARCH, parameters (not explanatory variables, which $R^2{adj}$ is adjusted for) are added to the model.  MA and GARCH parameters are not added to reduce $SSR$, rather they re added to increase the likelihood and/or decreases a *weighted* sum of squared residuals to reflect the lack of iid error terms.
Comment: Does this actually address the original post or my answer? In any case, I agree with your points.
Comment: What I was trying to point out is that $R^2_{adj}$ can't really be used to select upon GARCH components (and possibly MA components too) since it is based on the fraction of $SST-SSR$ over $SST$ which are biased estimators of variance when the error terms are not iid. (this is just a specific case of the bias you where talking about). In the case of ARMA-GARCH, you would never select a model with GARCH components, even if there was stochastic volatility in the data, because it does not increase $R^2$.  Basically, I am agreeing with you by trying to give specific examples.


proving $\sum_{k=1}^{\infty}\frac{1}{k(k+1)}=1$

Question: I would like to show that $\sum_{k=1}^{\infty}\frac{1}{k(k+1)}=1$
I was wondering if I could get a hint to get me started.
I tried trying to rewrite it in some sort of familiar sum like a Taylor Series for a function I know like the exponential but no luck. I also tried writing it as the sum of two terms but I'm having trouble knowing how to break it down (if this is even the right way to attack this problem?). Any advice would be appreciated. Thanks.
Comment: Have you heard of partial fraction decompositions? That gives you a nice telescoping series here.
Answer: Hint
$$\frac{1}{k(k+1)}=\frac{1}{k}-\frac{1}{k+1}$$
Comment: @Chio The decomposition comes from Partial Fraction Decomposition. I knew that it works from experience: whenever when the denominator is the product of terms in arithmetic progression, the (partial fraction) decomposition makes the sum into a telescopic one.
Comment: Thanks for the hint. I'll try using this fact now. Out of curiosity, is there a way you knew that this particular decomposition would be useful, or is this just from past experience?
Answer: Note that
$$
\sum_{k=1}^{\infty}\frac{1}{k(k+1)} = \frac{1}{2} + \sum_{k=2}^{\infty}\frac{1}{k(k+1)} = \frac{1}{2} + \sum_{j=1}^{\infty}\frac{1}{(j+1)(j+2)}, \ \text{with} \ j = k - 1
$$
But
$$
\frac{1}{(j+1)(j+2)} = \frac{1}{j+1} - \frac{1}{j+2} = \int_{0}^{1}x^jdx - \int_{0}^{1}x^{j+1}dx = \int_{0}^{1}x^j(1 - x)dx\\
\text{and} \ \sum_{j=1}^{\infty}x^jdx = \frac{x}{1 - x}, \quad |x| < 1
$$
Hence,
$$
\sum_{k=1}^{\infty}\frac{1}{k(k+1)} = \frac{1}{2} + \sum_{k=1}^{\infty}\int_{0}^{1}x^j(1 - x)dx = \frac{1}{2}+\int_{0}^{1}(1 - x)\sum_{j=1}^{\infty}x^jdx\\
= \frac{1}{2} + \int_{0}^{1}(1 - x)\frac{x}{1 - x}dx = \frac{1}{2} + \int_{0}^{1}xdx = \frac{1}{2} + \frac{1}{2} = 1
$$


A combinatorial sum and identity involving Stirling numbers of the second kind

Question: Let $n, k \geq 1$. Let $a(j),\, 1\leq j \leq k$, be a sequence of real numbers. Consider the sum
$$
\sum_{j=1}^k j! S(k, j) {n \choose j} a(j),
$$
where $S(k,j)$ are Stirling numbers of the second kind. Is there some kind of "inversion" identity that simplifies the sum? What is the sum in the simple case that $a(j) = 1$ for each $j$? Thanks.
Update: In the case when the $a(j) = 1$ the sum is well-known. It equals $n^k$. See Marc van Leeuwen's answer in abiessu's question, and Brian M. Scott's answer below. Any words on $a(j)$ arbitrary?
Comment: Please note this answer: http://math.stackexchange.com/a/519049/86846 where my question was not the same as yours, but the identity seems to fairly closely match the sum you mention.
Comment: Thanks for that. Seems the sum is $n^k$ when the $a(j) = 1$.
Answer: The expression has a simple combinatorial interpretation: for a fixed $j$ the expression $j!S(k,j)\binom{n}{j}$ is the number of functions from $[k]$ to $[n]$ whose range has cardinality $j$, so the sum is just the number of functions from $[k]$ to $[n]$, which is $n^k$.


Ubuntu Sendmail Gmail Relay verify=FAIL


Describing the equivalence classes (x, y)R geometrically.

Question: Let say (x, y) R (s, t) if  x + t = y + s and I have already proven that R is an equivalence relation, however, I need to show the equivalence classes (x, y)R geometrically. How would I go about doing so?
Comment: Use latex and tell us which space we are dealing with
Answer: HINT: Let $a$ be any real number. What does the set $\{\langle x,y\rangle:y-x=a\}$ look like when you graph it in the plane?
Comment: @ShadowViper: Note that $x+t=y+s$ if and only if $y-x=t-s$, so you really are looking at a set of points for which $y-x$ is a constant. What does that look like when you graph it?
Comment: So basically I would describe the slope from point (x, t) to (y, s)?
Comment: @dxiv: Thanks for catching that; I read too quickly. (Don't feel the slightest obligation to answer, but just out of curiosity, is that $514$?)
Comment: Funny you'd ask, but it is indeed.


Multi-Catches Problems

Question: I copied something from a different class, and yet it gave me an error even though it didn't in the original. Here's the code:
package com.dinobuilding;

import java.awt.EventQueue;
import java.awt.FontFormatException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.ImageObserver;
import java.io.IOException;

import javax.swing.*;

public class Window {

public static int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
public static int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;

public static ImageIcon background = new ImageIcon("resources/images/Background.png");

public static ImageObserver observer;

public Window() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame frame = new JFrame("DinoBuilding");

            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                ex.printStackTrace();
            }

            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setResizable(false);
            frame.pack();
            frame.setSize(screenWidth, screenHeight);
            frame.setVisible(true);
        }
    });
}

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

}

I've probably messed something up really trivial, but it will not stop telling me "Multi-catches are not supported at this language level". If you need more information that I probably forgot to mention, just ask. Thanks in advance!
Comment: You have a switch on your command line or IDE that's set to Java version 1.6 or less.  Multicatch requires 1.7 or greater.
Answer: Multi catch statements are only supported in Java 7 and  higher versions, make sure that you are not running a version below that.
Check this out  to see how you can change the Project language level in IDEA. I am assuming that you have Java 7 or a version higher installed on your system, if you don't then go and get the latest version of Java
Comment: Right click on the project -> module settings-> Project Language level-> Select Java 7
Comment: Thank you, but I copied it from the same IDE, so that doesn't make a ton of sense.
Comment: @LordMastodon Well, I've noticed that in IDEA as well. I don't know if there is a way to tell IDEA to use a certain lang version by default
Comment: So you're saying that each project has a different JDK thingy?
Comment: @LordMastodon Normally there is a default, but you can certainly set project specific runtimes & compile levels in any modern IDE.
Comment: @LordMastodon No, it has nothing to do with the JDK, IDEA sometimes select a random language level (at least for me )
Comment: @LordMastodon check the project language level and not the JDK
Comment: What do you mean? I'm kinda new to IntelliJ... How do I find that?
Answer: Multi-catches like catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) are only supported from Java 7 and onwards. I believe your JDK/Java compliter is earlier than JDK1.7.
http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Please check that. If possible, upgrade to JDK 1.7. Else use the catch block as following...
try {
  // Do something
} catch (ClassNotFoundException ex) {
  // Do something
} catch(InstantiationException ex) {
 // Do something
} catch(IllegalAccessException ex) {
 // Do something
} catch(UnsupportedLookAndFeelException ex) {
 // Do something
}

Cheers!
Comment: But it did not give me any errors in the original project, which was done in the same IDE.

Multi-Catches Problems


What can I do to address valves getting stuck on a trumpet?

Question: I have a problem with a low-end trumpet ($100 range, so you get what you paid for).
The valves occasionally get stuck-ish, and won't depress fully after being pressed (they stop at around ~2/3 or 3/4 way up). This is usually after oiling the valves.
What seems to fix it somewhat is unscrewing the valves, and pushing them in and out of their seats several times - it almost feels like there's some mis-fit and you have to smooth it out, since pushing in/out encounteres slight resistance. But that fixing is only temporary, and the problem reappears soon.
Is there a set of likely reasons for the issue? Specific steps I can take to troubleshoot and resolve it? (short of buying a more expensive trumpet :)
Answer: I've had similar problems with trumpets. It sounds like your valves / valve-casings are a bit misaligned. This can happen if the previous owner dropped any part of the trumpet / and or dust / dirt become stuck in the valve without them noticing and caused micro-abrasions.
First, and I know this sounds silly, but make sure all the correct valves are paired with their correct casing. There should be a number on each valve that corresponds with the casing.
Second, if everything is where it should be, then you'll want to take it to an instrument repair tech so they can re-grind the valve casings. It's not an expensive procedure - not more than the cost of the trumpet certainly. Bring it in. Get a quote. Have them do the repair. Presto, you have a trumpet.
Comment: With a brand new item, it should go straight back to where it was purchased. There's no 'running-in period' on trumpets.
Comment: note: It's a brand new one, so (hopefully?) no previous owner.
Comment: If the valves aren't in the right slots you'll get worse than sticking.  The holes won't line up and you'll get no sound at all!
Give the whole thing a good clean then apply a minimum amount of oil.  If the valves still stick, take it to a repair man.
Comment: Agreed with Tim - OP didn't specify a new trumpet in the question, so I would send that back to manufacturer.
Comment: For $100, it's almost certainly a trumpet made out of inferior materials and this is (unfortunately) quite inevitable.
Answer: Take out and inspect the sticky valve pistons, looking in particular at the finishing around the edges of the airway holes through the piston. It might be that the edges of the ports are extremely sharp (sharp enough to cut your finger - be careful), or even have slivers of metal hanging off. More expensive instruments don't generally have this problem. If this is the case, it's possible to very carefully burnish (not file!) away the sharp bits, leaving you with much smoother port edges.
There may also be residue in the instrument left over from manufacturing. You might be able to shift this by taking the instrument apart and very carefully cleaning through the tubes with a bendy brush, and the insides of the valve barrels thoroughly with an old toothbrush and washing-up liquid. Finally rinse through with lots of water, then dry and reassemble.
Your playing technique itself can make the valves bind unexpectedly. When you press the valve, ensure that all the force acts through the vertical axis of the valve. If there's any sideways component to the force, you push the valve piston and barrel closer together, making them more likely to stick.
Your choice of valve oil can also make a difference. Use a reputable make - rather than the cheapy stuff probably supplied with the instrument.
Comment: Very important mention of whether the valves are pressed straight down or at an angle.
Answer: This has happened to me before due to a tiny dent in the valve casing. Take the valves out and see if you can see any dents. I think you can get a tool to fix it but you might need to pay someone to fix it.
Answer: Give it a thorough clean.  Use LESS valve oil.   Make sure you are pushing the valves straight down, not 'crabbing' your fingers and pulling to one side.
Or perhaps there is an actual mechanical problem.  It's a new instrument.  Give the valves time to work themselves in.  Or get a repair man to look at it.  Or return it as faulty.


Is there a way to intercept a list of NID's created by a view and use them as a filter for another view?

Question: I am at the point in Drupal experience where I am attempting to solve site design challenges at the custom code level using Drupal and Views APIs. As usual, my apparently simple attempt to solve a problem has demonstrated to me how much I don't know yet!
I have a node-reference field that points to a 'related facts' content used by many different content types and subcategories for each of these types.  While I can create a relationship and display the 'related facts' for a view,  there are problems.  For one, I want the related facts put in a separate block and to display a single list of related facts for the entire list of articles provided by the view.  Views does not handle any duplicates for multiple nids with the same 'related facts' reference well.  In addition, I would have to generate separate 'related facts' views for each content type and subcategory which will be quite a large number.
If I could create a separate related facts view that can accept a list of nids as an argument, the related facts view could be simplified.  So my question is how to go about this. While it may be possible from within views, I am seeking a custom module php solution, so I need to achieve the following:

Extract the results of any of the 'content type' views as a list of arguments.  In addition to displaying the view results, I need to load the list of NIDs that are being displayed.
Call the related facts view and pass the list of nids to it to use as a filter or contextual filter in the 'related facts' view.

Additional Information:
Using this strategy I began by defining a view and attempting to extract the results from it.  This attempt led to a problem finding the results in the view object (see this question).  Once I get the results I will need to generate another view that has those results as filters. I have seen views implemented from code as include files where all the parameters are coded, but have not found examples that define and generate a view and manipulate the results using a php function.  Any examples or links would be appreciated.
Thus Far:
Two answers have addressed the process for applying the results of a view and placing it in another view as a contextual filter.  But I still face the problem of having dozens of content types with at least a dozen view content pane variations in each.  Instead of directly linking each view to the related facts, I will need to have the any of my view1 content views pass its results to a single, separate 'related fact' view.
CONTENT TYPE    SUB-CATEGORY       RELATED FACT (nid)
    Type 1 --------- General Info       101, 105
                     Specifications     103, 105
                     Inspections        102
                     Quality
                     etc...
   Type 2 ----------General Info       101, 106
                    Specifications     102, 103
                    Cost factors       107
                    etc...

View1 finds a specific content type and contains various sub-category articles sorted by the value in a subcategory field.  In addition it contains a node reference field for related facts.  View one filters for a content type and a subcategory and has exposed fields for display and a hidded field with thte related fact reference nodes.
View2 filters for 'related fact' articles and contains a contextual filter set for nid (although the setting applies to the URL)
Using the code in Letharion's answer, the foreach loop in line 6 is compiling a list of the article ID's, not the related fact id's (the articles hold a reference to related facts, but the related facts do not have a node reference to articles).  I need to extract the related fact id's from the facts field in each node.  I have included the facts field in the View1 definition, but cannot find the result since the command dpm($node); has been crashing and I don't know where the values are stored in the array.
Since there will be more than one View1 cloned for different content types I thought it may make sense to use hook_views_post_execute and have coded it as follows:
function mymodule_views_post_execute (&$sourceview) {

  $nids = '';
  foreach($sourceview->result as $node) {
    $nids += $node->nid . ',';  //I need field name for $node->facts

  }

  $nids = rtrim($nids, ',');
  $view = views_get_view('get_related');

  //dpm($nids);  // Fatal error: Cannot unset string offsets...

  $view->execute_display('panel_pane_1', array($nids));
  }

Finally,  I am not sure if I have to direct the display of the view to the proper location or is this done simply by placing the related facts content pane in the panel location through the Panels UI and let panels theming handle the rest.
Comment: Is this Drupal 7? If so I would recommend using [EntityFieldQuery](http://api.drupal.org/api/drupal/includes!entity.inc/class/EntityFieldQuery/7) to retrieve a list of nodes meeting your criteria.
Comment: Can you point to some example code where this API is used.  I am new to the world of Drupal coding and need to follow a real world type example to figure things out.
Comment: http://drupal.org/node/1343708 is a page called "How to use EntityFieldQueries".
Answer: Just off the top of my head
With views 'get_nids', and 'get_related', get_related taking a nid argument, that is set to accept multiple values. This option is hidden under "more", at the bottom of the configuration window.
Option 1:
$view = views_get_view('get_nids');
// Repeating query, ensure the View is set to cache the results.
$view->preview('display_machine_name', array($arg1, $arg2));

$nids = '';
foreach($view->result as $node) {
  $nids += $node->nid . ',';
}
$nids = rtrim($nids, ',');
$view = views_get_view('get_related');
$view->execute_display('display_machine_name', array($nids));
print $view->render();

Option 2:
Add a "context" display type to get_nids, and pass that context on as the argument to a content pane display of get_related. Unfortunately, I would have to guess that Views contexts lacks support for compressing multiple results into a single context, so that may require a feature request in Ctools.
Option 3:
Beth has an excellent suggestion in a comment, which is using EntityFieldQuery, for when you want a pure code solution, that would also work with MongoDB. Views though has the advantage that most of the work can be done in a UI, which is often convenient.
Comment: Hmm!  I think I was confused and may be making this more complicated than it needs to be. Thanks
Comment: Following the code in views_db_object for the ->execute method(Views.inc line 1060). I do not see anything in the method's code that reads the argument (array($nid)). Also, how do I configure the 'get_related' view to accept the filter values in the array($nids) argument?  Do I set filters to 'related content' and contextual filters to accept NIDs?
Comment: Sorry, you are absolutely right, that should have been [execute_display](http://drupalcontrib.org/api/drupal/contributions!views!includes!view.inc/function/view%3A%3Aexecute_display/7), added info about the contextual filter to answer. :)
Comment: I added more info to finish up the issue of displaying the content for the related facts in the question. Please see "Thus far".
Comment: Sorry, I don't understand where the problem is. According to your post, the node-reference field is shared among your content types, and as such view 'get_nids' will gather up all the refered entities. If not however, one would need a loop over the first view.
Comment: After reviewing this, I have edited the additional info section of my question to try and clarify my content and view structure. There are several things I am unclear on.  1. Right now your code is returning the nids of the content types, not the related fact ids. (How can I access them from $view->result  2.  How do I send the 'related fact' content sent to the pane (or is it automatic)?  Would it be possible to turn this into a chat.  This is my first venture into coding with Views api and I don't think I've got it quite clear.
Answer: Seeking out fields within a node and returning a list of NIDs is the exact thing that EntityFieldQueries was born to do. (See also: my own question on the topic).
An example from my code, which runs upon webform submission, and in which I seek out nodes of type "Quiz Anzwer Key" to find the one(s) with field "Quiz Reference" filled in with the NID of the currently-validating webform:
    $arg = arg();
    $nid = $arg[1]; //this finds us the NID of the current page
    $query = new EntityFieldQuery;  // this EntityFieldQuery searches through Entities for Nodes that point to the current Webform.
    $result = $query
        ->entityCondition('entity_type', 'node') // find nodes
        ->propertyCondition('status', 1) // that are published
        ->propertyCondition('type', 'quiz_answer_key')  // of type Quiz Answer Key
        ->fieldCondition('field_answer_quiz', 'nid', $nid, '=') // that point to the current node in their Quiz reference field
        ->execute(); // do the query
    $results        = $query->ordered_results; //grab the results

Then, if you want to actually load values from fields in the nodes, you'd use node_load to grab more info out of the nodes you want, like so:
    $ans_key_id     = $results[0]->entity_id;
    $ans_node       = node_load($ans_key_id);       //once the correct node has been identified, load the contents of that node and suss out the answers

Now $ans_node is an array (or object, I forget) that contains all the info in all the fields in the node. Voilá!
Answer: Ok a coded solution (there area  few) but here is one:

Create a view that gets all the nid's output these nid's as a comma de-liminated list, you can do this by using fields as your output and setting your style settings to Style Unfomatted, row style fields -> make the nid field inline and use a comma as a separator.
In your module create a function that calls this view and gets the output
Create your second view (or display) use this function as an argument in your second view that actually does the display output, so under arguments the argument should be node:nid, the Action to take should be set to "provide default" and you then use the PHP code setting to call your function: return mymodule_get_nids(); ensure he checkbox "allow multiple terms per argument" is ticked

Step 2 code
function mymodule_get_nids() {
    $view = views_get_view('getmynids')) // View name
        $view->set_display('mynids'); // Display name
        $view->execute();
        if ($view->result) {
         return $view->preview(); // Can't remember if this needs to be echo or return try both.
        }
    }
}

Should this be a separate answer?? or an edit??
Comment: I am looking for coded solutions.  I will clarify the question.
Comment: Please correct me if I'm wrong, but as far as I can tell, this wouldn't even solve the problem, as Ashlar is looking to pull in data from multiple relationships at the same time, while attachments will only the "current" one? (It was a while since I made use of attachments though, so I could be wrong)
Comment: Thanks for your effort.  I added more info to finish up the issue of displaying the content for the related facts in the question. Please see "Thus far".


Is it possible to make the set of all sets of cardinality $\aleph_0$?

Question: I know that in ZFC that some collections of objects cannot be gathered together into a set (for example, the "set of all sets") does not exist, nor is "the set that just contains itself."
Is it possible to construct the set of all sets with cardinality $\aleph_0$?  Or does this set not exist?
Thanks!
Answer: It does not exist. Suppose that it did, and call it $C$. The union axiom then ensures that the set $\bigcup C$ exists. But every set $x$ is an element of a countably infinite set, e.g., $\{x\}\cup\omega$, so for each set $x$ there is a $y\in C$ such that $x\in y$, and therefore $x\in\bigcup C$. That is, every set is an element of $\bigcup C$, which you already know is impossible. Thus, $C$ cannot exist.
Comment: Beautiful, thanks!
Comment: @templatetypedef: My pleasure!
Answer: No.
The reason is simple:
For every set $A$, the set $\{ A \} \cup \mathbb N$ is countable. And the set of all such sets would contain the "set" of all sets as a subset.
Answer: Suppose $x$ is a set, and consider corresponding set
$$X_x = \{(0, X), (1, X), (2, X), \ldots \}$$
Then each $X_x$ has cardinality $\aleph_0$, and there are as many of the $X_x$ as there are of sets $x$, i.e. too many to form a set.
Answer: The answer is 'no', as shown by many people here.
There are two ways of trying to make sense of the 'set of all sets', although not in the literal sense. If you are looking for a model of ZFC, then you can consider the collection of all sets whose rank is less than some inaccessible cardinal (assuming that one exists at all). This collection is, of course, still a set in the universe, and it yields a standard model of ZFC. However, inaccessible cardinals are uncountable, so this approach does not yield a countable 'set of all sets'. Note the quotation marks!
However, if ZFC is consistent, then there exists a countable model of ZFC, which is a consequence of the Löwenheim-Skolem Theorem from logic and model theory. Therefore, you may want to take this model to be your 'set of all sets'.
Whatever it is, from the model-theoretic point of view, this 'set of all sets' is never going to be an element of itself.


how to use custom markup for views field

Question: I have a view and there are about five fields in the view now I want to apply my own HTML markup on each field in a view. because I have created it in custom just need to apply on a view. how can I apply my own HTML markup on it?
Answer: This can be done with the fields style settings inside the view, rewrite results setting, or you can do this within a template file(or combination of all three) for full control over the output of the view.
This can be found under Advanced -> Theme -> Information.  There are various view template options which you can edit, but the primary one you'll probably want is: 'Row Style Output'.

You will notice various filenames after the 'Row Style Output'.  The first one being the default view theme (in bold).  Copy one of the file names (non bolded) and use that file name to create a new TPL file in your theme.
Once you have added the new file to your theme directory, within your view, in the theme: information settings window, at the bottom you will find a button 'rescan template files'.  After clicking this button, the view will recognize your newly added TPL file and use this to style your views rows.
From here, you simply need to render your fields with whatever HTML you want around them.

I prefer to keep everything in one place.  I do this by changing the style settings to render the field with '- none -' HTML elements.

Then from there I create my views TPL file and render the views with my custom HTML markup.  This, for me, is easier being able to manage all the HTML in a single file rather then editing the HTML per field.
Good luck!
Answer: Add a Global: custom text field and past your custom markup remove your existing content like text images etc and replace tokens by them from replacement patterns. you will get the same results on both custom and Drupal.
Comment: yes its very simple and its work fine for me
Answer: If you want to apply your own html wrapper for each field then edit your view and edit the field you want to apply markup.
Expand "Rewrite results" and check "Rewrite the output of this field" checkbox.
Click on "Replacement patterns" option and here you can see the token related to your field e.g ([nid] == Content: Nid) this is for nid field.
In textarea below "Rewrite Result" checkbox put your markup like
given in image.


Why $\mathbb{RP}^2$ can not be embedded to $\mathbb{R}^3$?

Question: Is there any answer of this question around basic theory of differentiable manifolds?
Comment: Georges Elencwjag has deleted a much better answer, just using his simple proof that every embedded hypersurface $S$ is the zero locus of a single equation with nontrivial differential on $S$, which I'll leave here until such time as he should undelete. http://math.stackexchange.com/questions/879334/smooth-surfaces-that-isnt-the-zero-set-of-fx-y-z/879449#879449
Comment: http://en.wikipedia.org/wiki/Real_projective_plane#Examples gives an outline of a proof using the Jordan separation theorem.
Comment: Dear @Kevin: your extremely kind words (for which I thank you)  have made me decide to undelete my answer...
Comment: @GeorgesElencwajg glad to hear it! As you say, it's a bit embarrassing that the argument is not obvious to one who's studied some differential topology, let alone that it's not well known.
Answer: Every closed smooth hypersurface   $X\subset \mathbb R^n$ (=submanifold of dimension $n-1$), compact or not, has an equation,  i.e.  $X=f^{-1}(0)$ for some  smooth $f:\mathbb R^n\to \mathbb R$ satisfying  $df(x)\neq0$ for all $x\in X$.
In particular $X$ is orientable so that  $\mathbb P^2(\mathbb R) $, which is not orientable, cannot be embedded into $\mathbb R^3$
(Non-) bibliography
The fact that every closed hypersurface  in $\mathbb R^n$ has an equation is unfortunately not proved nor even mentioned in any book I know on differential manifolds or differential geometry.
It is however rather elementary and depends on methods developed  60 years ago in complex analysis : I wrote a proof here. (See also there, where only orientability of hypersurfaces is proved.)
Comment: @John: Yes, for me a hypersurface is closed (else I'd speak of a locally closed hypersurface), but in order to prevent any misunderstanding I have edited the answer  and added the word "closed" explicitly to the word "hypersurface" . Thanks for your comment.
Comment: I guess the hypersurface has to be complete?
Answer: The Stiefel-Whitney class of $\Bbb RP^2$ is $(1+a)^3=a^2+a+1 \in H^*(\Bbb RP^2,\Bbb Z/2)$ where $a$ is the unique nonzero element in $H^1$. The inverse of this element in $H^*(\Bbb RP^2,\Bbb Z/2)$ is $1+a$. As the top Stiefel-Whitney class of the normal bundle of an embedding into $\Bbb R^n$ vanishes (c.f. Milnor-Stasheff Cor. 11.4) $1+a$ is not the Stiefel-Whitney class of the normal bundle to  an embedding into $\Bbb R^3$, hence there is no embedding $\Bbb RP^2\rightarrow \Bbb R^3$. The theory of characteristic classes gives numerous obstructions to embeddings, immersions, cobordisms and other similar geometric constructions. A place to start is the Milnor-Stasheff book Characteristic Classes cited in this answer.
The above argument easily generalizes to show $\Bbb RP^{2^n}$ does not embed in $\Bbb R^{2^{n+1}-1}$, hence the inequality in the strong Whitney embedding theorem is sharp for dimensions arbitrarily large.
Comment: Wonderful! I wanted to write that exact same argument  but I got stuck because I couldn't see why *a priori*  the first Stiefel-Whitney class of the normal bundle should vanish. Thanks for teaching me that great general vanishing result in Milnor-Stasheff, PVAL .
Answer: The simplest solution is via Alexander duality, which shows immediately that every surface in $S^3$, in particular in $\mathbb{R}^3$, is orientable.
Comment: Note that the separation theorem mentioned in the comments above is a special case of Alexander duality (which is much easier to prove than the full theorem).
Comment: The theorem Wiki cites is for a topological sphere. It seems like a big generalization to get to any surface-any idea whether it's actually still easier?


Eliminar sessão de usuário em ASP.NET MVC com [Authorize]

Question: Tenho um sistema web desenvolvido em ASP.NET MVC 4.
Uma das funcionalidades é o gerenciamento de usuários. Um CRUD de usuários.
Meu método de login é o seguinte:
[HttpPost]
public ActionResult Login(LoginViewModel loginViewModel)
{
    if (_loginService == null)
        _loginService = new LoginService();

    var result = _loginService.Login(loginViewModel.User, loginViewModel.Password);
    if (!result.Error)
    {
        var userData = JsonConvert.SerializeObject(result.User);
        FormsAuthentication.SetAuthCookie(result.User.Id, false);
        var ticket = new FormsAuthenticationTicket(1, result.Id, DateTime.Now, DateTime.Now.AddMinutes(9999), true, userData, FormsAuthentication.FormsCookiePath);
        var encryptedCookie = FormsAuthentication.Encrypt(ticket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie) { Expires = DateTime.Now.AddHours(14) };

        Response.Cookies.Add(cookie);
    }
    return new JsonResult
    {
        Data = result
    };
}

Sim, está em inglês mesmo porque o sistema será mantido por várias empresas.
Enfim, trato o retorno desse método no lado cliente, com javascript.
Como podem imaginar, eu utilizo o atributo [Authorize] em toda Controller em que a autenticação é obrigatória.
Vamos supor que eu acabei de logar no sistema com o usuário StackOverflow. Estou navegando normalmente até que um outro usuário identificado como DoMal resolve me excluir do sistema. Como eu estou somente excluindo o usuário na ação de Delete, o usuário StackOverflow irá navegar normalmente no site mesmo quando for excluido. Até, obviamente, o cookie expirar. O problema é que eu quero alguma maneira de terminar a sessão dele de imediato.
Tem alguma forma de terminar a sessão somente do StackOverflow no IIS? Ou forçar o cookie a expirar?
A unica coisa que eu não quero fazer é criar uma verificação de existencia do usuário on-line em cada ação feita no site.
Alguma ideia, sugestão?
Comment: Aqui tem um começo de onde pode seguir. http://stackoverflow.com/questions/12379215/how-to-force-logout-user-when-his-her-username-is-changed-by-another-user
Comment: Quando o usuario é removido, você tem acesso à id dele (ou algo do tipo). O que te impede de chamar SignOut nesse usuário? Nesse caso vc "deslogaria" esse usuario somente no metodo do controller que remove tal usuario. Para lidar o cookie, ja tentou FormsAuthentication.SetAuthCookie(user, false)? Se nada funcionar, voce pode fazer sua verificacao em Application_BeginRequest ao inves de espalhar pelo sistema.
Comment: @victor: Porque o `SignOut` não aceita parâmetros.. eu quero fazer o `SignOut` de um usuário que não seja o corrente. Sim, já uso o `FormsAuthentication.SetAuthCookie(user, false)`. Quanto a implementação do `beginRequest` é justamente o que eu não quero fazer: Em toda `request`, validar a existencia do usuário no banco.
Comment: @MarllonNasser por favor, caso a resposta abaixo esteja correta, favor assinlar. obrigado
Comment: @ThomasErichPimentel: A resposta não atende à minha necessidade em específico mas funcionaria no geral.
Answer: Você tem que implementar o seu próprio Authorize Attribute. Você pode reaproveitar a implementação existente e derivar do atributo authorize e fazer as modificações que necessita:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        if (actionContext.RequestContext.Principal != null &&
            actionContext.RequestContext.Principal.Identity.IsAuthenticated)
        {
            //o utilizador está autenticado, mas será que ainda existe na base de dados?

            var userName = actionContext.RequestContext.Principal.Identity.Name;
            object user = null;  //aqui faz consulta na base de dados por userName
            if (user == null) //se o utilizador nao existe, apaga o cookie
            {
                FormsAuthentication.SignOut();
            }

        }
        base.HandleUnauthorizedRequest(actionContext);
    }
}

Não garanto que esse código vá funcionar á primeira, mas deve dar-lhe uma ideia do que deve de fazer.
Comment: mas isso seria em cada requisição, certo?
Comment: @Marllon Nasser voce usa o atributo da mesma forma que o Authorize. Pode mete-lo nos controllers ou nas actions


How to turn off position-independent code compilation in Microsoft Visual Studio C/C++ compiler?

Question: I'm wondering if it's possible to turn off this position-independent code thing to change the assembly call instruction from something like
call [rip+0x1234] // this address is relative to the current code position

to something like
call qword ptr[0x12345678] // this address is absolute and doesn't crash the program

The reason for this is that I create a remote thread by calling CreateRemoteThread from WinAPI and I want to be able to call other WinAPI functions inside by just typing normal code, but now as the PIC is on, every time I call any function inside the remote thread I get an access violation and the process crashes. It's also worth mentioning that I know every process has different imported functions addresses, but I'm only calling functions from kernel32.dll which is loaded at the same absolute address in every process as far as I know, so this isn't a problem.
Is there some macro or compiler option for this? I would also like to change that behaviour only for compilation of one file, not all in the solution.
Of course my CPU architecture is amd64 but I thinks that's irrelevant.
Thanks in advance!
Comment: Very unlikely that you can.  RIP-relative addressing is more efficient than `[disp32]` so using `call qword ptr [abs address]` would be a pessimization (costing 1 extra byte of code size per such instruction).  That's why compilers always use RIP-relative addressing to load or store static data, only using absolute addressing in non-PIE (e.g. on Linux) for putting the address of a symbol into a register.  (`mov ecx, OFFSET symbol` is only 5 bytes.) See [Why does this MOVSS instruction use RIP-relative addressing?](https://stackoverflow.com/q/44967075)
Comment: problem not in this (anyway not exist any shared global variables which hold addresses of dll). problem - you dont know how write base independed code in c++. despite this is not too hard. use class. store all function addresses and data which you need in this class. you must not access any global variables. but you can access class/struct members
Comment: So your plan is to just copy a function generated by something you don't have full control over directly into another process and hope for the best?
Comment: @Anders no, my plan is to be able to call `kernel32.dll` functions inside remote thread routine, that's all
Answer: If I understood you correctly, this is wrong on at least three levels.

There is no guarantee the new host process is importing the APIs you call. If you call CryptAcquireContext the linker will be sure to add an entry for advapi32.dll and CryptAcquireContext in the PE built, which is the source binary. The target may not have such import in the first place.

call QWORD PTR [target] still uses a 32-bit RIP-relative displacement in MASM syntax, for a symbol name not a literal number. The import address fixed by the loader can very well be above 2GiB (and almost always is). I don't think you can force cl (try with the link option /LARGEADDRESSAWARE:no, but it's a link option, not a compiler one) to not use a RIP-relative address for these calls. But even if you did, that would work for your PE, not for the target PE. Your PE would need to be loaded below the 2GiB (for signed 32-bit absolute [disp32]) while it's almost certain the target PE will not be.
gcc -fno-pie -mcmodel=large would use indirect calls with 64-bit absolute addresses (mov reg, imm64 / call reg) for everything, not assuming that call targets are within +-2GiB, but MSVC probably doesn't have such an option.

An absolute address needs a relocation. You may be able to force cl/link to emit a PE that is not moveable and avoid the need for relocations but, again, this is for your PE, not the target one.

In short, your assembly code and your binary executable are tied together to create a process where your code will work as expected.
If you migrate to another process you have to make up for the differences and it won't be like writing normal code (including accessing global data).
If you are already writing a DLL the easiest thing is to use SetWindowsHookEx to hook the newly created remote thread with a function in your DLL. Windows will automatically inject your whole DLL into the target process. Use any hook you know will be called at least once (this is easy since you control the code of the remote thread).
Otherwise, you can move the injected code in a DLL and inject a shim/loader that loads said DLL from disk/memory.
Comment: I made some edits to clarify your points and correct some details, like that `[disp32]` addressing can only access the low 2GiB of address space, not 4G unless you also used a `67h` address-size prefix.  Because it's signed absolute.  You should probably have a look to make sure I understood the points you were trying to make and didn't distort things.
Comment: @PeterCordes Thanks, I always forget about this sign-extension effect :)


Is the Dynamic Time Warping constraint Itakura Parallelogram based on series length?

Question: I'm looking into the Itakura Parallelogram global constraint for Dynamic Time Warping.
I am confused about the maximum width of the parallelogram, is it solely based on the length of the two time series being compared, or can it be varied to achieve a bigger or smaller warping window?
Answer: The maximum width (or the length of the smaller diagonal) of the paralelogram is implicitly dependent on the maximum allowed delay (or distance), around the middle of the signal. In this example figure (taken from here), the maximum allowed delay is $dt=4$ and hence the length of the diagonal is $\sqrt{2} dt = 5.66$.
If you take that (maximum allowed delay) as parameter, the absolute width of the paralelogram does not change when the series length change. However, you could instead take as fixed parameter the slope of the paralelogram sides (which would be equivalent to impose a maximum "speed change" between the two signals). In this case, the shape of the paralelogram would not change with the series length, and the size of the smaller diagonal woul be proportional on the series length.
Comment: @Chris: you can change the maximum allowed delay (as in the Sakoe/Chiba bands) as you like
Comment: Does this mean I could alter the maximum allowed delay? So for the example figure could I set dt=6, so that I would have a wider parallelogram in the middle? Or for that example does dt always equal 4?
Comment: thanks for the clarification. I was just looking at the R implementation of Itakura Parallelogram and it has no way of setting max allowed delay, so it threw me off because I had assumed you could alter it.


Boundary of boundary of closed set equals boundary of this set

Question: I want to prove that for a closet set $A\subset \mathbb{R}^n$, $\partial A = \partial(\partial A)$. I've already proved that for an arbitrary subset $B$ of $\mathbb{R}^n$, $\partial(\partial B)\subseteq \partial B$ by arriving at the fact that $\partial B\backslash \mbox{interior}(B)\subseteq \partial B$, which points to the fact that the interior of the boundary of a set is not necessarily empty. However, unfortunately, I do not probably understand intuitively how it can be empty. Except that, in $\mathbb{R}^4$, say, the boundary can be a 3-dimensional subset, whose interior does not need to be empty. But then, why should the interior of the boundary of a $\underline{\text{closed}}$ set be necessarily empty? For if we consider the same analogy with $\mathbb{R}^4$, we should also intuitively feel that a boundary can be a 3-dimensional subset, whose interior need not be empty.
Here's also my attempt:
$\partial A= \overline{A}\backslash A^\circ=\overline{\overline{A}\backslash A^\circ}=\overline{A\backslash A^\circ}$.
Now, $(A\backslash A^\circ)^\circ=A\backslash \overline{A^\circ}$. If I can show that the RHS is the empty set then I'll deduce that
$\overline{\overline{A}\backslash A^\circ}\backslash (\overline A\backslash A^\circ)^\circ=\partial (\partial A)=\overline{\overline{A}\backslash A^\circ}=\overline{A}\backslash A^\circ=\partial A$.
I'd appreciate your help.
Answer: The boundary $\partial A$ of a closed subset $A \subseteq \mathbb{R}^n$ has empty interior, because any open neighborhood of any point $x \in \partial A$ contains points that are not in $A$ (by definition of boundary), therefore not in $\partial A$ (since $A$ is closed.)
This is certainly not true for arbitrary subsets. The boundary of $\mathbb{Q}^4$ is all of $\mathbb{R}^4$. But then $\mathbb{Q}^4$ is not closed.
Answer: Let $A \subset \mathbb{R}^N$ and let $a \in A$. We say that $a$ is an interior point of $A$ if there is a positive radius $r > 0$ such that $B(a,r) \subset A$, where $B(a,r)$ is the $N$-dimensional ball centered at $a$ with radius $r$. Notice that the ball you want to consider is $N$-dimensional independently of the dimension of the subset $A$. In particular, if $A$ is an $N-1$-dimensional subset then it cannot contain any $N$-dimensional ball and hence it will have empty interior. Indeed, most of the boundaries that we usually picture in our minds are hypersurfaces and hence have empty interior.
To conclude the proof we need to prove that $\partial A$ has empty interior. This follows from the fact that if $a \in \partial A$, then every neighborhood of $a$ contains a point that is not in $A$. Since $\partial A \subset A$ (recall that by assumption $A$ is closed) we have that every neighborhood of $a$ contains a point that is not in $\partial A$ and hence $a$ cannot be an interior point of $\partial A$.
Answer: We have $\partial A=\partial(\partial A)$ for closed $A$ in any topological space $X$ since $\partial (cA)=\partial\partial(cA)$ holds for all $A\subset X$ where $c$ is closure and $A$ is closed iff $A=cA.$ Perhaps the easiest way to prove this is to begin by substituting $\partial cA$ for $A$ in the identity $cA=\partial A\cup iA$ where $i$ is interior to get $\partial cA=\partial\partial cA\cup i\partial cA$ $(\mbox{since }c\partial A=\partial A).$ The result then follows since $ickA=kciA$ holds for all $A\subset X$ where $k$ is complement, $i$ distributes over intersection, and $c(cA)=cA,$ thus $$i\partial cA=i(c(cA)\cap ck(cA))=i(cA)\cap i(ck(cA))=i(cA)\cap k(ci(cA))=icA\setminus c(icA)=\emptyset.$$


É possível obter um atributo pai sendo que a classe define o atributo filho?

Question: Supondo que eu tenha a seguinte hierarquia:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class GrandpaAttribute : Attribute
{
    public GrandpaAttribute() {}
}

public class ParentAttribute() : GrandpaAttribute
{
    public string Name { get; }

    public ParentAttribute(string name)
    {
        Name = name;
    }
}

public class ChildAttribute() : ParentAttribute
{
    public int Number { get; }

    public ChildAttribute(string name, int number) : base(name)
    {
        Number = number;
    }
}

Em determinada aplicação, eu uso o atributo ChildAttribute:
public class Foo
{
    [Child("The Beast", 666)]
    public string Description { get; set; }
    public DateTime SomeDate { get; set; }
}

Surgiu a dúvida:
É possivel abstrair a herança entender que a propriedade Description possui o atributo GrandpaAttribute?
Minha intenção é obter uma instância de GrandaAttribute definida em uma propriedade da classe Foo como ParentAttribute, ChildAttribute ou qualquer outro atributo derivado dele.
Answer: Pelo que eu entendi, você deseja, chegar na instância da classe GrandpaAttribute, por motivos de teste adicionei uma propriedade First para que o teste seja realizado, primeiro se busca a instância real, e depois com um cast chega na classe GrandpaAttribute, exemplo:
using System;
using System.Reflection;

[System.AttributeUsage(AttributeTargets.Property,AllowMultiple=false, Inherited=true)]
public class GrandpaAttribute : Attribute
{
    public GrandpaAttribute()
    {
        First = "Teste";
    }
    public string First {get;set;}
}

public class ParentAttribute : GrandpaAttribute
{
    public string Name { get; private set; }

    public ParentAttribute(string name)
    {
        Name = name;
    }
}

public class ChildAttribute : ParentAttribute
{
    public int Number { get; private set; }

    public ChildAttribute(string name, int number)
        : base(name)
    {
        Number = number;
    }
}

public class Foo
{
    [Child("The Beast", 666)]
    public string Description { get; set; }
    public DateTime SomeDate { get; set; }
}

public class Program
{
    public static void Main()
    {
        ChildAttribute childAttribute = typeof(Foo)
                .GetProperty("Description")
                .GetCustomAttribute<ChildAttribute>(true);

        Console.WriteLine(((GrandpaAttribute)childAttribute).First);
    }
}

Um exemplo OnLine DotNetFiddle
Comment: Obrigado por checar, mas eu acho que não me expressei bem. Eu não quero ter que usar `GetCustomAttribute`, pois no método que eu estou planejando não me interessa especificamente qual descendente de `GrandaAttribute` está definida, se é `Child` ou `Parent` ou alguma outra que eu criar depois... Vou editar a minha pergunta incluindo isso, é uma informação relevante que eu deixei passar.
Comment: Ababei de perceber que funciona! Usando seu exemplo no DotNetFiddle fiz a modificação do tipo `Child` para `Grandpa` e funcionou perfeitamente. Vou fazer essa edição e lhe garantir os créditos. Obrigado.
Comment: Ele apenas quer `.GetCustomAttribute(true);` retorne também os `ChildAttribute`. @DiegoRafaelSouza  Isso funciona porque uma expressão: `(new ChildAttribute("",1) is GrandpaAttribute)` é verdadeira =]
Comment: @DiegoRafaelSouza fique um pouco sem entender, mas, qualquer coisa deixe uma explicação qual é o seu objetivo final
Comment: pois é, eu fiquei me questionando se o código da pergunta já não estava funcionando... rs mas não tive como dar atenção