问:
How to install or integrate typed.js with angular2/4?
I am trying to integrate typed.js into angular two but it's not working. The text appear alright but there is not animation. I have install jQuery and typed.js but the animation is still not working.

```<code>import { Component } from '@angular/core';
import { Typed } from 'typed.js';
import * as $ from 'jquery/dist/jquery.min.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  public ngOninit() {
    var options = {
    stringsElement: "#typed-strings",
    typeSpeed: 80,
    backDelay: 700,
    backSpeed: 100,
    showCursor: true,
    autoInsertCss: false,
    cursorChar: '|',
    loop: true,
    loopcount: Infinity,
    shuffle: true,
    }

    var typed = new Typed("#typing", options);
  }
}
</code>```

```<code>div id="typed-strings" >
<p>Typed.js is a <strong>JavaScript</strong> library.</p>
<p>It <em>types</em> out sentences.</p>
</div>
<span id="typing"></span>
</code>```

.angular-cli.json
import

```<code>"scripts": [
        "../node_modules/typed.js/lib/typed.min.js",
        "../node_modules/jquery/dist/jquery.min.js"
      ],
</code>```

答:
After install with npm install typed.js

```<code>  ngOnInit() {
    let options = {
      strings: ["Product ", "Web ", "UX/UI"],
      typeSpeed:200,
      backSpeed:10,
      showCursor: true,
      cursorChar: "",
      loop:true
    }

    let typed = new Typed(".typing-element", options);
  }
</code>```

and in html you need to add this only this class

```<code> <h1 class="typing-element"></h1>
</code>```

Body:
I am trying to integrate typed.js into angular two but it's not working. The text appear alright but there is not animation. I have install jQuery and typed.js but the animation is still not working.

import { Component } from '@angular/core';
import { Typed } from 'typed.js';
import * as $ from 'jquery/dist/jquery.min.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  public ngOninit() {
    var options = {
    stringsElement: "#typed-strings",
    typeSpeed: 80,
    backDelay: 700,
    backSpeed: 100,
    showCursor: true,
    autoInsertCss: false,
    cursorChar: '|',
    loop: true,
    loopcount: Infinity,
    shuffle: true,
    }

    var typed = new Typed("#typing", options);
  }
}

div id="typed-strings" >

Typed.js is a JavaScript library.

It types out sentences.

.angular-cli.json
import

"scripts": [
        "../node_modules/typed.js/lib/typed.min.js",
        "../node_modules/jquery/dist/jquery.min.js"
      ],

Body:
After install with npm install typed.js

  ngOnInit() {
    let options = {
      strings: ["Product ", "Web ", "UX/UI"],
      typeSpeed:200,
      backSpeed:10,
      showCursor: true,
      cursorChar: "",
      loop:true
    }

    let typed = new Typed(".typing-element", options);
  }

and in html you need to add this only this class

 <h1 class="typing-element"></h1>


来源: stackexchange

问:
How to specify no ri/rdoc exists for a gem so user doesn't get warning when trying to install
A gem I'm authoring doesn't have any inline ri/rdoc of any kind, so when users gem install it they get warnings when rubygems tries to compile the docs:

```<code>Successfully installed mygem-0.0.1
1 gem installed
Installing ri documentation for mygem-0.0.1...
File not found: lib
</code>```

I'm assuming this is due to it trying to run the ri tool against my app's lib folder which doesn't exist (gem is all binaries). How can I avoid this error? I tried placing dummy files in lib/ but that didn't help.

答:
So there was actually a confusion of issues on this question. I mistakenly assumed the error message about lib was associated with the message before it about the ri install.

This was not the case. The problem was that the default require_paths is ["lib"] which my gem did not have. Resetting the require_paths in my gemspec eliminated the error.

ContentLicense: CC BY-SA 2.5

Body:
A gem I'm authoring doesn't have any inline ri/rdoc of any kind, so when users gem install it they get warnings when rubygems tries to compile the docs:

Successfully installed mygem-0.0.1
1 gem installed
Installing ri documentation for mygem-0.0.1...
File not found: lib

I'm assuming this is due to it trying to run the ri tool against my app's lib folder which doesn't exist (gem is all binaries). How can I avoid this error? I tried placing dummy files in lib/ but that didn't help.


问:
How do we access/manipulate variable names which conflicts with byebug reserved keywords?
How do we access those variable names which conflict with byebug reserved name?

```<code>(byebug) var local
h = {"hierarchyId"=>"59f0b029e4b037ef11a055f7", "level"=>2, ...
self =                   <div class="index_as_table"></div>

(byebug)
</code>```

I want to access variable "h"

but typing h would show up the "help dialog box for byebug"

```<code>(byebug) h

  break      -- Sets breakpoints in the source code
  catch      -- Handles exception catchpoints
  condition  -- Sets conditions on breakpoints
  continue   -- Runs until program ends, hits a breakpoint or reaches a line
  debug      -- Spawns a subdebugger
  delete     -- Deletes breakpoints
  disable    -- Disables breakpoints or displays
  display    -- Evaluates expressions every time the debugger stops
  down       -- Moves to a lower frame in the stack trace
  edit       -- Edits source files
  enable     -- Enables breakpoints or displays
  finish     -- Runs the program until frame returns
  frame      -- Moves to a frame in the call stack
  help       -- Helps you using byebug
  history    -- Shows byebug's history of commands
  info       -- Shows several informations about the program being debugged
  interrupt  -- Interrupts the program
  irb        -- Starts an IRB session
  kill       -- Sends a signal to the current process
  list       -- Lists lines of source code
  method     -- Shows methods of an object, class or module
  next       -- Runs one or more lines of code
  pry        -- Starts a Pry session
  quit       -- Exits byebug
  restart    -- Restarts the debugged program
  save       -- Saves current byebug session to a file
  set        -- Modifies byebug settings
  show       -- Shows byebug settings
  source     -- Restores a previously saved byebug session
  step       -- Steps into blocks or methods one or more times
  thread     -- Commands to manipulate threads
  tracevar   -- Enables tracing of a global variable
  undisplay  -- Stops displaying all or some expressions when program stops
  untracevar -- Stops tracing a global variable
  up         -- Moves to a higher frame in the stack trace
  var        -- Shows variables and its values
  where      -- Displays the backtrace

(byebug)
</code>```

Is there any way to access variables who conflicts with these reserved keyword names. like exclamation prefix in python's pdb? (!h didn't work for byebug)

答:
You can surround it in parentheses:</p>
```<code>[1, 4] in /Users/max/test.rb
   1: require 'byebug'
   2:
   3: byebug
=> 4: false
(byebug) (h = 1)
1
(byebug) (h)
1
(byebug)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How do we access those variable names which conflict with byebug reserved name?

(byebug) var local
h = {"hierarchyId"=>"59f0b029e4b037ef11a055f7", "level"=>2, ...
self =

(byebug)

I want to access variable "h"

but typing h would show up the "help dialog box for byebug"

(byebug) h

  break      -- Sets breakpoints in the source code
  catch      -- Handles exception catchpoints
  condition  -- Sets conditions on breakpoints
  continue   -- Runs until program ends, hits a breakpoint or reaches a line
  debug      -- Spawns a subdebugger
  delete     -- Deletes breakpoints
  disable    -- Disables breakpoints or displays
  display    -- Evaluates expressions every time the debugger stops
  down       -- Moves to a lower frame in the stack trace
  edit       -- Edits source files
  enable     -- Enables breakpoints or displays
  finish     -- Runs the program until frame returns
  frame      -- Moves to a frame in the call stack
  help       -- Helps you using byebug
  history    -- Shows byebug's history of commands
  info       -- Shows several informations about the program being debugged
  interrupt  -- Interrupts the program
  irb        -- Starts an IRB session
  kill       -- Sends a signal to the current process
  list       -- Lists lines of source code
  method     -- Shows methods of an object, class or module
  next       -- Runs one or more lines of code
  pry        -- Starts a Pry session
  quit       -- Exits byebug
  restart    -- Restarts the debugged program
  save       -- Saves current byebug session to a file
  set        -- Modifies byebug settings
  show       -- Shows byebug settings
  source     -- Restores a previously saved byebug session
  step       -- Steps into blocks or methods one or more times
  thread     -- Commands to manipulate threads
  tracevar   -- Enables tracing of a global variable
  undisplay  -- Stops displaying all or some expressions when program stops
  untracevar -- Stops tracing a global variable
  up         -- Moves to a higher frame in the stack trace
  var        -- Shows variables and its values
  where      -- Displays the backtrace

(byebug)

Is there any way to access variables who conflicts with these reserved keyword names. like exclamation prefix in python's pdb? (!h didn't work for byebug)

Body:
You can surround it in parentheses:

[1, 4] in /Users/max/test.rb
   1: require 'byebug'
   2:
   3: byebug
=> 4: false
(byebug) (h = 1)
1
(byebug) (h)
1
(byebug)


问:
Symfony 3.3 Form - EntityType field does not select option
For some unknown reason, the EntityType form field will not display the selected option on submit, even though the name of the column matches and data passes.

I've created a form that I'm using to select some values that will filter a list of products.

```<code><?php namespace AppBundle\Filter;

use AppBundle\Entity\ProductCategory;
use AppBundle\Repository\ProductCategoryRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ProductFilterType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', null, [
                'required'   => false,
                'label'      => 'SKU'
            ])
            ->add('productCategory', EntityType::class,
                array(
                    'class' => ProductCategory::class,
                    'choice_label' => 'name',
                    'choice_value' => 'id',
                    'placeholder' => '',
                    'label_attr' => array('title' => 'Category for this product'),
                    'query_builder' => function (ProductCategoryRepository $v) {
                        return $v->createQueryBuilder('v')
                            ->orderBy('v.name',' ASC');
                    }
                ))
            ->add('name', null, [
                'required'   => false,
            ])
            ->add('description', null, [
                'required'   => false,
            ])

        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'app_bundle_product_filter_type';
    } }
</code>```

The form renders as expected, and it submits a post to the same URL, which filters based on the value received from the request.

That works ok.

However, when the form is re-rendered, the option that was selected before the form filter submission is no longer selected.  All other inputs are repopulating.

I did notice that when I'm working with a form that is bound to an Entity (ie:  Editting and saving the entity) and using the ConfigureOptions method to set the data class, that the EntityType form field works as expected.  However, I need it to work in this case where the overall form is not bound to an Entity.

EDIT:
Doing these steps worked for me...but it seems a bit odd.

Injected entity manager into the form constructor:

```<code>public $em;

public function __construct(EntityManager $em) {
    $this->em = $em;
}
</code>```

Then updated the EntityType form field to get the object based on the array value:

```<code>->add('productCategory', EntityType::class,
            array(
                'class' => ProductCategory::class,
                'choice_label' => 'name',
                'choice_value' => 'id',
                'placeholder' => '',
                'label_attr' => array('title' => 'Category for this product'),
                'data' =>  $this->em->getReference("AppBundle:ProductCategory",
                    isset($options['data']['productCategory']) ? $options['data']['productCategory'] : 0),
                'query_builder' => function (ProductCategoryRepository $v) {
                    return $v->createQueryBuilder('v')
                        ->orderBy('v.name',' ASC');
                }
            ))
</code>```

...

答:
My workaround was like this ...
pass data and entity manager to formType.

```<code>$form = $this->createForm(new xxxType($this->get('doctrine.orm.entity_manager')), xxxEntity, array(
        'method' => 'POST',
        'action' => $this->generateUrl('xxxurl', array('id' => $id)),
        'selectedId' => xxxId,
    ));
</code>```

setDefaultOptions in form Type initialize as an empty array for selectedId

```<code>$resolver->setDefaults(array(
        'data_class' => 'xxx',
        'selectedId' => array()
    ));
</code>```

and in builder

```<code>->add('productCategory', EntityType::class,
            array(
                'class' => ProductCategory::class,
                'choice_label' => 'name',
                'choice_value' => 'id',
                'placeholder' => '',
                'label_attr' => array('title' => 'Category for this product'),
                'query_builder' => function (ProductCategoryRepository $v) {
                    return $v->createQueryBuilder('v')
                        ->orderBy('v.name',' ASC');
                },
                'data'=>$this->em->getReference("xxx",$options['selectedId'])
            ))
</code>```

for more details, you can see this answer Symfony2 Setting a default choice field selection

ContentLicense: CC BY-SA 3.0

Body:
For some unknown reason, the EntityType form field will not display the selected option on submit, even though the name of the column matches and data passes.

I've created a form that I'm using to select some values that will filter a list of products.

<?php namespace AppBundle\Filter;

use AppBundle\Entity\ProductCategory;
use AppBundle\Repository\ProductCategoryRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ProductFilterType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', null, [
                'required'   => false,
                'label'      => 'SKU'
            ])
            ->add('productCategory', EntityType::class,
                array(
                    'class' => ProductCategory::class,
                    'choice_label' => 'name',
                    'choice_value' => 'id',
                    'placeholder' => '',
                    'label_attr' => array('title' => 'Category for this product'),
                    'query_builder' => function (ProductCategoryRepository $v) {
                        return $v->createQueryBuilder('v')
                            ->orderBy('v.name',' ASC');
                    }
                ))
            ->add('name', null, [
                'required'   => false,
            ])
            ->add('description', null, [
                'required'   => false,
            ])

        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'app_bundle_product_filter_type';
    } }

The form renders as expected, and it submits a post to the same URL, which filters based on the value received from the request.

That works ok.

However, when the form is re-rendered, the option that was selected before the form filter submission is no longer selected.  All other inputs are repopulating.

I did notice that when I'm working with a form that is bound to an Entity (ie:  Editting and saving the entity) and using the ConfigureOptions method to set the data class, that the EntityType form field works as expected.  However, I need it to work in this case where the overall form is not bound to an Entity.

EDIT:
Doing these steps worked for me...but it seems a bit odd.

Injected entity manager into the form constructor:

public $em;

public function __construct(EntityManager $em) {
    $this->em = $em;
}

Then updated the EntityType form field to get the object based on the array value:

->add('productCategory', EntityType::class,
            array(
                'class' => ProductCategory::class,
                'choice_label' => 'name',
                'choice_value' => 'id',
                'placeholder' => '',
                'label_attr' => array('title' => 'Category for this product'),
                'data' =>  $this->em->getReference("AppBundle:ProductCategory",
                    isset($options['data']['productCategory']) ? $options['data']['productCategory'] : 0),
                'query_builder' => function (ProductCategoryRepository $v) {
                    return $v->createQueryBuilder('v')
                        ->orderBy('v.name',' ASC');
                }
            ))

...

Body:
My workaround was like this ...
pass data and entity manager to formType.

$form = $this->createForm(new xxxType($this->get('doctrine.orm.entity_manager')), xxxEntity, array(
        'method' => 'POST',
        'action' => $this->generateUrl('xxxurl', array('id' => $id)),
        'selectedId' => xxxId,
    ));

setDefaultOptions in form Type initialize as an empty array for selectedId

$resolver->setDefaults(array(
        'data_class' => 'xxx',
        'selectedId' => array()
    ));

and in builder

->add('productCategory', EntityType::class,
            array(
                'class' => ProductCategory::class,
                'choice_label' => 'name',
                'choice_value' => 'id',
                'placeholder' => '',
                'label_attr' => array('title' => 'Category for this product'),
                'query_builder' => function (ProductCategoryRepository $v) {
                    return $v->createQueryBuilder('v')
                        ->orderBy('v.name',' ASC');
                },
                'data'=>$this->em->getReference("xxx",$options['selectedId'])
            ))

for more details, you can see this answer Symfony2 Setting a default choice field selection


问:
SQL Order by meta table column including ones without meta entry
I am using Laravel Query Builder. But I guess my issue is just SQL related.

I have a responses table and a response_metas table.

Where the response_metas table structure is:

```<code> id   |   response_id    |    name    |    value
-----------------------------------------------------
</code>```

All responses have some meta entries, some have the name=email meta.

Is there a way I can get:

Responses having an email (meta) attached and ordered by this meta. As well as the ones without the name=email meta entry.

I can do a simple join:

```<code>DB::table('responses')
 ->join('response_metas', 'responses.id', '=', 'response_metas.response_id');
 ->where( 'response_metas.name', 'email')
 ->orderBy( 'response_metas.value', 'ASC' )
</code>```

But obviously I am getting only the responses having an email meta. The goal is to get this result first. But also the ones without this meta entry.

Let me know if I can bring any clarification. I have done hours of failed tries using UNION, CASE, Conditions... None worked but I was likely not using them the right way.

Any help is much appreciated.

答:
 If you want all the meta data for responses and ordered like email meta data should appear/sort first and then rest of the meta data then you can use conditional order by

```<code>DB::table('responses')
     ->join('response_metas', 'responses.id', '=', 'response_metas.response_id');
     ->where( 'response_metas.name', 'email')
     ->orderByRaw('response_metas.name = "email" DESC')
     ->orderBy( 'response_metas.value', 'ASC' )
</code>```

The conditional clause if equivalent to below expression

```<code>->orderByRaw('CASE WHEN response_metas.name = "email" THEN 1 ELSE 0 END DESC')
</code>```

To get all the responses either they have/don't have meta data for email you can use left join and put the conditions directly in join part

```<code>DB::table('responses')
    ->leftJoin('response_metas', function ($join) {
                $join->on('responses.id', '=', 'response_metas.response_id')
                     ->where( 'response_metas.name', 'email');
    })
    ->orderByRaw('CASE WHEN response_metas.value IS NOT NULL THEN 1 ELSE 0 END DESC')
    ->orderBy( 'response_metas.value', 'ASC' );
</code>```

Body:
I am using Laravel Query Builder. But I guess my issue is just SQL related.

I have a responses table and a response_metas table.

Where the response_metas table structure is:

 id   |   response_id    |    name    |    value
-----------------------------------------------------

All responses have some meta entries, some have the name=email meta.

Is there a way I can get:

Responses having an email (meta) attached and ordered by this meta. As well as the ones without the name=email meta entry.

I can do a simple join:

DB::table('responses')
 ->join('response_metas', 'responses.id', '=', 'response_metas.response_id');
 ->where( 'response_metas.name', 'email')
 ->orderBy( 'response_metas.value', 'ASC' )

But obviously I am getting only the responses having an email meta. The goal is to get this result first. But also the ones without this meta entry.

Let me know if I can bring any clarification. I have done hours of failed tries using UNION, CASE, Conditions... None worked but I was likely not using them the right way.

Any help is much appreciated.

Body:
 If you want all the meta data for responses and ordered like email meta data should appear/sort first and then rest of the meta data then you can use conditional order by

DB::table('responses')
     ->join('response_metas', 'responses.id', '=', 'response_metas.response_id');
     ->where( 'response_metas.name', 'email')
     ->orderByRaw('response_metas.name = "email" DESC')
     ->orderBy( 'response_metas.value', 'ASC' )

The conditional clause if equivalent to below expression

->orderByRaw('CASE WHEN response_metas.name = "email" THEN 1 ELSE 0 END DESC')

To get all the responses either they have/don't have meta data for email you can use left join and put the conditions directly in join part

DB::table('responses')
    ->leftJoin('response_metas', function ($join) {
                $join->on('responses.id', '=', 'response_metas.response_id')
                     ->where( 'response_metas.name', 'email');
    })
    ->orderByRaw('CASE WHEN response_metas.value IS NOT NULL THEN 1 ELSE 0 END DESC')
    ->orderBy( 'response_metas.value', 'ASC' );


问:
Selenium Test - Check if url returns a pdf
I have a selenium test I am creating.  The application creates a pdf for the user.  I want to know how to test that a url returns a pdf file.  I don't really care what is in the pdf, just that one got created.

FYI - The url does not container .pdf

http://www.url.com/printp/something.php?pld=b8eiub9w6ar2am1i

答:
Can you test if //meta[contains(@http-equiv,Content-Type)][contains(@content,pdf)] exists!

I did not test !


问:
select products from specific category codeigniter
Products are available in following categories

```<code>product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5
</code>```

I want to select products of specific category e.g. all products from category 2. what will be sql syntax

答:
You can try this FIND_IN_SET for search comma separated values.

```<code>    <?php
    $this->db->select();
    $this->db->from('table_name');
    $this->db->where(' FIND_IN_SET(category_ids, "' . $category_ids . '") > 0', NULL, false);
    $query = $this->db->get();
    return $query->result();
    ?>
</code>```

I hope it will help.

Body:
Products are available in following categories

product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5

I want to select products of specific category e.g. all products from category 2. what will be sql syntax

Body:
You can try this FIND_IN_SET for search comma separated values.

    <?php
    $this->db->select();
    $this->db->from('table_name');
    $this->db->where(' FIND_IN_SET(category_ids, "' . $category_ids . '") > 0', NULL, false);
    $query = $this->db->get();
    return $query->result();
    ?>

I hope it will help.


问:
window.variableName
I am going through some code and at the beginning of the script we have var emailID = email. Later on, the code refers to emailID by going window.emailID. I am wondering what are the rules that allow you to refer to a variable by going window.variableName?

I cannot post my script online as it is directly related to my work and would violate my contract.

答:
It is used to define global variable in JavaScript.

```<code>globalVar = "Hello World";
function function1(){
    alert(window.globalVar);
}
function1();
</code>```

This will print "Hello World" in the popup.

```<code>    function function1(){
        globalVar = "Hello World";
        alert(window.globalVar);
    }function function2(){
        alert(window.globalVar);
    }
    function1();
    function2();
</code>```

This will create two popups with value "Hello World", one from function1() and another from function2().

So, by using window we can call a variable from any scope in javascript.

Title: window.variableName

Body:
It is used to define global variable in JavaScript.

globalVar = "Hello World";
function function1(){
    alert(window.globalVar);
}
function1();

This will print "Hello World" in the popup.

    function function1(){
        globalVar = "Hello World";
        alert(window.globalVar);
    }function function2(){
        alert(window.globalVar);
    }
    function1();
    function2();

This will create two popups with value "Hello World", one from function1() and another from function2().

So, by using window we can call a variable from any scope in javascript.


问:
How Android deals with high cpu and memory usage
If the memory or CPU usage of an android device is unusually high,will android take any kind of actions in that case? Like killing apps, reboot etc? Is there an in-built service in android that continuously monitors the CPU and memory usage and take necessary actions in case of any abnormal behavior? If available, at what threshold values of memory and cpu usage will it take action? I did perform a thorough google search but couldn't find any answers. I am talking about inbuilt feature of android and not any third party apps.</p>

答:
I quote this from a good article on android processes

Android does a good job of automatically managing these processes, which is why you don’t need a task killer on Android.

When Android needs more system resources, it will start killing the least important processes first. Android will start to kill empty and background processes to free up memory if you’re running low. If you need more memory — for example, if you’re playing a particularly demanding game on a device without much RAM, Android will then start to kill service processes, so your streaming music and file downloads may stop.

In most cases, Android does this all without you needing to worry about it. Android intelligently uses your device’s RAM for caching apps and other data, because there’s no point in leaving your RAM empty.

You should also read the official documentation on memory management by android operating system.

I think this should clear your doubts. Feel free to ask if you have more...


问:
Using celerity to login to saleforce.com on linux (w/ no gui), JS & VB errors
BACKGROUND:
The script below logs into my salesforce.com account and tries to click a bunch of "download" links and save the resulting .zip export files locally.

I'm using jruby and celerity (which is a jruby wrapper around htmlunit, a headless browser, which also supports javascript).

The requirement is that it runs from a LINUX command line without a gui/browser installed. The headless browser also needs to support javascript otherwise salesforce.com returns an error and it will not render the download links. (I tried CURL but it fails since it does not support javascript).
(Currently the script works fine when run from the command line on a WINDOWS box)

QUESTION:
When i try to run this from a linux box, i receive the error below and the script does not appear to login to salesforce. i believe the .js warning is ok (i think), but i don't understand what the VBScript not supported in Window.execScript() warning means?:

```<code>[root@ip-10-114-241-55 ~]# jruby download_sf_export_files.rb
Jan 18, 2011 2:16:41 AM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Expected content type of 'application/javascript' or 'application/ecmascript' for remotely loaded JavaScript element at 'https://www.salesforce.com/common/assets/js/global2.js?date=100817', but got 'application/x-javascript'.
Jan 18, 2011 2:16:41 AM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Expected content type of 'application/javascript' or 'application/ecmascript' for remotely loaded JavaScript element at 'https://www.salesforce.com/common/assets/thirdparty/omniture/s_code3.js?date=101012', but got 'application/x-javascript'.
Jan 18, 2011 2:38:05 AM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Expected content type of 'application/javascript' or 'application/ecmascript' for remotely loaded JavaScript element at 'https://na7.salesforce.com/static/101210/js/functions.js', but got 'application/x-javascript'.
Jan 18, 2011 2:38:06 AM com.gargoylesoftware.htmlunit.javascript.host.Window jsxFunction_execScript
WARNING: VBScript not supported in Window.execScript().

-----install instructions------
download jruby:                 http://jruby.org/download
install gem from command line:  jruby -S gem install celerity
run script from command line:   jruby download_sf_export_files.rb

-----download_sf_export_files.rb-------
require "rubygems"
require "celerity"

browser = Celerity::Browser.new
browser.goto('https://na7.salesforce.com')
browser.text_field(:name, 'username').value = 'myuserlogin@domain.com'
browser.text_field(:name, 'pw').value = 'mysecretpassword'
browser.button(:name, 'Login').click
browser.goto('https://na7.salesforce.com/ui/setup/export/DataExportPage/d')

## assume multiple 'download' links if a large SF data export
## group all links in a map, iterate and click each one

i=1
hrefs = browser.links.map { |link| link.href if link.text =~ /download/ }.compact hrefs.each do |href|
 browser.link(:url, href).download
 puts "found a 'download' link on page, clicking link..."
 io = browser.link(:text, "download").download
 File.open("sf_zip_file_#{i}.zip", "w+") { |file| file.write(io.read) }
 i+=i
end
</code>```

答:
(Copied from question comments just to remove it from "unanswered questions")

Can you try to capture the page Celerity "sees" after your login attempt? Maybe there's some error mentioned, maybe you could examine HTTP header you got back, verify if you have landed on address of Home page... I smell some security settings (machine with black-listed IP or perhaps this screen when you need to receive verification email and click link that comes in with Celerity to set cookie).

Body:
BACKGROUND:
The script below logs into my salesforce.com account and tries to click a bunch of "download" links and save the resulting .zip export files locally.

I'm using jruby and celerity (which is a jruby wrapper around htmlunit, a headless browser, which also supports javascript).

The requirement is that it runs from a LINUX command line without a gui/browser installed. The headless browser also needs to support javascript otherwise salesforce.com returns an error and it will not render the download links. (I tried CURL but it fails since it does not support javascript).
(Currently the script works fine when run from the command line on a WINDOWS box)

QUESTION:
When i try to run this from a linux box, i receive the error below and the script does not appear to login to salesforce. i believe the .js warning is ok (i think), but i don't understand what the VBScript not supported in Window.execScript() warning means?:

[root@ip-10-114-241-55 ~]# jruby download_sf_export_files.rb
Jan 18, 2011 2:16:41 AM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Expected content type of 'application/javascript' or 'application/ecmascript' for remotely loaded JavaScript element at 'https://www.salesforce.com/common/assets/js/global2.js?date=100817', but got 'application/x-javascript'.
Jan 18, 2011 2:16:41 AM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Expected content type of 'application/javascript' or 'application/ecmascript' for remotely loaded JavaScript element at 'https://www.salesforce.com/common/assets/thirdparty/omniture/s_code3.js?date=101012', but got 'application/x-javascript'.
Jan 18, 2011 2:38:05 AM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Expected content type of 'application/javascript' or 'application/ecmascript' for remotely loaded JavaScript element at 'https://na7.salesforce.com/static/101210/js/functions.js', but got 'application/x-javascript'.
Jan 18, 2011 2:38:06 AM com.gargoylesoftware.htmlunit.javascript.host.Window jsxFunction_execScript
WARNING: VBScript not supported in Window.execScript().

-----install instructions------
download jruby:                 http://jruby.org/download
install gem from command line:  jruby -S gem install celerity
run script from command line:   jruby download_sf_export_files.rb

-----download_sf_export_files.rb-------
require "rubygems"
require "celerity"

browser = Celerity::Browser.new
browser.goto('https://na7.salesforce.com')
browser.text_field(:name, 'username').value = 'myuserlogin@domain.com'
browser.text_field(:name, 'pw').value = 'mysecretpassword'
browser.button(:name, 'Login').click
browser.goto('https://na7.salesforce.com/ui/setup/export/DataExportPage/d')

## assume multiple 'download' links if a large SF data export
## group all links in a map, iterate and click each one

i=1
hrefs = browser.links.map { |link| link.href if link.text =~ /download/ }.compact hrefs.each do |href|
 browser.link(:url, href).download
 puts "found a 'download' link on page, clicking link..."
 io = browser.link(:text, "download").download
 File.open("sf_zip_file_#{i}.zip", "w+") { |file| file.write(io.read) }
 i+=i
end


问:
Python output file formatting - text
This is my first post so please be gentle, im trying to write two text files generated from some user input, the file "hostname - VLAN_config" is fine, i use that file elsewhere in my code, what i do need however is another file (in this case "hostname - Trunk_config" to be formatted in a certain manner in order to use it for another part of my code.

The below code produces a file that looks like this;
", 1, 2, 3"

but i need it to generate a text file that looks like;
1, 2, 3

```<code>print ('VLANS')
print('-----------------------------------------------')
print(' ')
condition = True
while (condition == True):
    vlan = raw_input('Specify a VLAN id: ')
    name = raw_input('What name for this VLAN: ')
    print(' ')
    with open(hostname + ' - VLAN_config', "ab") as f:
        f.write('vlan ' + vlan)
        f.write('\n')
        f.write('name ' + name)
        f.write('\n')
    with open(hostname + ' - Trunk_config', "ab") as f:
        f.write(', ' + vlan)
    test = raw_input('Would you like to add another? [Y] ')
    if test == (''):
        condition = True
    elif test == ('n'):
        condition = False
    else:
        test = raw_input('Invalid input, more?')
        if test == ('y'):
            condition = True
        elif test == ('n'):
            condition = False
</code>```

any help will be much appreciated!

答:
So the only problem is the first comma? Why don't you add a test to check if you are writing the first value?

Other solution: write ', ' only after the user said they want to add another input.

Title: Python output file formatting - text

Body:
This is my first post so please be gentle, im trying to write two text files generated from some user input, the file "hostname - VLAN_config" is fine, i use that file elsewhere in my code, what i do need however is another file (in this case "hostname - Trunk_config" to be formatted in a certain manner in order to use it for another part of my code.

The below code produces a file that looks like this;
", 1, 2, 3"

but i need it to generate a text file that looks like;
1, 2, 3

print ('VLANS')
print('-----------------------------------------------')
print(' ')
condition = True
while (condition == True):
    vlan = raw_input('Specify a VLAN id: ')
    name = raw_input('What name for this VLAN: ')
    print(' ')
    with open(hostname + ' - VLAN_config', "ab") as f:
        f.write('vlan ' + vlan)
        f.write('\n')
        f.write('name ' + name)
        f.write('\n')
    with open(hostname + ' - Trunk_config', "ab") as f:
        f.write(', ' + vlan)
    test = raw_input('Would you like to add another? [Y] ')
    if test == (''):
        condition = True
    elif test == ('n'):
        condition = False
    else:
        test = raw_input('Invalid input, more?')
        if test == ('y'):
            condition = True
        elif test == ('n'):
            condition = False

any help will be much appreciated!


问:
WPF DataGrid : Avoid Cell selection on RightClick
I am trying to disable the right click in a cell in a WPF DataGrid from selecting it and at the same time I want to bind context menu from my ParentWindow(MFC) so that my overall application will have same ContextMenu

if i do e.Handle=True in previewMouseRightButtonUp then right click event doesnt reach my parentWindow(MFC)

can anyone help me to fix this issue

same issue i have raised in msdn forum

ThankYou

Santhosh Devi

答:
In your DataGrid subscribe to the event

```<code>SelectionChanged += SelectionChangedHandler;
</code>```

and "disable" the selection.

```<code>void SelectionChangedHandler(object sender, SelectionChangedEventArgs e)
{
    UnselectAllCells();
}
</code>```

Body:
In your DataGrid subscribe to the event

SelectionChanged += SelectionChangedHandler;

and "disable" the selection.

void SelectionChangedHandler(object sender, SelectionChangedEventArgs e)
{
    UnselectAllCells();
}


问:
How to apply expiry times to keys in HTML5 indexeddb?
In indexedDB in html5 api, I can use it to store key-value pairs. But how can I make sure that after adding a certain key-value, after 1 day, that key should automatically be deleted from the db.

I was thinking of wrapping the value in an object with current datetime, and expiry time, and when u get the value, check the time difference, but is this the best way?

Thanks

答:
I wrote a npm module sometime back which expires indexedDB keys after x mins. Also it has very simple api (similar to memcache/localstorage) and is suited for use as a key-value store.

You can check it on npm here .


问:
Re-creating a python invocation
Is it possible to patch together a copy-and-pastable invocation for a python program from the invoked program itself? It doesn't have to be exactly the same invocation string, but the arguments should parse to the same thing.

Note that ' '.join(sys.argv) won't cut it, unfortunately. The main problem I have with this approach is that it won't properly quote arguments. Consider dummy.py with import sys; print(sys.argv); print(' '.join(sys.argv))

Running python dummy.py "1 2" prints:

```<code>['dummy.py', '1 2']
dummy.py 1 2
</code>```

And of course if we copy the latter we'll get a different invocation. Wrapping each argument in quotes won't work either. Consider dummy2.py:

```<code>import sys
print(sys.argv)
print(' '.join('"{}"'.format(s) for s in sys.argv))
</code>```

This will break for:

```<code>python dummy2.py ' " breaking " '
</code>```

答:
Use shlex.quote:

```<code>import sys
from shlex import quote

print(' '.join(quote(s) for s in sys.argv))
</code>```

in shell:

```<code>python space_in_argv.py "aa bb" ' " breaking " '
</code>```

yields:

```<code>space_in_argv.py 'aa bb' ' " breaking " '
</code>```

you may also want to include sys.executable, see more detail in the doc.

Title: Re-creating a python invocation

Body:
Is it possible to patch together a copy-and-pastable invocation for a python program from the invoked program itself? It doesn't have to be exactly the same invocation string, but the arguments should parse to the same thing.

Note that ' '.join(sys.argv) won't cut it, unfortunately. The main problem I have with this approach is that it won't properly quote arguments. Consider dummy.py with import sys; print(sys.argv); print(' '.join(sys.argv))

Running python dummy.py "1 2" prints:

['dummy.py', '1 2']
dummy.py 1 2

And of course if we copy the latter we'll get a different invocation. Wrapping each argument in quotes won't work either. Consider dummy2.py:

import sys
print(sys.argv)
print(' '.join('"{}"'.format(s) for s in sys.argv))

This will break for:

python dummy2.py ' " breaking " '

Body:
Use shlex.quote:

import sys
from shlex import quote

print(' '.join(quote(s) for s in sys.argv))

in shell:

python space_in_argv.py "aa bb" ' " breaking " '

yields:

space_in_argv.py 'aa bb' ' " breaking " '

you may also want to include sys.executable, see more detail in the doc.


问:
Is it possible to use CV_GUI_EXPANDED flag in Python?
I am new to opencv with python. I have used the flag CV_GUI_EXPANDED flag with opencv in c++. But after shifting to python, I am not able to use this flag. Is it not there in python version of opencv?

I am using the opencv available via anaconda and python 3.
Is there any other simple way to view the x, y coordinates and the r,g,b values of the points in a displayed image by hovering the mouse cursor over it, in python (as was possible with the use of the CV_GUI_EXPANDED flag in c++)??

Thank you in advance.

答:
Yes

Look at this documentation:

If you showed code I could apply to your situation, but to answer a general question with a general answer, yes it is possible, CV_GUI_EXPANDED is supported in C, C++ and Python.


问:
Template specialization for enum values
Is it possible to specialize a class method for individual enum values?
Specifically I have an enum and a class as follows:

```<code>#include <iostream>
#include <stdio.h>

using namespace std;

enum class Animal { dog, cat, bird  };
class Sound
{
   public:
      static void getSound ( const Animal& arg )
      {
         switch ( arg )
         {
           case Animal::dog:
             // dog specific processing
             break;

           case Animal::cat:
             // cat specific processing
             break;

           case Animal::bird:
             // bird specific processing
             break;

           default:
             return;
         }
      }
};
</code>```

I want to specialize getSound function for each of the enum values to get rid of the switch case. Is such template specialization possible?

答:
I don't see why you want to go for specialization. If this example is indicative and your enumnerators are sequential and starting from 0, you can just use a lookup table:

```<code>enum class Animal { dog, cat, bird, count = (bird - dog + 1) };

static std::string getSound ( Animal arg ) // Pass an enumeration by value, it's cheaper
{
  std::array<char const *, static_cast<std::size_t>(Animal::count)> const sound {{
    "bark", "meow", "chirp"
  }};
  return sound.at(static_cast<std::size_t>(arg));
}
</code>```

And that's it. It also replaces the the "unknown" string by an exception being thrown. I feel this is warranted, since a scoped enumeration implies we expect strict checking of the value being passed. And breaking that is an exceptional situation.

Even your edited question can be subjected to a lookup table:

```<code>static void getSound ( Animal arg ) // Pass an enumeration by value, it's cheaper
{
  std::array<std::function<void(void)>,
            static_cast<std::size_t>(Animal::count)> const handler{{
    [] { /*Process for dog*/ },
    [] { /*Process for cat*/ },
    [] { /*Process for bird*/ }
  }};
  handler.at(static_cast<std::size_t>(arg))(); // The last () is invocation
}
</code>```

Title: Template specialization for enum values

Body:
Is it possible to specialize a class method for individual enum values?
Specifically I have an enum and a class as follows:

#include <iostream>
#include <stdio.h>

using namespace std;

enum class Animal { dog, cat, bird  };
class Sound
{
   public:
      static void getSound ( const Animal& arg )
      {
         switch ( arg )
         {
           case Animal::dog:
             // dog specific processing
             break;

           case Animal::cat:
             // cat specific processing
             break;

           case Animal::bird:
             // bird specific processing
             break;

           default:
             return;
         }
      }
};

I want to specialize getSound function for each of the enum values to get rid of the switch case. Is such template specialization possible?

Body:
I don't see why you want to go for specialization. If this example is indicative and your enumnerators are sequential and starting from 0, you can just use a lookup table:

enum class Animal { dog, cat, bird, count = (bird - dog + 1) };

static std::string getSound ( Animal arg ) // Pass an enumeration by value, it's cheaper
{
  std::array<char const *, static_cast<std::size_t>(Animal::count)> const sound {{
    "bark", "meow", "chirp"
  }};
  return sound.at(static_cast<std::size_t>(arg));
}

And that's it. It also replaces the the "unknown" string by an exception being thrown. I feel this is warranted, since a scoped enumeration implies we expect strict checking of the value being passed. And breaking that is an exceptional situation.

Even your edited question can be subjected to a lookup table:

static void getSound ( Animal arg ) // Pass an enumeration by value, it's cheaper
{
  std::array<std::function<void(void)>,
            static_cast<std::size_t>(Animal::count)> const handler{{
    [] { /*Process for dog*/ },
    [] { /*Process for cat*/ },
    [] { /*Process for bird*/ }
  }};
  handler.at(static_cast<std::size_t>(arg))(); // The last () is invocation
}


问:
how to compress image without loosing its quality before uploading to database in php pdo mysql?
I'm presently working in online project..where users upload their images and that images will be first stored in server folder like "uploads" directory...and once the file will moved into that uploads directory..then the path will inserted into the mysql database using mysql query.
But the problem is..the images takes longer time to load on webpage...i want to reduce the image size before uploading into database and server..

here is my code

```<code>$upload_dir = 'user_images/'; // upload directory

        $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

        // valid image extensions
        $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

        // rename uploading image
        $userpic = rand(1000,1000000).".".$imgExt;

        // allow valid image file formats
        if(in_array($imgExt, $valid_extensions)){
            // Check file size '5MB'
            if($imgSize < 1000000){

                move_uploaded_file($tmp_dir,$upload_dir.$userpic);

            }
            else{
                $errMSG = "Sorry, your file is too large.";
            }
        }
        else{
            $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        }
    }
</code>```

And my query looks like..

```<code>if(!isset($errMSG))
    {

        $stmt = $user_home->runQuery("INSERT INTO cam_info (userID,
                                                            cam_name,
                                                cam_model,
                                            pixels,
                                    photoshoot,
                                    cam_rent,
                                    cam_img,
                                    mobile,
                                    state,
                                    address,
                                    upd_date,
                                    code )
                                                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");

        $stmt->bindParam(1,$id);
        $stmt->bindParam(2,$cam_name);
        $stmt->bindParam(3,$modelname);
        $stmt->bindParam(4,$pixel);
        $stmt->bindParam(5,$photoshoot);
        $stmt->bindParam(6,$rentpday);
        $stmt->bindParam(7,$userpic);
        $stmt->bindParam(8,$usermob);
        $stmt->bindParam(9,$state);
        $stmt->bindParam(10,$useraddrs);
        $stmt->bindParam(11,$upd_date);
        $stmt->bindParam(12,$ucode);

        if($stmt->execute())
        {

            $successMSG = "Record saved success";
        }
        else
        {
            $errMSG = "error while inserting....";
        }
</code>```

答:
Generally speaking it is not good idea to upload images into the database - the database will grow up very rapidly and may leads to performance and maintain issues in the future.

Use database to keep the metadata about the pictures and keep the images on file system.

Body:
I'm presently working in online project..where users upload their images and that images will be first stored in server folder like "uploads" directory...and once the file will moved into that uploads directory..then the path will inserted into the mysql database using mysql query.
But the problem is..the images takes longer time to load on webpage...i want to reduce the image size before uploading into database and server..

here is my code

$upload_dir = 'user_images/'; // upload directory

        $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

        // valid image extensions
        $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

        // rename uploading image
        $userpic = rand(1000,1000000).".".$imgExt;

        // allow valid image file formats
        if(in_array($imgExt, $valid_extensions)){
            // Check file size '5MB'
            if($imgSize < 1000000){

                move_uploaded_file($tmp_dir,$upload_dir.$userpic);

            }
            else{
                $errMSG = "Sorry, your file is too large.";
            }
        }
        else{
            $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        }
    }

And my query looks like..

if(!isset($errMSG))
    {

        $stmt = $user_home->runQuery("INSERT INTO cam_info (userID,
                                                            cam_name,
                                                cam_model,
                                            pixels,
                                    photoshoot,
                                    cam_rent,
                                    cam_img,
                                    mobile,
                                    state,
                                    address,
                                    upd_date,
                                    code )
                                                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");

        $stmt->bindParam(1,$id);
        $stmt->bindParam(2,$cam_name);
        $stmt->bindParam(3,$modelname);
        $stmt->bindParam(4,$pixel);
        $stmt->bindParam(5,$photoshoot);
        $stmt->bindParam(6,$rentpday);
        $stmt->bindParam(7,$userpic);
        $stmt->bindParam(8,$usermob);
        $stmt->bindParam(9,$state);
        $stmt->bindParam(10,$useraddrs);
        $stmt->bindParam(11,$upd_date);
        $stmt->bindParam(12,$ucode);

        if($stmt->execute())
        {

            $successMSG = "Record saved success";
        }
        else
        {
            $errMSG = "error while inserting....";
        }


问:
mappings on vim throwing an error (E10: \ should be followed by /, ? or &)
Hi I'm using MacVim 7.3
I'm following a PeepCode tutorial called smash into vim.

One of the topics is to assign various "mappings" (I think of them as shortcuts or aliases) for certain commands.

For example, here is part of my .vimrc file (see below)
The help files say that  is assigned as backslash (\) by default.  However, when I enter command-line mode and type :\tt I get the following error:

E10: \ should be followed by /, ? or &

Any thoughts on what I'm doing wrong?  I can tell that my .vimrc file is being used by macvim b/c I used the file to swap the semi-colon and colon bindings and now ; will cause the editor to enter command-line mode.

```<code>" Tab mappings.
map <leader>tt :tabnew<cr>
map <leader>te :tabedit
map <leader>tc :tabclose<cr>
map <leader>to :tabonly<cr>
map <leader>tn :tabnext<cr>
map <leader>tp :tabprevious<cr>
map <leader>tf :tabfirst<cr>
map <leader>tl :tablast<cr>
map <leader>tm :tabmove

" Controversial...swap colon and semicolon for easier commands
nnoremap ; :
nnoremap : ;

vnoremap ; :
vnoremap : ;
</code>```

答:
When you are mapping something like  <leader>tt it does not work in command mode (invoked using :) but in normal mode.

So all you have to do is to type \tt without : and see what happens : a new tab should open hopefully.

Regarding the use of <leader> in defining a new mapping, the main interest is that, if you are not satisfied with the use of \, you can redefine the  key the following way at the beginning of your .vimrc:

:let mapleader = ","

and you leader key will change in every subsequent mapping command : \tt becomes ,tt

Good luck on your way to become a proficient Vim user !

Body:
Hi I'm using MacVim 7.3
I'm following a PeepCode tutorial called smash into vim.

One of the topics is to assign various "mappings" (I think of them as shortcuts or aliases) for certain commands.

For example, here is part of my .vimrc file (see below)
The help files say that  is assigned as backslash (\) by default.  However, when I enter command-line mode and type :\tt I get the following error:

E10: \ should be followed by /, ? or &

Any thoughts on what I'm doing wrong?  I can tell that my .vimrc file is being used by macvim b/c I used the file to swap the semi-colon and colon bindings and now ; will cause the editor to enter command-line mode.

" Tab mappings.
map <leader>tt :tabnew<cr>
map <leader>te :tabedit
map <leader>tc :tabclose<cr>
map <leader>to :tabonly<cr>
map <leader>tn :tabnext<cr>
map <leader>tp :tabprevious<cr>
map <leader>tf :tabfirst<cr>
map <leader>tl :tablast<cr>
map <leader>tm :tabmove

" Controversial...swap colon and semicolon for easier commands
nnoremap ; :
nnoremap : ;

vnoremap ; :
vnoremap : ;


问:
Using REST for CRUD operations in Azure Cosmos DB
I am trying do CRUD operations on Azure Cosmos DB using REST. As per the link-
https://learn.microsoft.com/en-us/rest/api/documentdb/create-a-document
I have created my payload and trying to test it using Restman in Opera browser. Below is my payload details-

Headers

```<code>Authorization       ***************************

Content-Type        application/query+json

x-ms-date           Tue, 05 Dec 2017 16:49:31 GMT

x-ms-session-token  Session

x-ms-version        2017-02-22
</code>```

Body

```<code>id        sg4c828f-31f8-4db4-8e7c-e8bdff222dsg

value     {     "id": "AndersenFamily",     "LastName": "Andersen",     "Parents": [       {         "FamilyName": null,         "FirstName": "Thomas"       },       {         "FamilyName": null,         "FirstName": "Mary Kay"       }     ],     "Children": [       {         "FamilyName": null,         "FirstName": "Henriette Thaulow",         "Gender": "female",         "Grade": 5,         "Pets": [           {             "GivenName": "Fluffy"           }         ]       }     ],     "Address": {       "State": "WA",       "County": "King",       "City": "Seattle"     },     "IsRegistered": true   }
</code>```

The auth-token which is put in the request header has been generated in C# using below code (as per the sample in the link mentioned above)-

```<code>string GenerateAuthToken(string verb, string resourceType, string resourceId, string date, string key, string keyType, string tokenVersion)
{
    var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };

    verb = verb ?? "";
    resourceType = resourceType ?? "";
    resourceId = resourceId ?? "";

    string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
            verb.ToLowerInvariant(),
            resourceType.ToLowerInvariant(),
            resourceId,
            date.ToLowerInvariant(),
            ""
    );

    byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
    string signature = Convert.ToBase64String(hashPayLoad);

    return System.Web.HttpUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
        keyType,
        tokenVersion,
        signature));
}
</code>```

This is how pass the parameters-

```<code>GenerateAuthToken("GET", "dbs", "dbs/ToDoList", "Tue, 05 Dec 2017 16:49:31 GMT", PARENT_KEY, "master", "1.0");
</code>```

So when I make the POST request to the URL-

```<code>https://<account_name>.documents.azure.com:<port>/dbs/DCEAAA==/colls/DCEAAIcEVAA=/docs
</code>```

I get below response-

{
      "code": "Unauthorized",
      "message": "The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol,
  and check the key being used. Server used the following payload to
  sign: 'post\ndocs\ndceaaicevaa=\ntue, 05 dec 2017 16:49:31
  gmt\n\n'\r\nActivityId: 7565996c-d008-438d-a1e9-744d4871948a,
  Microsoft.Azure.Documents.Common/1.19.121.4" }

I am clueless what exactly is going wrong here. Please let me know if someone have any ideas. For any clarifications please let me know.

Edit: Adding the Restman screenshot below-

答:
I follow up you mentioned Document Create Document API, and do a demo to create documentdb document with rest API. You could refer to it. For other operates you could follow the following code and construct the hashed token.

According to the Common Azure Cosmos DB REST request headers, if we want to create a document we need to prepare the Header as following

```<code>Authorization,x-ms-date,Content-Type,x-ms-version
</code>```

We could get the x-m-version from this document. The latest version is  2017-02-22.

We could get the demo code you mentioned from this document,about how to constructing the hashed token signature for a master token please refer to this document. From the document we could know that resourceType could be  "dbs", "colls", "docs". We need to create a document, so resourceType = docs

```<code>var databaseId = "databaseName";
var collectionId = "collectionName";
var datetime = DateTime.UtcNow.ToString("R");
var verb = "post";
var resourceType = "docs"; //
var resourceId = $"dbs/{databaseId}/colls/{collectionId}";
var mastKey = "mastkey value";
var keyType = "master";
var tokenVersion = "1.0";
var authToken = GenerateAuthToken(verb, resourceType, resourceId, datetime, mastKey, keyType, tokenVersion);
</code>```

We also need to get the x-ms-date value from the above mentioned code varible datetime

```<code>Post https://{documentDBAccount}.documents.azure.com:443/dbs/{databaseName}/colls/{collectionId}/docs
</code>```

Update:

Please use the following data as json body

```<code>{
    "id": "sg4c828f-31f8-4db4-8e7c-e8bdff222dsg",
    "value": {
        "id": "AndersenFamily",
        "LastName": "Andersen",
        "Parents": [
            {
                "FamilyName": null,
                "FirstName": "Thomas"
            },
            {
                "FamilyName": null,
                "FirstName": "Mary Kay"
            }
        ],
        "Children": [
            {
                "FamilyName": null,
                "FirstName": "Henriette Thaulow",
                "Gender": "female",
                "Grade": 5,
                "Pets": [
                    {
                        "GivenName": "Fluffy"
                    }
                ]
            }
        ],
        "Address": {
            "State": "WA",
            "County": "King",
            "City": "Seattle"
        },
        "IsRegistered": true
    }
}
</code>```

Body:
I am trying do CRUD operations on Azure Cosmos DB using REST. As per the link-
https://learn.microsoft.com/en-us/rest/api/documentdb/create-a-document
I have created my payload and trying to test it using Restman in Opera browser. Below is my payload details-

Headers

Authorization       ***************************

Content-Type        application/query+json

x-ms-date           Tue, 05 Dec 2017 16:49:31 GMT

x-ms-session-token  Session

x-ms-version        2017-02-22

Body

id        sg4c828f-31f8-4db4-8e7c-e8bdff222dsg

value     {     "id": "AndersenFamily",     "LastName": "Andersen",     "Parents": [       {         "FamilyName": null,         "FirstName": "Thomas"       },       {         "FamilyName": null,         "FirstName": "Mary Kay"       }     ],     "Children": [       {         "FamilyName": null,         "FirstName": "Henriette Thaulow",         "Gender": "female",         "Grade": 5,         "Pets": [           {             "GivenName": "Fluffy"           }         ]       }     ],     "Address": {       "State": "WA",       "County": "King",       "City": "Seattle"     },     "IsRegistered": true   }

The auth-token which is put in the request header has been generated in C# using below code (as per the sample in the link mentioned above)-

string GenerateAuthToken(string verb, string resourceType, string resourceId, string date, string key, string keyType, string tokenVersion)
{
    var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };

    verb = verb ?? "";
    resourceType = resourceType ?? "";
    resourceId = resourceId ?? "";

    string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
            verb.ToLowerInvariant(),
            resourceType.ToLowerInvariant(),
            resourceId,
            date.ToLowerInvariant(),
            ""
    );

    byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
    string signature = Convert.ToBase64String(hashPayLoad);

    return System.Web.HttpUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
        keyType,
        tokenVersion,
        signature));
}

This is how pass the parameters-

GenerateAuthToken("GET", "dbs", "dbs/ToDoList", "Tue, 05 Dec 2017 16:49:31 GMT", PARENT_KEY, "master", "1.0");

So when I make the POST request to the URL-

https://<account_name>.documents.azure.com:<port>/dbs/DCEAAA==/colls/DCEAAIcEVAA=/docs

I get below response-

{
      "code": "Unauthorized",
      "message": "The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol,
  and check the key being used. Server used the following payload to
  sign: 'post\ndocs\ndceaaicevaa=\ntue, 05 dec 2017 16:49:31
  gmt\n\n'\r\nActivityId: 7565996c-d008-438d-a1e9-744d4871948a,
  Microsoft.Azure.Documents.Common/1.19.121.4" }

I am clueless what exactly is going wrong here. Please let me know if someone have any ideas. For any clarifications please let me know.

Edit: Adding the Restman screenshot below-

Body:
I follow up you mentioned Document Create Document API, and do a demo to create documentdb document with rest API. You could refer to it. For other operates you could follow the following code and construct the hashed token.

According to the Common Azure Cosmos DB REST request headers, if we want to create a document we need to prepare the Header as following

Authorization,x-ms-date,Content-Type,x-ms-version

We could get the x-m-version from this document. The latest version is  2017-02-22.

We could get the demo code you mentioned from this document,about how to constructing the hashed token signature for a master token please refer to this document. From the document we could know that resourceType could be  "dbs", "colls", "docs". We need to create a document, so resourceType = docs

var databaseId = "databaseName";
var collectionId = "collectionName";
var datetime = DateTime.UtcNow.ToString("R");
var verb = "post";
var resourceType = "docs"; //
var resourceId = $"dbs/{databaseId}/colls/{collectionId}";
var mastKey = "mastkey value";
var keyType = "master";
var tokenVersion = "1.0";
var authToken = GenerateAuthToken(verb, resourceType, resourceId, datetime, mastKey, keyType, tokenVersion);

We also need to get the x-ms-date value from the above mentioned code varible datetime

Post https://{documentDBAccount}.documents.azure.com:443/dbs/{databaseName}/colls/{collectionId}/docs

Update:

Please use the following data as json body

{
    "id": "sg4c828f-31f8-4db4-8e7c-e8bdff222dsg",
    "value": {
        "id": "AndersenFamily",
        "LastName": "Andersen",
        "Parents": [
            {
                "FamilyName": null,
                "FirstName": "Thomas"
            },
            {
                "FamilyName": null,
                "FirstName": "Mary Kay"
            }
        ],
        "Children": [
            {
                "FamilyName": null,
                "FirstName": "Henriette Thaulow",
                "Gender": "female",
                "Grade": 5,
                "Pets": [
                    {
                        "GivenName": "Fluffy"
                    }
                ]
            }
        ],
        "Address": {
            "State": "WA",
            "County": "King",
            "City": "Seattle"
        },
        "IsRegistered": true
    }
}


问:
Pandas scraped data not working in pandas
Why is when I enter data manually into an excel, pandas works.  Yet when I scrape data, put it in to a csv.  It gives me:

```<code>    zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
ValueError: operands could not be broadcast together with shapes (148,) (537,) ()
</code>```

It has not occurred for other sites.  Am I missing something obvious here?  Is the excel formatted incorrectly or the data is different here somehow?

df3

```<code>df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])
</code>```

df1

```<code>                                         EW    WE  \
0             Ponte Preta U20 v Cruzeiro U20  2.10
1  Fluminense RJ U20 v Defensor Sporting U20  2.00
2              Gremio RS U20 v Palmeiras U20  3.30
3                       Barcelona v Sporting  1.33

                                                  DA
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
</code>```

Code:

```<code>df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

df3['DAT'] = df2['AA']

zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
print(zz)
</code>```

I have provided all my scripts that create the dataframe 1, 2 and the pandas code up until where it creates the error here

I keep getting

Error:

```<code>    zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
ValueError: operands could not be broadcast together with shapes (0,) (4,) ()
</code>```

Error files created from scrape and loaded as a dataframe:

In case that is not sufficient I have also loaded up the files as they are.

File 1, File 2

Working files created manually:

Working:

File 1, File 2

Any idea how this can be fixed?

答:
Ok, let's get back to the drawing board. The code above is cleaner, but does exactly the same you're doing with numpy. Lets split your code apart.

1) I highly recommend you to use jupyter / jupyter notebooks to play with the data and understand what is going on at each line. Take a look here, for example:
https://gist.github.com/Casyfill/f432966ebabd93f4271e27a1e2e76579

So, your df1 has 100 rows and 3 columns. your df2 has 42 rows and 5 columns.

Now, you create df3 as an empty dataframe (0 rows) but 12 columns (by the way, perhaps you should use more explanatory column names). This step is totally fine, while you don't have to define all columns beforehand.

Lets go to the second line:
df3['DAT'] = df2['AA']

here you basically copy the column  from the second dataframe. Now, as we didn't have any rows in df3 before, it is totaly legitimate operation. By doing that, you create 42 rows in your df3. Again, this line by itself is fine.

now, last line. here the logic is the following: first, for each row in df3, we check if cell of df3.AL  (its value) is in df1.EW column. Just note, that we never defined df3.AL before, so the whole column contains only NANs, therefore this by itself does not make any sense.

Next, let's assume there is something in df3.AL. as we check everything row-wise, we'll get a pd.Series (think - one column) of booleans as a result of this test, column with 42 rows. Now, we're trying to use this column as a "mask", which defines if df1.WE should be the same or defaulted to Nan. but you can't do that, because df1 has 100 rows, not 42!. Hense, we've got an error.

So you need to redefine what you're actually want to do here - it's not clear what you're actually need to do here.

Body:
Why is when I enter data manually into an excel, pandas works.  Yet when I scrape data, put it in to a csv.  It gives me:

    zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
ValueError: operands could not be broadcast together with shapes (148,) (537,) ()

It has not occurred for other sites.  Am I missing something obvious here?  Is the excel formatted incorrectly or the data is different here somehow?

df3

df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

df1

                                         EW    WE  \
0             Ponte Preta U20 v Cruzeiro U20  2.10
1  Fluminense RJ U20 v Defensor Sporting U20  2.00
2              Gremio RS U20 v Palmeiras U20  3.30
3                       Barcelona v Sporting  1.33

                                                  DA
0  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
1  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
2  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...
3  https://www.bet365.com.au/#/AC/B1/C1/D13/E40/F...

Code:

df3 = pd.DataFrame(columns=['DAT', 'G', 'TN', 'O1', 'L1', 'TN2', 'O2', 'L2', 'D', 'AJ', 'AK', 'AL'])

df3['DAT'] = df2['AA']

zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
print(zz)

I have provided all my scripts that create the dataframe 1, 2 and the pandas code up until where it creates the error here

I keep getting

Error:

    zz = df1.WE=np.where(df3.AL.isin(df1.EW),df1.WE,np.nan)
ValueError: operands could not be broadcast together with shapes (0,) (4,) ()

Error files created from scrape and loaded as a dataframe:

In case that is not sufficient I have also loaded up the files as they are.

File 1, File 2

Working files created manually:

Working:

File 1, File 2

Any idea how this can be fixed?


问:
How to execute Jenkinsfile with gerrit trigger plugin for changeset in jenkins?
We use gerrit-trigger in Jenkins, the build is triggered when a new changeset is pushed for review.

Now we want to introduce pipeline and use solution Defining a pipeline in scm

Therefore we expect when the build is triggered, below pipeline plugin can work to checkout this refspec

But the ${GERRIT_REFSPEC} doesn't effect here, it checkouts the master still

```
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision adf5d360582b1b24f088cfa8ac0f0ebf64a57692 (refs/remotes/origin/master)
Commit message: "DO:CI End of summer"
 > git config core.sparsecheckout # timeout=10
 > git checkout -f adf5d360582b1b24f088cfa8ac0f0ebf64a57692
```

Any suggestion how it can work?

答:
Or you can use in Jenkins job.

Refspec: ${GERRIT_REFSPEC}

Branch Specifier: FETCH_HEAD.

Body:
We use gerrit-trigger in Jenkins, the build is triggered when a new changeset is pushed for review.

Now we want to introduce pipeline and use solution Defining a pipeline in scm

Therefore we expect when the build is triggered, below pipeline plugin can work to checkout this refspec

But the ${GERRIT_REFSPEC} doesn't effect here, it checkouts the master still

 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision adf5d360582b1b24f088cfa8ac0f0ebf64a57692 (refs/remotes/origin/master)
Commit message: "DO:CI End of summer"
 > git config core.sparsecheckout # timeout=10
 > git checkout -f adf5d360582b1b24f088cfa8ac0f0ebf64a57692

Any suggestion how it can work?


问:
Webpack Module not found: Error: Can't resolve
I am trying to migrate my project to webpack, but I've been struggling a lot with this issue:

```<code>ERROR in ./app/app.component.ts
Module not found: Error: Can't resolve '@common' in
 @ ./app/app.component.ts 16:16-34
 @ ./app/app.module.ts
 @ ./app/main.ts
</code>```

I have a custom library that I want to include in my build, this library was created with typescript and AMD modules. I'm also using an index file to re-export stuff and the import everything with something like:

```<code>import { a,b,c,d,e,f,g } from '@common'
</code>```

I have the following project structure:

```<code>--app/
---dir1/
---app.module.ts
---app.component.ts
---main.ts
--scripts/
---_app/
----common.d.ts
----common.js
--webpack.config.js
--tsconfig.js
</code>```

My webpack.config:

```<code>entry: {
        vendor: './src/vendor',
        //util: './scripts/_app/util.js',
        //common: './scripts/_app/common.js',
        app: './app/main'
    },
output: {
        filename: "[name].js",
        path: __dirname + "/dist",
        // Making sure the CSS and JS files that are split out do not break the template cshtml.
        publicPath: "/dist/",
        // Defining a global var that can used to call functions from within ASP.NET Razor pages.
        library: "app",
        libraryTarget: "var"
    },
 resolve: {
        // Add ".ts" and ".tsx" as resolvable extensions.
        extensions: [".js", ".tsx", ".ts", ".json", ".html"],
        modules: [
            path.resolve('.'),
            path.join(__dirname, "./scripts/_app"),
            path.resolve('./node_modules')
        ]
    },
    module: {
        loaders: [
            // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            {
                test: /\.tsx?$/,
                loader: 'ts-loader'
    },
</code>```

main.ts

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

import { LayoutComponent } from 'app/_layout/LayoutComponent';
import { ClientContext } from "@common";

@Component({
    selector: 'app',
    template: `
</code>```

package.json

```<code>{
  "version": "1.0.0",
  "name": "sds",
  "private": true,
  "description": "",
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "4.4.6",
    "@angular/compiler": "4.4.6",
    "@angular/core": "4.4.6",
    "@angular/forms": "4.4.6",
    "@angular/http": "4.4.6",
    "@angular/platform-browser": "4.4.6",
    "@angular/platform-browser-dynamic": "4.4.6",
    "@angular/router": "4.4.6",
    "@angular/animations": "4.4.6",
    "systemjs": "0.19.31",
    "core-js": "2.4.1",
    "rxjs": "5.4.3",
    "zone.js": "0.8.12",
    "font-awesome": "~4.7.0",
    "popper.js": "1.12.5",
    "bootstrap": "4.0.0-beta",
    "@swimlane/ngx-datatable": "9.3.0",
    "@angular/material": "2.0.0-beta.12",
    "@angular/cdk": "2.0.0-beta.12",
    "jquery": "3.2.1",
    "toastr": "2.1.2",
    "typescript": "2.4.1",
    "@types/linq": "latest"
  },
  "devDependencies": {
    "awesome-typescript-loader": "3.2.1",
    "ts-loader": "3.2.0",
    "clean-webpack-plugin": "0.1.17",
    "file-loader": "^0.11.2",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "2.30.1",
    "webpack": "3.8.1",
    "webpack-dev-server": "2.9.3",
    "webpack-merge": "4.1.1",
    "source-map-loader": "^0.2.1",
    "@ng-bootstrap/ng-bootstrap": "1.0.0-beta.4"
  },
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\"  ",
    "build:dev": "webpack --config webpack.dev.js",
    "build:prod": "webpack --config webpack.prod.js"
  },
  "-vs-binding": {
    "BeforeBuild": [
      "build:dev"
    ]
  }
}
</code>```

I tried with ts-loader and awesome-typescript-loader with no luck.

答:
Apparently, web pack doesn't support AMD named modules.

https://github.com/webpack/webpack/issues/6058

There must be a way to let webpack know how to resolve these custom scripts, I just don't know how.

Body:
I am trying to migrate my project to webpack, but I've been struggling a lot with this issue:

ERROR in ./app/app.component.ts
Module not found: Error: Can't resolve '@common' in
 @ ./app/app.component.ts 16:16-34
 @ ./app/app.module.ts
 @ ./app/main.ts

I have a custom library that I want to include in my build, this library was created with typescript and AMD modules. I'm also using an index file to re-export stuff and the import everything with something like:

import { a,b,c,d,e,f,g } from '@common'

I have the following project structure:

--app/
---dir1/
---app.module.ts
---app.component.ts
---main.ts
--scripts/
---_app/
----common.d.ts
----common.js
--webpack.config.js
--tsconfig.js

My webpack.config:

entry: {
        vendor: './src/vendor',
        //util: './scripts/_app/util.js',
        //common: './scripts/_app/common.js',
        app: './app/main'
    },
output: {
        filename: "[name].js",
        path: __dirname + "/dist",
        // Making sure the CSS and JS files that are split out do not break the template cshtml.
        publicPath: "/dist/",
        // Defining a global var that can used to call functions from within ASP.NET Razor pages.
        library: "app",
        libraryTarget: "var"
    },
 resolve: {
        // Add ".ts" and ".tsx" as resolvable extensions.
        extensions: [".js", ".tsx", ".ts", ".json", ".html"],
        modules: [
            path.resolve('.'),
            path.join(__dirname, "./scripts/_app"),
            path.resolve('./node_modules')
        ]
    },
    module: {
        loaders: [
            // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            {
                test: /\.tsx?$/,
                loader: 'ts-loader'
    },

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

app.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

import { LayoutComponent } from 'app/_layout/LayoutComponent';
import { ClientContext } from "@common";

@Component({
    selector: 'app',
    template: `

package.json

{
  "version": "1.0.0",
  "name": "sds",
  "private": true,
  "description": "",
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "4.4.6",
    "@angular/compiler": "4.4.6",
    "@angular/core": "4.4.6",
    "@angular/forms": "4.4.6",
    "@angular/http": "4.4.6",
    "@angular/platform-browser": "4.4.6",
    "@angular/platform-browser-dynamic": "4.4.6",
    "@angular/router": "4.4.6",
    "@angular/animations": "4.4.6",
    "systemjs": "0.19.31",
    "core-js": "2.4.1",
    "rxjs": "5.4.3",
    "zone.js": "0.8.12",
    "font-awesome": "~4.7.0",
    "popper.js": "1.12.5",
    "bootstrap": "4.0.0-beta",
    "@swimlane/ngx-datatable": "9.3.0",
    "@angular/material": "2.0.0-beta.12",
    "@angular/cdk": "2.0.0-beta.12",
    "jquery": "3.2.1",
    "toastr": "2.1.2",
    "typescript": "2.4.1",
    "@types/linq": "latest"
  },
  "devDependencies": {
    "awesome-typescript-loader": "3.2.1",
    "ts-loader": "3.2.0",
    "clean-webpack-plugin": "0.1.17",
    "file-loader": "^0.11.2",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "2.30.1",
    "webpack": "3.8.1",
    "webpack-dev-server": "2.9.3",
    "webpack-merge": "4.1.1",
    "source-map-loader": "^0.2.1",
    "@ng-bootstrap/ng-bootstrap": "1.0.0-beta.4"
  },
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\"  ",
    "build:dev": "webpack --config webpack.dev.js",
    "build:prod": "webpack --config webpack.prod.js"
  },
  "-vs-binding": {
    "BeforeBuild": [
      "build:dev"
    ]
  }
}

I tried with ts-loader and awesome-typescript-loader with no luck.


问:
Rotate a rect on canvas on user touch
I tried to check on web a lot about this but couldn't find any solution. I want to rotate a rect whenever a user drags it's bottom-right corner (pointed in the image) and the center of the rotation should be the same as center of the rect.

答:
general approach to determine rotation angle:

```<code>rotation center coordinates xc, yc

on touch (mouse) down:
  check whether touch point is in grab region
  remember coordinates x0, y0
  set flag "InRotation"

on touch move:
  current coordinates x1, y1
  check if (they are in allowed region) and (InRotation is set)
    calculate rotation angle as
       alpha = Math.atan2((x1-xc)*(y0-yc) - (x0-xc)*(y1-yc),
                            (x1-xc)*(x0-xc) + (y0-yc)*(y1-yc))
    redraw image using alpha angle

on touch up:
 clear InRotation flag
 make actions after rotation if needed
</code>```

Note that you have to use rotation center coordinates in affine matrix calculation to properly draw rotated rectangle:

```<code> canvas.save();
 canvas.rotate(alpha, xc, yc);
 canvas.drawRect(.....);
 canvas.restore();
</code>```

Title: Rotate a rect on canvas on user touch

Body:
general approach to determine rotation angle:

rotation center coordinates xc, yc

on touch (mouse) down:
  check whether touch point is in grab region
  remember coordinates x0, y0
  set flag "InRotation"

on touch move:
  current coordinates x1, y1
  check if (they are in allowed region) and (InRotation is set)
    calculate rotation angle as
       alpha = Math.atan2((x1-xc)*(y0-yc) - (x0-xc)*(y1-yc),
                            (x1-xc)*(x0-xc) + (y0-yc)*(y1-yc))
    redraw image using alpha angle

on touch up:
 clear InRotation flag
 make actions after rotation if needed

Note that you have to use rotation center coordinates in affine matrix calculation to properly draw rotated rectangle:

 canvas.save();
 canvas.rotate(alpha, xc, yc);
 canvas.drawRect(.....);
 canvas.restore();


问:
How to access only the related model with eager loading
I have these models in my project:

```<code>class User {

    public function favorites()
    {
        return $this->hasMany('App\Favorite');
    }

}
</code>```

-

```<code>class Product {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}
</code>```

-

```<code>class Favorite {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function product()
    {
        return $this->belongsTo('App\Product');
    }

}
</code>```

When I try to get the user's favorites i will do like this:-

```<code>$user = User::find(1);
return $user->favorites;
</code>```

Or with the products in his favorites:-

```<code>return $user->favorites->load('product');
</code>```

But It returns the results from both (products and favorites).

How do I get  the results only from Product model through the Favorite?

Like I want to retrieve only the products that the user added to his favorites?

I already tried to  make this in the User class and it doesn't work:-

```<code>public function favproducts()
{
    return this->hasManyThrough('App\Product', 'App\Favorite');
}
</code>```

Thank you in advance.

答:
Try:</p>

```<code>$user->favorites->product['name']
</code>```

Body:
I have these models in my project:

class User {

    public function favorites()
    {
        return $this->hasMany('App\Favorite');
    }

}

-

class Product {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}

-

class Favorite {

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function product()
    {
        return $this->belongsTo('App\Product');
    }

}

When I try to get the user's favorites i will do like this:-

$user = User::find(1);
return $user->favorites;

Or with the products in his favorites:-

return $user->favorites->load('product');

But It returns the results from both (products and favorites).

How do I get  the results only from Product model through the Favorite?

Like I want to retrieve only the products that the user added to his favorites?

I already tried to  make this in the User class and it doesn't work:-

public function favproducts()
{
    return this->hasManyThrough('App\Product', 'App\Favorite');
}

Thank you in advance.

Body:
Try:

$user->favorites->product['name']


问:
Is there an Objective-c regex replace with callback/C# MatchEvaluator equivalent?
I have a C# project I'm intending to port to Objective-C. From what I understand about Obj-C, it looks like there's a confusing variety of Regex options but I can't see anything about a way of doing a replace with callback.

I'm looking for something that is the equivalent of the C# MatchEvaluator delegate or PHP's preg_replace_callback. An example of what I want to do in C# is -

```<code>// change input so each word is followed a number showing how many letters it has

string inputString = "Hello, how are you today ?";
Regex theRegex = new Regex(@"\w+");

string outputString = theRegex.Replace(inputString, delegate (Match thisMatch){
   return thisMatch.Value + thisMatch.Value.Length;
});

// outputString is now 'Hello5, how3 are3 you3 today5 ?'
</code>```

How could I do this in Objective-C ? In my actual situation the Regex has both lookahead and lookbehind assertions in it though, so any alternative involving finding the strings in advance and then doing a series of straight string replaces won't work unfortunately.

答:
Foundation has a NSRegularExpression class (iOS4 and later), which may be useful to you.  From the docs:

The fundamental matching method for
  NSRegularExpression is a Block
  iterator method that allows clients to
  supply a Block object which will be
  invoked each time the regular
  expression matches a portion of the
  target string. There are additional
  convenience methods for returning all
  the matches as an array, the total
  number of matches, the first match,
  and the range of the first match.

For example:

```<code>NSString *input = @"Hello, how are you today?";

// make a copy of the input string. we are going to edit this one as we iterate
NSMutableString *output = [NSMutableString stringWithString:input];

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
                                regularExpressionWithPattern:@"\\w+"
                                                     options:NSRegularExpressionCaseInsensitive
                                                       error:&error];

// keep track of how many additional characters we've added (1 per iteration)
__block NSUInteger count = 0;

[regex enumerateMatchesInString:input
                        options:0
                          range:NSMakeRange(0, [input length])
                     usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

    // Note that Blocks in Objective C are basically closures
    // so they will keep a constant copy of variables that were in scope
    // when the block was declared
    // unless you prefix the variable with the __block qualifier

    // match.range is a C struct
    // match.range.location is the character offset of the match
    // match.range.length is the length of the match

    NSString *matchedword = [input substringWithRange:match.range];

    // the matched word with the length appended
    NSString *new  = [matchedword stringByAppendingFormat:@"%d", [matchedword length]];

    // every iteration, the output string is getting longer
    // so we need to adjust the range that we are editing
    NSRange newrange = NSMakeRange(match.range.location+count, match.range.length);
    [output replaceCharactersInRange:newrange withString:new];

    count++;
}];
NSLog(@"%@", output); //output: Hello5, how3 are3 you3 today5?
</code>```

Body:
I have a C# project I'm intending to port to Objective-C. From what I understand about Obj-C, it looks like there's a confusing variety of Regex options but I can't see anything about a way of doing a replace with callback.

I'm looking for something that is the equivalent of the C# MatchEvaluator delegate or PHP's preg_replace_callback. An example of what I want to do in C# is -

// change input so each word is followed a number showing how many letters it has

string inputString = "Hello, how are you today ?";
Regex theRegex = new Regex(@"\w+");

string outputString = theRegex.Replace(inputString, delegate (Match thisMatch){
   return thisMatch.Value + thisMatch.Value.Length;
});

// outputString is now 'Hello5, how3 are3 you3 today5 ?'

How could I do this in Objective-C ? In my actual situation the Regex has both lookahead and lookbehind assertions in it though, so any alternative involving finding the strings in advance and then doing a series of straight string replaces won't work unfortunately.

Body:
Foundation has a NSRegularExpression class (iOS4 and later), which may be useful to you.  From the docs:

The fundamental matching method for
  NSRegularExpression is a Block
  iterator method that allows clients to
  supply a Block object which will be
  invoked each time the regular
  expression matches a portion of the
  target string. There are additional
  convenience methods for returning all
  the matches as an array, the total
  number of matches, the first match,
  and the range of the first match.

For example:

NSString *input = @"Hello, how are you today?";

// make a copy of the input string. we are going to edit this one as we iterate
NSMutableString *output = [NSMutableString stringWithString:input];

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
                                regularExpressionWithPattern:@"\\w+"
                                                     options:NSRegularExpressionCaseInsensitive
                                                       error:&error];

// keep track of how many additional characters we've added (1 per iteration)
__block NSUInteger count = 0;

[regex enumerateMatchesInString:input
                        options:0
                          range:NSMakeRange(0, [input length])
                     usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

    // Note that Blocks in Objective C are basically closures
    // so they will keep a constant copy of variables that were in scope
    // when the block was declared
    // unless you prefix the variable with the __block qualifier

    // match.range is a C struct
    // match.range.location is the character offset of the match
    // match.range.length is the length of the match

    NSString *matchedword = [input substringWithRange:match.range];

    // the matched word with the length appended
    NSString *new  = [matchedword stringByAppendingFormat:@"%d", [matchedword length]];

    // every iteration, the output string is getting longer
    // so we need to adjust the range that we are editing
    NSRange newrange = NSMakeRange(match.range.location+count, match.range.length);
    [output replaceCharactersInRange:newrange withString:new];

    count++;
}];
NSLog(@"%@", output); //output: Hello5, how3 are3 you3 today5?


问:
android notification firebase
I send a notification to android through PHP, and it gets normal on android.

But when I send more than one, it only shows the last one, and I wanted it to show all of them.

is it possible?

How can i do this?

PHP

```<code>$msg = array
          (
        'nome'  => $comando,
          );
    $fields = array
            (
                'to'    => $token,
                'data'  => $msg
            );

    $headers = array
            (
                'Content-Type: application/json',
                'Authorization: key= KEY'
            );

#Send Reponse To FireBase Server
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );

#Echo Result Of FireBase Server
echo $result;
</code>```

android

```<code>Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
                        intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder notificationBuilder = new
                        NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setSound(alert)
                        .setContentTitle("teste")
                        .setContentText("teste "+msg+"!")
                        .setAutoCancel(true)
                        .setOnlyAlertOnce(true)
                        .setPriority(2)
                        .setContentIntent(pendingIntent);

                NotificationManager notificationManager =
                        (NotificationManager)
                                getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(1410, notificationBuilder.build());
</code>```

答:
It's easy:

```<code>notificationManager.notify(1410, notificationBuilder.build());
</code>```

you have written '1410', Instead of that assign Unique_Integer_number every time.

To get unique no everytime:

```<code>Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
</code>```

Title: android notification firebase

Body:
I send a notification to android through PHP, and it gets normal on android.

But when I send more than one, it only shows the last one, and I wanted it to show all of them.

is it possible?

How can i do this?

PHP

$msg = array
          (
        'nome'  => $comando,
          );
    $fields = array
            (
                'to'    => $token,
                'data'  => $msg
            );

    $headers = array
            (
                'Content-Type: application/json',
                'Authorization: key= KEY'
            );

#Send Reponse To FireBase Server
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );

#Echo Result Of FireBase Server
echo $result;

android

Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
                        intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder notificationBuilder = new
                        NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setSound(alert)
                        .setContentTitle("teste")
                        .setContentText("teste "+msg+"!")
                        .setAutoCancel(true)
                        .setOnlyAlertOnce(true)
                        .setPriority(2)
                        .setContentIntent(pendingIntent);

                NotificationManager notificationManager =
                        (NotificationManager)
                                getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(1410, notificationBuilder.build());

Body:
It's easy:

notificationManager.notify(1410, notificationBuilder.build());

you have written '1410', Instead of that assign Unique_Integer_number every time.

To get unique no everytime:

Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;


问:
How to publishing to .IPA from VS for Mac
I wanna Publishing .IPA,This step is success,but I cant install in my Iphone via Xcode,that show :

BTW, I can use Xcode with Swift publish .IPA ,and success install it,
but I'm must use Xamarin.

Thanks!

答:
For publishing your application on App store, you need to sign the application using distribution provisioning profile and certificate. By using distribution provisioning profile you can't install your application on device.

If you need to install your application on device please use the development provisioning profile and certificate to sign the application.

For further reference please visit -

XCode 8 A valid provisioning profile for this executable was not found