问:
Build step triggered by TeamCity always builds - even when there are no changes
The problem: I am setting up TeamCity as a build server for an ASP.NET MVC project. I am using Powershell with psake to run msbuild against our .csproj file and create a deployable package. From the build server, I can open up powershell, run the script and, because there are no source code changes, msbuild does not regenerate the project DLL files. BUT, when I call the exact same script from the TeamCity web interface, msbuild ALWAYS rebuilds and regenerates the DLL files even though there are no changes. Not what it should do AFAIK.

I have narrowed this problem down to a single step. To keep it simple, I have set up my TeamCity config so it is not using any source control, it runs a single "powershell" build step that calls my powershell script.

The powershell script runs a single command:

```<code>exec { &$msbuild $ProjectFile /t:Package "/p:PackageLocation=$PackageFile;OutDir=$TempPath;Configuration=$Config;SolutionDir=$BaseDir\Source\" /v:m }
</code>```

When I call the script manually from a powershell command line, I see:

```<code>CoreCompile:
Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.
</code>```

When I call the exact same script through TeamCity, I see:

```<code>[11:11:26]: CoreCompile:
[11:11:26]:   c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Csc.exe /noconfig ...
<SNIP>
[11:11:32]: CopyFilesToOutputDirectory:
[11:11:32]:   Copying file from "obj\Demo\Website.Web.dll" to "d:\deploy\Build\package\Demo\temp\Website.Web.dll".
[11:11:32]:   Website.Web -> d:\deploy\Build\package\Demo\temp\Website.Web.dll
[11:11:32]:   Copying file from "obj\Demo\Website.Web.pdb" to "d:\deploy\Build\package\Demo\temp\Website.Web.pdb".
[11:11:32]: _CopyWebApplicationLegacy:
[11:11:32]:   Copying Web Application Project Files for Website.Web
[11:11:32]:   Copying file from "obj\Demo\Website.Web.dll" to "d:\deploy\Build\package\Demo\temp\_PublishedWebsites\Website.Web\bin\Website.Web.dll".
[11:11:32]:   Copying file from "obj\Demo\Website.Web.pdb" to "d:\deploy\Build\package\Demo\temp\_PublishedWebsites\Website.Web\bin\Website.Web.pdb".
[11:11:32]:   Copying file from "d:\deploy\Build\package\Demo\temp\Website.Data.dll" to "d:\deploy\Build\package\Demo\temp\_PublishedWebsites\Website.Web\bin\Website.Data.dll".
[11:11:32]:   Copying file from "d:\deploy\Build\package\Demo\temp\Website.Data.pdb" to "d:\deploy\Build\package\Demo\temp\_PublishedWebsites\Website.Web\bin\Website.Data.pdb".
</code>```

Any ideas why running this script from TeamCity causes msbuild to detect changes and rebuild, but running the exact same script manually does not?

UPDATE:
Thinking this might be caused by some quirk with the TeamCity Powershell runner, I just tried making a batch file that passes the script into Powershell.exe and called it using the Command Line runner:

```<code>C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -File D:\deploy\Build\run-build.ps1 && exit /b %ERRORLEVEL%
</code>```

and I get the exact same behavior. If I call this batch file from the command line, the msbuild skips compilation. If I call it from TeamCity, the DLLs are recompiled.

UPDATE #2:
Eureka! I turned on diagnostic debugging in msbuild and found the cause of the forced recompile. It is caused by the GenerateTargetFrameworkMonikerAttribute target. Here is the key bits from the log output:

```<code>[15:23:28]: Target "GenerateTargetFrameworkMonikerAttribute" in file "c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets" from project "d:\deploy\source\Website.Data\Website.Data.csproj" (target "BeforeCompile" depends on it):
[15:23:28]: Building target "GenerateTargetFrameworkMonikerAttribute" completely.
[15:23:28]: Output file "C:\TeamCity\buildAgent\temp\buildTmp\.NETFramework,Version=v4.0.AssemblyAttributes.cs" does not exist.
[15:23:28]: Using "WriteLinesToFile" task from assembly "Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
[15:23:28]: Task "WriteLinesToFile"
[15:23:28]: Done executing task "WriteLinesToFile".
[15:23:28]: Done building target "GenerateTargetFrameworkMonikerAttribute" in project "SMM.Data.csproj".
</code>```

It looks like this target creates/updates an AssemblyAttributes file in the TEMP dir as specified in the TEMP environment variable. Apparently TeamCity overrides the TEMP environment variable and sets it to: C:\TeamCity\buildAgent\temp\buildTmp and this directory is cleaned before every build.

I can see this if I call Get-ChildItem Env: from powershell:

```<code>TEMP                           C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp
TMP                            C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp
</code>```

But if I call it from the powershell script as called from TeamCity:

```<code>TEMP                           C:\TeamCity\buildAgent\temp\buildTmp
TMP                            C:\TeamCity\buildAgent\temp\buildTmp
</code>```

The key piece is that after this file is regnerated:

```<code>[15:23:28]: Building target "CoreCompile" completely.
[15:23:28]: Input file "C:\TeamCity\buildAgent\temp\buildTmp\.NETFramework,Version=v4.0.AssemblyAttributes.cs" is newer than output file "obj\Demo\SMM.Data.pdb".
</code>```

And this is why the whole project is getting recompiled.

When I run the script from Powershell, the temp directory is not changed or cleaned and the build runs as expected.

So, anyone know how I can either change the directory that this AssemblyAttributes file is created, or tell TeamCity to use a different TEMP dir? I have to believe that this is an issue that others have run into.

Thanks!

答:
As a variation of obliojoe's answer, you can backup and restore these files to/from TEMP folder, if you do not want or cannot change the individual project files:

First attempt to restore the files from a backup:

```<code>copy temp\*.* %%temp%% /y
echo AssemblyAttributes restore attempted
</code>```

Then perform your build step(s) using TeamCity build runner

Backup the files:

```<code>mkdir temp 2> nil
copy %%temp%%\*AssemblyAttributes.cs temp /y
echo AssemblyAttributes files saved
</code>```

Both batch files need to run from the same directory.

Do note the final ECHO in these batch files, it is there to guarantee successful exit (error code 0).

Body:
The problem: I am setting up TeamCity as a build server for an ASP.NET MVC project. I am using Powershell with psake to run msbuild against our .csproj file and create a deployable package. From the build server, I can open up powershell, run the script and, because there are no source code changes, msbuild does not regenerate the project DLL files. BUT, when I call the exact same script from the TeamCity web interface, msbuild ALWAYS rebuilds and regenerates the DLL files even though there are no changes. Not what it should do AFAIK.

I have narrowed this problem down to a single step. To keep it simple, I have set up my TeamCity config so it is not using any source control, it runs a single "powershell" build step that calls my powershell script.

The powershell script runs a single command:

exec { &$msbuild $ProjectFile /t:Package "/p:PackageLocation=$PackageFile;OutDir=$TempPath;Configuration=$Config;SolutionDir=$BaseDir\Source\" /v:m }

When I call the script manually from a powershell command line, I see:

CoreCompile:
Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files.

When I call the exact same script through TeamCity, I see:

[11:11:26]: CoreCompile:
[11:11:26]:   c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Csc.exe /noconfig ...
<SNIP>
[11:11:32]: CopyFilesToOutputDirectory:
[11:11:32]:   Copying file from "obj\Demo\Website.Web.dll" to "d:\deploy\Build\package\Demo\temp\Website.Web.dll".
[11:11:32]:   Website.Web -> d:\deploy\Build\package\Demo\temp\Website.Web.dll
[11:11:32]:   Copying file from "obj\Demo\Website.Web.pdb" to "d:\deploy\Build\package\Demo\temp\Website.Web.pdb".
[11:11:32]: _CopyWebApplicationLegacy:
[11:11:32]:   Copying Web Application Project Files for Website.Web
[11:11:32]:   Copying file from "obj\Demo\Website.Web.dll" to "d:\deploy\Build\package\Demo\temp\_PublishedWebsites\Website.Web\bin\Website.Web.dll".
[11:11:32]:   Copying file from "obj\Demo\Website.Web.pdb" to "d:\deploy\Build\package\Demo\temp\_PublishedWebsites\Website.Web\bin\Website.Web.pdb".
[11:11:32]:   Copying file from "d:\deploy\Build\package\Demo\temp\Website.Data.dll" to "d:\deploy\Build\package\Demo\temp\_PublishedWebsites\Website.Web\bin\Website.Data.dll".
[11:11:32]:   Copying file from "d:\deploy\Build\package\Demo\temp\Website.Data.pdb" to "d:\deploy\Build\package\Demo\temp\_PublishedWebsites\Website.Web\bin\Website.Data.pdb".

Any ideas why running this script from TeamCity causes msbuild to detect changes and rebuild, but running the exact same script manually does not?

UPDATE:
Thinking this might be caused by some quirk with the TeamCity Powershell runner, I just tried making a batch file that passes the script into Powershell.exe and called it using the Command Line runner:

C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -NonInteractive -File D:\deploy\Build\run-build.ps1 && exit /b %ERRORLEVEL%

and I get the exact same behavior. If I call this batch file from the command line, the msbuild skips compilation. If I call it from TeamCity, the DLLs are recompiled.

UPDATE #2:
Eureka! I turned on diagnostic debugging in msbuild and found the cause of the forced recompile. It is caused by the GenerateTargetFrameworkMonikerAttribute target. Here is the key bits from the log output:

[15:23:28]: Target "GenerateTargetFrameworkMonikerAttribute" in file "c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets" from project "d:\deploy\source\Website.Data\Website.Data.csproj" (target "BeforeCompile" depends on it):
[15:23:28]: Building target "GenerateTargetFrameworkMonikerAttribute" completely.
[15:23:28]: Output file "C:\TeamCity\buildAgent\temp\buildTmp\.NETFramework,Version=v4.0.AssemblyAttributes.cs" does not exist.
[15:23:28]: Using "WriteLinesToFile" task from assembly "Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
[15:23:28]: Task "WriteLinesToFile"
[15:23:28]: Done executing task "WriteLinesToFile".
[15:23:28]: Done building target "GenerateTargetFrameworkMonikerAttribute" in project "SMM.Data.csproj".

It looks like this target creates/updates an AssemblyAttributes file in the TEMP dir as specified in the TEMP environment variable. Apparently TeamCity overrides the TEMP environment variable and sets it to: C:\TeamCity\buildAgent\temp\buildTmp and this directory is cleaned before every build.

I can see this if I call Get-ChildItem Env: from powershell:

TEMP                           C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp
TMP                            C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp

But if I call it from the powershell script as called from TeamCity:

TEMP                           C:\TeamCity\buildAgent\temp\buildTmp
TMP                            C:\TeamCity\buildAgent\temp\buildTmp

The key piece is that after this file is regnerated:

[15:23:28]: Building target "CoreCompile" completely.
[15:23:28]: Input file "C:\TeamCity\buildAgent\temp\buildTmp\.NETFramework,Version=v4.0.AssemblyAttributes.cs" is newer than output file "obj\Demo\SMM.Data.pdb".

And this is why the whole project is getting recompiled.

When I run the script from Powershell, the temp directory is not changed or cleaned and the build runs as expected.

So, anyone know how I can either change the directory that this AssemblyAttributes file is created, or tell TeamCity to use a different TEMP dir? I have to believe that this is an issue that others have run into.

Thanks!

Body:
As a variation of obliojoe's answer, you can backup and restore these files to/from TEMP folder, if you do not want or cannot change the individual project files:

First attempt to restore the files from a backup:

copy temp\*.* %%temp%% /y
echo AssemblyAttributes restore attempted

Then perform your build step(s) using TeamCity build runner

Backup the files:

mkdir temp 2> nil
copy %%temp%%\*AssemblyAttributes.cs temp /y
echo AssemblyAttributes files saved

Both batch files need to run from the same directory.

Do note the final ECHO in these batch files, it is there to guarantee successful exit (error code 0).


来源: stackexchange

问:
GroupBy and sum to dictionary
I have two tables that are joined together like this..

```<code>var query = (from t1 in _db.Table1 join t2 in _db.Table2 on t1.CId equals
              t2.ID where t1.DateAdded >= fromDate && t1.DateAdded <= toDate select t2)
             .GroupBy(c => c.Brand)
             .ToDictionary(t => t.Key, t => t.Count());
</code>```

This almost give me what I want, it return the number of different cFormat rows,
but I would like to it to be summarized on t2.Qty instead

If the data look like this...

```<code>Brand           Qty
Volvo           2
Volvo           1
Tesla           4
Tesla           9
</code>```

My current query give me a result like this..

```<code>Volvo           2
Tesla           2
</code>```

But I would like it to be

```<code>Volvo           3
Tesla           13
</code>```

How can I change it to work like that?

答:
Use Sum instead of Count:

```<code>.ToDictionary(t => t.Key, t => t.Sum(c => c.Qty));
</code>```

ContentLicense: CC BY-SA 3.0

Title: GroupBy and sum to dictionary

Body:
I have two tables that are joined together like this..

var query = (from t1 in _db.Table1 join t2 in _db.Table2 on t1.CId equals
              t2.ID where t1.DateAdded >= fromDate && t1.DateAdded <= toDate select t2)
             .GroupBy(c => c.Brand)
             .ToDictionary(t => t.Key, t => t.Count());

This almost give me what I want, it return the number of different cFormat rows,
but I would like to it to be summarized on t2.Qty instead

If the data look like this...

Brand           Qty
Volvo           2
Volvo           1
Tesla           4
Tesla           9

My current query give me a result like this..

Volvo           2
Tesla           2

But I would like it to be

Volvo           3
Tesla           13

How can I change it to work like that?

Body:
Use Sum instead of Count:

.ToDictionary(t => t.Key, t => t.Sum(c => c.Qty));


问:
Node.js async taking too long to execute
I've got my array of queries

```<code>var array = [ 'UPDATE EVALUATION SET mark = "16" WHERE id_eval = "21" AND id_usr = "125"',
              'UPDATE EVALUATION SET mark = "9" WHERE id_eval = "22" AND id_usr = "125"',
              'UPDATE EVALUATION SET mark = "8" WHERE id_eval = "34" AND id_usr = "125"'
            ]
</code>```

However, when I try to execute them all at once with async, my web page says Waiting for localhost... and it keeps on loading forever. What am I doing wrong?

```<code>async.forEach(array, function(query, callback) {
    connection.query(query, function(err, rows, fields) {
        if(err) {
            return console.error(err);
        }

        callback();
    });
}, function(err){
    if(err) {
        return console.log(err);
    }
});
</code>```

答:
Just make sure that you return the response after the forEach callback is called:

```<code>async.forEach(array, function(query, callback) {
    connection.query(query, function(err, rows, fields) {
        if(err) {
            console.error(err);
        }

        callback();
    });
}, function(err){
    if(err) {
        console.log(err);
    }

    res.redirect('/next-page');
});
</code>```

That way, the redirection will occur only at the end of all the queries.

Some things you should verify:

Verify you didn't call res.end() or res.redirect() or anything similar before the above code.

Verify that your DB query method actually expect only 2 arguments: query and callback, and not anything in between (e.g. the query parameters).

Verify this piece of code is actually called when you expect it. Try debugging the request all the way.

Currently there's no real error handling here. You should consider returning an HTTP error if something went wrong. This should also help you debugging this code in the future.

Body:
I've got my array of queries

var array = [ 'UPDATE EVALUATION SET mark = "16" WHERE id_eval = "21" AND id_usr = "125"',
              'UPDATE EVALUATION SET mark = "9" WHERE id_eval = "22" AND id_usr = "125"',
              'UPDATE EVALUATION SET mark = "8" WHERE id_eval = "34" AND id_usr = "125"'
            ]

However, when I try to execute them all at once with async, my web page says Waiting for localhost... and it keeps on loading forever. What am I doing wrong?

async.forEach(array, function(query, callback) {
    connection.query(query, function(err, rows, fields) {
        if(err) {
            return console.error(err);
        }

        callback();
    });
}, function(err){
    if(err) {
        return console.log(err);
    }
});

Body:
Just make sure that you return the response after the forEach callback is called:

async.forEach(array, function(query, callback) {
    connection.query(query, function(err, rows, fields) {
        if(err) {
            console.error(err);
        }

        callback();
    });
}, function(err){
    if(err) {
        console.log(err);
    }

    res.redirect('/next-page');
});

That way, the redirection will occur only at the end of all the queries.

Some things you should verify:

Verify you didn't call res.end() or res.redirect() or anything similar before the above code.

Verify that your DB query method actually expect only 2 arguments: query and callback, and not anything in between (e.g. the query parameters).

Verify this piece of code is actually called when you expect it. Try debugging the request all the way.

Currently there's no real error handling here. You should consider returning an HTTP error if something went wrong. This should also help you debugging this code in the future.


问:
Php form html integration not working properly (Ion Auth register)
I want to add some nice bottstrap html and css to my register page, but i don't know how to embedding php into html input and show it with style. Is there any way to do this?

The code produces the next view:

Full .php file

Note: it is showing both forms(to compare results), php and html + php. form with only php works fine, the problem is to give it style.

```<code><?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<link rel="stylesheet" href="<?= base_url('assets/bootstrap2/bootstrap.min.css'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/bootstrap2/bootstrap.css'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/js2/bootstrap.js'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/js2/bootstrap.min.js'); ?>">
<div class="container">
    <?php
    echo isset($_SESSION['auth_message']) ? $_SESSION['auth_message'] : FALSE;
    ?>
    <h1>Registro usuario</h1>
    <?php
    echo form_open();
    echo form_label('Nombre:','first_name').'<br />';
    echo form_error('first_name');
    echo form_input('first_name',set_value('first_name')).'<br />';
    echo form_label('Apellidos:','last_name').'<br />';
    echo form_error('last_name');
    echo form_input('last_name',set_value('last_name')).'<br />';
   // echo form_label('Username:','username').'<br />';
    //echo form_error('username');
    //echo form_input('username',set_value('username')).'<br />';
    echo form_label('Email:','email').'<br />';
    echo form_error('email');
    echo form_input('email',set_value('email')).'<br />';
    echo form_label('Contraseña:', 'password').'<br />';
    echo form_error('password');
    echo form_password('password').'<br />';
    echo form_label('Confirmar contraseña:', 'confirm_password').'<br />';
    echo form_error('confirm_password');
    echo form_password('confirm_password').'<br /><br />';
    echo form_submit('register','Confirmar');
    echo form_close();
    ?>
</div>
<form class="form-horizontal">
<fieldset>

<!-- Form Name -->
<legend>Registro de usuario</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">Nombre</label>
  <div class="col-md-4">
     <!-- <input value="" id="textinput" name="textinput" type="text" placeholder="Ej: José Manuel..." class="form-control input-md" required=""> -->
     <?php $nombre = array(
          'name'        => 'first_name',
          'id'          => 'first_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: José Manuel...',
        ); ?>

 <?php echo form_input($nombre); ?>
   <!-- <?php echo form_input('first_name',set_value('first_name')); ?> -->
  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">Apellidos</label>
  <div class="col-md-4">
    <!--  <input value="" id="textinput" name="textinput" type="text" placeholder="Ej: Palma..." class="form-control input-md" required=""> -->

      <?php $apellidos = array(
          'name'        => 'last_name',
          'id'          => 'last_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: Palma...',
        ); ?>

 <?php echo form_input($apellidos); ?>

  <!--  <?php echo form_input('last_name',set_value('last_name')); ?> -->
  </div>
</div>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">Email</label>
  <div class="col-md-4">
   <!--   <input value="" id="textinput" name="textinput" type="text" placeholder="Ej: herba@gmail.com..." class="form-control input-md" required=""> -->

      <?php $email = array(
          'name'        => 'email',
          'id'          => 'email',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herba@gmail.com...',
        ); ?>

 <?php echo form_input($email); ?>

  <!--  <?php echo form_input('email',set_value('email'));?> -->
  </div>
</div>

<!-- Password input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="passwordinput">Contraseña</label>
  <div class="col-md-4">
  <!--  <input value="" id="passwordinput" name="passwordinput" type="password" placeholder="Ej: herbaricemills9..." class="form-control input-md" required=""> -->

    <?php $password = array(
          'name'        => 'password',
          'id'          => 'password',
          'type'          => 'password',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herbaricemills9...',
        ); ?>

 <?php echo form_input($password); ?>

    <!--  <?php echo form_password('password'); ?> -->
  </div>
</div>

<!-- Password input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="passwordinput">Confirmar contraseña</label>
  <div class="col-md-4">
   <!--   <input value="" id="passwordinput" name="passwordinput" type="password" placeholder="Repetir contraseña..." class="form-control input-md" required=""> -->

       <?php $password1 = array(
          'name'        => 'confirm_password',
          'id'          => 'confirm_password',
          'type'          => 'password',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Repetir contraseña...',
        ); ?>

 <?php echo form_input($password1); ?>

  <!--  <?php echo form_password('confirm_password');?> -->
  </div>
</div>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="singlebutton"></label>
  <div class="col-md-4">
    <!--  <button  value="" id="singlebutton" name="singlebutton" class="btn btn-primary">Confirmar</button> -->

    <!--  <?php $confirm = array(
          'name'        => 'singlebutton',
          'id'          => 'singlebutton',
          //'type'          => 'password',
          'class'       => 'btn btn-primary',

        ); ?>

 <?php echo form_input($confirm); ?> -->

   <?php echo form_submit('register','Confirmar');?>

  </div>
</div>

</fieldset>
</form>
</code>```

答:
for inserting this

```<code><input value="" id="textinput" name="textinput" type="text" placeholder="Ej: herba@gmail.com..." class="form-control input-md" required="">
</code>```

try to use this example:

```<code>$data = array(
          'name'        => 'textinput',
          'id'          => 'textinput',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herba@gmail.com...',
        );

 echo form_input($data);
</code>```

Body:
I want to add some nice bottstrap html and css to my register page, but i don't know how to embedding php into html input and show it with style. Is there any way to do this?

The code produces the next view:

Full .php file

Note: it is showing both forms(to compare results), php and html + php. form with only php works fine, the problem is to give it style.

<?php defined('BASEPATH') OR exit('No direct script access allowed');?>
<link rel="stylesheet" href="<?= base_url('assets/bootstrap2/bootstrap.min.css'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/bootstrap2/bootstrap.css'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/js2/bootstrap.js'); ?>">
<link rel="stylesheet" href="<?= base_url('assets/js2/bootstrap.min.js'); ?>">

    <?php
    echo isset($_SESSION['auth_message']) ? $_SESSION['auth_message'] : FALSE;
    ?>

Registro usuario

    <?php
    echo form_open();
    echo form_label('Nombre:','first_name').'
';
    echo form_error('first_name');
    echo form_input('first_name',set_value('first_name')).'
';
    echo form_label('Apellidos:','last_name').'
';
    echo form_error('last_name');
    echo form_input('last_name',set_value('last_name')).'
';
   // echo form_label('Username:','username').'
';
    //echo form_error('username');
    //echo form_input('username',set_value('username')).'
';
    echo form_label('Email:','email').'
';
    echo form_error('email');
    echo form_input('email',set_value('email')).'
';
    echo form_label('Contraseña:', 'password').'
';
    echo form_error('password');
    echo form_password('password').'
';
    echo form_label('Confirmar contraseña:', 'confirm_password').'
';
    echo form_error('confirm_password');
    echo form_password('confirm_password').'

';
    echo form_submit('register','Confirmar');
    echo form_close();
    ?>

<form class="form-horizontal">
<fieldset>

<legend>Registro de usuario</legend>

  Nombre

     <?php $nombre = array(
          'name'        => 'first_name',
          'id'          => 'first_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: José Manuel...',
        ); ?>

 <?php echo form_input($nombre); ?>

  Apellidos

      <?php $apellidos = array(
          'name'        => 'last_name',
          'id'          => 'last_name',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: Palma...',
        ); ?>

 <?php echo form_input($apellidos); ?>

  Email

      <?php $email = array(
          'name'        => 'email',
          'id'          => 'email',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herba@gmail.com...',
        ); ?>

 <?php echo form_input($email); ?>

  Contraseña

    <?php $password = array(
          'name'        => 'password',
          'id'          => 'password',
          'type'          => 'password',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herbaricemills9...',
        ); ?>

 <?php echo form_input($password); ?>

  Confirmar contraseña

       <?php $password1 = array(
          'name'        => 'confirm_password',
          'id'          => 'confirm_password',
          'type'          => 'password',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Repetir contraseña...',
        ); ?>

 <?php echo form_input($password1); ?>

   <?php echo form_submit('register','Confirmar');?>

</fieldset>
</form>

Body:
for inserting this

<input value="" id="textinput" name="textinput" type="text" placeholder="Ej: herba@gmail.com..." class="form-control input-md" required="">

try to use this example:

$data = array(
          'name'        => 'textinput',
          'id'          => 'textinput',
          'type'          => 'text',
          'class'       => 'form-control input-md',
          'placeholder'       => 'Ej: herba@gmail.com...',
        );

 echo form_input($data);


问:
Store values from JSON output retrieved from SPARQL endpoint in a array
Here is the working code:

```<code>var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $http) {
  $scope.name = 'World';

  $http({
    url: 'http://landregistry.data.gov.uk/landregistry/query',
    headers: { 'Content-type' : 'application/x-www-form-urlencoded',
            'Accept' : 'application/sparql-results+json' },
    method: "GET",
    params: {
            query : "select * where {?s a ?o} limit 10",
            format: "json"
        }
  })

  .success(function(data, status, headers, config) {
    $scope.results = data.results.bindings;
    // this callback will be called asynchronously when the response is available
   })

  .error(function(data, status, headers, config) {
    // called asynchronously if an error occurs or server returns response with an error status.
  });

});
</code>```

http://plnkr.co/edit/LfkIPZRsZ4QHTfq2A2vc?p=preview

My doubt is how to store for instance, all s.values in an array such that the array can be further used to populate a drop down menu without having to save the JSON output to an external file.

Thanks.

答:
You are already storing the results as a list in $scope.results.

To use the values for s in a dropdown menu, for example, you can do this:

<select ng-options="item as item.s.value for item in results" ng-model="selected"></select>

Plunkr

Body:
Here is the working code:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $http) {
  $scope.name = 'World';

  $http({
    url: 'http://landregistry.data.gov.uk/landregistry/query',
    headers: { 'Content-type' : 'application/x-www-form-urlencoded',
            'Accept' : 'application/sparql-results+json' },
    method: "GET",
    params: {
            query : "select * where {?s a ?o} limit 10",
            format: "json"
        }
  })

  .success(function(data, status, headers, config) {
    $scope.results = data.results.bindings;
    // this callback will be called asynchronously when the response is available
   })

  .error(function(data, status, headers, config) {
    // called asynchronously if an error occurs or server returns response with an error status.
  });

});

http://plnkr.co/edit/LfkIPZRsZ4QHTfq2A2vc?p=preview

My doubt is how to store for instance, all s.values in an array such that the array can be further used to populate a drop down menu without having to save the JSON output to an external file.

Thanks.

ContentLicense: CC BY-SA 4.0


问:
Reasons for using Ant Properties files over "Properties Tasks"
I'm currently working with some developers who like to set up Ant tasks that define environment specific variables rather than using properties files.  It seems they prefer to do this because it's easier to type:

```<code>ant <environment task> dist
</code>```

Than it is to type:

```<code>ant -propertyfile <environment property file> dist
</code>```

So for example:

```<code><project name="whatever" default="dist">

<target name="local">
    <property name="webXml" value="WebContent/WEB-INF/web-local.xml"/>
</target>

<target name="remote">
    <property name="webXml" value="WebContent/WEB-INF/web-remote.xml"/>
</target>

<target name="build">
    <!-- build tasks here --->
</target>

<target name="dist" depends="build">
    <war destfile="/dist/foo.war" webxml="${webXml}">
         <!-- rest of war tasks here -->
    </war>
</target>
</code>```

I am finding it hard to convince them that properties files are they right way to go.  I believe properties files are better because:

They provides more flexibility - if you need a new environment just add a new properties file

It's clearer what's going on - You have to know about this little "trick" to realize what they're accomplishing

Doesn't provide default values and the ability to use overrides - if they used property files they could provide defaults at the top of the project but have the ability to override them with a file

Script won't break if an environment task isn't supplied on command line

Of course all they hear is that they need to change their Ant script and have to type more on the command line.

Can you provide any additional arguments in favor of properties files over "property tasks"?

答:
Properties tasks tightly couple the build file to environments. If your fellow developers are arguing that they "have to change their ant script" with your suggestions, why aren't they arguing about changing it every time they have to deploy to a new environment? :)

Perhaps you can convince them to allow both properties file and command-line configuration. I set up my Ant builds so that if a build.properties exists in the same directory as the build.xml, it reads it in. Otherwise it uses a set of default properties hard-coded into the build. This is very flexible.

```<code><project name="example">

    <property file="build.properties"/>

    <property name="foo.property" value="foo"/>
    <property name="bar.property" value="bar"/>

    ...
</project>
</code>```

I don't provide a build.properties with the project (i.e. build.properties is not versioned in SCM). This way developers aren't forced to use the property file. I do provide a build.properties.example file that developers can reference.

Since Ant properties, once set, are immutable, the build file will use properties defined in this order:

Properties provided with -D or -propertyfile via the command line

Properties loaded from build.properties

Default properties within build.xml

Advantages of this approach:

The build file is smaller and therefore more maintainable, less bug-prone

Developers that just can't get away from setting properties at the command line can still use them.

Properties files can be used, but aren't required

OwnerDisplayName: spilth

ContentLicense: CC BY-SA 2.5

Body:
I'm currently working with some developers who like to set up Ant tasks that define environment specific variables rather than using properties files.  It seems they prefer to do this because it's easier to type:

ant <environment task> dist

Than it is to type:

ant -propertyfile <environment property file> dist

So for example:

<project name="whatever" default="dist">

<target name="local">
    <property name="webXml" value="WebContent/WEB-INF/web-local.xml"/>
</target>

<target name="remote">
    <property name="webXml" value="WebContent/WEB-INF/web-remote.xml"/>
</target>

<target name="build">

</target>

<target name="dist" depends="build">
    <war destfile="/dist/foo.war" webxml="${webXml}">

    </war>
</target>

I am finding it hard to convince them that properties files are they right way to go.  I believe properties files are better because:

They provides more flexibility - if you need a new environment just add a new properties file

It's clearer what's going on - You have to know about this little "trick" to realize what they're accomplishing

Doesn't provide default values and the ability to use overrides - if they used property files they could provide defaults at the top of the project but have the ability to override them with a file

Script won't break if an environment task isn't supplied on command line

Of course all they hear is that they need to change their Ant script and have to type more on the command line.

Can you provide any additional arguments in favor of properties files over "property tasks"?

Body:
Properties tasks tightly couple the build file to environments. If your fellow developers are arguing that they "have to change their ant script" with your suggestions, why aren't they arguing about changing it every time they have to deploy to a new environment? :)

Perhaps you can convince them to allow both properties file and command-line configuration. I set up my Ant builds so that if a build.properties exists in the same directory as the build.xml, it reads it in. Otherwise it uses a set of default properties hard-coded into the build. This is very flexible.

<project name="example">

    <property file="build.properties"/>

    <property name="foo.property" value="foo"/>
    <property name="bar.property" value="bar"/>

    ...
</project>

I don't provide a build.properties with the project (i.e. build.properties is not versioned in SCM). This way developers aren't forced to use the property file. I do provide a build.properties.example file that developers can reference.

Since Ant properties, once set, are immutable, the build file will use properties defined in this order:

Properties provided with -D or -propertyfile via the command line

Properties loaded from build.properties

Default properties within build.xml

Advantages of this approach:

The build file is smaller and therefore more maintainable, less bug-prone

Developers that just can't get away from setting properties at the command line can still use them.

Properties files can be used, but aren't required

OwnerDisplayName: robhruska

LastEditorDisplayName: robhruska


问:
How can i return value from one method to another & swapping
I have this

```<code>public class Mapper implements ScramblerIF
{
 private static String map = "drsjckpwrypwsftylmzxopqtdo";

public static String charAt(String str)
{
 //char[] chars = str.toCharArray();
int length = str.length();

 for(int i=0; i<length; i++)
{
 char aChar = str.charAt(i);
 char upper = Character.toUpperCase(aChar);
 int num = (upper - 'A');
char mChar = map.charAt(num);
 //String chard = Character.toString(mChar);

 StringBuffer buf = new StringBuffer( str);
   buf.setCharAt( i, mChar );
 }
   return str;
 }

public String scramble(String str) {
return charAt(str);
 }
}
</code>```

I am trying to get it to where the method

```<code> public String scramble(String str) {
return charAt(str);
 }
</code>```

returns the computed value from the

```<code> public static String charAt(String str)
</code>```

method. Don't know where i went wrong.

Also instead of using

```<code>StringBuffer buf = new StringBuffer( str);
   buf.setCharAt( i, mChar );
</code>```

how would i be able to use the swap function?
When I try

```<code> char temp = chars[i];
chars[i] = chars[mChar];
chars[mChar] = temp;
</code>```

I am given an ArrayIndexOutOfBoundsException.
Summary of what i am trying to do is "For each character in the original string, use its position in the alphabet to look up its replacement in the map string. For example, the string “dog” would be translated to “jtp”."

答:
StringBuffer.setCharAt() will throw an exception if you try to set a character beyond the buffer. You haven't put anything in the buffer.

In addition, take a look at when you are creating the buffer.

Body:
I have this

public class Mapper implements ScramblerIF
{
 private static String map = "drsjckpwrypwsftylmzxopqtdo";

public static String charAt(String str)
{
 //char[] chars = str.toCharArray();
int length = str.length();

 for(int i=0; i<length; i++)
{
 char aChar = str.charAt(i);
 char upper = Character.toUpperCase(aChar);
 int num = (upper - 'A');
char mChar = map.charAt(num);
 //String chard = Character.toString(mChar);

 StringBuffer buf = new StringBuffer( str);
   buf.setCharAt( i, mChar );
 }
   return str;
 }

public String scramble(String str) {
return charAt(str);
 }
}

I am trying to get it to where the method

 public String scramble(String str) {
return charAt(str);
 }

returns the computed value from the

 public static String charAt(String str)

method. Don't know where i went wrong.

Also instead of using

StringBuffer buf = new StringBuffer( str);
   buf.setCharAt( i, mChar );

how would i be able to use the swap function?
When I try

 char temp = chars[i];
chars[i] = chars[mChar];
chars[mChar] = temp;

I am given an ArrayIndexOutOfBoundsException.
Summary of what i am trying to do is "For each character in the original string, use its position in the alphabet to look up its replacement in the map string. For example, the string “dog” would be translated to “jtp”."


问:
How to play .mp4 video as a background video in Android?
I have watched many tutorials but somethings wrong. I have simple mainactivity and there is a VideoView on the it's layout. I downloaded a video from youtube as a .mp4 file size is about 10 mb. I found a great sample about videoview on youtube as the following link.

https://www.youtube.com/watch?v=tPeDn18FrGY&t=75s

ublic class MainActivity extends AppCompatActivity {

```<code>private VideoView bgVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bgVideo=(VideoView) findViewById(R.id.bg_videoview);

        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

        bgVideo.setVideoURI(uri);
        bgVideo.start();

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
    }
}
</code>```

I use genymotion emulator. While i run the app i take "can't play this" error. And at the android monitor things like this.

```<code>06-07 03:16:28.675 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.675 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.692 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.692 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.709 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.709 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.742 2146-2146/com.sample E/MediaPlayer: Error (1,-32)
06-07 03:16:28.742 2146-2146/com.sample D/VideoView: Error: 1,-32
06-07 03:16:28.758 2146-2146/com.sample E/MediaPlayer: Error (1,-38)
06-07 03:16:28.758 2146-2146/com.sample D/VideoView: Error: 1,-38
06-07 03:16:29.526 2146-2146/com.sample I/Choreographer: Skipped 44 frames!  The application may be doing too much work on its main thread.
</code>```

How can i fix it ?

答:
Try this code :</p>

```<code> try {
            // Start the MediaController
            MediaController mediacontroller = new MediaController(
                    MainActivity.this);
            mediacontroller.setAnchorView(bgVideo);
            // Get the URL from String VideoURL
            Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

            bgVideo.setMediaController(mediacontroller);
            bgVideo.setVideoURI(uri);

        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
bgVideo.requestFocus();

    bgVideo.setOnPreparedListener(new OnPreparedListener() {

                public void onPrepared(MediaPlayer mp) {
                    mp.setLooping(true);
                    bgVideo.start();
                }
            });
</code>```

Body:
I have watched many tutorials but somethings wrong. I have simple mainactivity and there is a VideoView on the it's layout. I downloaded a video from youtube as a .mp4 file size is about 10 mb. I found a great sample about videoview on youtube as the following link.

https://www.youtube.com/watch?v=tPeDn18FrGY&t=75s

ublic class MainActivity extends AppCompatActivity {

private VideoView bgVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bgVideo=(VideoView) findViewById(R.id.bg_videoview);

        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

        bgVideo.setVideoURI(uri);
        bgVideo.start();

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
    }
}

I use genymotion emulator. While i run the app i take "can't play this" error. And at the android monitor things like this.

06-07 03:16:28.675 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.675 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.692 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.692 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.709 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.709 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.742 2146-2146/com.sample E/MediaPlayer: Error (1,-32)
06-07 03:16:28.742 2146-2146/com.sample D/VideoView: Error: 1,-32
06-07 03:16:28.758 2146-2146/com.sample E/MediaPlayer: Error (1,-38)
06-07 03:16:28.758 2146-2146/com.sample D/VideoView: Error: 1,-38
06-07 03:16:29.526 2146-2146/com.sample I/Choreographer: Skipped 44 frames!  The application may be doing too much work on its main thread.

How can i fix it ?

Body:
Try this code :

 try {
            // Start the MediaController
            MediaController mediacontroller = new MediaController(
                    MainActivity.this);
            mediacontroller.setAnchorView(bgVideo);
            // Get the URL from String VideoURL
            Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

            bgVideo.setMediaController(mediacontroller);
            bgVideo.setVideoURI(uri);

        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
bgVideo.requestFocus();

    bgVideo.setOnPreparedListener(new OnPreparedListener() {

                public void onPrepared(MediaPlayer mp) {
                    mp.setLooping(true);
                    bgVideo.start();
                }
            });


问:
imagepullbackoff while pulling image from azure container registry
First i have created the docker image and created kubernetes cluster in azure container service.
Then tag and push the image to my repository, but while pulling my image from azure container registry to kubernetes cluster the pod are created but in status it shows imagepullback off

The yaml file for basic api image

```<code>**apiVersion: v1
kind: Pod
metadata:
  name: myapis
spec:
  containers:
    - name: myapis
      image: ciqsample.azurecr.io/myapis
  imagePullSecrets:
    - name: samplekey**
</code>```

答:
This error means we use wrong key and password to pull image.

Can you run this command to check secret exist or not?kubectl get secret

```<code>root@k8s-master-BBF71727-0:~# kubectl get secret
NAME                  TYPE                                  DATA      AGE
azurecr               kubernetes.io/dockercfg               1         57m
default-token-clm2d   kubernetes.io/service-account-token   3         2h
</code>```

Then check the secret.

```<code>root@k8s-master-BBF71727-0:~# kubectl get secret azurecr --output=yaml
</code>```

We can use this command script to create secret:

```<code>kubectl create secret docker-register yoursecretname --docker-server=jason.azurecr.io/xxxx/test --docker-username={UserName} --docker-password={Password} --docker-email=team@domain.com
</code>```

By the way, for test please login Azure container registry with your registry credentials, then try to pull image from Azure container registry.

Login

docker login myregistry.azurecr.io -u xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -p myPassword

Pull the image from your registry

```<code>docker pull myregistry.azurecr.io/samples/nginx
</code>```

Body:
First i have created the docker image and created kubernetes cluster in azure container service.
Then tag and push the image to my repository, but while pulling my image from azure container registry to kubernetes cluster the pod are created but in status it shows imagepullback off

The yaml file for basic api image

**apiVersion: v1
kind: Pod
metadata:
  name: myapis
spec:
  containers:
    - name: myapis
      image: ciqsample.azurecr.io/myapis
  imagePullSecrets:
    - name: samplekey**

Body:
This error means we use wrong key and password to pull image.

Can you run this command to check secret exist or not?kubectl get secret

root@k8s-master-BBF71727-0:~# kubectl get secret
NAME                  TYPE                                  DATA      AGE
azurecr               kubernetes.io/dockercfg               1         57m
default-token-clm2d   kubernetes.io/service-account-token   3         2h

Then check the secret.

root@k8s-master-BBF71727-0:~# kubectl get secret azurecr --output=yaml

We can use this command script to create secret:

kubectl create secret docker-register yoursecretname --docker-server=jason.azurecr.io/xxxx/test --docker-username={UserName} --docker-password={Password} --docker-email=team@domain.com

By the way, for test please login Azure container registry with your registry credentials, then try to pull image from Azure container registry.

Login

docker login myregistry.azurecr.io -u xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -p myPassword

Pull the image from your registry

docker pull myregistry.azurecr.io/samples/nginx


问:
How to calculate centrality of graph nodes in neo4j and cypher
I'm trying to calculate the eigenvector/page rank centrality for a neo4j graph. I've found that we could do it with gremlin plugin. I have already written the code in cql. Is it possible to use both gremlin and cypher. If not then how to calculate centrality using cypher </p>

答: Might be tough with Cypher alone. You may want to take a look at APOC Procedures, which includes procedures for closeness and betweenness centrality.</p>


问:
Cannot finish Installing sbteclipse
I tried to install the sbt integration with Eclipse as the documentation said, but I'm almost sure I'm missing something.
I created ~/.sbt/0.13/plugins/plugins.sbt with the line the github provided:
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "5.1.0")
Then, when I launched > sbt from a terminal it apparently downloaded it automatically:

Updated file /home/leandro/.sbt/0.13/plugins/project/build.properties setting sbt.version to: 0.13.15
[info] Loading project definition from /home/leandro/.sbt/0.13/plugins/project
[info] Updating {file:/home/leandro/.sbt/0.13/plugins/project/}plugins-build...
[info] Resolving org.scala-sbt.ivy#ivy;2.3.0-sbt-48dd0744422128446aee9ac31aa356e[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.
[info] Set current project to plugins (in build file:/home/leandro/.sbt/0.13/plugins/)

However, the same readme says I should be able to run eclipse from the sbt shell to create Eclipse project files, but the shell doesn't recognizes the command.
I also don't know how use the Import Wizard to import Existing Projects into Workspace in Eclipse.

Thanks in advance.

答:
File > Import

General > Existing Project into Workspace > Next

Browse for the project, select the one you want to import and FInish import.

or this might help
How do i import an existing directory into eclipse?

or just maybe use IDEA

Title: Cannot finish Installing sbteclipse


问:
Decimal number to 32 bit binary
```<code>int main()
{
    unsigned n;
    cin>>n;
    for(int i=(1<<31);i>0;i/=2)
        (i&n)?(cout<<1):(cout<<0);
}
</code>```

I ran the following code with n=1 but it prints nothing on the console. Changing the type of variable i to unsigned did the trick and printed 00000000000000000000000000000001. Any idea why?

答:
Assuming two's complement, 1 << 31 results in a negative value, so your test for i > 0 fails immediately with the first test. You most likely would have had more luck with i != 0 then.

But we aware that 1 << 31 is a signed integer overflow, which is undefined behaviour anyway! So you should do 1U << 31 instead, too. If you assign this then positive value to a signed int, which is not capable to hold it, you have again undefined behaviour. So the correct for loop would look like this:

```<code>for(unsigned int i = 1U << 31; i > 0; i /= 2)
</code>```

Although i /= 2 for unsigned values is equivalent to a bitshift (and is likely to be compiled to), I would prefere the bitshift operation explicitly here (i >>= 1), as this is what you actually intend.

Title: Decimal number to 32 bit binary

Body:
int main()
{
    unsigned n;
    cin>>n;
    for(int i=(1<<31);i>0;i/=2)
        (i&n)?(cout<<1):(cout<<0);
}

I ran the following code with n=1 but it prints nothing on the console. Changing the type of variable i to unsigned did the trick and printed 00000000000000000000000000000001. Any idea why?

Body:
Assuming two's complement, 1 << 31 results in a negative value, so your test for i > 0 fails immediately with the first test. You most likely would have had more luck with i != 0 then.

But we aware that 1 << 31 is a signed integer overflow, which is undefined behaviour anyway! So you should do 1U << 31 instead, too. If you assign this then positive value to a signed int, which is not capable to hold it, you have again undefined behaviour. So the correct for loop would look like this:

for(unsigned int i = 1U << 31; i > 0; i /= 2)

Although i /= 2 for unsigned values is equivalent to a bitshift (and is likely to be compiled to), I would prefere the bitshift operation explicitly here (i >>= 1), as this is what you actually intend.


问:
Cassandra counter usage
I am finding some difficulties in the data modeling of an application which may involve the use of counters.

The app is basically a messaging app. Messages are bounded for free users, hence the initial plan of using a counter column to keep track of the total count.

I've discovered that batches (logged or not) cannot contain operations on both standard tables and counter ones. How do I ensure correctness if I cannot batch the operation I am trying to perform and the counter update together? Is the counter type really needed if there's basically no race condition on the column, being that associated to each individual user?

My second idea would be to use a standard int column to use only inside batches. Is this a viable option?

Thank you

答:
If you can absolutely guarantee that each user will produce only one update at time then you could rely on plain ints to perform the job.

The problem however is that you will need to perform a read-before-write anti-pattern. You could solve this as well, eg skipping the read part by caching your ints and performing in-memory updates followed by writes only. This is viable by coupling your system with a caching server (e.g. Redis).

And thinking about it, you should still need to read these counters at some point, because if the number of messages a free user can send is bound to some value then you need to perform a check when they login/try to send a new message/look at the dashboard/etc and block their action.

Another option (if you store the messages sent by each user somewhere and don't want to add complexity to your system) could be to directly count them with a SELECT COUNT... type query, even if this could be become pretty inefficient very soon in the Cassandra world.

Title: Cassandra counter usage


问:
Maven Error Resolving version for plugin
I am trying to run a kurento-java client hello world example as given in this link
http://doc-kurento.readthedocs.io/en/stable/tutorials/java/tutorial-helloworld.html

I am providing a kurento media server url while compiling the code as

mvn compile exec:java -Dkms.url=ws://kms_host:kms_port/kurento

I keep getting error as:

Error resolving version for plugin '.url=ws://kms_host:kms_port' from the repositories

答: This error will be thrown if you have a space before the dot in -Dkms.url. Please make sure to run the command exactly as in the documentation you are referring to.


问:
Specflow Container of the steps class has not been initialized
```<code>public class BaseSteps : Steps
{
    [BeforeFeature]
    public static void BeforeFeatureStep()
    {
        var otherStep = new OtherStep();
        otherStep.ExecuteStep();
    }
}

public class OtherStep : Steps
{
    public void ExecuteStep()
    {
        var key = 'key';
        var val = 'val';
        this.FeatureContext.Add(key, val);
    }
}
</code>```

This is a sample snippet. When I try to access this.FeatureContext.Add(), I get an exception stating Container of the steps class has not been initialized

Any help on this is appreciated.

答:
The FeatureContext is not initialized, because the Step class is not resolved by the SpecFlow DI Container. So the SetObjectContainer method is not called (https://github.com/techtalk/SpecFlow/blob/master/TechTalk.SpecFlow/Steps.cs#L10).

As a general rule, you should not instantiate the steps classes on your own, but get them via Context Injection (http://specflow.org/documentation/Context-Injection).

But that is not possible in your case because you are in a BeforeFeature hook.

A possible solution would be, that you use the latest pre-release of SpecFlow (https://www.nuget.org/packages/SpecFlow/2.2.0-preview20170523).
There you can get the FeatureContext via a parameter in the hook method.
It looks like this:

```<code>[BeforeFeature]
public static void BeforeFeatureHook(FeatureContext featureContext)
{
    //your code
}
</code>```

Your code could then look like this:

```<code>public class FeatureContextDriver
{
    public void FeatureContextChanging(FeatureContext featureContext)
    {
        var key = 'key';
        var val = 'val';
        featureContext.Add(key, val);
    }
}

[Binding]
public class BaseSteps : Steps
{
    [BeforeFeature]
    public static void BeforeFeatureStep(FeatureContext featureContext)
    {
        var featureContextDriver = new FeatureContextDriver();
        featureContextDriver.FeatureContextChanging(featureContext);
    }
}

[Binding]
public class OtherStep : Steps
{
    private FeatureContextDriver _featureContextDriver;
    public OtherStep(FeatureContextDriver featureContextDriver)
    {
        _featureContextDriver = featureContextDriver;
    }

    public void ExecuteStep()
    {
        _featureContextDriver.FeatureContextChanging(this.FeatureContext);
    }
}
</code>```

Code is not tested/tried out and applies the Driver Pattern.

Full Disclosure: I am one of the maintainers of SpecFlow and SpecFlow+.

Body:
public class BaseSteps : Steps
{
    [BeforeFeature]
    public static void BeforeFeatureStep()
    {
        var otherStep = new OtherStep();
        otherStep.ExecuteStep();
    }
}

public class OtherStep : Steps
{
    public void ExecuteStep()
    {
        var key = 'key';
        var val = 'val';
        this.FeatureContext.Add(key, val);
    }
}

This is a sample snippet. When I try to access this.FeatureContext.Add(), I get an exception stating Container of the steps class has not been initialized

Any help on this is appreciated.

Body:
The FeatureContext is not initialized, because the Step class is not resolved by the SpecFlow DI Container. So the SetObjectContainer method is not called (https://github.com/techtalk/SpecFlow/blob/master/TechTalk.SpecFlow/Steps.cs#L10).

As a general rule, you should not instantiate the steps classes on your own, but get them via Context Injection (http://specflow.org/documentation/Context-Injection).

But that is not possible in your case because you are in a BeforeFeature hook.

A possible solution would be, that you use the latest pre-release of SpecFlow (https://www.nuget.org/packages/SpecFlow/2.2.0-preview20170523).
There you can get the FeatureContext via a parameter in the hook method.
It looks like this:

[BeforeFeature]
public static void BeforeFeatureHook(FeatureContext featureContext)
{
    //your code
}

Your code could then look like this:

public class FeatureContextDriver
{
    public void FeatureContextChanging(FeatureContext featureContext)
    {
        var key = 'key';
        var val = 'val';
        featureContext.Add(key, val);
    }
}

[Binding]
public class BaseSteps : Steps
{
    [BeforeFeature]
    public static void BeforeFeatureStep(FeatureContext featureContext)
    {
        var featureContextDriver = new FeatureContextDriver();
        featureContextDriver.FeatureContextChanging(featureContext);
    }
}

[Binding]
public class OtherStep : Steps
{
    private FeatureContextDriver _featureContextDriver;
    public OtherStep(FeatureContextDriver featureContextDriver)
    {
        _featureContextDriver = featureContextDriver;
    }

    public void ExecuteStep()
    {
        _featureContextDriver.FeatureContextChanging(this.FeatureContext);
    }
}

Code is not tested/tried out and applies the Driver Pattern.

Full Disclosure: I am one of the maintainers of SpecFlow and SpecFlow+.


答:
Just change your Count call to a Sum call, specifying the property that you want to sum on, like this:

```<code>var query = (from t1 in _db.Table1 join t2 in _db.Table2 on t1.CId equals
             t2.ID where t1.DateAdded >= fromDate && t1.DateAdded <= toDate select t2)
            .GroupBy(c => c.Brand)
            .ToDictionary(t => t.Key, t => t.Sum(x => x.Qty));
</code>```

Title: GroupBy and sum to dictionary

Body:
I have two tables that are joined together like this..

var query = (from t1 in _db.Table1 join t2 in _db.Table2 on t1.CId equals
              t2.ID where t1.DateAdded >= fromDate && t1.DateAdded <= toDate select t2)
             .GroupBy(c => c.Brand)
             .ToDictionary(t => t.Key, t => t.Count());

This almost give me what I want, it return the number of different cFormat rows,
but I would like to it to be summarized on t2.Qty instead

If the data look like this...

Brand           Qty
Volvo           2
Volvo           1
Tesla           4
Tesla           9

My current query give me a result like this..

Volvo           2
Tesla           2

But I would like it to be

Volvo           3
Tesla           13

How can I change it to work like that?

Body:
Just change your Count call to a Sum call, specifying the property that you want to sum on, like this:

var query = (from t1 in _db.Table1 join t2 in _db.Table2 on t1.CId equals
             t2.ID where t1.DateAdded >= fromDate && t1.DateAdded <= toDate select t2)
            .GroupBy(c => c.Brand)
            .ToDictionary(t => t.Key, t => t.Sum(x => x.Qty));


问:
Add id css via rails enum
I would like to know I can set id via rails enum. For example,

```<code><% @products.each_with_index do |product, index| %>
            <tr id="<% #{index} %>" >
                      .
                      .
<% end %>
</code>```

答:
you can directly assign index to id

```<code><% @products.each_with_index do |product, index| %>
  <tr id=<%= index.to_s %> >
                  .
                  .
<% end %>
</code>```

Title: Add id css via rails enum

Body:
I would like to know I can set id via rails enum. For example,

<% @products.each_with_index do |product, index| %>
            <tr id="<% #{index} %>" >
                      .
                      .
<% end %>

Body:
you can directly assign index to id

<% @products.each_with_index do |product, index| %>
  <tr id=<%= index.to_s %> >
                  .
                  .
<% end %>


问:
slick db.run is not called
I want to insert a record in database but the db.run is not called

my code looks like this

```<code>val insertQueryStep = processStepTemplates returning processStepTemplates.map(_.id) into ((processStep, id) => processStep.copy(id = Some(id)))

  /**
    * Generates a new ProcessStepTemplate
    *
    * @param step
    * @return
    */
  def addProcessStepTemplateToProcessTemplate(step: ProcessStepTemplatesModel, processId: Int): Future[Some[ProcessStepTemplatesModel]] = {
    println("In DTO: " + step + ", processtemplate: " + processId)

    //val p = processStepTemplates returning processStepTemplates.map(_.id) += step
    val p = insertQueryStep += step

    db.run(p).map(id => {
      println("Die Query lautet: " + p)
      println("Die erzeugte ID lautet: " + id)

      //Update the foreign key
      val q = for { p <- processStepTemplates if p.id == id } yield p.processtemplate
      val updateAction = q.update(Some(processId))

      db.run(updateAction).map(id => {
        println("Der neue Prozesschritt lautet: " + step)
        Some(step)
      })
      Some(step)
    })
  }
</code>```

What could be a problem in this case?

答:
You should compose your futures as monads (with flatMap). Because the inner future will not complete.
Try to change your code in the following way (see comments #1, #2):

```<code>def addProcessStepTemplateToProcessTemplate(step: ProcessStepTemplatesModel, processId: Int): Future[Some[ProcessStepTemplatesModel]] = {
    println("In DTO: " + step + ", processtemplate: " + processId)

    //val p = processStepTemplates returning processStepTemplates.map(_.id) += step
    val p = insertQueryStep += step

    db.run(p).flatMap(id => {                   // #1 change map to flatMap
      println("Die Query lautet: " + p)
      println("Die erzeugte ID lautet: " + id)

      //Update the foreign key
      val q = for { p <- processStepTemplates if p.id == id } yield p.processtemplate
      val updateAction = q.update(Some(processId))

      val innerFuture = db.run(updateAction).map(id => {
        println("Der neue Prozesschritt lautet: " + step)
        Some(step)
      })
      innerFuture                              // # 2 return inner future
    })
  }
</code>```

Also use a logging for detecting another issues (connected with db-schema, queries, etc).

Title: slick db.run is not called

Body:
I want to insert a record in database but the db.run is not called

my code looks like this

val insertQueryStep = processStepTemplates returning processStepTemplates.map(_.id) into ((processStep, id) => processStep.copy(id = Some(id)))

  /**
    * Generates a new ProcessStepTemplate
    *
    * @param step
    * @return
    */
  def addProcessStepTemplateToProcessTemplate(step: ProcessStepTemplatesModel, processId: Int): Future[Some[ProcessStepTemplatesModel]] = {
    println("In DTO: " + step + ", processtemplate: " + processId)

    //val p = processStepTemplates returning processStepTemplates.map(_.id) += step
    val p = insertQueryStep += step

    db.run(p).map(id => {
      println("Die Query lautet: " + p)
      println("Die erzeugte ID lautet: " + id)

      //Update the foreign key
      val q = for { p <- processStepTemplates if p.id == id } yield p.processtemplate
      val updateAction = q.update(Some(processId))

      db.run(updateAction).map(id => {
        println("Der neue Prozesschritt lautet: " + step)
        Some(step)
      })
      Some(step)
    })
  }

What could be a problem in this case?

Body:
You should compose your futures as monads (with flatMap). Because the inner future will not complete.
Try to change your code in the following way (see comments #1, #2):

def addProcessStepTemplateToProcessTemplate(step: ProcessStepTemplatesModel, processId: Int): Future[Some[ProcessStepTemplatesModel]] = {
    println("In DTO: " + step + ", processtemplate: " + processId)

    //val p = processStepTemplates returning processStepTemplates.map(_.id) += step
    val p = insertQueryStep += step

    db.run(p).flatMap(id => {                   // #1 change map to flatMap
      println("Die Query lautet: " + p)
      println("Die erzeugte ID lautet: " + id)

      //Update the foreign key
      val q = for { p <- processStepTemplates if p.id == id } yield p.processtemplate
      val updateAction = q.update(Some(processId))

      val innerFuture = db.run(updateAction).map(id => {
        println("Der neue Prozesschritt lautet: " + step)
        Some(step)
      })
      innerFuture                              // # 2 return inner future
    })
  }

Also use a logging for detecting another issues (connected with db-schema, queries, etc).


答:
You are mixing string interpolation with Rails tags. You should do

```<code><tr id="#{index}">
</code>```

Or

You can also do

```<code><tr id="<%=index%>">
</code>```

Title: Add id css via rails enum

Body:
You are mixing string interpolation with Rails tags. You should do

<tr id="#{index}">

Or

You can also do

<tr id="<%=index%>">


问:
Issue with Fluent nhibernate and the type Decimal
I am encoutering an issue with the decimal type and fluent nhibernate.

Here is my problem:

I have a class with a property:

```<code>public virtual decimal? Amount { get; set; }
</code>```

In my mapping I have :

```<code>Map(x => x.Amount, "SOMETHING").Length(8).Precision(19).Scale(4).CustomSqlType("money");
</code>```

The Nhibernate mapping I get is:

```<code><property name="Amount" type="System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
  <column name="SOMETHING" length="8" sql-type="money" precision="19" scale="4" />
</property>
</code>```

And what I get when I try to update this value with a sql server 2000 is:

```<code>Disallowed implicit conversion from data type varchar to data type money, table 'ANYTABLE, column '...'. Use the CONVERT function to run this query.
</code>```

I am using MsSqlConfiguration.MsSql2000 to configure fluent hibernate and version 1.1.0.0 of fluent nhibernate.

Thanks for your help!

答:
It works fine here, at least with NH 3.

How are you updating the value? Can you post the generated SQL?

Body:
I am encoutering an issue with the decimal type and fluent nhibernate.

Here is my problem:

I have a class with a property:

public virtual decimal? Amount { get; set; }

In my mapping I have :

Map(x => x.Amount, "SOMETHING").Length(8).Precision(19).Scale(4).CustomSqlType("money");

The Nhibernate mapping I get is:

<property name="Amount" type="System.Nullable`1[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
  <column name="SOMETHING" length="8" sql-type="money" precision="19" scale="4" />
</property>

And what I get when I try to update this value with a sql server 2000 is:

Disallowed implicit conversion from data type varchar to data type money, table 'ANYTABLE, column '...'. Use the CONVERT function to run this query.

I am using MsSqlConfiguration.MsSql2000 to configure fluent hibernate and version 1.1.0.0 of fluent nhibernate.

Thanks for your help!


问:
Unable to bring uploaded images into uploads file using php
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

```<code><form action="" class="navbar-form navbar-right" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Find Art Here">
                    </div>
                    <button type="submit" class="btn btn-primary">Search</button>
                </form>
</code>```

and here's the php

```<code><?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}
</code>```

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!

答:
Your <form> misses an attribute to send files:

```<code>enctype="multipart/form-data"
</code>```

And to be sure the upload is done, put the move_uploaded_file() in a condition because the function returns a boolean :

```<code>if (move_uploaded_file($fileTmpName, $fileDestination)) {
    header("Location: index.php?uploadsucess");
} else {
    header("Location: index.php?uploadfail");
}
</code>```

Also, a better way to get your file extension is using pathinfo() :

```<code>pathinfo($fileName, PATHINFO_EXTENSION);
</code>```

you don't have any <input type="file"> in your form

you maybe mispelled your upload directory : uplaods

php.net - move_uploaded_file()

php.net - pathinfo()

Body:
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

<form action="" class="navbar-form navbar-right" role="search">

                        <input type="text" class="form-control" placeholder="Find Art Here">

                    <button type="submit" class="btn btn-primary">Search</button>
                </form>

and here's the php

<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!

Body:
Your <form> misses an attribute to send files:

enctype="multipart/form-data"

And to be sure the upload is done, put the move_uploaded_file() in a condition because the function returns a boolean :

if (move_uploaded_file($fileTmpName, $fileDestination)) {
    header("Location: index.php?uploadsucess");
} else {
    header("Location: index.php?uploadfail");
}

Also, a better way to get your file extension is using pathinfo() :

pathinfo($fileName, PATHINFO_EXTENSION);

you don't have any <input type="file"> in your form

you maybe mispelled your upload directory : uplaods

php.net - move_uploaded_file()

php.net - pathinfo()


问:
Compare 2 arrays for difference with some values repeating
I have 2 arrays to compare and I am using array_diff to compute the difference of columns as follows:

```<code>//array1 is as static array I have created to validate the sheet columns
$array1 = array('Category','Subcategory','Unknown','Age','0-9','Unknown','Region','Zone');

// array2 is coming dynamically from excel sheet columns so user can change the names
$array2 = array('Category','Subcategory','Unknowns','Age','0-9','Unknown','Region');

$diff = array_diff($array1,$array2);
$columnNames = implode(',',$diff);
if(!$diff){
   return true;
}
else{
  echo 'Some columns are missing:'. $columnNames ;
}
</code>```

output: Zone

Expected output: Zone, Unknowns

The above code works fine if Unknown columns are unchanged. I know array_diff will only check the first array and compare the values present in next array. But, I want to compare these arrays and display user a message that some columns are missing and their names. So, here if one of the column is changed to Unknowns in excel sheet i.e array2 then it should show the error message Some columns are missing: Zone, Unknowns

答:
You can substrct the intersect of the two arrays from the union of the two arrays. Live Demo.

```<code>$array = array_diff(array_merge($array1, $array2), array_intersect($array1, $array2));
</code>```

Body:
I have 2 arrays to compare and I am using array_diff to compute the difference of columns as follows:

//array1 is as static array I have created to validate the sheet columns
$array1 = array('Category','Subcategory','Unknown','Age','0-9','Unknown','Region','Zone');

// array2 is coming dynamically from excel sheet columns so user can change the names
$array2 = array('Category','Subcategory','Unknowns','Age','0-9','Unknown','Region');

$diff = array_diff($array1,$array2);
$columnNames = implode(',',$diff);
if(!$diff){
   return true;
}
else{
  echo 'Some columns are missing:'. $columnNames ;
}

output: Zone

Expected output: Zone, Unknowns

The above code works fine if Unknown columns are unchanged. I know array_diff will only check the first array and compare the values present in next array. But, I want to compare these arrays and display user a message that some columns are missing and their names. So, here if one of the column is changed to Unknowns in excel sheet i.e array2 then it should show the error message Some columns are missing: Zone, Unknowns

Body:
You can substrct the intersect of the two arrays from the union of the two arrays. Live Demo.

$array = array_diff(array_merge($array1, $array2), array_intersect($array1, $array2));


问:
how to traverse object value with attributes in php
I am having my data in xml. And I want to traverse it.
When I print
    var_dump($video_xml->playlist->video->labels->label)
the output is

```<code>object(SimpleXMLElement)#41 (4) {
  ["@attributes"]=>
  array(11) {
    ["id"]=>
    string(1) "0"
    ["start"]=>
    string(1) "0"
    ["end"]=>
    string(17) "8.639527777777777"
    ["pos"]=>
    string(12) "124,66,95,45"
    ["marker"]=>
    string(5) "false"
    ["href"]=>
    string(0) ""
    ["bold"]=>
    string(5) "false"
    ["italic"]=>
    string(5) "false"
    ["color"]=>
    string(17) "rgb(62, 201, 106)"
    ["face"]=>
    string(7) "Verdana"
    ["size"]=>
    string(2) "24"
  }
  [0]=>
  string(8) "Label1fg"
  [1]=>
  string(6) "Label0"
  [2]=>
  string(6) "Label0"
}
</code>```

however when I print each object in a foreach loop it gives

```<code>object(SimpleXMLElement)#56 (1) {
  ["@attributes"]=>
  array(11) {
    ["id"]=>
    string(1) "0"
    ["start"]=>
    string(1) "0"
    ["end"]=>
    string(17) "8.639527777777777"
    ["pos"]=>
    string(12) "124,66,95,45"
    ["marker"]=>
    string(5) "false"
    ["href"]=>
    string(0) ""
    ["bold"]=>
    string(5) "false"
    ["italic"]=>
    string(5) "false"
    ["color"]=>
    string(17) "rgb(62, 201, 106)"
    ["face"]=>
    string(7) "Verdana"
    ["size"]=>
    string(2) "24"
  }
}
</code>```

I want to print object value like Label0.
How can I get it.
I am using following code to print label

```<code>foreach($video_xml->playlist->video->labels->label as $label){
        var_dump($label);
    }
</code>```

and I am expecting output as:
string(8) "Label1fg"
string(6) "Label0"
string(6) "Label0"

答:
A SimpleXMLElement object behaves like an object, but is actually a system RESOURCE, (specifically a libxml resource). All its properties are also SimpleXMLElement objects. You need to convert each leaf node to the expected type to get primitive values (strings, f.e.).

```<code>foreach ($video_xml->playlist->video->labels->label as $label) {
    var_dump((string)$label);
}
</code>```

should print what you want.

If the nodes of your XML document do not have attributes and you do only simple operations with it (get data from some nodes), a simpler way to work with it is to use json_encode()/json_decode() to convert it to an multi-level array:

```<code>// TRUE as the second argument to json_decode() to get back arrays, not objects
$video_data = json_decode(json_encode($video_xml), TRUE));

foreach ($video_data['playlist']['video']['labels']['label'] as $label) {
    var_dump($label);
}
</code>```

If you don't pass TRUE as the second argument to json_decode() it returns an object (stdClass) and you can use the existing code to navigate through it.

If you have to operate on the XML document structure, in my opinion it's easier to work with DOMElement and the other DOM classes.

Body:
I am having my data in xml. And I want to traverse it.
When I print
    var_dump($video_xml->playlist->video->labels->label)
the output is

object(SimpleXMLElement)#41 (4) {
  ["@attributes"]=>
  array(11) {
    ["id"]=>
    string(1) "0"
    ["start"]=>
    string(1) "0"
    ["end"]=>
    string(17) "8.639527777777777"
    ["pos"]=>
    string(12) "124,66,95,45"
    ["marker"]=>
    string(5) "false"
    ["href"]=>
    string(0) ""
    ["bold"]=>
    string(5) "false"
    ["italic"]=>
    string(5) "false"
    ["color"]=>
    string(17) "rgb(62, 201, 106)"
    ["face"]=>
    string(7) "Verdana"
    ["size"]=>
    string(2) "24"
  }
  [0]=>
  string(8) "Label1fg"
  [1]=>
  string(6) "Label0"
  [2]=>
  string(6) "Label0"
}

however when I print each object in a foreach loop it gives

object(SimpleXMLElement)#56 (1) {
  ["@attributes"]=>
  array(11) {
    ["id"]=>
    string(1) "0"
    ["start"]=>
    string(1) "0"
    ["end"]=>
    string(17) "8.639527777777777"
    ["pos"]=>
    string(12) "124,66,95,45"
    ["marker"]=>
    string(5) "false"
    ["href"]=>
    string(0) ""
    ["bold"]=>
    string(5) "false"
    ["italic"]=>
    string(5) "false"
    ["color"]=>
    string(17) "rgb(62, 201, 106)"
    ["face"]=>
    string(7) "Verdana"
    ["size"]=>
    string(2) "24"
  }
}

I want to print object value like Label0.
How can I get it.
I am using following code to print label

foreach($video_xml->playlist->video->labels->label as $label){
        var_dump($label);
    }

and I am expecting output as:
string(8) "Label1fg"
string(6) "Label0"
string(6) "Label0"

Body:
A SimpleXMLElement object behaves like an object, but is actually a system RESOURCE, (specifically a libxml resource). All its properties are also SimpleXMLElement objects. You need to convert each leaf node to the expected type to get primitive values (strings, f.e.).

foreach ($video_xml->playlist->video->labels->label as $label) {
    var_dump((string)$label);
}

should print what you want.

If the nodes of your XML document do not have attributes and you do only simple operations with it (get data from some nodes), a simpler way to work with it is to use json_encode()/json_decode() to convert it to an multi-level array:

// TRUE as the second argument to json_decode() to get back arrays, not objects
$video_data = json_decode(json_encode($video_xml), TRUE));

foreach ($video_data['playlist']['video']['labels']['label'] as $label) {
    var_dump($label);
}

If you don't pass TRUE as the second argument to json_decode() it returns an object (stdClass) and you can use the existing code to navigate through it.

If you have to operate on the XML document structure, in my opinion it's easier to work with DOMElement and the other DOM classes.


问:
GIT 1.9 - remote: error: 'receive.denyCurrentBranch'
I have an error using Git 1.9.

When I try to "git push" I receive the following error:

```<code>remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
</code>```

So, my first step was to read a lot here in this forum and tried to find some results from google. Sadly all I found was not working in my case.

I am working on Linux x86 and installed Git 1.9.

I can "git clone" one repository from my server and work in it.

For example I "touch testfile" in it to create a new file. Now I will "git commit" this file.

After this step I "git push" it and then I get the error code.

I found in other article's that the problem is solved in git 2.3
And that it should be helpful to change the value from "receive.denyCurrentBranch" in the config file from the repository.
Helpful values should be: refuse, updateInstead and ignore

I tried all of them and the error will be always the same.

On Server the config value ist:

```<code>[receive]
        denyCurrentBranch = refuse
</code>```

and the "git branch"

```<code>*master
</code>```

On client the "git status" is:

```<code>On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)
</code>```

So, the error will appear any time, I do not really know how to fix it yet.

How can I avoid that error message?

答:
As the git message hint you, 'receive.denyCurrentBranch' is not recommended.

We usually version control by git with remote repo and local repo. And the remote the repo is the place where git really version controlled. Usually the remote repo is bare.

So the recommend method is convert the remote repo as bare in your server and treat it as remote repo by
git clone <URL of repo> --bare, now work for it as remote repo.

Now you can clone the above bare repo and commit/push to it.

Body:
I have an error using Git 1.9.

When I try to "git push" I receive the following error:

remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.

So, my first step was to read a lot here in this forum and tried to find some results from google. Sadly all I found was not working in my case.

I am working on Linux x86 and installed Git 1.9.

I can "git clone" one repository from my server and work in it.

For example I "touch testfile" in it to create a new file. Now I will "git commit" this file.

After this step I "git push" it and then I get the error code.

I found in other article's that the problem is solved in git 2.3
And that it should be helpful to change the value from "receive.denyCurrentBranch" in the config file from the repository.
Helpful values should be: refuse, updateInstead and ignore

I tried all of them and the error will be always the same.

On Server the config value ist:

[receive]
        denyCurrentBranch = refuse

and the "git branch"

*master

On client the "git status" is:

On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

So, the error will appear any time, I do not really know how to fix it yet.

How can I avoid that error message?


问:
Find previous call - SQL
In my table of customer calls I have the following data:

```<code> ID | PHONE_NO | ASSET_ID | CALLTIME           | PREV_ID
====+==========+==========+====================+========
1256|0123456789|  69456321| 2017-04-10 14:32:11|
1257|0214566985|  48563256| 2017-04-11 09:08:47|
1258|0123456789|  69456321| 2017-04-12 10:58:12|    1256 <- prev call ID (phone_no+asset_id)
1259|0315654258|  98643215| 2017-04-15 22:14:36|
1260|0412365214|  69456321| 2017-04-18 18:32:54|    1258 <- prev call ID (asset_id)
</code>```

I need the query which will find if there was a call from the same customer in previous 10 days (this query should update PREV_ID column). The previous call is call from the same customer (means from the same PHONE_NO or with the same ASSET_ID) occured within 10 days prior to the current call. PREV_ID column has to contain the ID of previous call (the closest one because within 10 days there could be more of them from the same customer).

答:
Here's a MERGE that should do the trick:

```<code>MERGE INTO customer_calls tgt
  USING (SELECT ID,
                phone_no,
                asset_id,
                calltime,
                prev_id
         FROM   (SELECT ID,
                        phone_no,
                        asset_id,
                        calltime,
                        CASE WHEN calltime - LAG(calltime) OVER (PARTITION BY phone_no ORDER BY calltime) <= 10 THEN
                                  LAG(ID) OVER (PARTITION BY phone_no ORDER BY calltime)
                             WHEN calltime - LAG(calltime) OVER (PARTITION BY asset_id ORDER BY calltime) <= 10 THEN
                                  LAG(ID) OVER (PARTITION BY asset_id ORDER BY calltime)                            END prev_id
                 FROM   customer_calls)
         WHERE  prev_id IS NOT NULL) src
  ON (tgt.id = src.id) -- assuming id is the primary key
WHEN MATCHED THEN
  UPDATE SET tgt.prev_id = src.prev_id;
</code>```

I would test this and David's solution to see which one is more performant for your data etc.

Title: Find previous call - SQL

Body:
In my table of customer calls I have the following data:

 ID | PHONE_NO | ASSET_ID | CALLTIME           | PREV_ID
====+==========+==========+====================+========
1256|0123456789|  69456321| 2017-04-10 14:32:11|
1257|0214566985|  48563256| 2017-04-11 09:08:47|
1258|0123456789|  69456321| 2017-04-12 10:58:12|    1256 <- prev call ID (phone_no+asset_id)
1259|0315654258|  98643215| 2017-04-15 22:14:36|
1260|0412365214|  69456321| 2017-04-18 18:32:54|    1258 <- prev call ID (asset_id)

I need the query which will find if there was a call from the same customer in previous 10 days (this query should update PREV_ID column). The previous call is call from the same customer (means from the same PHONE_NO or with the same ASSET_ID) occured within 10 days prior to the current call. PREV_ID column has to contain the ID of previous call (the closest one because within 10 days there could be more of them from the same customer).

Body:
Here's a MERGE that should do the trick:

MERGE INTO customer_calls tgt
  USING (SELECT ID,
                phone_no,
                asset_id,
                calltime,
                prev_id
         FROM   (SELECT ID,
                        phone_no,
                        asset_id,
                        calltime,
                        CASE WHEN calltime - LAG(calltime) OVER (PARTITION BY phone_no ORDER BY calltime) <= 10 THEN
                                  LAG(ID) OVER (PARTITION BY phone_no ORDER BY calltime)
                             WHEN calltime - LAG(calltime) OVER (PARTITION BY asset_id ORDER BY calltime) <= 10 THEN
                                  LAG(ID) OVER (PARTITION BY asset_id ORDER BY calltime)                            END prev_id
                 FROM   customer_calls)
         WHERE  prev_id IS NOT NULL) src
  ON (tgt.id = src.id) -- assuming id is the primary key
WHEN MATCHED THEN
  UPDATE SET tgt.prev_id = src.prev_id;

I would test this and David's solution to see which one is more performant for your data etc.