text:
Q: Filtering based on a URI in SParQL You can run the query below at the Linked MDB SPARQL Explorer. The values of ?imdbID (the last variable) contains IRIs from one of three possible domains (freebase.com, rottentomatoes.com or imdb.com). I would like to know how to apply a filter such that only the rows from the imdb.com domain are retained.
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc: <http://purl.org/dc/terms/>
PREFIX movie: <http://data.linkedmdb.org/resource/movie/>

SELECT ?title ?date ?director ?imdbID
WHERE {
 ?film foaf:page ?imdbID.
 ?film dc:title ?title.
 ?film dc:date ?date .
 ?film movie:director ?directorURI.
 ?directorURI rdfs:label ?director .
}

A: Not sure why this wasn't posted by @JoshuaTaylor as an answer but adding @JoshuaTaylor's filter to your query is what you are requesting:
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc: <http://purl.org/dc/terms/>
PREFIX movie: <http://data.linkedmdb.org/resource/movie/>

SELECT ?title ?date ?director ?imdbID
WHERE {
 ?film foaf:page ?imdbID.
 ?film dc:title ?title.
 ?film dc:date ?date .
 ?film movie:director ?directorURI.
 ?directorURI rdfs:label ?director .
 FILTER(regex(str(?imdbID), "www.imdb.com" ) )
}

Which returns:
<?xml version="1.0"?>
<sparql
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:xs="http://www.w3.org/2001/XMLSchema#"
    xmlns="http://www.w3.org/2005/sparql-results#" >
  <head>
    <variable name="title"/>
    <variable name="date"/>
    <variable name="director"/>
    <variable name="imdbID"/>
  </head>
  <results>
    <result>
      <binding name="title">
        <literal>Buffy the Vampire Slayer</literal>
      </binding>
      <binding name="date">
        <literal>1992-07-31</literal>
      </binding>
      <binding name="director">
        <literal>Fran Rubel Kuzui (Director)</literal>
      </binding>
      <binding name="imdbID">
        <uri>http://www.imdb.com/title/tt0103893</uri>
      </binding>
    </result>
    <result>
      <binding name="title">
        <literal>Batman</literal>
      </binding>
      <binding name="date">
        <literal>1989-06-23</literal>
      </binding>
      <binding name="director">
        <literal>Tim Burton (Director)</literal>
      </binding>
      <binding name="imdbID">
        <uri>http://www.imdb.com/title/tt0096895</uri>
      </binding>
    </result>
    <result>
      <binding name="title">
        <literal>Batman</literal>
      </binding>
      <binding name="date">
        <literal>1966-07-30</literal>
      </binding>
      <binding name="director">
        <literal>Leslie H. Martinson (Director)</literal>
      </binding>
      <binding name="imdbID">
        <uri>http://www.imdb.com/title/tt0060153</uri>
      </binding>
    </result>
    <result>
      <binding name="title">
        <literal>Batman & Robin</literal>
      </binding>
      <binding name="date">
        <literal>1997-06-20</literal>
      </binding>
      <binding name="director">
        <literal>Joel Schumacher (Director)</literal>
      </binding>
      <binding name="imdbID">
        <uri>http://www.imdb.com/title/tt0118688</uri>
      </binding>
    </result>
    <result>
      <binding name="title">
        <literal>Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb</literal>
      </binding>

If you want to make it case insensitive you can use the i flag like so:
FILTER(regex(str(?imdbID), "www.IMDB.com", "i" )

If you want to see some more information on filter have a look at 3.1 Restricting the Values of Strings.


text:
Q: How to shift from /admin to the domain name? My problem is that I have installed worpress on CPanel. But when I access my site name i.e. www.loophole.ml it shows the index / page. But when I open www.loophole.ml/admin then I shows my website.
How I can make it directly that when I search www.loophole.ml my website appear not the Index/ page.

A: Easiest solution is to take wordpress out of the admin folder and install it in the parent folder, e.g.
public_html <-- Copy files into this folder
 - admin
 - cgi-bin

Once the files are in place you will need to alter the database so that the home_url and site_url are the same (http://loophole.ml/). These fields are located in the wp_options table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Key-Based Caching in Play Framework with Scalaz Involved I am attempting to do some key-based caching for my Play Framework application. Here is the code for the handler at my endpoint:
optionT(findById(id)).map { thing =>
      val cacheKey = thingCacheKey(thing)
      cached(cacheKey) {
        Action.async { implicit request =>
          val result = //Produce a result—probably Ok("content")
          } yield result
        }
      }
}.run.map {
  case Some(actionF) => actionF
  case None => Action.async(Future.successful(NotFound()))
}

As you can see, I am using Scalaz's optionT monad transformer.
Not terribly surprisingly, I get this error:
Cannot use a method returning scala.concurrent.Future[play.api.mvc.EssentialAction] as a Handler for requests
Can you show me how to return a Result rather than EssentialAction with this approach?

A: Play cache api has not any monadic composers nor has it Action so really need to run actions up to Iteratee which has flatten method that could unwrap this Future. This is example of successfully compiled approach
Action.async { implicit request => Iteratee.flatten {
  optionT(findById(id)).map { thing =>
    val cacheKey = thingCacheKey(thing)
    val action = cached(cacheKey) {
      Action.async{
        Future(Ok)   // replace with your processing of "request"
      }
    }

    action.apply(request)
  }.getOrElse(Iteratee.ignore[Array[Byte]].map(_ => NotFound))
}.run
}

Here we unwrapping OptionT transformer via getOrElse, not via run.map{ }, and then running Iteratee to Future[Result]


text:
Q: Selenium WebDriver findElement(By.xpath()) get value of this element Part of it look like this:
<input type="hidden" id="recaptcha-token" value="Need This Value">

I'm running Selenium like this:
driver.findElement(By.xpath("[@id=\"recaptcha-token\"]"));

How I can get "Need This Value" from running this code ?

A: For your specific case, you can first get the element like so:
driver.findElement(By.xpath("//*[@id='recaptcha-token']")); // Any element with that id

driver.findElement(By.xpath("//input[@id='recaptcha-token']")); // More specific to your tag

And then you get the attribute you want using getAttribute(String attrName).
A one-liner would then be:
driver.findElement(By.xpath("//input[@id='recaptcha-token']")).getAttribute("value");

If you only want to look for an element with that id, you could simplify that call by using By.id() instead of By.xpath():
driver.findElement(By.id("recaptcha-token"));


text:
Q: I need a very simple way for my VB.NET program to 'phone home' (i.e. send a simple message) I used to get it to send an email, but this seems to only work half of the time.
I just need a relatively fail-safe way to send a ~20KB plain text message to somewhere I, the developer, can access on the Internet.
Any suggestions would be greatly appreciated. Thanks.


text:
Q: SAS store the character representation on a date in a macro variable I have a table looking like this
DATE
01FEB2001
02FEB2001
...

After loading this table I create macro-variables like
data _null_;
    set TBL end=eof;
    call symput('dtBourse'||left(_N_),DATE);
run;

My problem is that the dtBourse1,dtBourse2 macro variables are worth 17433... (their underlying integer value as a date is stored as an integer)
How can I make sure the macro-variable are characters "01FEB2001","02FEB2001"

A: The easiest way is to use the VVALUE function, which returns the formatted value
call symput('dtBourse'||left(_N_),vvalue(DATE));


text:
Q: OpenGL es 2.0 draw line with red color I have shader code like below:
static const char s_v_shader[] =
"attribute vec4 vPosition; \n"
"attribute vec2 my_Texcoor;     \n"
"uniform   mat4 u_TransMatrix;   \n"
"varying vec2 vTexcoor;         \n"
"void main() \n"
"{ \n"
"  vTexcoor = my_Texcoor;       \n"
" gl_Position = u_TransMatrix*vPosition; \n"
"} \n";

static const char s_f_shader[] =
"precision mediump float;\n"
"uniform sampler2D my_Sampler;                    \n"
"varying vec2 vTexcoor;                           \n"

"void main() \n"
"{ \n"
" vec4 tex = texture2D(my_Sampler, vTexcoor);    \n"
"  gl_FragColor = tex;                            \n"
//" gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );\n"
"} \n";

I want to draw line on this texture and fill red color to the line.
I am able to draw the line but color is always black.
Please someone help me to color the line with red or yellow or green.

A: You can not draw to a texture. You may draw to a FBO (frame buffer object) which has an attached texture.
To achieve this you simply need to generate a new frame buffer GLuint bufferID; glGenFramebuffers(1, &bufferID); then you need to bind the buffer and attach the texture to it glBindFramebuffer(GL_FRAMEBUFFER, bufferID) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureID, 0). Now you can normally draw to this buffer using your commands to draw the line. In this case there is no need to use a texture in the shader at all, you only need to output the color. But this only draws to the texture, if you need to show it then you will need to bind your main buffer and use the shader with the texture and draw a full screen rectangle with the texture you have.
On the other hand if you only want to draw the texture and the line over it then you need 2 draw calls. First draw the texture in the background by drawing a rectangle with the texture in the shader. Then draw a line with a shader that only takes in the color, no textures there.

A: With reference to above shaders, below is the code

vertShaderNum = glCreateShader(GL_VERTEX_SHADER);
pixelShaderNum = glCreateShader(GL_FRAGMENT_SHADER);
CompileShader(s_v_shader, vertShaderNum);
CompileShader(s_f_shader, pixelShaderNum);
programHandle = glCreateProgram();
glAttachShader(programHandle, vertShaderNum);
glAttachShader(programHandle, pixelShaderNum);
glBindAttribLocation ( programHandle, 0, "vPosition" );
glLinkProgram(programHandle);
glUseProgram(programHandle);

locVertices = glGetAttribLocation(programHandle, "vPosition");
locTexcoord = glGetAttribLocation(programHandle, "my_Texcoor");
locTransformMat = glGetUniformLocation(programHandle, "u_TransMatrix");
locSampler = glGetUniformLocation(programHandle, "my_Sampler");

glGenTextures(1, &gTexObj);
        glBindTexture(GL_TEXTURE_2D, gTexObj);

const GLfloat vertices[][2] = {
                        { -1.0f, -1.0f},
                        {  1.0f, -1.0f},
                        { -1.0f, 1.0f},
                        {  1.0f,  1.0f}
                };

const GLfloat texcoords[][2] = {
        { 0.0f, 1.0f},
        { 1.0f, 1.0f},
        { 0.0f, 0.0f},
        { 1.0f, 0.0f}
};
GLfloat transformMatrix[16] =
{
        1.0f, 0.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 1.0f, 0.0f,
        0.0f, 0.0f, 0.0f, 1.0f
};
glUniformMatrix4fv(locTransformMat, 1, GL_FALSE, transformMatrix);
glUniform1i(locSampler, 0);

Now in infinite loop
While(1)
{

glEnableVertexAttribArray(locVertices);
        glEnableVertexAttribArray(locTexcoord);

        // set data in the arrays.
        glVertexAttribPointer(locVertices, 2, GL_FLOAT, GL_FALSE, 0, &vertices[0][0]);
        glVertexAttribPointer(locTexcoord, 2, GL_FLOAT, GL_FALSE, 0, &texcoords[0][0]);

=========> I am rendering camera video logic......................

float vVertices[] =
        {
                -0.85f, -0.9f, -0.6f, -0.5f,
        };
        glVertexAttribPointer ( 0, 2, GL_FLOAT, GL_FALSE, 0, vVertices );
        glEnableVertexAttribArray ( 0 );
        lDrawArrays ( GL_LINES , 0, 2 );
        glLineWidth( width_test );

Till now everything is good. camera Video is rendered on display.
Line is drawn on Video texture.
Now I want to color the line............. I am stuck as there is no API call support to color the line in opengles 2.0....

A: @Matic
static const char s_v_shader[] =
"attribute vec4 vPosition; \n"
"attribute vec2 my_Texcoor;     \n"
"uniform   mat4 u_TransMatrix;   \n"
"varying vec2 vTexcoor;         \n"
"void main() \n"
"{ \n"
"  vTexcoor = my_Texcoor;       \n"
" gl_Position = u_TransMatrix*vPosition; \n"
"} \n";
static const char s_f_shader[] =
"precision mediump float;\n"
"uniform lowp vec4 Texture;  \n "
"uniform sampler2D my_Sampler;                    \n"
"varying vec2 vTexcoor;                           \n"

"void main() \n"
"{ \n"
" vec4 tex = texture2D(my_Sampler, vTexcoor);    \n"
"  gl_FragColor = tex;                            \n"
"} \n";
#endif

static const char s_v_shader_new[] =
"attribute vec4 vPosition_new; \n"
"attribute vec2 my_Texcoor_new;     \n"
"uniform   mat4 u_TransMatrix_new;   \n"
"varying vec2 vTexcoor_new;         \n"
"void main() \n"
"{ \n"
"  vTexcoor_new = my_Texcoor_new;       \n"
" gl_Position = u_TransMatrix_new*vPosition_new; \n"
"} \n";

static const char s_f_shader_new[] =
"precision mediump float;\n"
//"uniform sampler2D my_Sampler_new;                    \n"
"uniform lowp vec4 uniformColor;\n"
//"uniform vec4 uniformColor;\n"
"varying vec2 vTexcoor_new;                           \n"

"void main() \n"
"{ \n"
" gl_FragColor = vec4 ( 1.0, 0.0, 0.0, 1.0 );\n"
"} \n";
#endif

const GLfloat vertices[][2] = {
    { -1.0f, -1.0f},
    {  1.0f, -1.0f},
    { -1.0f, 1.0f},
    {  1.0f,  1.0f}
};

const GLfloat texcoords[][2] = {
    { 0.0f, 1.0f},
    { 1.0f, 1.0f},
    { 0.0f, 0.0f},
    { 1.0f, 0.0f}
};

// Triangle Vertex colors.
const GLfloat color[][3] = {
    {1.0f, 0.0f, 0.0f},
    {0.0f, 1.0f, 0.0f},
    {0.0f, 0.0f, 1.0f},
    {1.0f, 1.0f, 0.0f}
};

// Start with an identity matrix.
GLfloat transformMatrix[16] =
{
    1.0f, 0.0f, 0.0f, 0.0f,
    0.0f, 1.0f, 0.0f, 0.0f,
    0.0f, 0.0f, 1.0f, 0.0f,
    0.0f, 0.0f, 0.0f, 1.0f
};

void LoadShaders_new(const char * vShader, const char * pShader)
{
        vertShaderNum_new = glCreateShader(GL_VERTEX_SHADER);
        pixelShaderNum_new = glCreateShader(GL_FRAGMENT_SHADER);
#if 1
        if (CompileShader(vShader, vertShaderNum_new) == 0)
        {
                printf("%d: PS compile failed.\n", __LINE__);
                return;
        }
#endif
        if (CompileShader(pShader, pixelShaderNum_new) == 0)
        {
                printf("%d: VS compile failed.\n", __LINE__);
                return;
        }

        programHandle_new = glCreateProgram();

        glAttachShader(programHandle_new, vertShaderNum_new);
        glAttachShader(programHandle_new, pixelShaderNum_new);

        // Bind vPosition to attribute 0
     //   glBindAttribLocation ( programHandle_new, 0, "vPosition_new" );
#if 1
    glLinkProgram(programHandle_new);
        // Check if linking succeeded.
        GLint linked = 0;
        glGetProgramiv(programHandle_new, GL_LINK_STATUS, &linked);
        if (!linked)
        {
                printf("%d: Link failed.\n", __LINE__);
                // Retrieve error buffer size.
                GLint errorBufSize, errorLength;
                glGetShaderiv(programHandle_new, GL_INFO_LOG_LENGTH, &errorBufSize);

                char * infoLog = (char*)malloc(errorBufSize * sizeof (char) + 1);
                if (infoLog)
                {
                        // Retrieve error.
                        glGetProgramInfoLog(programHandle_new, errorBufSize, &errorLength, infoLog);
                        infoLog[errorBufSize + 1] = '\0';
                        fprintf(stderr, "%s", infoLog);

                        free(infoLog);
                }

                return;
        }
        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
     //   glUseProgram(programHandle_new);
#endif
}

// Wrapper to load vetex and pixel shader.
void LoadShaders(const char * vShader, const char * pShader)
{
    vertShaderNum = glCreateShader(GL_VERTEX_SHADER);
    pixelShaderNum = glCreateShader(GL_FRAGMENT_SHADER);

    if (CompileShader(vShader, vertShaderNum) == 0)
    {
        printf("%d: PS compile failed.\n", __LINE__);
        return;
    }

    if (CompileShader(pShader, pixelShaderNum) == 0)
    {
        printf("%d: VS compile failed.\n", __LINE__);
        return;
    }

    programHandle = glCreateProgram();

    glAttachShader(programHandle, vertShaderNum);
    glAttachShader(programHandle, pixelShaderNum);

    // Bind vPosition to attribute 0
    glBindAttribLocation ( programHandle, 0, "vPosition" );

    glLinkProgram(programHandle);
    // Check if linking succeeded.
    GLint linked = 0;
    glGetProgramiv(programHandle, GL_LINK_STATUS, &linked);
    if (!linked)
    {
        printf("%d: Link failed.\n", __LINE__);
        // Retrieve error buffer size.
        GLint errorBufSize, errorLength;
        glGetShaderiv(programHandle, GL_INFO_LOG_LENGTH, &errorBufSize);

        char * infoLog = (char*)malloc(errorBufSize * sizeof (char) + 1);
        if (infoLog)
        {
            // Retrieve error.
            glGetProgramInfoLog(programHandle, errorBufSize, &errorLength, infoLog);
            infoLog[errorBufSize + 1] = '\0';
            fprintf(stderr, "%s", infoLog);

            free(infoLog);
        }

        return;
    }
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glUseProgram(programHandle);
}

main()

{

LoadShaders(s_v_shader, s_f_shader);
LoadShaders_new(s_v_shader_new, s_f_shader_new);

// Grab location of shader attributes.
    locVertices = glGetAttribLocation(programHandle, "vPosition");
    //locColors   = glGetAttribLocation(programHandle, "my_Color");
    locTexcoord = glGetAttribLocation(programHandle, "my_Texcoor");
    // Transform Matrix is uniform for all vertices here.
    locTransformMat = glGetUniformLocation(programHandle, "u_TransMatrix");
    locSampler = glGetUniformLocation(programHandle, "my_Sampler");

    /* Create the texture. */
    glGenTextures(1, &gTexObj);
    glBindTexture(GL_TEXTURE_2D, gTexObj);
    if (gTexObj == 0)
    {
        printf("Could not load the texture \n");
        return -1;
    }

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glUniformMatrix4fv(locTransformMat, 1, GL_FALSE, transformMatrix);

    glUniform1i(locSampler, 0);

    glClearColor(0.0f, 0.5f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);

while(1)

{
        glEnableVertexAttribArray(locVertices);
    glEnableVertexAttribArray(locTexcoord);

    // set data in the arrays.
    glVertexAttribPointer(locVertices, 2, GL_FLOAT, GL_FALSE, 0, &vertices[0][0]);
    glVertexAttribPointer(locTexcoord, 2, GL_FLOAT, GL_FALSE, 0, &texcoords[0][0]);

>>>>>>>>>>>>>>>>>>>>>> Render Video logic on Texture <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

float vVertices[] =
    {
        -0.85f, -0.9f, -0.6f, -0.5f,
    };

    glUseProgram(programHandle_new); >>>>>>>>>>>>>>>>>>>>>>> Video render stops display is not streaming
    glVertexAttribPointer ( 0, 2, GL_FLOAT, GL_FALSE, 0, vVertices );
        glEnableVertexAttribArray (0 );

    glDrawArrays ( GL_LINES , 0, 2 );
    glLineWidth( width_test );

}

}

}


text:
Q: Having a remote test repository with git In my current set up, my development server has a bunch of bare git repositories from which me and some other users push to. However, now, I'd like to integrate PHPUnit testing on the server itself.
My initial idea was to have a sub directory in each repo named tests, then have something like VisualPHPUnit run the tests so I can see the results through the server's "website". However, seeing as the remote repositories are bare, I can't exactly tell VPHPU to look for the test directories -- as they aren't really there.
Is there a better way of doing things? I was thinking of maybe having another repository that would contain tests for all the projects and just making it not bare -- but that goes against git standards and could possibly break stuff.

A: I'd think you'd do better to setup Jenkins or QuickBuild.  Jenkins is open-source, whereas QuickBuild is not.  But QuickBuild does have a free version, and I've found it to be more reliable than the former.  Both will allow you to checkout your source, run tests, and post the results.  And over the long haul, it'll allow you to do more, such as packaging your product for deployment.
If you're dead set on trying to make your current idea work, you'll need a post-receive hook that will checkout the code somewhere, run your tests against the checkout, and post the results to a known location.  You'll need to think about a few things though.  For instance, do you want to test every branch?  Just a single one?  The post-receive hook will tell you about all branches being updated, so you might need to filter if you only want to test master.  Pro Git has some information on hooks and how to customize them.
I'd avoid using a bare repository.  You'll have to deal with things like pushing into a bare repository, which is frowned upon.  I think in the end, you'll really want Jenkins or QuickBuild to help you.

A: I would suggest managing your remote git repository with gerrit and setting up jenkins for running all automatic tests using the gerrit plugin.
That way you push your change to gerrit, gerrit will notify jenkins, jenkins runs all test on the freshly pushed code. Now gerrit opens a review presenting the change and the result of the tests. Then when jenkins is happy and the change looks sane, you merge your changes to the official branch from which another developer can fetch it again.
This procedure might seem a bit complex, but it makes sure only successfully tested code will reside in your repository, and if you break any test you can be sure you broke it. - That's the whole point of automatic testing. ;)


text:
Q: Trigger AngularJS $scope event on key press Is it possible to trigger a $scope function on keypress. I like to know whats the most comfortable way to handle key press in a "form case". I created a dummy plunker.
Controller
// Code goes here
var myApp = angular.module("myApp", []);

//main controller define
myApp.controller('MainCtrl', ['$scope', MainCtrl]);

/**
 * MainCtrl object wrapper
 */
function MainCtrl ($scope) {

  /**
   * Submit function
   */
  $scope.submit = function () {
    console.log('Submit was triggered');
  }
}

View
<!DOCTYPE html>
<html>
  <head>
    <script data-require="angular.js@1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body ng-app="myApp">
    <div ng-controller="MainCtrl">
      <input type="text" placeholder="Trigger on enter key" />
      <button ng-click="submit();">Trigger on click</button>
    </div>
  </body>
</html>

A: Try wrapping it in a form tag and using ng-submit
<form ng-submit="submit()">
    <input type="text" placeholder="Trigger on enter key" />
    <button>Trigger on click</button>
</form>


text:
Q: JavaScript and Classic ASP: Trimming variable down to first five digits I have the following on a checkout page and need to only pass the first five digits of the sSTFormZip variable. There's something strange going on behind the scenes that causes the five-digit Zip Code field to be appended with four digits that aren't correct for returning customers. (It's a long story, but the short of it is that they were repurposing the last four digits to identify the county for those Zips that span over more than one county.)
<input id="STZIP" type=TEXT name="ST_ZIP" maxlength="<%= oRFF.max_length %>"
 value="<%= sSTFormZip %>" onChange="setRecalcFlag();">

How can I populate the field with 92708 when the database is storing something like 92708-1234?
After seeing one of the suggestions below, I added this above the input, but it did not impact the field:
<script>
    sSTFormZip = sSTFormZip.substring(0, 5);
</script>
<input id="STZIP" type=TEXT name="ST_ZIP" maxlength="<%= oRFF.max_length %>"
 value="<%= sSTFormZip %>" onChange="setRecalcFlag();">

A: <%
dim s
sArray = Split(sSTFormZip,"-")
%>

<input id="STZIP" type=TEXT name="ST_ZIP" maxlength="<%= oRFF.max_length %>"
value="<%= sArray(0) %>" onChange="setRecalcFlag();">

A: If you want to take the first five characters of the sSTFormZIP variable, then the VBScript Mid function is the one you're after:
Mid(sSTFormZIP, 1, 5)

Should return the first five characters. The parameters to Mid are:

*

*The string that you want to extract a part of

*The index (1 based) of the first character you want to extract

*The number of characters you want to extract

You could also use the Left function:
Left(sSTFormZIP, 5)

Which will take the left-most five characters of sSTFormZIP and return them.


text:
Q: Walk/Car mode detection through skobbler API I want to implement a functionality in my iOS app that detects if the user is Walking or driving. Is there a way i can detect the modes in Skobbler. I am using the Skobbler 2.1. Please suggest something. Thanks :)

A: If you are navigating on a route then the used routing profile might be a good indicator of travel mode.
If you are in "free drive" mode then the only metric you get is the current speed - above a certain threshold you may assume that the user is driving (or biking?). Other than these 2 things I don't know what else you could do.


text:
Q: MMORPG game Server and Client with a high level communication library I am developing a MMORPG game for Mobile (mostly windows mobile 8.1), I have written the server using Java and client side using C#. I am using JSON objects for the communication between server and client. I have a TCP connection and a UDP connection.
The mechanism I am using right now is that I send a Request object to the server and waits for a response Object. Rather than this is there a good high level communication library or something that I can use just to make it easier and effective. ?

A: I suggest you stream asynchronous events and only do request response when your game cannot continue unless you have a response e.g. login.
You can use netty on the server and any one of a number of JSON libraries on the JSON side.  I imagine C# has a similar range of communication and JSON libraries.


text:
Q: How to use multiple auths/ logins for same docker registry I'm using latest gitlab and the integrated docker registry. For each project I create an individual deploy token. On the host where I want to deploy the images I do docker login https://registry.example.com/project1, enter the deploy token and get success. Pulling the image just works fine.
On the same host I need to deploy another image from the same registry. So I do docker login https://registry.example.com/project2, the the deploy token (which is differrent to token 1, because each project has its own deploy tokens) and get success.
However looking in the .docker/config.json I can see docker just stores the domain, not the full url, and so replaces the old auth token with the new one. So I can only pull image 2 now, but not image 1 anymore.
Is this a bug in docker? How to use more than one auth/ deploy token for the same registry?

A: You can use the --config option of the Docker client to store multiple credentials into different paths:
docker --config ~/.project1 login registry.example.com -u <username> -p <deploy_token>
docker --config ~/.project2 login registry.example.com -u <username> -p <deploy_token>

Then you are able to call Docker commands by selecting your credential:
docker --config ~/.project1 pull registry.example.com/project1
docker --config ~/.project2 pull registry.example.com/project2

A: I had the same issue and my workaround for now is to use a dedicated user / token:

*

*Create a new User

*Add the user to all the projects you need with role Reporter

*Create a new Personal Access Token with scope read_registry
You can now login using the newly created token and pull:
docker login https://registry.example.com -u REPORTER_USER -p PERSONAL_ACCESS_TOKEN
This should do the trick, you can create a token with an existing user too

A: The contents of my compose.yml file:
version: '3.5'
services:

    test1:
        image: <mygitlabregistryurl>/project1
        deploy:
            replicas: 1

    test2:
        image: <mygitlabregistryurl>/project2
        deploy:
            replicas: 1

There are 2 ways to solve.

*

*You can login with the following command, but then you must make the service updates together with CI.
docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY

*For the authorized user in the project, you can create a personal access token with the permission of read_registry and use the following command.
docker login -u <username> -p <access_token> $CI_REGISTRY

Gitlab docs here: https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#authenticating-to-the-container-registry

A: Currently it's not possible. See https://github.com/moby/moby/issues/37569.
However, one workaround, in case it serves you, is to store credentials in a CWD-dependant directory:
export DOCKER_CONFIG=.docker
cd your-docker-project
docker login registry.example.com
docker-compose pull

cd ../other project
# repeat steps here

This way, by changing directory, you change credentials. You have to cd to use git and docker-compose anyways.


text:
Q: Correct usage of FB.Logout in Facebook Unity3D SDK I'm currently working on some lightweight code to correctly wrap usage of the Facebook Unity SDK for some client applications, and I've run into a minor problem, wherein the Facebook Unity SDK docs suggest that I shouldn't be doing what I am. Basically I want to know if what I'm doing is right.

*

*To preface - the documentation for FB.Logout suggests that a client app should never really need to call it, as it will log the user out of facebook globally, in contradiction of their expectations. (See https://developers.facebook.com/docs/unity/reference/current/FB.Logout)

*In my code when I receive an error from facebook which could mean the token has been invalidated, I ping off a simple request which should always succeed if the user's token is still valid. If this fails, I invoke FB.Logout, because without doing so, calling FB.Login again will simply fail - the user's token will remain the same, and the Login call will succeed.

*Behaviourally everything behaves as I would want - calling FB.Logout just clears the local state and lets me go back to my 'initialised but not logged in' situation.

Basically, I want to know if this is expected behaviour, and whether, contrary to the documentation, this is the correct case for calling FB.Logout.
Cheers,
Jeremy

A: FB.Logout will log you out of Facebook and your app on the web.
On mobile, it will sign out from your app.
This is by design, and your implementation is correct.

On Web, this method will log the user out of both your site and
  Facebook. On iOS and Android, it will log the user out of your
  Application.
On all the platforms it will also invalidate any access token that you
  have for the user that was issued before the logout.

cf. https://developers.facebook.com/docs/unity/reference/current/FB.Logout/


text:
Q: Is there any way to separate MySQL query results by table name in PHP? Example:
SELECT chapter.id, book.title, book.author FROM chapter
INNER JOIN book ON (chapter.book = book.id)

After fetching that query, I would like to get something like this:
Array
(
    [0] => Array
        (
            [chapter] => Array
                (
                    [id] => 1
                )

            [book] => Array
                (
                    [title] => Lorem Ipsum
                    [author] => John Doe
                )

         )

)

Better yet, stdClass objects.
Well, after searching and working  for some time, I've found a way of doing what I want by parsing the SQL statement with php-sql-parser, But this is really not a good solution for my issue.
I have specific reasons for this, and a solution would be a great benefit for my project. Though I don't really think that there is a simpler way of doing this...

A: One approach would be to name (alias) the columns of your result set in such a way that your PHP code knows where to "file" them, e.g. with the table and column split with ::
SELECT chapter.id as `chapter:id`, book.title as `book:title`, book.author as `book:author` ...

Then when retrieving the results from PDO/mysqli, you can split the resulting keys to know where to store your data:
$formatted_row = array();
foreach ( $db_row as $column_alias => $value )
{
     list($table, $column) = explode(':', $column_alias);
     $formatted_row[$table][$column] = $value;
}

A: The fetch_fields() function will give you the information you need. The script
<?php
$sql = "
SELECT u.user, h.db, RAND() x FROM mysql.user u
LEFT JOIN mysql.host h ON h.host = u.host
";
$conn = new mysqli('localhost', 'root', '', 'mysql');
$stmt = $conn->query($sql);
$fields = $stmt->fetch_fields();
print_r($fields);

produces the following output:
Array(
    [0] => stdClass Object(
            [name] => user
            [orgname] => User
            [table] => u
            [orgtable] => user
            [def] =>
            [db] => mysql
            ...
        )
    [1] => stdClass Object(
            [name] => db
            [orgname] => Db
            [table] => h
            [orgtable] => host
            [def] =>
            [db] => mysql
            ...
        )
    [2] => stdClass Object(
            [name] => x
            [orgname] =>
            [table] =>
            [orgtable] =>
            [def] =>
            [db] =>
            ...
        )
)

so you can use the db and orgtable fields to determine what table each field came from.

A: $query         = $myPdoInstance->prepare('SELECT lorem FROM ipsum...');
$metaData      = array();
$data          = new stdClass;
$i             = 0;
$tablesIdField = 'id';

$query->execute();

while ($columnsMeta = $query->getColumnMeta($i++)) {
    $metaData[] = $columnsMeta;
}

foreach ($query->fetch(PDO::FETCH_NUM) as $key => $columnValue) {

    $currentTable = $meta[$key]['table'];

    if (!isset($data->{$currentTable})) {
        $data->{$currentTable} = new stdClass;
    } elseif (!is_object($data->{$currentTable})) {
        $prev                                    = $data->{$currentTable};
        $data->{$currentTable}                   = new stdClass;
        $data->{$currentTable}->{$tablesIdField} = $prev;
    }

    $data->{$currentTable}->{$meta[$key]['name']} = $columnValue;
}

This is a very simple example of what I did. It is quite a solution for my project.
The code I'm using in my project is too complex and class implemented for me to post it here.
So, if there is any syntax error in this example, I'm sorry!


text:
Q: Nick name bug on stackoverflow.com
Possible Duplicate:
What happened to my user name?

Im not sure if this is the right place to report bugs (i guess no) but i just did not find any other (better) place to do so...
So my problem is that everywhere on stackoverflow i see user70542 instead of my real nick name psicho.... any idea why ? :)

A: To change your username (what you are calling a "nick name"), simply click the "userXXXXX" you see at the top of the page. Then click the "Edit" link and enter your desired username.


text:
Q: Error while initiating Firebase Robo test with Google Play services My issue is that I cannot test my Android application using Firebase Robo tests.
The issue started after the integration of FirebaseUI for sign in. The error i received then was that the application should update Google Play services.. Testing on my own device works without a problem, and testing on a virtual device works with sign in disabled.
Testing the disabled sign in version on Firebase yields
java.lang.RuntimeException: Unable to get provider com.google.firebase.perf.provider.FirebasePerfProvider:
java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.perf.provider.FirebasePerfProvider" on path:
DexPathList[[zip file "/data/app/APP-PATH-1/base.apk"],nativeLibraryDirectories=[/data/app/APP-PATH-1/lib/arm, /vendor/lib, /system/lib]]

I am not sure whats causing this issue in Firebase

A: I had the similar issue, new compiler helped me. To enable D8 add android.enableD8=true to gradle.properties file.


text:
Q: Joomla cannot unset mod_languages/css/template.css Joomla 3.x
The following code is not working
unset($doc->_styleSheets[JURI::root(true).'/media/mod_languages/css/template.css']);

thank you

A: The code is correct and I tested it, it's working fine.
Possibly you are running it in a plugin event after the head is rendered, or you have cached the page and the code is not really running.
In either case, try to put it at the component level, clear cache, and it should work

Update
to identify the component: turn SEF off, and look at the URL it shows as option=com_componentname;
to identify the module, simply rename the modules folder, and update the site; if it works, it's a module.
For plugins, rename the plugins/system and plugins/content first, then drill down until you spot it.
Alternatively, but much slower, you can turn modules and plugins on and off from the backend, until you find the culprit.

A: A variation which I've used with success in the past:
unset($doc->_styleSheets[$this->baseurl.'/media/mod_languages/css/template.css']);

Update
Here's an alternate method using a module override which should work for you.

*

*if it doesn't already exist, create a new directory titled html in your template's folder, ie: /templates/your-template/html/

*inside this, create an new mod_languages folder, ie /templates/your-template/html/mod_languages/

*copy the file from joomla-site-root/modules/mod_languages/tmp/default.php to the folder above, ie /templates/your-template/html/mod_languages/default.php

*open this file with a text editor and around line 12 look for the line where JHtml is loading the mod_languages CSS, and comment it out.
// JHtml::_('stylesheet', 'mod_languages/template.css', array(), true);
That's it, hopefully, this will do the trick for you.
Overriding Joomla core output using this method is safe and you won't loose your work with future Joomla updates.
More info about Joomla overrides:
https://docs.joomla.org/How_to_override_the_output_from_the_Joomla!_core
Good luck!


text:
Q: WPF MVVM await: Cancel task does not stop my progressbar I am working on a .NET 4.5 small WPF/MVVM thing and I am trying to get a progressbar to work correct together with async/await.
I have gotten things to work ok, but I am not able to cancel the task properly. Or, I think the task maybe is cancelled, but the progressbar runs the full length no matter what.
I am calling the "LongRun" method both on "Start" and "Stop", but with the optional cancellation token parameter when I want to stop. This might be an unusual way of doing things, but I think it looks ok - at least in theory :-)
Here are some code:
ViewModel
public MainViewModel()
    {
        _progress = new Progress<int>(ReportProgress);
        CountFilesCreatedCommand = new RelayCommand<IProgress<int>>(progress => LongRun(Progress));
        _tokenSource = new CancellationTokenSource();
        _tokenSource.Cancel();
        StopCountFilesCommand = new RelayCommand<CancellationToken>(token => LongRun(Progress, _tokenSource.Token));
        ProgressText = "...";
    }

    private void ReportProgress(int result)
    {
        PercentProgress = result;
    }

    private async void LongRun(IProgress<int> progress, CancellationToken token = default(CancellationToken))
    {
        try
        {
            // Start long running task here
            int i = 0;
            for (; i != 101; ++i)
            {
                if (token.IsCancellationRequested)
                {
                    // This part of the code is executed when I
                    // try to stop the Task, I can see the "Cancelled!"
                    // text flicker for a second, and then the code
                    // resume to run
                    _tokenSource.Cancel();
                    progress?.Report(PercentProgress);
                    ProgressText = "Cancelled!";
                 }
                await Task.Delay(TimeSpan.FromSeconds(0.1), token).ConfigureAwait(false);
                                    progress?.Report(i);
                ProgressText = i + "%";
            }
        }
        catch (OperationCanceledException)
        {

            //throw;
        }
    }

XAML
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <StackPanel>
        <!--<Button Margin="10,18,10,0" Content="Start Long Run" Height="30" Click="Button_Click_Async"/>-->
        <ProgressBar x:Name="pbStatus" Margin="10,10,10,0" Height="30" IsIndeterminate="False" Visibility="Visible" Minimum="0" Maximum="100" Value ="{Binding PercentProgress, Mode=TwoWay}"/>
        <TextBlock x:Name="tbResultat" Margin="0,10,0,10" HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding ProgressText}" />
        <DockPanel>
            <Button Margin="10,0" Content="Start Long Run" Height="30" Width="200" Command="{Binding CountFilesCreatedCommand}"/>
            <Button Margin="10,0" Content="Stop Long Run" Height="30" Width="200" HorizontalAlignment="Right" Command="{Binding StopCountFilesCommand}"/>
        </DockPanel>
    </StackPanel>
</Grid>

I have a feeling that the solution might have something to do with the XAML?
Any help would be greatly appreciated!

A:
I am calling the "LongRun" method both on "Start" and "Stop", but with the optional cancellation token parameter when I want to stop.

That's where your problem is. When you stop, you want the existing call to LongRun to exist, not create a new call to LongRun.
Something like this would be more appropriate (assuming that this operation can only be done once, and you're enabling/disabling buttons as necessary):
_progress = new Progress<int>(ReportProgress);
_tokenSource = new CancellationTokenSource();
CountFilesCreatedCommand = new RelayCommand(() => LongRun(_progress, _tokenSource.Token));
StopCountFilesCommand = new RelayCommand(() => _tokenSource.Cancel());
ProgressText = "...";

On a side note, you should avoid async void (as I describe in an MSDN article). async void has awkward error handling semantics and is not unit testable.


text:
Q: MonoTouch Load image in background I am having a problem trying to load an image and display it using System.Threading.Task
My Code is as follows
    Task DownloadTask { get; set; }

    public string Instrument { get; set; }

    public PriceChartViewController(string Instrument) {
        this.Instrument = Instrument;
        DownloadTask = Task.Factory.StartNew(() => { });
    }

    private void LoadChart(ChartType chartType) {
        NSData data = new NSData();

        DownloadTask = DownloadTask.ContinueWith(prevTask => {
            try {
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;

                NSUrl nsUrl = new NSUrl(chartType.Uri(Instrument));
                data = NSData.FromUrl(nsUrl);
            }
            finally {
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
            }
        });

        DownloadTask = DownloadTask.ContinueWith(t => {
            UIImage image = new UIImage(data);

            chartImageView = new UIImageView(image);
            chartImageView.ContentScaleFactor = 2f;

            View.AddSubview(chartImageView);

            this.Title = chartType.Title;
        }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
    }

The second Continue with does not seem to be being called?
Initially my code looked like the following without the background processing and it worked perfectly.
    private void oldLoadChart(ChartType chartType) {

        UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;

        NSUrl nsUrl = new NSUrl(chartType.Uri(Instrument));
        NSData data = NSData.FromUrl(nsUrl);
        UIImage image = new UIImage(data);

        chartImageView = new UIImageView(image);
        chartImageView.ContentScaleFactor = 2f;

        View.AddSubview(chartImageView);

        this.Title = chartType.Title;

        UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
    }

Does anyone know what I am doing wrong?

A: Your first part of the thread is crashing, that's why it is never getting to the second:
You are calling  UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
 from a non-UI thread. Setting the network activity indicator is a UI operation and may only be executed on the main thread. You'll have to wrap it in InvokeOnMainThread().
If you add a try-catch, you'll see the exception.

A: Add catch before finally. Maybe you just have an exception so workflow doesn't go any further.


text:
Q: Chain Requests Kotlin Coroutines I have an array of URLs, each providing a zip file. I want to download them and store them in my app folders, inside the internal memory.
Question:
Since I do not know the number of URLs I will need to access, what is the best way to go about this? I am just beginning to work with Kotlin coroutines.
This is my 'download from url' method
fun downloadResourceArchiveFromUrl(urlString: String, context: Context): Boolean {

    Timber.d("-> Started downloading resource archive.. $urlString")
    lateinit var file: File
    try {
        val url = URL(urlString)

        val urlConn = url.openConnection()
        urlConn.readTimeout = 5000
        urlConn.connectTimeout = 10000

        val inputStream = urlConn.getInputStream()
        val buffInStream = BufferedInputStream(inputStream, 1024 * 5)

        val fileNameFromUrl = urlString.substringAfterLast("/")

        file = File(context.getDir("resources", Context.MODE_PRIVATE) , fileNameFromUrl)

        val outStream = FileOutputStream(file)
        val buff = ByteArray(5 * 1024)

        while (buffInStream.read(buff)  != -1){
            outStream.write(buff, 0, buffInStream.read(buff))
        }

        outStream.flush()
        outStream.close()
        buffInStream.close()

    } catch (e: Exception) {
        e.printStackTrace()
        Timber.d("Download finished with exception: ${e.message} -<")
        return false
    }

    Timber.d("Download finished -<")
    return true
}

Could you simply create a loop and call download method each time?
        for (i in resources.indices) {
            asyncAwait {
                downloadResourcesFromUrl(resources[i].url, context)
                return@asyncAwait
            }

Also, is it a good idea to do this synchronously? Wait for every file to download then proceed to the next one?

A: Turn your blocking download function into a suspending one:
suspend fun downloadResourceArchiveFromUrl(
    urlString: String, context: Context
): Boolean = withContext(Dispatchers.IO) {
   ... your function body
}

Now run your loop inside a coroutine you launch:
myActivity.launch {
    resources.forEach {
        val success = downloadResourceArchiveFromUrl(it.url, context)
        ... react to success/failure ...
    }
}

Also be sure to properly implement structured concurrency on your activity.


text:
Q: S2S VPN Subnet Mask Collisions I am trying to educate myself on the creation of a site-to-site vpn for a planned vpn tunnel we will be creating at work.  I am having trouble understanding what I should put for local-remote sub-nets for the tunnel.
at one site, there is only one sub-net we are worried about, for simplicity sake we'll say 192.168.4.0/24
at our main site, we are splitting up different groups into sub-nets to prevent access to certain resources on an IP based scheme. (sub-nets will be acl'd from seeing specific resources, as an added layer of security).  For example these sub-nets would be:
192.168.1.0/24
192.168.11.0/24
192.168.12.0/24
192.168.13.0/24
192.168.14.0/24
192.168.15.0/24
192.168.16.0/24

the sub-nets at .4 and .1 are unchangeable for the foreseeable future.
The point here is all sub-nets live within the same /16
My initial question is, would it be possible to do a remote/local setup like 192.168.4.0/24,192.168.0.0/16 and would this cause problems.
If it won't work, what would be a recommended configuration of the subnets?
EDIT:
I'm wondering if setting up the vpn with one end with the /16 and the other with the 4.0/24, will the overlap cause a problem with .4

A: We ended up choosing just the particular subnets that at the moment that need access, and added a tunnel for them, i.e. .1.0/24 and .11.0/24, and excluding the others.  Given current knowledge and experience (or lack thereof at the moment), this seemed to be best option.


text:
Q: what is the linux command for creating an anonymous pipe(unnamed pipe) Want to create an unnamed pipe. On ubuntu 14, i tried "pipe", did not work, and can not find out with the internet search. For the named pipe,  "mkfifo" works.

A: An anonymous pipe (a.k.a. a "pipe", since pipes are anonymous) is created by the shell when you use the | operator:
grep example . -r | less

You can't create a pipe with one command and then use it with another command later, not without some wacky /proc trickery.  If you need to use something later, you have to have some name to refer to it, at which point it's no longer a pipe.  Just be sure to connect each end in the right order (read before write).
Under the hood, a pipe is created as a pair of open file handles using the pipe() function.  After calling pipe(), the shell creates two subprocesses, and each subprocess selects the appropriate end of the pipe before calling exec().  In general, it's not possible to replace shell builtins with your own programs.  Other examples are cd and export.
You can create pipes yourself in a program using pipe().


text:
Q: Distribution for ${1^TX}/\sqrt{X^TQX}$, when $X$~$N(\mu, \Sigma)$? I have been looking for an illustrative way to quantify the risk of an investor not being able stay above the minimum capital requirement. I would like to find a neat solution for the probability that the investor goes out of business in a very simple set up.
First, denote the solvency capital of an investor with $C$=$1^TX$, where
$X_i$ = value of the portfolio component $i$ ($i=1,2,...,n$) and
$X$ ~ $N(\mu,\Sigma)$
Also, assume that the investor has some obligations in the future and until that the solvency capital has to stay above the minimum solvency capital level denoted as
$C_m=\sqrt{X^TQX}$, where
$Q$ is a positive semi-definite $n$ x $n$ matrix defined by the legislator. The legislator has set $Q$ so that $\sqrt{X^TQX}$ represents their view on the portfolio max loss during the period considered.
I assume that the investor goes out of business whenever the risk buffer is not high enough, i.e. if $C-C_m < 0$. Therefore, in the best case I would find a distribution for $\frac{C}{C_m}$ or $C-C_m$. Do you have an idea of a probability distribution that could be applied here?
I am not very familiar with various probability distributions but,

*

*ratios of quadratic forms in normal variables have been discussed here

*according to these notes I would understand that $X^TQX$ ~ $\chi^2(r,\lambda)$ and so should be the case with $X^TX$ also. Should I rather consider $(X^TX)/(X^TQX)$?


text:
Q: Modifying ID (index) of listitems So I ran into a situation where I have two lists containing the same information but in different languages (don't ask me why they chose to do it this way).
Each item links through a workflow-created field to the corresponding item in the other list.
Eg:
/Lists/List1/DispForm.aspx?ID=1
Has a link to:
/Lists/List2/DispForm.aspx?ID=1
So it links to the ID (index) of the item.
This means, that the guys responsible for the data has to make sure each item is in the same order.
However, they already messed up, and deleted the messed up entries. Sharepoint doesn't automatically continue from the former index though, but apparently just keeps going with an internal index I guess, so now there's a gap in indexes, making the lists 'unmatched'.
That is, the elements at ID 1825 and above doesn't match the elements in the other list.
Anyone have any idea of how to "normalize" the ID's or maybe bulk-modyfing the existing elements, and then making sure, the list continues at the same IDs?
I appreciate any and all pointers at this point.
/Dynde

A: Don't use the ID column. As you can't control it, you'll go into messing up more and more.
A suggestion : use you own "business key". You can maybe add a Guid column on both lists, and populate the same guid for the two records.
Another possibility, use a "master" list having the ID, and reference this master list in the two child list with a lookup column.

A: I ended up changing the custom workflow code from the simple method of forming a link using the same ID as the symbol, and instead searching for the same title in the opposite list. It takes a performance hit (because of the search), but works well. It also allows me to output "no corresponding element found in opposite list" if the other list hasn't been updated.
Thanks for all the help


text:
Q: Rotina em Background para compilação de dados é uma boa ideia? A última empresa em que eu trabalhava tinha umas regras bem peculiares, estas não sendo tão comuns(até onde eu sei) em outras empresas de TI.
Basicamente a gente fazia a compilação de todos os dados que seriam usados nos gráficos do sistema.
Nessa compilação os dados eram agrupados por dia e por hora, e salvos em duas tabelas, uma sendo compilados_dia e outra compilados_hora.
A ideia de fazer isto era a seguinte, eu tenho vamos supor 1 milhão de registros de vendas na tabela de vendas, ao invés de carregar todos os 1 milhão de registros da tabela de vendas, eram carregados apenas os dados da tabela de compiled_daily, dessa forma havia uma substancial queda no número de registros que eram carregados. Como para o cliente, só é importante a forma que ele vai visualizar os dados, não importa como os dados do gráfico mensal foram montados.
Dando um exemplo mais claro, vamos supor que temos 100 mil registros na tabela de vendas neste mês.
Se eu pegar os dados da tabela bruta, vou ter que carregar 100 mil registros, se eu pegar os dados da tabela de dados compilados, serão apenas 30 registros, um pra cada dia, ai na compilação eu tenho a soma de todos os registros.
O que vocês acham, é uma boa ideia? Ou tem algum problema técnico com ela?


text:
Q: Single quote strings in C++
Possible Duplicate:
What do single quotes do in C++ when used on multiple characters?

I was writing some C++ code over the weekend and by chance realised that the compiler has no qualms with single-quote strings - as long as they are 4 or less characters long.
(*by chance - When you use single-quote strings in javascript and SQL, you might find yourself getting them mixed up in other programming environments/languages)
Well, the outcomes are actually different. Look at the following lines:
cout << "Test" << endl;
cout << 'Test' << endl;
//! cout << 'Tests' << endl; // Lexical error: max of 4 characters in string exceeded

They compile without a hitch and you get the following results:
Test
1415923836
The third commented line wont compile citing a Lexical error. Can someone please explain to me what is happening here, or how C++ interprets the single-quote string?


text:
Q: TypeError: unsupported operand type(s) for +: 'function' and 'function' and an issue with list comprehension I'm trying to write a function to calculate Simpson's rule that takes a function as an argument.
# Imports
from numpy import sum, exp, linspace

def compSimpsons(a, b, n, f):
  endpts = linspace(a, b, n+1) # Use linspace to get endpoints
  functions = []
  f = lambda x : f
  fvals = [f(x) for x in endpts]
  h = (b-a)/n
  h4 = h**4
  h5 = h**5
  sum_even = sum(fvals[2:(n-1):2])
  sum_odd = sum(fvals[1: :2])
  Sn = (h/3)*(fvals[0] + fvals[-1] + 2*sum_even + 4*sum_odd)
  result_actual = 1.5 - 0.5 * exp(-2)
  print("%5g | %.16f | %.16f | %.16f | %.16f" % (n, h4, h5, Sn, abs(Sn - result_actual)))

However, I get the following error when I try to run the program:
TypeError                                 Traceback (most recent call last)
<ipython-input-123-44442d95a7b4> in <module>
      3
      4 for n in range(2, 41, 2):
----> 5   Sn = compSimpsons(0, 1, n, (1+exp(-2*x)))

<ipython-input-122-b9245c03d75c> in compSimpsons(a, b, n, f)
     12   sum_even = sum(fvals[2:(n-1):2])
     13   sum_odd = sum(fvals[1: :2])
---> 14   Sn = (h/3)*(fvals[0] + fvals[-1] + 2*sum_even + 4*sum_odd)
     15   result_actual = 1.5 - 0.5 * exp(-2)
     16   print("%5g | %.16f | %.16f | %.16f | %.16f" % (n, h4, h5, Sn, abs(Sn - result_actual)))

TypeError: unsupported operand type(s) for +: 'function' and 'function'

I modified the function to print fvals and got the following:
[<function compSimpsons.<locals>.<lambda> at 0x7f39576e5170>, <function compSimpsons.<locals>.<lambda> at 0x7f39576e5170>, <function compSimpsons.<locals>.<lambda> at 0x7f39576e5170>]

It seems that I'm creating a list of functions when I want a list of values, but I'm not sure how to fix this problem. What can I do?


text:
Q: Professional Engineering-related Business Letter For one of my Engineering Courses, I had to write a professional Business Letter to inform my hypothetical employer of my analysis about two alternatives, and which one of them is better.
For this letter, as I was communicating directly with the employer, and using my own calculations and results, I thought first person would the right way to write (I used lots of "I", some of "my" etc.). Although I think I did a decent job, the professor took lots of points off saying that my letter should always be in third person.
I hope someone who is familiar with this matter can help me shed some light on this matter. Should business letters always be written in third person? I am not compatible with the professor, so I figured I should check online first, just to be sure. I am not a native speaker, so any information and advice, no matter how trivial, would be greatly appreciated.
Thank you very much.


text:
Q: No indentation after empty line Indentation can be selectively suppressed using \noindent or completely with the option parindent=full to the KOMA document classes. Books (fiction) are usually structured using paragraphs, indented as the LaTeX default. Additionally, greater changes are indicated by an empty line that is followed by a non-indented paragraph, like the first one in a section.
Is there a possibility to insert such a line break into a LaTeX document or automatically omit indentation after empty lines?

A: First a variant of Werner's solution that allows empty lines after \changebreak:
\documentclass{scrreprt}
\usepackage{lipsum}

\makeatletter
\newcommand*{\changebreak}{%
  \par
  \vspace{\baselineskip}%
  \changebreak@skippar
}
\def\changebreak@skippar{%
  \@ifnextchar\par{%
    \expandafter\changebreak@skippar\@gobble
  }{%
    \noindent
    \ignorespaces
  }%
}
\makeatother

\begin{document}
\lipsum[1-3]
\changebreak
\lipsum[4-6]

\changebreak

\lipsum[7-9]
\end{document}

The detection of the empty line quickly fails if there is something
inbetween, a macro definition, an assignment (but comments do not
disturb).
LaTeX has the same problem for its section headers. There it uses macro \@afterheading that uses \everypar to
get at the start of the next paragraph and undoes the paragraph indent with a \lastbox trick, because the paragraph indent is set as box. \@afterindentfalse tells the
macro \@afterheading that the indent at the next paragraph is not wanted.
The other task of \@afterheading to keep the first two lines of the starting paragraph together is here
also welcome.
\documentclass{scrreprt}
\usepackage{lipsum}

\makeatletter
\newcommand*{\changebreak}{%
  \par
  \vspace{\baselineskip}%
  \@afterindentfalse
  \@afterheading
}
\makeatother

\begin{document}
\lipsum[1-2]
\changebreak
\lipsum[3-4]

\changebreak

\lipsum[5-6]
\changebreak
\typeout{Last changebreak}

\lipsum[7-8]
\end{document}

For the case (probably not likely) that it should be avoided that the break hits a page break,
then the following prevents a page break at the break. And if the
previous paragraph is not yet finished, a last lonely line could also be forbidden.
LaTeX's \@afterheading tries the same with the next two lines.
\documentclass{scrreprt}
\usepackage[nopar]{lipsum}
% Option `nopar' suppresses the
% paragraph ends in lipsum paragraphs

\makeatletter
\newcount\chgbrk@widowpenalty
\newcommand*{\changebreak}{%
  % If we are happy and the previous paragraph
  % is not yet finished, we can change
  % the widowpenalty to prevent a previous
  % lonely line.
  \chgbrk@widowpenalty\widowpenalty
  \widowpenalty\@M
  \par
  \widowpenalty\chgbrk@widowpenalty
  \nobreak
  \vspace{\baselineskip}%
  \@afterindentfalse
  \@afterheading
}
\makeatother

%\setlength{\textheight}{\baselineskip}% stress test

\begin{document}
\lipsum[1]

\lipsum[2]
\changebreak
\lipsum[3]

\lipsum[4]

\changebreak

\lipsum[5]

\lipsum[6]
\end{document}

A: I would suggest defining a command to do this, for two reasons:

*

*This might be done in an ad-hoc fashion; and

*LaTeX interprets an empty line as a paragraph break anyway, so it may be difficult to construct something that (say) counts the number of blank lines in order to produce a "change break".

My suggestion would be something like \changebreak that is similar to \bigskip:

\documentclass{scrreprt}
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\def\changebreak{\par\vspace{\baselineskip}\noindent}
\showthe\baselineskip
\begin{document}
\lipsum[1-3]
\changebreak
\lipsum[4-10]
\end{document}

The traditional \bigskip inserts \bigskipamount which is fixed at 12pt plus 4pt minus 4pt. I've modified that to use \baselineskip since you're after an empty line. \noindent is automatically inserted to remove the indentation in the subsequent paragraph.

A: The memoir class (of course) offers a good selection of 'anonymous' breaks.  The simplest, \plainbreak{<num>} produces a gap of <num> * \baselineskip and then suppresses indentation of the next line (while the starred version does indent the next line:
\newcommand{\fancybreak}{\@ifstar{\@sfbreak}{\@fbreak}}
\newcommand{\@fbreak}[1]{\par
  \penalty -100
  \noindent\parbox{\linewidth}{\centering #1}%%\null
  \par
  \@afterindentfalse
  \@afterheading}
\newcommand{\@sfbreak}[1]{\par
  \penalty -100
  \noindent\parbox{\linewidth}{\centering #1}%%\null
\par
  \@afterindenttrue
  \@afterheading}

There are several other related commands, some of these will print arbitrary symbols or text (\fancybreak), others will give a plain or fancy break depending on whether they appear near the top or bottom of a page (\plainfancybreak and \pfbreak).  If you are interested, consult the memoir manual; and note that the code for these commands are easily 'lifted' from memoir.cls if you can't use memoir itself for some reason.  (As the above example hopefully shows, although I did remove some comments.)


text:
Q: how to change the index of the CoreData when reordering the TableView? Please go through the code and tell me what i am doing wrong here.
TableViewController.m
-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];
    NSManagedObjectContext *context = [self managedObjectContext];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:context];

    NSFetchRequest *fetchrequest = [[NSFetchRequest alloc]initWithEntityName:entity];
    _devices = [[context executeFetchRequest:fetchrequest error:nil]mutableCopy];
    [self.tableView reloadData]; // When TableView is reloading the data in tableview updating according to the data stored via CoreData.

}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {

    if (fromIndexPath != toIndexPath ) {

        NSManagedObjectContext *context = [self managedObjectContext];
        NSManagedObject *device = [self.devices objectAtIndex:fromIndexPath.row];

        NSString *str1 = [device valueForKey:@"text1"];

        NSLog(@"%@",str1);
        [self.devices removeObject:device];

        [self.devices insertObject:device atIndex:[toIndexPath row]];

//        int i = 0;
//        for (NSManagedObject *mo in self.devices)
//        {
//            NSManagedObject *new = [self.devices objectAtIndex:i];
//            NSString *check = [new valueForKey:@"text1"];
//            NSLog(@"%@",check);
//            NSString *check1 = [new valueForKey:@"text2"];
//            NSLog(@"%@",check1);
//            NSString *check2 = [new valueForKey:@"text3"];
//            NSLog(@"%@",check2);
//            [mo setValue:[NSString stringWithFormat:@"%@",[new valueForKey:@"text1"]] forKey:@"text1"];
//            [mo setValue:[NSString stringWithFormat:@"%@",[new valueForKey:@"text2"]] forKey:@"text2"];
//            [mo setValue:[NSString stringWithFormat:@"%@",[new valueForKey:@"text3"]] forKey:@"text3"];
//            i++;
//        }

        NSError *error;

        if(![context save:&error]){
            NSLog(@"%@ %@",error, [error localizedDescription]);
        }

    }

}

I have entity Name: Device and with column names: text1,text2,text3
I don't want to sort the data in Core Data, actually i want to move the rows in TableView and i want to update the index of the data saved in columns text1,text2,text3. In total, there are 5 rows in tableview and i just want to update the index of the values with respect to the tableview index which is updated.

A: Check below tutorial
http://www.cimgf.com/2010/06/05/re-ordering-nsfetchedresultscontroller/
for short you need to add "displayIndex" property to the objects you are trying to reoder


text:
Q: C# adding datatable to SQL with primary key autoincrement I have a database and I am trying to add some rows into it. These rows come from a datatable, the problem is that my SQL Server table has a primary key to autoincrement, I am not sure how to accomplish this so what I did was send always a 1 thinking the database would ignore and place correct value but didn't.
I got this error

Violation of PRIMARY KEY constraint 'PK_NWActivity'. Cannot insert duplicate key in object 'dbo.Activity'. The duplicate key value is (1).

My code is this
if (owner_response != null)
{
            DataTable periodData = new DataTable();
            periodData.Columns.Add("idActivity", typeof(int));
            periodData.Columns.Add("eventSubType", typeof(String));
            periodData.Columns.Add("antena", typeof(String));
            periodData.Columns.Add("economico", typeof(String));
            periodData.Columns.Add("Latitude", typeof(float));
            periodData.Columns.Add("Longitud", typeof(float));
            periodData.Columns.Add("Location", typeof(String));
            periodData.Columns.Add("site", typeof(String));
            periodData.Columns.Add("IgnitionOn", typeof(Boolean));
            periodData.Columns.Add("speed", typeof(float));
            periodData.Columns.Add("activityDate", typeof(DateTime));
            periodData.Columns.Add("sensor1", typeof(Boolean));
            periodData.Columns.Add("sensor2", typeof(Boolean));

            foreach (var owner in owner_response.Owners)
            {
                var period_response = new GetPeriodActivityResponse();

                do
                {
                    period_response = proxy.GetActivityByOwner(owner.OwnerId,startTimer , (period_response.Version != 0) ? period_response.Version : 0);

                    if (period_response != null)
                    {
                        periodData.Clear();

                        foreach (var activity in period_response.Activities)
                        {
                            DataRow[] vehiculo = vehicleData.Select("[VehicleId] = '" + activity.VehicleID +"'");
                            DataRow[] sitio = SiteTable.Select("[SiteId] = '" + activity.SiteID + "'");
                            periodData.Rows.Add(
                                1,
                                activity.EventSubType,
                                vehiculo[0][15],
                                vehiculo[0][4],
                                activity.Latitude,
                                activity.Longitude,
                                activity.Location,
                                (sitio.Length > 1) ? sitio[4].ToString() : "",
                                activity.IgnitionOn,
                                activity.Speed,
                                activity.ActivityDateTime.ToLocalTime(),
                                false,
                                false);

                        }
                    }
                } while (period_response.MoreItemsAvailable);

            }

            if (periodData.Rows.Count > 0)
            {
                SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
                bc.DestinationTableName = "Activity";
                bc.BatchSize = periodData.Rows.Count;

                if (con.State != ConnectionState.Open)
                {
                    con.Close();
                    con.Open();
                }

                bc.WriteToServer(periodData);
                bc.Close();
                con.Close();
            }
        }

A: Just ignore the primarykey column. Don't add it to the DataTable, the server should take care of the value.
DataTable periodData = new DataTable();
//periodData.Columns.Add("idActivity", typeof(int));
periodData.Columns.Add("eventSubType", typeof(String));
periodData.Columns.Add("antena", typeof(String));
periodData.Columns.Add("economico", typeof(String));
periodData.Columns.Add("Latitude", typeof(float));
periodData.Columns.Add("Longitud", typeof(float));
periodData.Columns.Add("Location", typeof(String));
periodData.Columns.Add("site", typeof(String));
periodData.Columns.Add("IgnitionOn", typeof(Boolean));
periodData.Columns.Add("speed", typeof(float));
periodData.Columns.Add("activityDate", typeof(DateTime));
periodData.Columns.Add("sensor1", typeof(Boolean));
periodData.Columns.Add("sensor2", typeof(Boolean));
...


text:
Q: Reverse a linked list, is my idea correct? I was reading this: https://www.geeksforgeeks.org/reverse-a-linked-list/
I think I found an easier answer but since it wasn't written their and they used more complicated one I think something is wrong with mine and can't figure it out.
We start from the first node which we will copy and insert it into a new list.
then we go one step to the right, copy the value, create a new list with that value and setting its right the previous list and so on.
What's wrong with my algorithm?

A: If I interpret your idea correctly, it is something like this:
void forward_list::reverse() {
    forward_list new_list;

    for(auto& v : *this)
        new_list.emplace_front(std::move(v));

    std::swap(new_list, *this);   // or *this = std::move(new_list);
}

... and this would work. It even looks pretty nice I'd say.

What's wrong with my algorithm?

*

*It's creates a new node for every old node and then has to copy/move the data from the old node to the new node. The old nodes will then be destroyed.

*Some types aren't even copyable or moveable so this reverse algorithm couldn't be used with such types.

*It invalidates references and iterators.

Consider the alternative, reversing the links. It's a bit more complex but gets the job done without any of the drawbacks mentioned above.
Here's my take on reversing the links, which is not implemented exactly the same way as in the link you shared but it works pretty much in the same way. I think this one has fewer assignments though.
curr will point one step ahead of head and next is used to save the next pointer when the relinking is being done.
void forward_list::reverse() {
    if(head) {                               // must have at least one node
        node* curr = head->next;             // head + 1
        head->next = nullptr;                // this will be the new last node
        node* next;                          // for saving next while relinking
        while(curr) {                        // while curr != nullptr
            next = curr->next;               // save the next pointer
            curr->next = head;               // relink backwards
            head = curr;                     // move head forward
            curr = next;                     // move curr forward
        }
        // head now points at the new start of the list automatically
    }
}

A: Your algorithm is functionally correct, but since you are creating an entirely new list instead of reversing the existing nodes in-place, you are using twice the memory. You also have to deal with the cleanup of deleting the old nodes once you have your new list.


text:
Q: Login and Forgot password in Lightbox How do i get Wordpress Login & Forgot password forms in one light-box which can then be displayed inside pages where the user has to be logged in to see the content?
Can i just copy some of the code in wp-login.php and then put it in a light box and alternate between the forms using anchor links as tabs would normally work? So for example, when you click forgot password, the login form is hidden and and the forgot password form becomes visible.
Then when the user enters their details for example, they are logged in and without being redirected to the default login page.I want the login in and the forgot password to all work within the light-box without leaving the page.

A: First you need your login form.  I put this in header.php.

<?php wp_login_form( array ( 'redirect' => site_url( $_SERVER['REQUEST_URI'] ), 'value_remember' => true ) ); ?>
    <a href="<?php echo esc_url( wp_login_url() ); ?>?action=register">Register

    <a href="<?php echo esc_url( wp_login_url() ); ?>?action=lostpassword">Lost your password

Next your link to login or register.

    <?php if ( ! is_user_logged_in() ) { ?>
    Login  |
    <a href="<?php echo esc_url( wp_login_url() ); ?>?action=register">Register
    <?php } else {
    $current_user = wp_get_current_user(); ?>
    <?php echo  $current_user->user_firstname. ' | ';?> <a href="<?php echo esc_url( admin_url( '/profile.php' ) ); ?>">Update Profile | <a href = "<?php echo wp_logout_url( home_url() ); ?>" title = "Logout" > Log out

    <?php } ?>

Last step is your javascript.  I'm using fancybox for this.
 $(".fancy-zoom").fancybox({
            fitToView   : false,
            width       : 360,
            height      : 320,
            autoSize    : true,
            closeClick  : false,
            openEffect  : 'none',
            closeEffect : 'none'
        });

A: This plugin called SimpleModal Login works great http://wordpress.org/extend/plugins/simplemodal-login/
It has options for registration and password recovery and provides multiple ways to shaw the login dialog.


text:
Q: 2nd domain on rails 3 app, solely for URL shortening? So lets say I have the following rails app:
myrailsapp.com
and if you want to view and item here, its myrailsapp.com/items/1
now lets say I buy, mrsap.com
lets say item 1's name is "frank"
and I want the item's name such as "Frank" to become the short url.
So mrsap.com/frank would go to myrailsapp.com/items/1
Any ideas for how I can go about doing this?

A: If you are using Rails 3 you could do this with a request based constraint in your routes. Something like this.
match "/:name" => "items#show_by_name", :constraints => {:host => "mrsap.com"}

And in items_controller.
def show_by_name
  @item = Item.find_by_name(params[:name])
  render :action => "show"
end

A: It's probably best to run it as a separate app. You pass the app a full URL, it creates a slug for a tinyurl. Separation of concerns is always best.


text:
Q: Convergence in the product topology for B([0,1]) Let $I = [0, 1]$ with its usual topology and let $B(I)$ be the set of all functions $f : I \rightarrow I$. Furthermore, for all $i \in I$ let $X_i = I$ and $X = \Pi_i X_i$ with the product topology. We can identify $X$ with $B(I)$ and therefore endow $B(I)$ with the product topology. Now let $C(I)$ be the set of all continuous functions from $I$ to $I$ and $F(I)$ be the set of all functions with finite support.
Show that if $f \in C(I)$ and $f(i) \neq 0$ for some $i$ then there is no sequence of functions in $F(I)$ that converges to $f$ for the product topology.
I am having some trouble proving this, it makes sense intuitively since $f$ itself does not have finite support but it seems to me that for any basis set of the product topology that contains $f$ will also contain an element of $F(I)$

A: It is indeed true that any basic set of the product topology contains a member of $F(I)$. So $F(I)$ is dense in $B(I)$. So you'd expect (in a metric space, e.g.) there to be a sequence from $F(I)$ converging to any point of $B(I)$ and this exercise shows that this is not the case.
If $f_n$ is a sequence of functions from $F(I)$ converging to some $f \in B(I)$, so the support of $f_n$ (i.e. $S_n:=\{x \in I: f_n(x) \neq 0\}$) is finite and let $S=\bigcup_n S_n$, which is an at most countable set. The fact that we use the product topology on $B(I)$ implies that $f_n(x) = 0$ for all $n$ and $x \notin S$ and so $f(x)=0$ for all $x \notin S$, i.e. $f$ has at most countable support. This uses that $f_n(x) \to f(x)$ for all $x$ (product topology is pointwise convergence, or projections are continuous).
Now note that any continuous $f: I \to I$ with $f(p) \neq 0$ for some $p \in I$, has uncountable support so cannot be a limit of a sequence from $F(I)$.


text:
Q: RxJava - Combine 2 calls I have 2 Observables, which call 2 WS

*

*Get a list of cars (at this point, each car from this list doesn't have his owner)

*Get the owner of the car

So first I get the list of cars. Everything is ok. But I would to get the owner for each car and set it in the Car entity, like car.setOwner(owner) and send the final list of cars, containing their owner.
Api.getCars()
.subscribe(new Action1<List<Car>>() {
    @Override
    public void call(List<Car> cars) {
    // get the list of cars, but need to get their owner
    });

Which is the best way to do this? (Moreover, without lambdas.)

A: You could utilize this flatMap overload:
Api.getCars()
    .flatMap(cars -> Observable.from(cars)) // flatten your list
    .flatmap(car -> Api.getOwner(car), // request each owner
            (car, owner) -> {
                car.setOwner(owner); // assign owner to the car
                return Observable.just(car);
            })
    .toList() // collect items into List
    ... // here is your Observable<List<Car>>


text:
Q: SharePoint CSOM (C#) to get list of User alerts present in SharePoint site collection I want to use microsoft.Sharepoint.client.dll and microsoft.Sharepoint.client.runtime.dll to retrieve the list of user alerts.
Can any one please let me know how to retrieve the user alerts from sharepoint site.

A: Try the below code:
//load all users in the site collection
var siteUsersColl = from user in oWeb.SiteUsers
                where user.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.User
                select user;
var usersResult = context.LoadQuery(siteUsersColl);
context.ExecuteQuery();

int count = 0;
foreach (var user in siteUsersColl)
{
    //ensure that user is present
    var curruser = oWeb.EnsureUser(user.LoginName);

    //load the users alerts, available after jan 2017 CSOM update in SPO, not sure about OnPrem
    var alerts = user.Alerts;
    context.Load(alerts);
    context.ExecuteQuery();

    foreach (Alert alert in alerts)
    {
        //get the alert
        var type = alert.Title;
    }

    count += alerts.Count;
}

Reference - CSOM January 2017 update


text:
Q: How to set the distance widget in android How to set distance widget as below in android
I Clearly am able to set the rating bar but the next one i am having trouble in attaining
Is there any solution

Code i have now ::
<RatingBar
        android:id="@+id/ratingBar"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/RestaurantPicImageLinearViewID"
        android:layout_centerHorizontal="true" />


text:
Q: Don't overwrite value in mongo if new value is null when doing mongoose with node i can update a document in mongo with..
      const account = await userModel
        .findOneAndUpdate(
          { 'shared.email': email },
          {
          $set: {
            'shared.username': req.body.username,
             ...
            'shared.country': req.body.country,
            'shared.dob': dob,
            },
          },
          {
            new: true,
          }
        )
        .exec();

and req.body.username is null or '' and shared.username already in mongo  is James
is there anyway to keep the username James and not overwrite it with null or ''?
The userModel Schema is...
const userSchema: Schema = new Schema(
  {
    email: {
      confirmationCode: { type: String, unique: true, index: true },
      confirmationSentAt: { type: Date },
      confirmed: { type: Boolean, default: false },
    },
    password: {
      hash: { type: String },
      resetCode: { type: String, unique: true, index: true },
      sentAt: { type: Date },
    },
    shared: {
      avatarId: { type: String },
      bio: { type: String },
      country: { type: String },
      dob: { type: Date },
      email: { type: String, required: true, unique: true, index: true },
      fullName: { type: String },
      gender: { type: String },
      language: { type: String, default: 'en' },
      location: { type: String },
      loggedIn: { type: Boolean, default: true },
      username: { type: String, unique: true, index: true },
      warningMessage: { type: String, default: 'verify' },
      webSite: { type: String },
    },
  },
  {
    timestamps: true,
  }
);

A: You can  exclude the fields with falsy values, and send this filtered object to the update query.
  const { email, username, country } = req.body;

  let filteredBody = {};

  if (username) {
    filteredBody["shared.username"] = username;
  }

  if (country) {
    filteredBody["shared.country"] = country;
  }

  console.log(filteredBody);

  const account = await userModel.findOneAndUpdate(
    { "shared.email": email },
    filteredBody,
    {
      new: true
    }
  );

Test:
Let's say we have this existing user in our collection.
{
    "_id": "5df24ed1ec018d37785c23bd",
    "shared": {
        "email": "user1@gmail.com",
        "username": "user1",
        "country": "USA"
    }
}

When we send a request body like this:
{
        "email": "user1@gmail.com",
        "username": "",
        "country": "England"
}

The username field will not be updated, but the country will be updated like this:
{
    "shared": {
        "email": "user1@gmail.com",
        "username": "user1",
        "country": "England"
    },
    "_id": "5df24ed1ec018d37785c23bd"
}

A: //Pass all you need to update in all cases to setData. And append username if available
const setData = {
        'shared.country': req.body.country,
        'shared.dob': dob,
        },
}

if(req.body.username){
  setData['shared.username'] = req.body.username;
}

const account = await userModel
    .findOneAndUpdate(
      { 'shared.email': email },
      {
      $set: setData,
      {
        new: true,
      }
    )
    .exec();

A: The expected behavior of Mongoose is to accept "null" even if you specified a type for the field.
So, if you want to reject a "null" value, you have two options :
Option 1. In your schema, add "required: true" to the field. It will work also for "undefined" value and empty strings.
Option 2. In your function, add an if statement which will check the value before updating.


text:
Q: an upstream response is buffered to a temporary file I have a rather large and slow (complex data, complex frontend) web application build in RoR and served by Puma with nginx as reverse proxy.
Looking at the nginx error log, I see quite a few entries like:
2014/04/08 09:46:08 [warn] 20058#0: *819237 an upstream response is buffered to a temporary file
    /var/lib/nginx/proxy/8/47/0000038478 while reading upstream,
    client: 5.144.169.242, server: engagement-console.foo.it,
    request: "GET /elements/pending?customer_id=2&page=2 HTTP/1.0",
    upstream: "http://unix:///home/deployer/apps/conversationflow/shared/sockets/puma.sock:/elements/pending?customer_id=2&page=2",
    host: "ec.reputationmonitor.it",
    referrer: "http://ec.foo.it/elements/pending?customer_id=2&page=3"

I am rather curious as it's very unlikely that the page remains the same for different users and different user interactions, and I would not think that buffering the response on disk is necessary/useful.
I know about proxy_max_temp_file_size and setting it to 0, but it seems to me a little bit awkward (my proxy tries to buffer but has no file where to buffer to... how can that be faster?).
My questions are:

*

*How can I remove the [warn] and avoid buffering responses? Is it better to turn off proxy_buffering or to set proxy_max_temp_file_size to 0? Why?

*If nginx buffers a response: When does it serve the buffered response, to whom, and why?

*Why nginx turns proxy_buffering on by default and then [warn]s you if it actually buffers a response?

*When does a response trigger that option? When it takes > some seconds (how many?) to serve the response? Is this configurable?
TIA, ngw.

A: The following configuration works fine on my server.
proxy_buffers 16 16k;
proxy_buffer_size 16k;

A:

*

*How can I remove the [warn] and avoid buffering responses? Is it better to turn off proxy_buffering or set proxy_max_temp_file_size to 0? Why?

You should set proxy_max_temp_file_size to 0 in order to remove it. The proxy_buffering directive isn't directly related to the warning. You can switch it off to stop any buffering at all but that isn't recommended in general (unless it's needed for Comet).

*If nginx buffers a response when does it serve the buffered response, to whom and why?

It serves the response immediately, but a client usually has a much slower connection and can't consume the response data as fast as it is produced by your application. Nginx tries to buffer the whole response in order to release your application ASAP.
See also: http://aosabook.org/en/nginx.html

*Why nginx turns proxy_buffering on by default and then [warn]s you if it actually buffers a response?

As I already mentioned, the proxy_buffering isn't directly related to the warning. It's generally needed for optimized proxy operations and turning it off degrades performance and throughput.
Nginx only warns you when a response doesn't fit into configured memory buffers. You may ignore the warning if it's ok for you.

*When does a response triggers that option? When it takes > than some seconds (how many?) to serve the response? Is this configurable?

It triggers when memory buffers are full. Please, look at the docs, the whole mechanism is explained: http://nginx.org/r/proxy_max_temp_file_size
You may want to increase memory buffers.


text:
Q: How to determines the context of entities nltk python I am working on a nlp project where i have to determine word context in a sentence forexample the word crane, for instance, could refer to a machine used to lift heavy objects, a type of bird, or even a movement of someone's neck.
and i do not know how to proceed. I am using NLTK Python and wordnet. with wordnet i can find out the meaning of word but how to get the appropriate context of word. Like - i saw a crane flying then i want a result like crane with referring to bird with score


text:
Q: NSURLSessionDataTask completion handler not executing in command line project I have looked on multiple stack overflow posts regarding this issue and attempted to implement those fixes to no avail. Neither of the top two answers from this question worked NSURLSessionDataTask not executing the completion handler block
Here is my very simple code
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
@autoreleasepool {
    NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@", json);
    }];

    [dataTask resume];
}
return 0;
}

I'm never getting any console output.
I have tried instantiating the session in different ways, like
 [NSURLSession sharedSession]

which didn't work,
as well as trying to execute the code in the completion block in a different thread
 dispatch_sync(dispatch_get_main_queue(), ^{
   // Completion code goes here
 });

which also didn't work.
I've also tried different URL's. I have no idea why it's not working.

A: A command line interface does not have a runloop by default so asynchronous tasks cannot work.
You have to start and stop the runloop explicitly
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        CFRunLoopRef runloop = CFRunLoopGetCurrent();
        NSURLSession* session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@", json);
            CFRunLoopStop(runloop);
        }];

        [dataTask resume];
        CFRunLoopRun();
    }
    return 0;
}

You should handle the dataTask error to exit with a value != 0

A: add this code in main function.
 [[NSRunLoop currentRunLoop] run];

this code will keep the runloop still run,so that the request can be  executed totally.

A: Every progress has one thread, that is, main thread in it by default. A program ends up with return 0; in general, that is, your command line program will be exited after the last line return 0; no matter how many threads alive there.
If you want to get the request response, you should let the main thread wait until the background request thread finishes the task. Check the dispatch_semaphore_signal out, it helps you.
How about the generic iOS/macOS UI application? Because they have an infinite loop called event loop inside to receive the user interactions, so the return 0; in the main function won't be called immediately.


text:
Q: cardinality of $\mathbb R$ is the same as the cardinality of $\mathbb R^2$ A problem in my homework is to prove the cardinality of $\mathbb R$ and the cardinality of $\mathbb R^2$ is the same. I'm in my first semester and I have no clue how to do this, do I need the axiom of choice to prove this? Can I find a bijection, or must I use Cantor-Schroeder-Bernstein? Apparently if we assume choice we can go further and prove the cardinality of any set $A$ is is equal to the cardinality of $A^2$ thank you very much, I need help.
Regards.

A: I just wanted to get the selfie badge. The solution I found at the end is the following:
We want an injection from $\mathbb R^2 $ to $\mathbb R$ we take a surjection from $\mathbb R$ to $\mathbb R^2$ and what we want is the right inverse.
As an example of a surjection I took the following: let the number in $\mathbb R$ be $(-1)^n(k+.d_1d_2d_3\dots)$ if $k$ is not of the form $2^a3^b5^c7^d$ send it to zero. if it is send it it to $((-1)^ad_1d_3d_5\dots,((-1)^bd_2d_4d_6\dots)$. And leave $c$ and $d$ digits before adding the decimal point.


text:
Q: (Python) Why is it returning 9.0 instead of 9? Trying to make a simple counter in python for a project in a "Learn Python Book"
Brief: Write a program that counts for the user. Let the user enter the starting number, the ending number and the amount by which to count.
Problem: Ok so basically trying to make sure that if the user were to          type
         in (start at 2 and count to 17 in 2's) that the program would flag         it up as not possible.
print ("Welcome to the program for those who are to lazy to count")
print ("You must be really really lazy too use this")

input ("\n Press any key to continue")

Num1 = int(input ("Please Enter Starting Number: \n"))
Num2 = int(input ("Please Enter Ending Number: \n"))
count = int(input ("Count up in: \n"))

differ = (Num2 - Num1)

test =(differ/count)

if isinstance(test,int):
 while (Num1 < Num2):
  Num1 += count
  print (Num1)
  isinstance( test, int )
else:
    print ("Sorry Starting at",Num1,"You can not get to",Num2,"counting up by",count,)

(( I did some testing and found that the variable test was always coming        back as a float.A whole number for example 9 would be 9.0 which would of course make my if statement false. Can anyone explain why this is occurring and how to fix/get around it?))

A: You should test to see if (differ % count) == 0 instead of checking to see if your test is an integer. The result of your division operation is always a float because python 3 defaults to floating point division. It can be forced to perform integer division with //.
See the python docs for modulo.

A: wilbur's answer is the best, but if you still want to use division instead of modulo, instead of checking if isinstance(test, int) which checks if test is really an integer type (which is not true for 9.0), you can try if test.is_integer() which will return True if it's a float with an integer value (which is true for 9.0).
This is not an approach you can count on because division with floats is imprecise. Using a modulo operator is a lot more reliable!

A: Python 3 does floating-point division by default.  If you want to force integer division, express double slashes in your quotient (differ // count).

A: Python 3 / always returns float. For integer division, use //.