问:
Logic using cURL, PHP and Twitter without using API
I have this code, which saves the cookies in a .txt file, and authenticates the user with Twitter

```<code><?php

require_once 'class/Cookies.php';

$cookie = [];

$username = 'formUser';
$password = 'formPass';

$index_url = 'https://twitter.com';

$token = curl_init();
curl_setopt_array($token, [
      CURLOPT_URL             => $index_url,
      CURLOPT_CUSTOMREQUEST   => 'GET',
      CURLOPT_RETURNTRANSFER  => true,
      CURLOPT_SSL_VERIFYPEER  => false,
      CURLOPT_SSL_VERIFYHOST  => 2,
      CURLOPT_USERAGENT       => $_SERVER['HTTP_USER_AGENT'],
      //CURLOPT_COOKIEFILE      => __DIR__ . DIRECTORY_SEPARATOR . 'cookies' . DIRECTORY_SEPARATOR . $username . '.txt',
      CURLOPT_COOKIEJAR       => __DIR__ . DIRECTORY_SEPARATOR . 'cookies' . DIRECTORY_SEPARATOR . $username . '.txt',
      CURLOPT_COOKIESESSION   => true,
      CURLOPT_REFERER         => $index_url,
      CURLOPT_HEADER          => true,
      CURLOPT_HTTPHEADER      => ['Cookie:' . http_build_query($cookie, '', ';') . ';'],
      CURLOPT_HEADERFUNCTION => function ($curl, $header) use (&$cookie) {
        if (stripos($header, 'Set-Cookie:') === 0) {
          if (preg_match('/Set-Cookie:\s?(.*?)=(.*?);/i', $header, $matches)) {
            $cookie[$matches[1]] = urldecode($matches[2]);
          }
        }
        return strlen($header);
      }
    ]
);
$access = curl_exec($token);

preg_match('/value="(.*?)" name="authenticity_token"/', $access, $matches);

$authenticity_token = $matches[1];

//var_dump($authenticity_token);

$session_post = "session[username_or_email]=$username&session[password]=$password&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token=$authenticity_token";

$session_url = 'https://twitter.com/sessions';

curl_setopt_array($token, [
      CURLOPT_URL             => $session_url,
      CURLOPT_CUSTOMREQUEST   => 'POST',
      CURLOPT_POSTFIELDS      => $session_post,
      CURLOPT_RETURNTRANSFER  => true,
      CURLOPT_HTTPHEADER      => [
        "Content-type: application/x-www-form-urlencoded",
        'Cookie: '. http_build_query($cookie, '', ';').';'
      ],
      CURLOPT_USERAGENT       => $_SERVER['HTTP_USER_AGENT'],
      CURLOPT_HEADER          => true,
      CURLOPT_FOLLOWLOCATION  => true,
      CURLOPT_MAXREDIRS       => 2,
      CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
      CURLOPT_POSTREDIR       => 2,
      CURLOPT_AUTOREFERER     => 1
  ]

);
$auth = curl_exec($token);

var_dump($cookie);

if (isset($cookie['auth_token']))
{
  $twid = filter_var($cookie['twid'], FILTER_SANITIZE_NUMBER_INT);

  Cookies::set('login_token', $cookie['ct0']);
  Cookies::set('kdt', $cookie['kdt']);
  Cookies::set('user_id', $twid);
  Cookies::set('auth_token', $cookie['auth_token']);
  Cookies::set('username', $username);

  echo json_encode(array(
    "status"      => "success",
    "message"     => "Authentication successful, we are redirecting you.",
  ));
}
else
{
  echo json_encode(
    array(
      "status" => "error",
      'message'=> "Unable to authenticate with Twitter.",
    ));
}
</code>```

And this code that captures the information of the logged in user:

```<code><?php

$username = 'sessionUser';

$url = 'https://twitter.com/' . $username;

$user = curl_init();
curl_setopt_array($user, [
      CURLOPT_URL             => $url,
      CURLOPT_CUSTOMREQUEST   => 'GET',
      CURLOPT_CAINFO          => 'cacert-2017-06-07.pem',
      CURLOPT_RETURNTRANSFER  => true,
      CURLOPT_SSL_VERIFYPEER  => false,
      CURLOPT_SSL_VERIFYHOST  => 2,
      CURLOPT_HTTPHEADER      => [
        "Content-type:text/html;charset=utf-8",
      ],
      CURLOPT_USERAGENT       => $_SERVER['HTTP_USER_AGENT'],
      CURLOPT_HEADER          => true,
      CURLOPT_FOLLOWLOCATION  => true,
      CURLOPT_MAXREDIRS       => 2,
      CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
      CURLOPT_POSTREDIR       => 2,
      CURLOPT_AUTOREFERER     => 1,
      CURLOPT_ENCODING        => "gzip"
  ]
);

$user_info = curl_exec($user);

$header_size = curl_getinfo($user, CURLINFO_HEADER_SIZE);
$header = substr($user_info, 0, $header_size);
$body = substr($user_info, $header_size);

$dom = new DOMDocument("5.0", "utf-8");
@$dom->loadHTML($body);

$data = json_decode($dom->getElementById("init-data")->getAttribute("value"));

echo "Nome: ", $data->profile_user->id, PHP_EOL;
echo "Nome: ", $data->profile_user->name, PHP_EOL;
echo "Usuário: ", $data->profile_user->screen_name, PHP_EOL;
echo "Foto de perfil: ", $data->profile_user->profile_image_url, PHP_EOL;
</code>```

I need help so that the cookies of users saved in the .txt or in the database, make followers exchange.

How can I do this?

EDIT

Who downvote, leave comments.

EDIT 2

File follow.php

```<code><?php

require_once '../modules/config.php';
require_once '../modules/class/Cookies.php';

$username = Cookies::get('username');

$friend_url = 'https://api.twitter.com/1.1/friendships/create.json';

$friend = curl_init();

curl_setopt_array($friend, [
        CURLOPT_URL             => $friend_url,
        CURLOPT_SSL_VERIFYPEER  => 1,
        CURLOPT_SSL_VERIFYHOST  => 2,
        CURLOPT_CAINFO          => ROOT . 'modules' . SEPARATOR . 'cacert' . SEPARATOR . 'cacert-2017-06-07.pem',
        CURLOPT_CUSTOMREQUEST   => 'POST',
        CURLOPT_POSTFIELDS      => 'screen_name=' . $username,
        CURLOPT_USERAGENT       => $_SERVER['HTTP_USER_AGENT'],
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_HTTPHEADER      => [
            "Content-type: application/json; charset=utf-8",
      ],
        CURLOPT_HEADER          => true,
    ]

);

$response  = curl_exec($friend);

var_dump($response);
</code>```

Response:

```<code>C:\wamp64\www\brfollow\api\follow.php:32:string 'HTTP/1.1 400 Bad Request
content-length: 62
content-type: application/json; charset=utf-8
date: Fri, 07 Jul 2017 08:09:54 GMT
server: tsa_d
set-cookie: guest_id=v1%3A149941499419523606; Domain=.twitter.com; Path=/; Expires=Sun, 07-Jul-2019 08:09:54 UTC
strict-transport-security: max-age=631138519
x-connection-hash: 9e951d1215095efa246c5b852acd2e8a
x-response-time: 131
x-tsa-request-body-time: 0

{"errors":[{"code":215,"message":"Bad Authentication data."}]}' (length=472)
</code>```

答:
You have to use

```<code>CURLOPT_COOKIEJAR       => __DIR__ . DIRECTORY_SEPARATOR . 'cookies' . DIRECTORY_SEPARATOR . $username . '.txt',
</code>```

in your second request too.

Body:
I have this code, which saves the cookies in a .txt file, and authenticates the user with Twitter

<?php

require_once 'class/Cookies.php';

$cookie = [];

$username = 'formUser';
$password = 'formPass';

$index_url = 'https://twitter.com';

$token = curl_init();
curl_setopt_array($token, [
      CURLOPT_URL             => $index_url,
      CURLOPT_CUSTOMREQUEST   => 'GET',
      CURLOPT_RETURNTRANSFER  => true,
      CURLOPT_SSL_VERIFYPEER  => false,
      CURLOPT_SSL_VERIFYHOST  => 2,
      CURLOPT_USERAGENT       => $_SERVER['HTTP_USER_AGENT'],
      //CURLOPT_COOKIEFILE      => __DIR__ . DIRECTORY_SEPARATOR . 'cookies' . DIRECTORY_SEPARATOR . $username . '.txt',
      CURLOPT_COOKIEJAR       => __DIR__ . DIRECTORY_SEPARATOR . 'cookies' . DIRECTORY_SEPARATOR . $username . '.txt',
      CURLOPT_COOKIESESSION   => true,
      CURLOPT_REFERER         => $index_url,
      CURLOPT_HEADER          => true,
      CURLOPT_HTTPHEADER      => ['Cookie:' . http_build_query($cookie, '', ';') . ';'],
      CURLOPT_HEADERFUNCTION => function ($curl, $header) use (&$cookie) {
        if (stripos($header, 'Set-Cookie:') === 0) {
          if (preg_match('/Set-Cookie:\s?(.*?)=(.*?);/i', $header, $matches)) {
            $cookie[$matches[1]] = urldecode($matches[2]);
          }
        }
        return strlen($header);
      }
    ]
);
$access = curl_exec($token);

preg_match('/value="(.*?)" name="authenticity_token"/', $access, $matches);

$authenticity_token = $matches[1];

//var_dump($authenticity_token);

$session_post = "session[username_or_email]=$username&session[password]=$password&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token=$authenticity_token";

$session_url = 'https://twitter.com/sessions';

curl_setopt_array($token, [
      CURLOPT_URL             => $session_url,
      CURLOPT_CUSTOMREQUEST   => 'POST',
      CURLOPT_POSTFIELDS      => $session_post,
      CURLOPT_RETURNTRANSFER  => true,
      CURLOPT_HTTPHEADER      => [
        "Content-type: application/x-www-form-urlencoded",
        'Cookie: '. http_build_query($cookie, '', ';').';'
      ],
      CURLOPT_USERAGENT       => $_SERVER['HTTP_USER_AGENT'],
      CURLOPT_HEADER          => true,
      CURLOPT_FOLLOWLOCATION  => true,
      CURLOPT_MAXREDIRS       => 2,
      CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
      CURLOPT_POSTREDIR       => 2,
      CURLOPT_AUTOREFERER     => 1
  ]

);
$auth = curl_exec($token);

var_dump($cookie);

if (isset($cookie['auth_token']))
{
  $twid = filter_var($cookie['twid'], FILTER_SANITIZE_NUMBER_INT);

  Cookies::set('login_token', $cookie['ct0']);
  Cookies::set('kdt', $cookie['kdt']);
  Cookies::set('user_id', $twid);
  Cookies::set('auth_token', $cookie['auth_token']);
  Cookies::set('username', $username);

  echo json_encode(array(
    "status"      => "success",
    "message"     => "Authentication successful, we are redirecting you.",
  ));
}
else
{
  echo json_encode(
    array(
      "status" => "error",
      'message'=> "Unable to authenticate with Twitter.",
    ));
}

And this code that captures the information of the logged in user:

<?php

$username = 'sessionUser';

$url = 'https://twitter.com/' . $username;

$user = curl_init();
curl_setopt_array($user, [
      CURLOPT_URL             => $url,
      CURLOPT_CUSTOMREQUEST   => 'GET',
      CURLOPT_CAINFO          => 'cacert-2017-06-07.pem',
      CURLOPT_RETURNTRANSFER  => true,
      CURLOPT_SSL_VERIFYPEER  => false,
      CURLOPT_SSL_VERIFYHOST  => 2,
      CURLOPT_HTTPHEADER      => [
        "Content-type:text/html;charset=utf-8",
      ],
      CURLOPT_USERAGENT       => $_SERVER['HTTP_USER_AGENT'],
      CURLOPT_HEADER          => true,
      CURLOPT_FOLLOWLOCATION  => true,
      CURLOPT_MAXREDIRS       => 2,
      CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
      CURLOPT_POSTREDIR       => 2,
      CURLOPT_AUTOREFERER     => 1,
      CURLOPT_ENCODING        => "gzip"
  ]
);

$user_info = curl_exec($user);

$header_size = curl_getinfo($user, CURLINFO_HEADER_SIZE);
$header = substr($user_info, 0, $header_size);
$body = substr($user_info, $header_size);

$dom = new DOMDocument("5.0", "utf-8");
@$dom->loadHTML($body);

$data = json_decode($dom->getElementById("init-data")->getAttribute("value"));

echo "Nome: ", $data->profile_user->id, PHP_EOL;
echo "Nome: ", $data->profile_user->name, PHP_EOL;
echo "Usuário: ", $data->profile_user->screen_name, PHP_EOL;
echo "Foto de perfil: ", $data->profile_user->profile_image_url, PHP_EOL;

I need help so that the cookies of users saved in the .txt or in the database, make followers exchange.

How can I do this?

EDIT

Who downvote, leave comments.

EDIT 2

File follow.php

<?php

require_once '../modules/config.php';
require_once '../modules/class/Cookies.php';

$username = Cookies::get('username');

$friend_url = 'https://api.twitter.com/1.1/friendships/create.json';

$friend = curl_init();

curl_setopt_array($friend, [
        CURLOPT_URL             => $friend_url,
        CURLOPT_SSL_VERIFYPEER  => 1,
        CURLOPT_SSL_VERIFYHOST  => 2,
        CURLOPT_CAINFO          => ROOT . 'modules' . SEPARATOR . 'cacert' . SEPARATOR . 'cacert-2017-06-07.pem',
        CURLOPT_CUSTOMREQUEST   => 'POST',
        CURLOPT_POSTFIELDS      => 'screen_name=' . $username,
        CURLOPT_USERAGENT       => $_SERVER['HTTP_USER_AGENT'],
        CURLOPT_RETURNTRANSFER  => true,
        CURLOPT_HTTPHEADER      => [
            "Content-type: application/json; charset=utf-8",
      ],
        CURLOPT_HEADER          => true,
    ]

);

$response  = curl_exec($friend);

var_dump($response);

Response:

C:\wamp64\www\brfollow\api\follow.php:32:string 'HTTP/1.1 400 Bad Request
content-length: 62
content-type: application/json; charset=utf-8
date: Fri, 07 Jul 2017 08:09:54 GMT
server: tsa_d
set-cookie: guest_id=v1%3A149941499419523606; Domain=.twitter.com; Path=/; Expires=Sun, 07-Jul-2019 08:09:54 UTC
strict-transport-security: max-age=631138519
x-connection-hash: 9e951d1215095efa246c5b852acd2e8a
x-response-time: 131
x-tsa-request-body-time: 0

{"errors":[{"code":215,"message":"Bad Authentication data."}]}' (length=472)

Body:
You have to use

CURLOPT_COOKIEJAR       => __DIR__ . DIRECTORY_SEPARATOR . 'cookies' . DIRECTORY_SEPARATOR . $username . '.txt',

in your second request too.


来源: stackexchange

问:
Deleting contents of text file
I'm reading and writing to a text file. There is an instance where I want to delete the contents of the file (but not the file) as a kind of reset. How can I do this?</p>

```<code>if ((dirs) != nil) {
    var dir = dirs![0]; //documents directory

    let path = dir.stringByAppendingPathComponent("UserInfo.txt");
    println(path)
    let text = "Rondom Text"

    //writing
    text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)

    //reading
    let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)

    println(text2)
</code>```

答:
Swift 3.x

```<code>let text = ""
do {
     try text.write(toFile: fileBundlePath, atomically: false, encoding: .utf8)
} catch {
     print(error)
}
</code>```

Swift 4.x

```<code>let text = ""
do {
     try text.write(to: filePath, atomically: false, encoding: .utf8)
   } catch {
     print(error)
   }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Deleting contents of text file

Body:
I'm reading and writing to a text file. There is an instance where I want to delete the contents of the file (but not the file) as a kind of reset. How can I do this?

if ((dirs) != nil) {
    var dir = dirs![0]; //documents directory

    let path = dir.stringByAppendingPathComponent("UserInfo.txt");
    println(path)
    let text = "Rondom Text"

    //writing
    text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil)

    //reading
    let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)

    println(text2)

Body:
Swift 3.x

let text = ""
do {
     try text.write(toFile: fileBundlePath, atomically: false, encoding: .utf8)
} catch {
     print(error)
}

Swift 4.x

let text = ""
do {
     try text.write(to: filePath, atomically: false, encoding: .utf8)
   } catch {
     print(error)
   }


问:
Three.js tween camera.lookat
I'm attempting to tween the camera.lookAt in Three.js using Tween.js with little success.

This works

```<code>    selectedHotspot = object;

    var tween = new TWEEN.Tween(camera.lookAt( object.position),600).start();
</code>```

But rotates the camera directly to the object.position.

How do I get a nice smooth rotation?

This is the render function

```<code>  function update() {

    lat = Math.max(-85, Math.min(85, lat));
    phi = THREE.Math.degToRad(90 - lat);
    theta = THREE.Math.degToRad(lon);

    target.x = 512 * Math.sin(phi) * Math.cos(theta);
    target.y = 512 * Math.cos(phi);
    target.z = 512 * Math.sin(phi) * Math.sin(theta);

    if(!selectedHotspot)
        camera.lookAt(target);

    renderer.render(scene, camera);

}
</code>```

UPDATE

OK I can't actually tween the camera on anything. I think there must be something else wrong. Should there be something else in the render function?

答:
I use controls.target to tween camera'rotation and it work well.  </p>

```<code>createjs.Tween.get(controls.target)
.to({
  x: tweenPos.x,
  y: tweenPos.y - 11,
  z: tweenPos.z + 0.001
}, 800,createjs.Ease.linear);
</code>```

Title: Three.js tween camera.lookat

Body:
I'm attempting to tween the camera.lookAt in Three.js using Tween.js with little success.

This works

    selectedHotspot = object;

    var tween = new TWEEN.Tween(camera.lookAt( object.position),600).start();

But rotates the camera directly to the object.position.

How do I get a nice smooth rotation?

This is the render function

  function update() {

    lat = Math.max(-85, Math.min(85, lat));
    phi = THREE.Math.degToRad(90 - lat);
    theta = THREE.Math.degToRad(lon);

    target.x = 512 * Math.sin(phi) * Math.cos(theta);
    target.y = 512 * Math.cos(phi);
    target.z = 512 * Math.sin(phi) * Math.sin(theta);

    if(!selectedHotspot)
        camera.lookAt(target);

    renderer.render(scene, camera);

}

UPDATE

OK I can't actually tween the camera on anything. I think there must be something else wrong. Should there be something else in the render function?

Body:
I use controls.target to tween camera'rotation and it work well.

createjs.Tween.get(controls.target)
.to({
  x: tweenPos.x,
  y: tweenPos.y - 11,
  z: tweenPos.z + 0.001
}, 800,createjs.Ease.linear);


问:
HAML on Rails 3 returning "Template is missing" error
I have tried to render some files with HAML in Rails 3 without success.

My testfiles have the extension .html.haml.

In my Gemfile, I have the line gem 'haml' and have run bundle install.

When I run my app, I get the following error:

Template is missing

Missing template posts/index with {:locale=>[:en, :en], :formats=>[:html], :handlers=>[:rjs, :rhtml, :rxml, :builder, :erb]} in view paths "/Users/piet/Sites/blog/app/views"`

Any idea on how to resolve this?

答:
For rails 3 all you need to do is add:

gem "haml-rails"

to your Gemfile, then do a "bundle install"

See https://github.com/indirect/haml-rails

If you still seeing the error try restarting your server.

ContentLicense: CC BY-SA 2.5


问:
Password Widget and Password Hashing in Django Admin
I am new in Python coding and now trying to learn Django.
Right now i am using django 1.11.3 version.
So i have learned the basic thing in Django and created an app.

In my app, i have created a student model which include an password field. What i have noticed is, in Admin module password field is stored in simple text. So i need help to hash the password field in admin module. I need md5 hashing.

So can u guys help me. Is there any method to solve this?

This is what i have tried.

My Model

```<code>class student(models.Model):
    name = models.CharField(max_length=100)
    age = models.CharField(max_length=2)
    dob = models.DateField()
    father_name = models.CharField(max_length=100)
    username = models.CharField(max_length=25,null=True)
    password = models.CharField(max_length=100,null=True)
    def __unicode__(self):
        return self.name
</code>```

My Admin

```<code>from django.contrib import admin
from django import forms
from .models import student

admin.site.register(student)

class studentAdmin(admin.ModelAdmin):
    formfield_overrides = {
        student.password: {'widget': forms.PasswordInput},
        }
</code>```

答:
You must not do this.

Django includes an authentication framework that has everything you need already, including the ability to customise the model to include your date of birth field.

(Note, there is no point including age as well; you can always calculate that from the dob when you need it.)

Body:
I am new in Python coding and now trying to learn Django.
Right now i am using django 1.11.3 version.
So i have learned the basic thing in Django and created an app.

In my app, i have created a student model which include an password field. What i have noticed is, in Admin module password field is stored in simple text. So i need help to hash the password field in admin module. I need md5 hashing.

So can u guys help me. Is there any method to solve this?

This is what i have tried.

My Model

class student(models.Model):
    name = models.CharField(max_length=100)
    age = models.CharField(max_length=2)
    dob = models.DateField()
    father_name = models.CharField(max_length=100)
    username = models.CharField(max_length=25,null=True)
    password = models.CharField(max_length=100,null=True)
    def __unicode__(self):
        return self.name

My Admin

from django.contrib import admin
from django import forms
from .models import student

admin.site.register(student)

class studentAdmin(admin.ModelAdmin):
    formfield_overrides = {
        student.password: {'widget': forms.PasswordInput},
        }


问:
How to download a child folder , if exists, for a given TFS project using PowerShell?
I am trying to download a folder child from a given TFS project.
All i have done so far is connecting to the server using a url https://.visualstudio.com ,  username, a password  and listing all the projects.
This is my code so far:

```<code>Add-Type -Path "$path1\Microsoft.TeamFoundation.Client.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.Common.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.WorkItemTracking.Client.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.VersionControl.Client.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.ProjectManagement.dll"
Add-Type -Path "$path2\Microsoft.TeamFoundation.PowerTools.PowerShell.dll"
$tfsurl = 'https://something.visualstudio.com'
$username = 'someuser@outlook.com'
$password = 'somepasswd'
$_tfs_server =[Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfs_uri)

$cred = New-Object System.Net.NetworkCredential($username,$password)
$_tfs_server.Credentials = $cred
$_tfs_server.EnsureAuthenticated()

if($_tfs_server.HasAuthenticated){
Write-Host -ForegroundColor Green "Connected to Team Foundation Server [" $tfs_uri "]"
$tfsConfigurationServer = [Microsoft.TeamFoundation.Client.TfsConfigurationServerFactory]::GetConfigurationServer($tfs_uri)
$tpcService = $tfsConfigurationServer.GetService("Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService")

$sortedCollection = $tpcService.GetCollections() | Sort-Object -Property Name
foreach($col in $sortedCollection){
    Write-Host $col.Name
}

$cssService = $_tfs_server.GetService("Microsoft.TeamFoundation.Server.ICommonStructureService3")

$sortedProjects = $cssService.ListAllProjects() | Sort-Object -Property Name
Write-Host "Listing Projects"

foreach($project in $sortedProjects){
    Write-Host (" - " + $project.Name)
}

 }
 else {
return;
 }
</code>```

https://i.stack.imgur.com/iCXNQ.jpg

答:
Simple code to get files from source control:

```<code>    $teamProjectCollection=new-object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsCollectionUrl,$cret)
    $teamProjectCollection.EnsureAuthenticated()
    $VersionControl = $teamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$workspace = $VersionControl.CreateWorkspace("BasicSccExamplePS", $VersionControl.AuthorizedUser);
    $workspace.Map("$/Agile2015/ClassLibrary2", "D:\\temp\\BasicSccExample")
    $workspace.Get()
</code>```

To check whether folder/file exists, you can use GetItems() method:

```<code>$items=$VersionControl.GetItems("$/ScrumStarain/CustomCode/Properties2");
    Write-Output $items.Items.Count
    If($items.Items.Count -ne 0)
    {

    }
</code>```

Body:
I am trying to download a folder child from a given TFS project.
All i have done so far is connecting to the server using a url https://.visualstudio.com ,  username, a password  and listing all the projects.
This is my code so far:

Add-Type -Path "$path1\Microsoft.TeamFoundation.Client.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.Common.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.WorkItemTracking.Client.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.VersionControl.Client.dll"
Add-Type -Path "$path1\Microsoft.TeamFoundation.ProjectManagement.dll"
Add-Type -Path "$path2\Microsoft.TeamFoundation.PowerTools.PowerShell.dll"
$tfsurl = 'https://something.visualstudio.com'
$username = 'someuser@outlook.com'
$password = 'somepasswd'
$_tfs_server =[Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfs_uri)

$cred = New-Object System.Net.NetworkCredential($username,$password)
$_tfs_server.Credentials = $cred
$_tfs_server.EnsureAuthenticated()

if($_tfs_server.HasAuthenticated){
Write-Host -ForegroundColor Green "Connected to Team Foundation Server [" $tfs_uri "]"
$tfsConfigurationServer = [Microsoft.TeamFoundation.Client.TfsConfigurationServerFactory]::GetConfigurationServer($tfs_uri)
$tpcService = $tfsConfigurationServer.GetService("Microsoft.TeamFoundation.Framework.Client.ITeamProjectCollectionService")

$sortedCollection = $tpcService.GetCollections() | Sort-Object -Property Name
foreach($col in $sortedCollection){
    Write-Host $col.Name
}

$cssService = $_tfs_server.GetService("Microsoft.TeamFoundation.Server.ICommonStructureService3")

$sortedProjects = $cssService.ListAllProjects() | Sort-Object -Property Name
Write-Host "Listing Projects"

foreach($project in $sortedProjects){
    Write-Host (" - " + $project.Name)
}

 }
 else {
return;
 }

https://i.stack.imgur.com/iCXNQ.jpg

Body:
Simple code to get files from source control:

    $teamProjectCollection=new-object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsCollectionUrl,$cret)
    $teamProjectCollection.EnsureAuthenticated()
    $VersionControl = $teamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
$workspace = $VersionControl.CreateWorkspace("BasicSccExamplePS", $VersionControl.AuthorizedUser);
    $workspace.Map("$/Agile2015/ClassLibrary2", "D:\\temp\\BasicSccExample")
    $workspace.Get()

To check whether folder/file exists, you can use GetItems() method:

$items=$VersionControl.GetItems("$/ScrumStarain/CustomCode/Properties2");
    Write-Output $items.Items.Count
    If($items.Items.Count -ne 0)
    {

    }


问:
Putting a click event for a dialogue box with Django Tables2
I am trying to make a click event with Django Tables2 so that whenever someone clicks on a delete link in a row it will create a dialogue box for confirmation before deleting the row. Here is my code:

models.py

```<code>class Schedules(models.Model):
    course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
    location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield')
    room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A')
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am')
    end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am')
    instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')
    total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six')
    hours_per_class = models.CharField(max_length=128, choices=HOURS_PER_CLASS_CHOICES, default='four_and_half')
    frequency = models.CharField(max_length=128)
    status = models.CharField(max_length=128, choices=STATUS_CHOICES)
    interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day')
    initiated_by = models.CharField(max_length=128, null=True)
    schedule_id = models.IntegerField(default=0)
</code>```

tables.py

```<code>class ScheduleListTable(tables.Table):
    change = tables.TemplateColumn('<a href="/schedule/update_schedule/{{ record.id }}">Update</a> / Cancel / Event / '
                                   '<a href="/schedule/delete_schedule/{{ record.id }}"
                                   onclick="return confirm("Are you sure you want to delete this?")">Delete</a>',
                                   verbose_name=u'Change', )
    class Meta:
        model = Schedules
        fields = ('id', 'course_name', 'start_date', 'start_time', 'hours_per_class', 'instructor', 'change',)
        attrs = {"class": "paleblue"}
</code>```

views.py

```<code>def schedule_List(request):
    context_dict = {}
    schedule_list = Schedules.objects.order_by('start_date')
    table = ScheduleListTable(schedule_list)
    context_dict['table'] = table
    return render(request, "schedule/schedule_list.html", context_dict)
</code>```

schedule_list.html

```<code><div id="schedule_list_table">
    {% if table %}
        {% render_table table %}
    {% endif %}
</div>
</code>```

For some reason, I can't make the onclick event that makes the confirmation dialogue box appear, and it just goes straight to deleting. I assume that it's written incorrectly in tables.py, but I don't know how to write it correctly in that case. Or do I need to do something else?

答:
Have a look at the rendered html, for example using your browsers inspect context menu option. I think you could see there that there is a problem with the double quotes you use.

The onclick-attribute is enclosed by double quotes, but the message passed as argument to confirm() is also enclosed by double quotes. This results in your browser interpreting the attribute as `onclick="return confirm(" and ignores the gibberish it cannot understand which is your message.

You can fix that by using single quotes to enclose the message argument to confirm(), either by escaping them in the syntax you used (\'), or by using triple quotes like this:

```<code>template_code = '''
<a href="/schedule/update_schedule/{{ record.id }}">Update</a> / Cancel / Event /
<a href="/schedule/delete_schedule/{{ record.id }}"
    onclick="return confirm('Are you sure you want to delete this?')">Delete</a>'''
</code>```

Body:
I am trying to make a click event with Django Tables2 so that whenever someone clicks on a delete link in a row it will create a dialogue box for confirmation before deleting the row. Here is my code:

models.py

class Schedules(models.Model):
    course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
    location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield')
    room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A')
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am')
    end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am')
    instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')
    total_hours = models.CharField(max_length=128, choices=TOTAL_HOURS_CHOICES, default='six')
    hours_per_class = models.CharField(max_length=128, choices=HOURS_PER_CLASS_CHOICES, default='four_and_half')
    frequency = models.CharField(max_length=128)
    status = models.CharField(max_length=128, choices=STATUS_CHOICES)
    interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='1 day')
    initiated_by = models.CharField(max_length=128, null=True)
    schedule_id = models.IntegerField(default=0)

tables.py

class ScheduleListTable(tables.Table):
    change = tables.TemplateColumn('Update / Cancel / Event / '
                                   'Delete',
                                   verbose_name=u'Change', )
    class Meta:
        model = Schedules
        fields = ('id', 'course_name', 'start_date', 'start_time', 'hours_per_class', 'instructor', 'change',)
        attrs = {"class": "paleblue"}

views.py

def schedule_List(request):
    context_dict = {}
    schedule_list = Schedules.objects.order_by('start_date')
    table = ScheduleListTable(schedule_list)
    context_dict['table'] = table
    return render(request, "schedule/schedule_list.html", context_dict)

schedule_list.html

    {% if table %}
        {% render_table table %}
    {% endif %}

For some reason, I can't make the onclick event that makes the confirmation dialogue box appear, and it just goes straight to deleting. I assume that it's written incorrectly in tables.py, but I don't know how to write it correctly in that case. Or do I need to do something else?

Body:
Have a look at the rendered html, for example using your browsers inspect context menu option. I think you could see there that there is a problem with the double quotes you use.

The onclick-attribute is enclosed by double quotes, but the message passed as argument to confirm() is also enclosed by double quotes. This results in your browser interpreting the attribute as `onclick="return confirm(" and ignores the gibberish it cannot understand which is your message.

You can fix that by using single quotes to enclose the message argument to confirm(), either by escaping them in the syntax you used (\'), or by using triple quotes like this:

template_code = '''
<a href="/schedule/update_schedule/{{ record.id }}">Update</a> / Cancel / Event /
<a href="/schedule/delete_schedule/{{ record.id }}"
    onclick="return confirm('Are you sure you want to delete this?')">Delete</a>'''


问:
Enable Tableview Scrolling but disable touches
I want to disable my tableview. Means that no button,TextFields and other controls can be touched but also i want that my tableview scroll should be working properly.

```<code>self.tableView.userInteractionEnabled=true;
</code>```

I have used this but this made scrolling also disable.

答:
You can disable selection when you started scrolling. Implement UIScrollViewDelegate

In scrollViewWillBeginDragging:

```<code>tableView.allowsSelection = NO;
</code>```

In scrollViewDidEndDragging:willDecelerate:

```<code>tableView.allowsSelection = YES;
</code>```

Body:
I want to disable my tableview. Means that no button,TextFields and other controls can be touched but also i want that my tableview scroll should be working properly.

self.tableView.userInteractionEnabled=true;

I have used this but this made scrolling also disable.

Body:
You can disable selection when you started scrolling. Implement UIScrollViewDelegate

In scrollViewWillBeginDragging:

tableView.allowsSelection = NO;

In scrollViewDidEndDragging:willDecelerate:

tableView.allowsSelection = YES;


问:
Ranking in PHP and MySQL
```<code>  `id` int(11) NOT NULL,
  `ip` text NOT NULL,
  `song` text NOT NULL,
  `vote` int(11) NOT NULL
</code>```

I have created a voting system and I would like to print the songs with more votes ... how do I do it? Thank you

答:
You need to try below query.you can get higest voted songs.
put your table name in 'table_name'.

SELECT song,SUM(vote)as VOTECOUNT FROM table_name GROUP BY song order by VOTECOUNT desc

Title: Ranking in PHP and MySQL

Body:
  `id` int(11) NOT NULL,
  `ip` text NOT NULL,
  `song` text NOT NULL,
  `vote` int(11) NOT NULL

I have created a voting system and I would like to print the songs with more votes ... how do I do it? Thank you


问:
why am getting this exception: Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException
i am reading excel file using apache poi 3.16 here is my code

```<code>try
        {
            String excelPath = "C:\\Users\\wecme\\Desktop\\AccountStatement.xls";
            FileInputStream fileInputStream = new FileInputStream(new File(excelPath));

            // Create Workbook instance holding .xls file
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);

            // Get the first worksheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            // Iterate through each rows
            java.util.Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext())
            {
                // Get Each Row
                Row row = rowIterator.next();

                // Iterating through Each column of Each Row
                java.util.Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext())
                {

                    Cell cell = cellIterator.next();

                    // Checking the cell format
                    switch (cell.getCellType())
                    {
                   case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                   case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t");
                        break;

                    }
                }
                System.out.println("");
            }

        } catch (IOException ie)
        {
            ie.printStackTrace();
        }
</code>```

my excel data looks like this:

```<code>Datetime    Description TransactionId   Credit Amount   Debit Amount    Remaining   OdAmount    EnteredBy   Remarks
1/6/2017 8:14   IDEA (9542010237) COMMISSION    GLGHQN  0.31    0   2721.92 0   iNHYD0390437LO  IDEA COMMISSION
</code>```

when i read other file which is not having time with date its reading properly ,but when  i try to read this file this exception coming

```<code>Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
at excelRead.ReadExcel.main(ReadExcel.java:27)
</code>```

please help me , thank you.

答:
You're creating a XSSFWorkbook which is only suitable for working on xlsx files, i.e. the new xml based office format. Your file extension (xls) however suggests that this is the older Microsoft Office (2003 I guess) format. In order to fix the error you need to convert the file to xlsx format or you need to work with a HSSFWorkbook

You can find some samples concerning HSSF here: https://poi.apache.org/spreadsheet/examples.html#hssf-only
Some examples concerning XDDF can be found here: https://poi.apache.org/spreadsheet/examples.html#xssf-only

Body:
i am reading excel file using apache poi 3.16 here is my code

try
        {
            String excelPath = "C:\\Users\\wecme\\Desktop\\AccountStatement.xls";
            FileInputStream fileInputStream = new FileInputStream(new File(excelPath));

            // Create Workbook instance holding .xls file
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);

            // Get the first worksheet
            XSSFSheet sheet = workbook.getSheetAt(0);

            // Iterate through each rows
            java.util.Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext())
            {
                // Get Each Row
                Row row = rowIterator.next();

                // Iterating through Each column of Each Row
                java.util.Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext())
                {

                    Cell cell = cellIterator.next();

                    // Checking the cell format
                    switch (cell.getCellType())
                    {
                   case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        break;
                   case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t");
                        break;
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t");
                        break;

                    }
                }
                System.out.println("");
            }

        } catch (IOException ie)
        {
            ie.printStackTrace();
        }

my excel data looks like this:

Datetime    Description TransactionId   Credit Amount   Debit Amount    Remaining   OdAmount    EnteredBy   Remarks
1/6/2017 8:14   IDEA (9542010237) COMMISSION    GLGHQN  0.31    0   2721.92 0   iNHYD0390437LO  IDEA COMMISSION

when i read other file which is not having time with date its reading properly ,but when  i try to read this file this exception coming

Exception in thread "main" org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file
at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:286)
at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:758)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:327)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:291)
at excelRead.ReadExcel.main(ReadExcel.java:27)

please help me , thank you.


问:
How can I combine 2 django query into one with object limit
I have multiple type of obj_type in database

What i am currently doing is

```<code>a =  Search_model.objects.filter(obj_type="mall", city=city)[:2]

b = Search_model.objects.filter(obj_type="store", city=city)[:2]
</code>```

and then combine a and b so it gives me:-

```<code>[{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"store"}, {"name":"d","obj_type":"store"}]
</code>```

what i want is something like this

```<code>    if not search_in == None:
        search_in_queries = [q for q in re.split(",", search_in) if q]

        for query in search_in_queries:
            search_in_dict.append(('obj_type__contains', query))

        search_in_query = [Q(x) for x in search_in_dict]
    else:
        search_in_query = None
</code>```

such that value of search_in is "mall,store"

```<code>a =  Search_model.objects.filter(reduce(operator.or_, search_in_query), city=city)[:4]
</code>```

but it gives me all mall type obj

```<code>[{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"mall"}, {"name":"d","obj_type":"mall"}]
</code>```

so my query is how can i achieve the above result in one query

答:
If it's Postgres, you can use ROW_NUMBER along with raw sql:

```<code>Search_model.objects.raw("SELECT id, obj_type from (
        SELECT t.*, ROW_NUMBER() OVER (PARTITION BY obj_type) AS rn
        FROM search_model t
    ) WHERE rn < 3 and obj_type in ('mall', 'store')"
);
</code>```

Would not prefer this way, as last I checked sqlite3 has no ROW_NUMBER.

For SqlLite3 you can fire:

```<code>SELECT id, obj_type
FROM search_model t1
WHERE id in (
   select id from search_model t2
   where t2.obj_type = t1.obj_type
   order by t2.obj_type desc limit 2
)
ORDER BY id, obj_type DESC;
</code>```

With Django ORM, we might look into, Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database:

```<code>from django.db.models import Q

mall_items = Search_model.objects.filter(obj_type="mall", city=city).values_list("id", flat=True)[:2]
store_items = Search_model.objects.filter(obj_type="store", city=city).values_list("id", flat=True)[:2]

print Search_model.objects.filter(Q(id__in=mall_items)|Q(id__in=store_items))
</code>```

Body:
I have multiple type of obj_type in database

What i am currently doing is

a =  Search_model.objects.filter(obj_type="mall", city=city)[:2]

b = Search_model.objects.filter(obj_type="store", city=city)[:2]

and then combine a and b so it gives me:-

[{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"store"}, {"name":"d","obj_type":"store"}]

what i want is something like this

    if not search_in == None:
        search_in_queries = [q for q in re.split(",", search_in) if q]

        for query in search_in_queries:
            search_in_dict.append(('obj_type__contains', query))

        search_in_query = [Q(x) for x in search_in_dict]
    else:
        search_in_query = None

such that value of search_in is "mall,store"

a =  Search_model.objects.filter(reduce(operator.or_, search_in_query), city=city)[:4]

but it gives me all mall type obj

[{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"mall"}, {"name":"d","obj_type":"mall"}]

so my query is how can i achieve the above result in one query

Body:
If it's Postgres, you can use ROW_NUMBER along with raw sql:

Search_model.objects.raw("SELECT id, obj_type from (
        SELECT t.*, ROW_NUMBER() OVER (PARTITION BY obj_type) AS rn
        FROM search_model t
    ) WHERE rn < 3 and obj_type in ('mall', 'store')"
);

Would not prefer this way, as last I checked sqlite3 has no ROW_NUMBER.

For SqlLite3 you can fire:

SELECT id, obj_type
FROM search_model t1
WHERE id in (
   select id from search_model t2
   where t2.obj_type = t1.obj_type
   order by t2.obj_type desc limit 2
)
ORDER BY id, obj_type DESC;

With Django ORM, we might look into, Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database:

from django.db.models import Q

mall_items = Search_model.objects.filter(obj_type="mall", city=city).values_list("id", flat=True)[:2]
store_items = Search_model.objects.filter(obj_type="store", city=city).values_list("id", flat=True)[:2]

print Search_model.objects.filter(Q(id__in=mall_items)|Q(id__in=store_items))


问:
Kendo DropDownList Conditional if else template
Currently my template looks like this:

```<code>template: '#:data.Name# (#:data.Code#)'
</code>```

What I would like to do is to check the data.Code parameter if it's empty.
If (data.Code == '') then

```<code>template: '#:data.Name#
</code>```

else the first template that contains both name and code.

I've been trying something like this but it doesn't seem to work.

```<code>template: "#if(#:data.Code#==''){ #:data.Name# (#:data.Code#)}else {#:data.Name#}#"
</code>```

Help would be very appreciated.

答:
Managed to make it work with help from replys.</p>

```<code>template: "# if(data.Code != '')" +
          "{# #:data.Name# (#:data.Code#) #}" +
          "else {# #:data.Name# #} #"
</code>```

Body:
Currently my template looks like this:

template: '#:data.Name# (#:data.Code#)'

What I would like to do is to check the data.Code parameter if it's empty.
If (data.Code == '') then

template: '#:data.Name#

else the first template that contains both name and code.

I've been trying something like this but it doesn't seem to work.

template: "#if(#:data.Code#==''){ #:data.Name# (#:data.Code#)}else {#:data.Name#}#"

Help would be very appreciated.

Body:
Managed to make it work with help from replys.

template: "# if(data.Code != '')" +
          "{# #:data.Name# (#:data.Code#) #}" +
          "else {# #:data.Name# #} #"


答:
A great place to see how this is done is to look at the Django source code in django.contrib.auth, they handle this same scenario for a User.

The idea is that you would use a custom admin form with a password field so that you can get the raw password from the form and then manually set the password running it through a hasher first.

```<code>from django.contrib.auth.hashers import make_password

class Student(models.Model):

    def set_password(self, raw_password):
        self.password = make_password(raw_password)
</code>```

The make_password also takes a hasher type arguement if you don't want to use the default one.

Title: Password Widget and Password Hashing in Django Admin

Body:
A great place to see how this is done is to look at the Django source code in django.contrib.auth, they handle this same scenario for a User.

The idea is that you would use a custom admin form with a password field so that you can get the raw password from the form and then manually set the password running it through a hasher first.

from django.contrib.auth.hashers import make_password

class Student(models.Model):

    def set_password(self, raw_password):
        self.password = make_password(raw_password)

The make_password also takes a hasher type arguement if you don't want to use the default one.


问:
How can i print Unmarshalled data in golang?
I am reading json from Raabbitmq in golang and mapping the json in an interface

My struct looks like this, and

```<code>type Documents struct {
    user_id    string
    partner_id []string
    last_login int
}
</code>```

and I am mapping the incoming json in the above struct, but for debugginf purpose, i want to see the interface array , how can i print the mapped data array (body in my case )

```<code>        var body []Documents
        json.Unmarshal(d.Body, &body)

        log.Printf("Received a message: %s", body)
</code>```

Do i need to put other identifier instead of %s ?

答:
You have problem with your struct definition. You need use Exported identifier, like-

```<code>type Documents struct {
    UserID    string    `json:"user_id"`
    PartnerID []string  `json:"partner_id"`
    LastLogin int       `json:"last_login"`
}
</code>```

For your question, refer to format printing verbs.

To print values of body-

```<code>log.Printf("Received a message: %v", body)
</code>```

To print values along with variable name -

```<code>log.Printf("Received a message: %#v", body)
</code>```

Body:
I am reading json from Raabbitmq in golang and mapping the json in an interface

My struct looks like this, and

type Documents struct {
    user_id    string
    partner_id []string
    last_login int
}

and I am mapping the incoming json in the above struct, but for debugginf purpose, i want to see the interface array , how can i print the mapped data array (body in my case )

        var body []Documents
        json.Unmarshal(d.Body, &body)

        log.Printf("Received a message: %s", body)

Do i need to put other identifier instead of %s ?

Body:
You have problem with your struct definition. You need use Exported identifier, like-

type Documents struct {
    UserID    string    `json:"user_id"`
    PartnerID []string  `json:"partner_id"`
    LastLogin int       `json:"last_login"`
}

For your question, refer to format printing verbs.

To print values of body-

log.Printf("Received a message: %v", body)

To print values along with variable name -

log.Printf("Received a message: %#v", body)


问:
C# Execute the catch block when the type is string
Here I'm struggling to work with catch block like I wanted to execute the catch block when the value type is a string.

Here I'm using dynamic type to accept all the type of values when the method will returns.

Now I wanted to execute the catch block when the method will return the string type.
Here my code is

```<code>dynamic paymentResult = null;
try
{
    paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
}
catch (Exception ex) when (paymentResult is string)
{
    return Content(HttpStatusCode.InternalServerError,
        $"{Messages.DonationPaymentFailed} {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
}
</code>```

答: I guess, if the ExecuteSquarePayment method throws an exception, paymentResult will always be null(not set).</p>

Body:
Here I'm struggling to work with catch block like I wanted to execute the catch block when the value type is a string.

Here I'm using dynamic type to accept all the type of values when the method will returns.

Now I wanted to execute the catch block when the method will return the string type.
Here my code is

dynamic paymentResult = null;
try
{
    paymentResult = await ExecuteSquarePayment(db, checkoutViewModel);
}
catch (Exception ex) when (paymentResult is string)
{
    return Content(HttpStatusCode.InternalServerError,
        $"{Messages.DonationPaymentFailed} {checkoutViewModel.PaymentMethod} : {ex.ToString()}");
}


问:
Whats wrong in my php mysql counter script code?
I am writing a Php 5 and Mysql 5 page counter script. When a student having id as 'visitorid' visits a page having id 'pageid' (both int(11)) the page counter tries to log the visit in 'visitors' database.  But counter is not updating in mysql db, instead the visit_counter int(4) turns to 0.Whats wrong with my code? visitdate is datetime.

```<code><?php
 $pageid = 101;
 $visitorid = 234;

  $sql   = "SELECT *  FROM   visitors
                      WHERE  pageid    = ".$pageid."
                      AND    visitorid = ".$visitorid;

 $temp  = mysql_query($sql) or die("Error 1.<br>".mysql_error());
 $data  = mysql_fetch_array($temp);

 // visit_counter is a field in table
 if(($data['visit_counter']) != NULL){
 echo "Entery exists <br>";
 // Tried below version also
 $visit = " SET visit_counter  = visit_counter+1";

 //$visit_counter = $data['visit_counter'];
 //$visit = " SET visit_counter  = ".$visit_counter++ ;

// Valid SQL
// UPDATE `visitors`
//      SET visit_counter = visit_counter+1
//      WHERE pageid = 101 and visitorid=234
// This manual sql query updates in phpmyadmin

 $sql  = "UPDATE visitors  ".$visit."
           AND visitdate = NOW()
           WHERE pageid    = ".$pageid."
           AND   visitorid = ".$visitorid;

$temp = mysql_query($sql) or die("ERROR 3.<br>".mysql_error());
//No error is displayed on above query.

} else {
//first entry
$visit_count = "1";
$sql    = "INSERT INTO  visitors
            (`pageid`,`visitorid`, `visitdate`, `visit_counter`)
    VALUES ('".$pageid."','".$visitorid."', NOW(), '".$visit_count."')";
 $temp = mysql_query($sql);
 //first entry is inserted successfully
 //and visit_counter shows 1 as entry.
}
?>
</code>```

Can anyone tell me whats wrong with this code?

答:
Oh! I got answer by myself. Sometimes just little errors make us go crazy..
I made a mistake in udate query.. rather than using and I should have user a comma instead. .. working well now!</p>

Body:
I am writing a Php 5 and Mysql 5 page counter script. When a student having id as 'visitorid' visits a page having id 'pageid' (both int(11)) the page counter tries to log the visit in 'visitors' database.  But counter is not updating in mysql db, instead the visit_counter int(4) turns to 0.Whats wrong with my code? visitdate is datetime.

<?php
 $pageid = 101;
 $visitorid = 234;

  $sql   = "SELECT *  FROM   visitors
                      WHERE  pageid    = ".$pageid."
                      AND    visitorid = ".$visitorid;

 $temp  = mysql_query($sql) or die("Error 1.
".mysql_error());
 $data  = mysql_fetch_array($temp);

 // visit_counter is a field in table
 if(($data['visit_counter']) != NULL){
 echo "Entery exists
";
 // Tried below version also
 $visit = " SET visit_counter  = visit_counter+1";

 //$visit_counter = $data['visit_counter'];
 //$visit = " SET visit_counter  = ".$visit_counter++ ;

// Valid SQL
// UPDATE `visitors`
//      SET visit_counter = visit_counter+1
//      WHERE pageid = 101 and visitorid=234
// This manual sql query updates in phpmyadmin

 $sql  = "UPDATE visitors  ".$visit."
           AND visitdate = NOW()
           WHERE pageid    = ".$pageid."
           AND   visitorid = ".$visitorid;

$temp = mysql_query($sql) or die("ERROR 3.
".mysql_error());
//No error is displayed on above query.

} else {
//first entry
$visit_count = "1";
$sql    = "INSERT INTO  visitors
            (`pageid`,`visitorid`, `visitdate`, `visit_counter`)
    VALUES ('".$pageid."','".$visitorid."', NOW(), '".$visit_count."')";
 $temp = mysql_query($sql);
 //first entry is inserted successfully
 //and visit_counter shows 1 as entry.
}
?>

Can anyone tell me whats wrong with this code?


问:
camel netty4 ChannelHandlerFactory ByteToMessageDecoder error
as i am a beginner of camel. i wanna get a hint to solve my problem.
here is my code

full source link : https://github.com/kcy0142/camel_netty_test

```<code>@Configuration
public class ChannelHandlerFactoryByteArrayDecoder implements ChannelHandlerFactory {

    @Bean(name="vpaByteDecoder")
    @Qualifier("vpaByteDecoder")
    public ChannelHandler newChannelHandler() {
      return (ChannelHandler) new VpaByteDecoder();
    }
    public  class VpaByteDecoder extends ByteToMessageDecoder{

    }
}
</code>```

and my router is

```<code>from("netty4:tcp://localhost:8004?textline=true&sync=true&decoders=#vpaByteDecoder&encoders=#stringEncoder").
</code>```

and error is invoked like this

```<code>io.netty.channel.ChannelPipelineException: config.ChannelHandlerFactoryDecoder$VpaByteDecoder is not a @Sharable handler, so can't be added or removed multiple times.
</code>```

ByteToMessageDecoder should not sharable. so i implenmented ChannelHandlerFactory

i dont know the reason.plaease show me the way to understand my problem.

答:
Its the factory class that should be named not the bean method, something like this instead, and remove the <code>@Bean</code> </p>

```<code>@Component(name="vpaByteDecoder")
public class ChannelHandlerFactoryByteArrayDecoder implements ChannelHandlerFactory {
</code>```

Body:
as i am a beginner of camel. i wanna get a hint to solve my problem.
here is my code

full source link : https://github.com/kcy0142/camel_netty_test

@Configuration
public class ChannelHandlerFactoryByteArrayDecoder implements ChannelHandlerFactory {

    @Bean(name="vpaByteDecoder")
    @Qualifier("vpaByteDecoder")
    public ChannelHandler newChannelHandler() {
      return (ChannelHandler) new VpaByteDecoder();
    }
    public  class VpaByteDecoder extends ByteToMessageDecoder{

    }
}

and my router is

from("netty4:tcp://localhost:8004?textline=true&sync=true&decoders=#vpaByteDecoder&encoders=#stringEncoder").

and error is invoked like this

io.netty.channel.ChannelPipelineException: config.ChannelHandlerFactoryDecoder$VpaByteDecoder is not a @Sharable handler, so can't be added or removed multiple times.

ByteToMessageDecoder should not sharable. so i implenmented ChannelHandlerFactory

i dont know the reason.plaease show me the way to understand my problem.

Body:
Its the factory class that should be named not the bean method, something like this instead, and remove the @Bean

@Component(name="vpaByteDecoder")
public class ChannelHandlerFactoryByteArrayDecoder implements ChannelHandlerFactory {


问:
memory alignment issues with union
Is there guarantee, that memory for this object will be properly aligned if we create object of this type in stack?

```<code>union my_union
{
  int value;
  char bytes[4];
};
</code>```

If we create char bytes[4] in stack and then try to cast it to integer there might be alignment problem. We can avoid that problem by creating it in heap, however, is there such guarantee for union objects? Logically there should be, but I would like to confirm.

Thanks.

答:
Well, that depends on what you mean.

If you mean:

Will both the int and char[4] members of the union be properly aligned so that I may use them independently of each other?

Then yes. If you mean:

Will the int and char[4] members be guaranteed to be aligned to take up the same amount of space, so that I may access individual bytes of the int through the char[4]?

Then no. This is because sizeof(int) is not guaranteed to be 4. If ints are 2 bytes, then who knows which two char elements will correspond to the int in your union (the standard doesn't specify)?

If you want to use a union to access the individual bytes of an int, use this:

```<code>union {
  int i;
  char c[sizeof(int)];
};
</code>```

Since each member is the same size, they're guaranteed to occupy the same space. This is what I believe you want to know about, and I hope I've answered it.

Title: memory alignment issues with union

Body:
Is there guarantee, that memory for this object will be properly aligned if we create object of this type in stack?

union my_union
{
  int value;
  char bytes[4];
};

If we create char bytes[4] in stack and then try to cast it to integer there might be alignment problem. We can avoid that problem by creating it in heap, however, is there such guarantee for union objects? Logically there should be, but I would like to confirm.

Thanks.

Body:
Well, that depends on what you mean.

If you mean:

Will both the int and char[4] members of the union be properly aligned so that I may use them independently of each other?

Then yes. If you mean:

Will the int and char[4] members be guaranteed to be aligned to take up the same amount of space, so that I may access individual bytes of the int through the char[4]?

Then no. This is because sizeof(int) is not guaranteed to be 4. If ints are 2 bytes, then who knows which two char elements will correspond to the int in your union (the standard doesn't specify)?

If you want to use a union to access the individual bytes of an int, use this:

union {
  int i;
  char c[sizeof(int)];
};

Since each member is the same size, they're guaranteed to occupy the same space. This is what I believe you want to know about, and I hope I've answered it.


问:
Matplotlib plot time series graph
I have a pandas dataframe with 2 columns:

```<code>Time     Values
07:40         5
08:10         6
08:25         3
08:53         4
...         ...
</code>```

How can I plot a line chart which x-axis is the time and y-axis is values? I tried:

```<code>plt.plot(df["Time"],df["Values"])
</code>```

But I got an error message: ValueError: invalid literal for float: 18:03. I converted the column to datetime format and tried plot_date, but all failed

答:
you need to make sure you use the datetime library properly for example
if your time come as a string of the format "HH:MM" you should split it and do the following

```<code>import datetime

def process_time(x):
  h, m = x.split(":")
  return datetime.time(hour=int(h), minute=int(m))

df['Time'].apply(process_time)

df.plot(x='Time', y='Values')
</code>```

pandas have it own plot function which will plot the line for you

Title: Matplotlib plot time series graph

Body:
I have a pandas dataframe with 2 columns:

Time     Values
07:40         5
08:10         6
08:25         3
08:53         4
...         ...

How can I plot a line chart which x-axis is the time and y-axis is values? I tried:

plt.plot(df["Time"],df["Values"])

But I got an error message: ValueError: invalid literal for float: 18:03. I converted the column to datetime format and tried plot_date, but all failed

Body:
you need to make sure you use the datetime library properly for example
if your time come as a string of the format "HH:MM" you should split it and do the following

import datetime

def process_time(x):
  h, m = x.split(":")
  return datetime.time(hour=int(h), minute=int(m))

df['Time'].apply(process_time)

df.plot(x='Time', y='Values')

pandas have it own plot function which will plot the line for you


问:
Portable way to convert an unsigned value to its signed negation in C++14
I'm looking for a portable C++ function that computes the mathematical function f(x) = -x where the input is unsigned and the output is signed.  The function should work for the full range of long long values and throw an exception if the input is out of range.  It should not rely on compiler support for an even bigger integer type to catch overflow.  Here are two working but undesirable functions that compute what I want:

```<code>#include <cerrno>
#include <limits>
#include <stdexcept>

using namespace std;

long long
slow_negate(unsigned long long val)
{
  string s = '-' + to_string(val);
  errno = 0;
  long long r = strtoll(s.c_str(), nullptr, 10);
  if (errno)
    throw range_error("slow_convert overflow");
  return r;
}

constexpr long long
twos_complement_negate(unsigned long long val)
{
  constexpr long long minll = numeric_limits<long long>::min(),
                      maxll = numeric_limits<long long>::max();
  static_assert(minll == ~maxll && -(minll + 1) == maxll,
                "only works for two's complement arithmetic");
  return val > maxll + 1U ? throw range_error("twos_complement_negate overflow")
    : val >= 0 ? (unsigned long long) -val
    : (unsigned long long) (-val + 1) + 1;
}
</code>```

The problem here is that the first function is obviously horribly slow and not a constexpr (which such a simple function really should be), while the second function makes additional assumptions about two's complement integer representation that are not guaranteed by the language spec.

It sounds like such an easy problem, but somehow I've been unable to come up with a good portable solution that works for every possible input.

答:
Did I miss something or why couldn't you just do

```<code>constexpr signed long long f(unsigned long long input)
{
   return (input > static_cast<unsigned long long>(
       std::numeric_limits<signed long long>::max()))
       ? throw std::range_error{ "overflow" }
       : -static_cast<signed long long>(input);
}
</code>```

or, more general

```<code>template<typename T>
constexpr auto f(T input) -> std::make_signed_t<T>
{
    using signed_t = std::make_signed_t<T>;
    return (input > static_cast<T>(std::numeric_limits<signed_t>::max()))
        ? throw std::range_error{ "overflow" }
        : -static_cast<signed_t>(input);
}
</code>```

Body:
I'm looking for a portable C++ function that computes the mathematical function f(x) = -x where the input is unsigned and the output is signed.  The function should work for the full range of long long values and throw an exception if the input is out of range.  It should not rely on compiler support for an even bigger integer type to catch overflow.  Here are two working but undesirable functions that compute what I want:

#include <cerrno>
#include <limits>
#include <stdexcept>

using namespace std;

long long
slow_negate(unsigned long long val)
{
  string s = '-' + to_string(val);
  errno = 0;
  long long r = strtoll(s.c_str(), nullptr, 10);
  if (errno)
    throw range_error("slow_convert overflow");
  return r;
}

constexpr long long
twos_complement_negate(unsigned long long val)
{
  constexpr long long minll = numeric_limits<long long>::min(),
                      maxll = numeric_limits<long long>::max();
  static_assert(minll == ~maxll && -(minll + 1) == maxll,
                "only works for two's complement arithmetic");
  return val > maxll + 1U ? throw range_error("twos_complement_negate overflow")
    : val >= 0 ? (unsigned long long) -val
    : (unsigned long long) (-val + 1) + 1;
}

The problem here is that the first function is obviously horribly slow and not a constexpr (which such a simple function really should be), while the second function makes additional assumptions about two's complement integer representation that are not guaranteed by the language spec.

It sounds like such an easy problem, but somehow I've been unable to come up with a good portable solution that works for every possible input.

Body:
Did I miss something or why couldn't you just do

constexpr signed long long f(unsigned long long input)
{
   return (input > static_cast<unsigned long long>(
       std::numeric_limits<signed long long>::max()))
       ? throw std::range_error{ "overflow" }
       : -static_cast<signed long long>(input);
}

or, more general

template<typename T>
constexpr auto f(T input) -> std::make_signed_t<T>
{
    using signed_t = std::make_signed_t<T>;
    return (input > static_cast<T>(std::numeric_limits<signed_t>::max()))
        ? throw std::range_error{ "overflow" }
        : -static_cast<signed_t>(input);
}


问:
how to fetch data in view or display it in a page in codeigniter
this is my profile.php code i want to display it in webpage

```<code><!-- Bridegroom Profile Details -->
<div class="w3ls-list">

    <div class="container">

                <h2>Bridegroom Profile Details</h2>

    <div class="col-md-9 profiles-list-agileits">
        <div class="single_w3_profile">
            <div class="agileits_profile_image">
    <?php foreach ($profile_details as $row) { ?>
                                <img src="<?php echo $row['upload'];?>" alt="profile image" />
                                           <?php } ?>

            </div>

            <div class="clearfix"></div>
        </div>

        <div class="profile_w3layouts_details">

            <div class="agileits_aboutme">
                <h4>Profile</h4>
                <h5>Personal Details:</h5>
                <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Profile for : </label>
                    <div class="col-sm-9 w3_details">

                                               <!--Brother-->
                    </div>
                    <div class="clearfix"> </div>
                </div>
                <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Name : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Gender : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                                    <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Dob : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                                    <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Religion : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                                    <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Mobile : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                                    </div>

                            </div>

        </div>

    </div>
           </div>

    </div>
</code>```

this is my controller home.php
please help to how to diplay this profile

```<code> public function profile($param1='')
 {

     //$data['user_detail'] = $this->db->get_where('admin',array('id'=> $this->session->userdata('admin_id')))->result_array();
     $data['page_name']='profile';
     $data['profile_details']=$this->db->get_where('profile',array('id' => $param1))->result_array();

     $this->load->view('index',$data);
 }
</code>```

答:
Since Your fetching single record so no need foreach here simple do like this

```<code><?php if(isset($profile_details[0]['upload'])) { ?>
      <img src="<?php echo $profile_details[0]['upload'];?>" alt="profile image" >
<?php } ?>
</code>```

and

```<code> <div class="form_but1">
     <label class="col-sm-3 control-label1" for="Relation">Name : </label>
         <div class="col-sm-9 w3_details">
               <?php if(isset($profile_details[0]['Name'])) {
                            echo $profile_details[0]['Name'];
                 } ?>
          </div>
          <div class="clearfix"> </div>
        </div>
</code>```

Body:
this is my profile.php code i want to display it in webpage

Bridegroom Profile Details

    <?php foreach ($profile_details as $row) { ?>
                                <img src="<?php echo $row['upload'];?>" alt="profile image" />
                                           <?php } ?>

Profile

Personal Details:

                    Profile for :

                    Name :

                    Gender :

                    Dob :

                    Religion :

                    Mobile :

this is my controller home.php
please help to how to diplay this profile

 public function profile($param1='')
 {

     //$data['user_detail'] = $this->db->get_where('admin',array('id'=> $this->session->userdata('admin_id')))->result_array();
     $data['page_name']='profile';
     $data['profile_details']=$this->db->get_where('profile',array('id' => $param1))->result_array();

     $this->load->view('index',$data);
 }

Body:
Since Your fetching single record so no need foreach here simple do like this

<?php if(isset($profile_details[0]['upload'])) { ?>
      <img src="<?php echo $profile_details[0]['upload'];?>" alt="profile image" >
<?php } ?>

and

 <div class="form_but1">
     <label class="col-sm-3 control-label1" for="Relation">Name : </label>
         <div class="col-sm-9 w3_details">
               <?php if(isset($profile_details[0]['Name'])) {
                            echo $profile_details[0]['Name'];
                 } ?>
          </div>
          <div class="clearfix"> </div>
        </div>


问:
How to know how many pixels were scrolled in RecyclerView?
I have a RecyclerView that contains different child views.

Then user scrolls it.

I want to know exactly how many pixels user scrolled in comparison with the beginning state.

In other words, I want to know exactly the distance (in pixels) from current content of screen and the first item of RecyclerView.

I see RecyclerView has a method computeVerticalScrollOffset. But that method returns wrong value.

答:
It's possible with OnScrollListener. Override onScroll() method, and its arguments are the distance scrolled by horizontal or vertical axis.

But there are few problems. This passes not the final scroll value, but many values, u have to summarize until the state becomes RecyclerView.SCROLL_STATE_IDLE.

```<code>private class YourOnScrollListener extends RecyclerView.OnScrollListener {

        private int scrollXDistance = 0;
        private int scrollYDistance = 0;

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                Log.d(TAG, "X distance: " + scrollXDistance + " " + "Y distance:" + scrollYDistance);
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            scrollXDistance += dx;
            scrollYDistance += dy;
        }
    }
</code>```

Body:
It's possible with OnScrollListener. Override onScroll() method, and its arguments are the distance scrolled by horizontal or vertical axis.

But there are few problems. This passes not the final scroll value, but many values, u have to summarize until the state becomes RecyclerView.SCROLL_STATE_IDLE.

private class YourOnScrollListener extends RecyclerView.OnScrollListener {

        private int scrollXDistance = 0;
        private int scrollYDistance = 0;

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                Log.d(TAG, "X distance: " + scrollXDistance + " " + "Y distance:" + scrollYDistance);
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            scrollXDistance += dx;
            scrollYDistance += dy;
        }
    }


问:
Selected Option to none value is not working
I am having a Select input field in html page.In a if block a condition should work.

```<code><select id='selectopt'>
  <option value="">Select<option>
  <option value="1">1<option>
</select>

<input type="text" id='text1'>

if($('#text1').val==='name'){
    $("#selectopt option[value='']").attr('selected', true);
}
else{
}
</code>```

when i put this condition inside if its working in chrome and IE but not working in firefox..

答:
You're comparing a jquery object against a string

```<code>$('#text1') === 'name'
</code>```

Maybe you want to compare the value of this object?

```<code>$('#text1').val() === 'name'
</code>```

You could also simplify setting the dropdown value by:

$("#selectopt").val("")

Body:
I am having a Select input field in html page.In a if block a condition should work.

<select id='selectopt'>
  <option value="">Select<option>
  <option value="1">1<option>
</select>

<input type="text" id='text1'>

if($('#text1').val==='name'){
    $("#selectopt option[value='']").attr('selected', true);
}
else{
}

when i put this condition inside if its working in chrome and IE but not working in firefox..

Body:
You're comparing a jquery object against a string

$('#text1') === 'name'

Maybe you want to compare the value of this object?

$('#text1').val() === 'name'

You could also simplify setting the dropdown value by:

$("#selectopt").val("")


问:
Change default rule type in SonarQube 6.4
Is there a way to change the type for rules existing in SonarQube 6.4 (not custom rules). For example, can I change an existing rule from a bug to a vulnerability or a code smell etc.. ?

Thanks in advance

答: Sorry, rule type is not settable, although as @Simon pointed out, you can change the type of an issue.</p>


问:
Multiple-File Template Implementation
With normal functions, the declaration and definition are often separated across multiple files like so:

```<code>// Foo.h

namespace Foo
{
    void Bar();
}
</code>```

.

```<code>// Foo.cpp

#include "Foo.h"

void Foo::Bar()
{
    cout << "Inside function." << endl;
}
</code>```

It is my understanding that this cannot be done with templates.  The declaration and definition must not be separate because the appropriate form of the template is created "on-demand" when needed.

So, how and where are templates typically defined in a multiple-file project like this?  My intuition is that it would be in Foo.cpp because that's where the "meat" of functions normally is, but on the other hand it's the header file that's going to be included.

答:
You need to write definitions of templated methods in a .hxx file and include it at the end of your header file (.hh) in which you declare it. The .cc/.cpp is used to define non-templated methods.

So you'll have one .hh, one .hxx (included at the end of the .hh), and one .cc; so that including your templated class header file will include its definition too.

Example:

```<code>// list.hh
#IFNDEF LIST_HH
# DEFINE LIST_HH

template <typename T>
class List
{
  void fun1(T a);

  void fun2();
}

# include "list.hxx"

#ENDIF

// list.hxx
#IFNDEF LIST_HXX
# DEFINE LIST_HXX

# include "list.hh"

template <typename T>
void List::fun1(T a)
{
   // ...
}

#ENDIF

// list.cc

#include "list.hh"

void List::fun2()
{
   // ...
}

// anywhere.cc

#include "list.hh"

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

EDIT

There are several strategies to compile templates. The most common strategy is the one described above to let every user of the class template instantiate the code.

But, because the *.hh file includes the *.hxx file, each time a simple declaration of a template is needed, the full implementation comes with it. And if the implementation requires other declarations such as std::string, you force all the client code to parse the string header.

To avoid instantiations several times (time and space consuming), you can introduce a fourth type of file, *.hcc: files that must be compiled once for each concrete template parameter.

See Also Compile-Time Dependencies

EDIT2

Writing the template definition directly in the header file is called inclusion model. Doing so increases the cost of including the header. Not only because we added the definition of the template but because we included headers (, , whatever) which represent thousands of lines. A real problem for significant programs to compile (we are talking about hours of compilation here).
The separation model

Source

And my last argument: keep clear the header file so that it only contains the class declaration and its documentation. Like that, any other programmer is able to fastly read your header file: what is the public interface of this class, what does the documentation says.

Title: Multiple-File Template Implementation

Body:
With normal functions, the declaration and definition are often separated across multiple files like so:

// Foo.h

namespace Foo
{
    void Bar();
}

.

// Foo.cpp

#include "Foo.h"

void Foo::Bar()
{
    cout << "Inside function." << endl;
}

It is my understanding that this cannot be done with templates.  The declaration and definition must not be separate because the appropriate form of the template is created "on-demand" when needed.

So, how and where are templates typically defined in a multiple-file project like this?  My intuition is that it would be in Foo.cpp because that's where the "meat" of functions normally is, but on the other hand it's the header file that's going to be included.

Body:
You need to write definitions of templated methods in a .hxx file and include it at the end of your header file (.hh) in which you declare it. The .cc/.cpp is used to define non-templated methods.

So you'll have one .hh, one .hxx (included at the end of the .hh), and one .cc; so that including your templated class header file will include its definition too.

Example:

// list.hh
#IFNDEF LIST_HH
# DEFINE LIST_HH

template <typename T>
class List
{
  void fun1(T a);

  void fun2();
}

# include "list.hxx"

#ENDIF

// list.hxx
#IFNDEF LIST_HXX
# DEFINE LIST_HXX

# include "list.hh"

template <typename T>
void List::fun1(T a)
{
   // ...
}

#ENDIF

// list.cc

#include "list.hh"

void List::fun2()
{
   // ...
}

// anywhere.cc

#include "list.hh"

// ...

EDIT

There are several strategies to compile templates. The most common strategy is the one described above to let every user of the class template instantiate the code.

But, because the *.hh file includes the *.hxx file, each time a simple declaration of a template is needed, the full implementation comes with it. And if the implementation requires other declarations such as std::string, you force all the client code to parse the string header.

To avoid instantiations several times (time and space consuming), you can introduce a fourth type of file, *.hcc: files that must be compiled once for each concrete template parameter.

See Also Compile-Time Dependencies

EDIT2

Writing the template definition directly in the header file is called inclusion model. Doing so increases the cost of including the header. Not only because we added the definition of the template but because we included headers (, , whatever) which represent thousands of lines. A real problem for significant programs to compile (we are talking about hours of compilation here).
The separation model

Source

And my last argument: keep clear the header file so that it only contains the class declaration and its documentation. Like that, any other programmer is able to fastly read your header file: what is the public interface of this class, what does the documentation says.


问:
How to load property file values dynamically in apache camel + spring
I am a newbie using camel 2.17 with spring. I have a processor which receives an error code from a web service and I configured the error description in the property file like

```<code>  myproject.errorCode=1001:error1 description, 1002:error2 description, 1003:....
</code>```

Currently I am reading the value  myproject.errorCode using property injection and parsing all the errorCode with description which is working fine. But the error code list is very huge and maintaining it in a single property is very difficult. So I want to split the properties like

```<code>   myproject.errorCode.1001=error1 description
   myproject.errorCode.1002=error2 description
   myproject.errorCode.1003=error3 description
   .....
</code>```

and I want to read the property in my processor class according to the error code received from the web service like

```<code>  String errorCodeRecieved  = myWebService.getErrorCode();
  String errorString = "myproject.errorCode.";
  String errorDescription = something.getProperty(errorString + errorCodeRecieved);
</code>```

How can I achieve this facility. Thanks in advance

答:
you can make a MessageSource available in your context,

```<code>@Bean
MessageSource myMessageSource() {
    ResourceBundleMessageSource r = new ResourceBundleMessageSource();
    r.setBasenames("/messages/sample");
    r.setDefaultEncoding("UTF-8");
    return r;
}
</code>```

And then use this in your processor to fetch the appropriate message like:

```<code>messageSource.getMessage(code, null, null, locale)
</code>```

Body:
I am a newbie using camel 2.17 with spring. I have a processor which receives an error code from a web service and I configured the error description in the property file like

  myproject.errorCode=1001:error1 description, 1002:error2 description, 1003:....

Currently I am reading the value  myproject.errorCode using property injection and parsing all the errorCode with description which is working fine. But the error code list is very huge and maintaining it in a single property is very difficult. So I want to split the properties like

   myproject.errorCode.1001=error1 description
   myproject.errorCode.1002=error2 description
   myproject.errorCode.1003=error3 description
   .....

and I want to read the property in my processor class according to the error code received from the web service like

  String errorCodeRecieved  = myWebService.getErrorCode();
  String errorString = "myproject.errorCode.";
  String errorDescription = something.getProperty(errorString + errorCodeRecieved);

How can I achieve this facility. Thanks in advance

Body:
you can make a MessageSource available in your context,

@Bean
MessageSource myMessageSource() {
    ResourceBundleMessageSource r = new ResourceBundleMessageSource();
    r.setBasenames("/messages/sample");
    r.setDefaultEncoding("UTF-8");
    return r;
}

And then use this in your processor to fetch the appropriate message like:

messageSource.getMessage(code, null, null, locale)


问:
What is the correct way in reactjs?
I am new to react. In my project, I have a Home Component.

```<code>class Home extends Component {

        logOut(){
            console.log('log out in side home js');
            this.props.LogOutAction();
            localStorage.setItem('loginFlag', null);
        }

        render(){

                return(
                        <div>
                            <Header />
                            <br/>
                            <div className="col-md-12 ">
                                <div className="col-md-3 home-border">
                                        a
                                </div>
                                <div className="col-md-6 home-border">
                                    <User/>

                                </div>
                                <div className="col-md-3 home-border">
                                        c
                                </div>
                            </div>
                        </div>
                )
        }
}
</code>```

And my User component is

```<code>class User extends React.Component {

        viewProfile(id){

        }

        render() {
                var userdetails     =   [   {"id":"1", "name":"Abraham", "country": "USA", "age":"29", "image":""},
                                            {"id":"2", "name":"Gregory", "country": "Canada", "age":"23", "image":""},
                                            {"id":"3", "name":"Mathews", "country": "Newzeland", "age":"24", "image":""},
                                            {"id":"4", "name":"Williamson", "country": "China", "age":"27", "image":""},
                                            {"id":"5", "name":"Edwerd", "country": "Germany", "age":"22", "image":""}
                                ];
                 var myStyle = {
                                      border:"1px solid black",
                                      height:"170px",
                                }

                return(
                        <div>
                            <div>
                                {userdetails.map((data, i) => <div className="col-md-12 div-bottom" style={myStyle} key={i}>

                                        <div  className="col-md-12">
                                            <div className="col-md-12">
                                                <img className="img-thumbnail img-margin" width="150" height="236" src = {'profile.jpg'} />
                                            </div>
                                            <div className="col-md-12 div-bottom"><label>{data.name}</label></div>
                                            <div className="col-md-12 div-bottom">
                                                <div className="col-md-6"><label>age:</label>  {data.age}</div>
                                                <div className="col-md-3"><label>Country:</label> {data.country}</div>
                                            </div>
                                            <div className="col-md-4 .div-bottom"><button className="btn btn-primary" onClick={  () => { this.viewProfile(data.id) } }>view Profile</button></div>
                                        </div>
                                    </div>)
                                }
                            </div>
                        </div>
                )
        }

}
</code>```

I want to show the more user details in place of 'c' in the Home Component on the button click in the User Component.What is the correct method and how it can done?. Thanks in advance..

答:
What does 'a' stand for?

First of all , who does query you user's data?

I think Home must handle server calls, then you need to store that data in the Home component's state, then you need to pass them as props to the User and UserDetails component.

In my opinion Flux or Redux are needed only if your application become really big, and you don't want to have to many server calls during the session.

As a tips, if your User and UserDetails components only need to visualize data you can try to make them 'stateless' (refer to stateless components), in than way you don't need to handle willReceiveProps.

You can Handle 'viewProfile' method in the Home component, calling it from the User component with a callback (passed as a prop)

Title: What is the correct way in reactjs?

Body:
I am new to react. In my project, I have a Home Component.

class Home extends Component {

        logOut(){
            console.log('log out in side home js');
            this.props.LogOutAction();
            localStorage.setItem('loginFlag', null);
        }

        render(){

                return(

                                        a

                                    <User/>

                                        c

                )
        }
}

And my User component is

class User extends React.Component {

        viewProfile(id){

        }

        render() {
                var userdetails     =   [   {"id":"1", "name":"Abraham", "country": "USA", "age":"29", "image":""},
                                            {"id":"2", "name":"Gregory", "country": "Canada", "age":"23", "image":""},
                                            {"id":"3", "name":"Mathews", "country": "Newzeland", "age":"24", "image":""},
                                            {"id":"4", "name":"Williamson", "country": "China", "age":"27", "image":""},
                                            {"id":"5", "name":"Edwerd", "country": "Germany", "age":"22", "image":""}
                                ];
                 var myStyle = {
                                      border:"1px solid black",
                                      height:"170px",
                                }

                return(

                                {userdetails.map((data, i) =>

{data.name}

age:  {data.age}

Country: {data.country}

<button className="btn btn-primary" onClick={  () => { this.viewProfile(data.id) } }>view Profile</button>

)
                                }

                )
        }

}

I want to show the more user details in place of 'c' in the Home Component on the button click in the User Component.What is the correct method and how it can done?. Thanks in advance..


问:
Issue with deleting items from array in for loop
So I am having a problem with deleting items from an array while in a for loop

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this, 1));
    this.remove();
    console.log(array);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
  </head>
  <body>

    <div>

    </div>

  </body>
</html></code>```

So the problem is that when I click on an item to delete it, it doesn't delete that specific one. No matter which one I click on, it deletes starting from the bottom ("iPhone" to "iPod" to "iPad").

Visually, it deletes the right one but when I go to the console I can see that it deletes from the bottom up. Any help would be so very much appreciated.

答:
please have a look of this to this.innerHTML

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
array.splice(array.indexOf(this.innerHTML), 1);
this.remove();
console.log(array);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
  </head>
  <body>

    <div>

    </div>

  </body>
</html></code>```

Body:
So I am having a problem with deleting items from an array while in a for loop

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this, 1));
    this.remove();
    console.log(array);
  }

}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>

So the problem is that when I click on an item to delete it, it doesn't delete that specific one. No matter which one I click on, it deletes starting from the bottom ("iPhone" to "iPod" to "iPad").

Visually, it deletes the right one but when I go to the console I can see that it deletes from the bottom up. Any help would be so very much appreciated.

Body:
please have a look of this to this.innerHTML

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
array.splice(array.indexOf(this.innerHTML), 1);
this.remove();
console.log(array);
  }

}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
  </head>
  <body>

    <div>

    </div>

  </body>
</html>


问:
The animation scroll to top button does not work
a couple of days ago i started working with my companies website. I saw it was missing something so I decided to make a scroll to top button with animation. I am a noob in programming so i decided to look on the Internet. There I found this example. I literally copied the whole code but it does not work.

the button in the html:

```<code><a href="javascript:" id="return-to-top"><i class="icon-chevron-up"></i></a>
</code>```

and this is the jQuery:

```<code>$(window).scroll(function() {
    if ($(this).scrollTop() >= 50) {
        $('#return-to-top').fadeIn(200);
    } else {
        $('#return-to-top').fadeOut(200);
    }
});
$('#return-to-top').click(function() {
    $('body, html').animate({
        scrollTop : 0
    }, 500);
});
</code>```

I dont know what the problem is because it works on the codepen. Does anyone know how to fix this?

Thanks in advance

答:
You should do something like this :

```<code>$('#return-to-top').click(function(e) {
e.preventDefault();
$('body, html').stop().animate({
    scrollTop : 0
}, 500);
});
</code>```

And first of all, check if you have include jQuery :

```<code><script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
</code>```

Body:
a couple of days ago i started working with my companies website. I saw it was missing something so I decided to make a scroll to top button with animation. I am a noob in programming so i decided to look on the Internet. There I found this example. I literally copied the whole code but it does not work.

the button in the html:

and this is the jQuery:

$(window).scroll(function() {
    if ($(this).scrollTop() >= 50) {
        $('#return-to-top').fadeIn(200);
    } else {
        $('#return-to-top').fadeOut(200);
    }
});
$('#return-to-top').click(function() {
    $('body, html').animate({
        scrollTop : 0
    }, 500);
});

I dont know what the problem is because it works on the codepen. Does anyone know how to fix this?

Thanks in advance

Body:
You should do something like this :

$('#return-to-top').click(function(e) {
e.preventDefault();
$('body, html').stop().animate({
    scrollTop : 0
}, 500);
});

And first of all, check if you have include jQuery :

<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>