问:
Persist from Kernel Listener throw EntityManager is closed
I want to persist a Log entity (ip,url,path,user,date...) everytime a URL is requested or served. I'm getting the "EntityManager is closed" error.
I'm looking for a simple solution if possible.
My code is the following:

First the YAML
    services:

```<code>kernelListener:
    class: AppBundle\EventListener\KernelListener
    arguments: [ '@my_logger']
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
        - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
        - { name: kernel.event_listener, event: kernel.terminate, method: onKernelTerminate }
        - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

my_logger:
    class:        AppBundle\Service\Logger
    arguments: ['@doctrine.orm.entity_manager', '@security.token_storage' ]
    scope: prototype
</code>```

Here it's my Logger service:

```<code> namespace AppBundle\Service;
use AppBundle\Entity\Log;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

class Logger {

private $em, $token;
public function __construct(EntityManager $em, TokenStorage $token) {
    $this->em = $em;
    $this->token_storage = $token;
}

public function persist($r) {

    $log = new Log();
    $log->setAjax($r->isXmlHttpRequest());
    $log->setIp($r->getClientIp());
    $log->setMethod($r->getMethod());
    $log->setPath($path);
    $log->setUrl($r->getUri());

    if ($this->token_storage->getToken()) {
        $user = $this->token_storage->getToken()->getUser();
        if ($user instanceof \AppBundle\Entity\User) {
            $log->setUser($user);
        }
    }

    $this->em->persist($log);
    $this->em->flush();
}

}
</code>```

and the KernelListener.php

```<code> namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use AppBundle\Service\Logger;

class KernelListener {

protected $logger;

public function __construct(Logger $logger) {
    $this->logger = $logger;
}

public function onKernelRequest(GetResponseEvent $event) {

}

public function onKernelResponse(FilterResponseEvent $event) {
}

 public function onKernelController(FilterControllerEvent $event) {
    $r = $event->getRequest();
    $this->logger->persist($r);
}

public function onKernelTerminate(PostResponseEvent $event) {
}
}
</code>```

If I remove the flush() no error is thrown, but no Log in the DB logically.

答:
Error EntityManager is closed appears because there were some database-level exceptions. So, logic of entity manager is following: if there was an exception, EntityManager switches to "closed" state and you can't use it anymore.

If you want to use an EntityManager - you need to create a new one. For example, as explained in https://stackoverflow.com/a/19077050/6699227:

```<code>if (!$this->entityManager->isOpen()) {
    $this->entityManager = $this->entityManager->create(
        $this->entityManager->getConnection(),
        $this->entityManager->getConfiguration()
    );
}
</code>```

Another solution for your case could be to create another entity manager, just for writing logs. It will not be used by application itself, so it will never be closed.

Body:
I want to persist a Log entity (ip,url,path,user,date...) everytime a URL is requested or served. I'm getting the "EntityManager is closed" error.
I'm looking for a simple solution if possible.
My code is the following:

First the YAML
    services:

kernelListener:
    class: AppBundle\EventListener\KernelListener
    arguments: [ '@my_logger']
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
        - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
        - { name: kernel.event_listener, event: kernel.terminate, method: onKernelTerminate }
        - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

my_logger:
    class:        AppBundle\Service\Logger
    arguments: ['@doctrine.orm.entity_manager', '@security.token_storage' ]
    scope: prototype

Here it's my Logger service:

 namespace AppBundle\Service;
use AppBundle\Entity\Log;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

class Logger {

private $em, $token;
public function __construct(EntityManager $em, TokenStorage $token) {
    $this->em = $em;
    $this->token_storage = $token;
}

public function persist($r) {

    $log = new Log();
    $log->setAjax($r->isXmlHttpRequest());
    $log->setIp($r->getClientIp());
    $log->setMethod($r->getMethod());
    $log->setPath($path);
    $log->setUrl($r->getUri());

    if ($this->token_storage->getToken()) {
        $user = $this->token_storage->getToken()->getUser();
        if ($user instanceof \AppBundle\Entity\User) {
            $log->setUser($user);
        }
    }

    $this->em->persist($log);
    $this->em->flush();
}

}

and the KernelListener.php

 namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use AppBundle\Service\Logger;

class KernelListener {

protected $logger;

public function __construct(Logger $logger) {
    $this->logger = $logger;
}

public function onKernelRequest(GetResponseEvent $event) {

}

public function onKernelResponse(FilterResponseEvent $event) {
}

 public function onKernelController(FilterControllerEvent $event) {
    $r = $event->getRequest();
    $this->logger->persist($r);
}

public function onKernelTerminate(PostResponseEvent $event) {
}
}

If I remove the flush() no error is thrown, but no Log in the DB logically.

Body:
Error EntityManager is closed appears because there were some database-level exceptions. So, logic of entity manager is following: if there was an exception, EntityManager switches to "closed" state and you can't use it anymore.

If you want to use an EntityManager - you need to create a new one. For example, as explained in https://stackoverflow.com/a/19077050/6699227:

if (!$this->entityManager->isOpen()) {
    $this->entityManager = $this->entityManager->create(
        $this->entityManager->getConnection(),
        $this->entityManager->getConfiguration()
    );
}

Another solution for your case could be to create another entity manager, just for writing logs. It will not be used by application itself, so it will never be closed.


来源: stackexchange

问:
Amchart switch bullet on/off
have some graph with bullet displayed:

my chart is created wit JSON script:

```<code>var chart2 = AmCharts.makeChart("idchart",.....);
</code>```

How to disable bullets with javascript accessing object chart2?

thank you

答:
Just remove the value of bullet on each graphs.</p>

```<code>$.each(chart2.graphs, function(key, value){
    value.bullet = 'none';
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Amchart switch bullet on/off

Body:
have some graph with bullet displayed:

my chart is created wit JSON script:

var chart2 = AmCharts.makeChart("idchart",.....);

How to disable bullets with javascript accessing object chart2?

thank you

Body:
Just remove the value of bullet on each graphs.

$.each(chart2.graphs, function(key, value){
    value.bullet = 'none';
});


问:
PostgreSQL - multiple aggregate queries from the same function call
I have a function that returns a setof from a table:

CREATE OR REPLACE FUNCTION get_assoc_addrs_from_bbl(_bbl text)
RETURNS SETOF wow_bldgs AS $$
  SELECT bldgs.* FROM wow_bldgs AS bldgs
  ...
$$ LANGUAGE SQL STABLE;
```

<p>Here's a sample of what the table would return: </p>

<p><img src="https://i.stack.imgur.com/xsOFx.png" alt="enter image description here"></p>

<p>Now I'm writing an "aggregate" function that will return only one row that with various (aggregated) data points about the table that this function returns. Here is my current working (& naive) example:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
  count(distinct registrationid) as bldgs,
  sum(unitsres) as units,
  round(avg(yearbuilt), 1) as age,
  (SELECT first(corpname) FROM (
    SELECT unnest(corpnames) as corpname
    FROM get_assoc_addrs_from_bbl('3012380016')
    GROUP BY corpname ORDER BY count(*) DESC LIMIT 1
  ) corps) as topcorp,
  (SELECT first(businessaddr) FROM (
    SELECT unnest(businessaddrs) as businessaddr
    FROM get_assoc_addrs_from_bbl('3012380016')
    GROUP BY businessaddr ORDER BY count(*) DESC LIMIT 1
  ) rbas) as topbusinessaddr
FROM get_assoc_addrs_from_bbl('3012380016') assocbldgs
</code>```

As you can see, for the two "subqueries" that require a custom grouping/ordering method, I need to repeat the call to get_assoc_addrs_from_bbl(). Ideally, I'm looking for a structure that would avoid the repeated calls as the function requires a lot of processing and I want the capacity for an arbitrary number of subqueries. I've looked into CTEs and window expressions and the like but no luck.

Any tips? Thank you!

答:
Create simple aggregate function:

```<code>create aggregate array_agg2(anyarray) (
  sfunc=array_cat,
  stype=anyarray);
</code>```

It aggregates array values into one single-dim array. Example:

```<code># with t(x) as (values(array[1,2]),(array[2,3,4])) select array_agg2(x) from t;
┌─────────────┐
│ array_agg2  │
╞═════════════╡
│ {1,2,2,3,4} │
└─────────────┘
</code>```

After that your query could be rewritten as

```<code>SELECT
  count(distinct registrationid) as bldgs,
  sum(unitsres) as units,
  round(avg(yearbuilt), 1) as age,
  (SELECT first(corpname) FROM (
    SELECT * FROM unnest(array_agg2(corpnames)) as corpname
    GROUP BY corpname ORDER BY count(*) DESC LIMIT 1
  ) corps) as topcorp,
  (SELECT first(businessaddr) FROM (
    SELECT * FROM unnest(array_agg2(businessaddrs)) as businessaddr
    GROUP BY businessaddr ORDER BY count(*) DESC LIMIT 1
  ) rbas) as topbusinessaddr
FROM get_assoc_addrs_from_bbl('3012380016') assocbldgs
</code>```

(surely if I understand your goal correctly)

Body:
I have a function that returns a setof from a table:

CREATE OR REPLACE FUNCTION get_assoc_addrs_from_bbl(_bbl text)
RETURNS SETOF wow_bldgs AS $$
  SELECT bldgs.* FROM wow_bldgs AS bldgs
  ...
$$ LANGUAGE SQL STABLE;

Here's a sample of what the table would return:

Now I'm writing an "aggregate" function that will return only one row that with various (aggregated) data points about the table that this function returns. Here is my current working (& naive) example:

SELECT
  count(distinct registrationid) as bldgs,
  sum(unitsres) as units,
  round(avg(yearbuilt), 1) as age,
  (SELECT first(corpname) FROM (
    SELECT unnest(corpnames) as corpname
    FROM get_assoc_addrs_from_bbl('3012380016')
    GROUP BY corpname ORDER BY count(*) DESC LIMIT 1
  ) corps) as topcorp,
  (SELECT first(businessaddr) FROM (
    SELECT unnest(businessaddrs) as businessaddr
    FROM get_assoc_addrs_from_bbl('3012380016')
    GROUP BY businessaddr ORDER BY count(*) DESC LIMIT 1
  ) rbas) as topbusinessaddr
FROM get_assoc_addrs_from_bbl('3012380016') assocbldgs

As you can see, for the two "subqueries" that require a custom grouping/ordering method, I need to repeat the call to get_assoc_addrs_from_bbl(). Ideally, I'm looking for a structure that would avoid the repeated calls as the function requires a lot of processing and I want the capacity for an arbitrary number of subqueries. I've looked into CTEs and window expressions and the like but no luck.

Any tips? Thank you!

Body:
Create simple aggregate function:

create aggregate array_agg2(anyarray) (
  sfunc=array_cat,
  stype=anyarray);

It aggregates array values into one single-dim array. Example:

# with t(x) as (values(array[1,2]),(array[2,3,4])) select array_agg2(x) from t;
┌─────────────┐
│ array_agg2  │
╞═════════════╡
│ {1,2,2,3,4} │
└─────────────┘

After that your query could be rewritten as

SELECT
  count(distinct registrationid) as bldgs,
  sum(unitsres) as units,
  round(avg(yearbuilt), 1) as age,
  (SELECT first(corpname) FROM (
    SELECT * FROM unnest(array_agg2(corpnames)) as corpname
    GROUP BY corpname ORDER BY count(*) DESC LIMIT 1
  ) corps) as topcorp,
  (SELECT first(businessaddr) FROM (
    SELECT * FROM unnest(array_agg2(businessaddrs)) as businessaddr
    GROUP BY businessaddr ORDER BY count(*) DESC LIMIT 1
  ) rbas) as topbusinessaddr
FROM get_assoc_addrs_from_bbl('3012380016') assocbldgs

(surely if I understand your goal correctly)


问:
Concatenation of two hex-decimal addresses (PPN and VPO), forming a physical address
I'm reading about MMU translation and how a CPU can execute a load instruction that reads a byte at an address, leading to it concatenating the PPN from the PTE with the VPO from a virtual address, making a physical address. But I'm not sure how this concatenation is done. This is the paragraph I'm referring to:

To begin, the MMU extracts the VPN ( OxOF) from the virtual address and
  checks with the TLB to see if it has cached a copy of PTE OxOF from some previous
  memory reference. The TLB extracts the TLB index (Ox03) and the TLB tag (Ox03)
  from the VPN, hits on a valid match in the second entry of set Ox3, and returns
  the cached PPN (OxOD) to the MMU.
  If the TLB had missed, then the MMU would need to fetch the PTE from main
  memory. However, in this case, we got lucky and had a TLB hit. The MMU now
  has everything it needs to form the physical address. It does this by concatenating
  the PPN (OxOD) from the PTE with the VPO (Ox14) from the virtual address, which
  forms the physical address (Ox354).

But my question is, how are (0x14) and (0x0d) concatenated? Could someone possibly show me the steps to how this is done?

答:
It's basically

```<code>(0xf << 6) | 0x14 // 0x3d4
</code>```

So you take 6 bits from VPO and prepend it with bits from VPN.

Body:
It's basically

(0xf << 6) | 0x14 // 0x3d4

So you take 6 bits from VPO and prepend it with bits from VPN.


问:
Printing an Array as a String with 10 elements per line
```<code>// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input;
    char userChoice;
    int newVal, index;
    IntegerList intList = null;

    printMenu();

    do {
        System.out.print("Please enter a command or type? ");
        input = scan.nextLine();
        if (input.length() != 0)
            userChoice = input.charAt(0);
        else
            userChoice = ' ';
        switch (userChoice) {
        case 'a':
            System.out.print("How big should the list be? ");
            intList = new IntegerList(scan.nextInt());
            scan.nextLine();
            System.out.print("What is range of the values for each random draw? ");
            intList.randomize(scan.nextInt());
            scan.nextLine();
            break;
        case 'b':
            System.out.println(intList.toStrng());
            break;
</code>```

The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.

```<code>// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {

private int arrSize;

public  IntegerList(int size) {
    size = arrSize;
}

private int[] IntArray = new int[arrSize];

public void randomize (int num) {
    for(int i = 0;i<IntArray.length;i++) {
        IntArray[i] =(int) (Math.random()*(num+1));
    }

}

public void addElement(int newVal, int index) {
    for(int i = index;i<IntArray.length;i++) {
        int temp = IntArray[i];
        IntArray[i]=newVal;
        IntArray[i+1]=temp;
        if(i == IntArray.length){
            increaseSize(IntArray);
        }
    }

}

private static void increaseSize(int[] x) {
    int[] temp = new int[2*x.length];
    for(int i = 0; i<x.length;i++) {
        temp[i]=x[i];
    }
    x = temp;
}

public void removeFirst(int nextInt) {
    // TODO Auto-generated method stub

}

public String range() {
    // TODO Auto-generated method stub
    return null;
}

public String toStrng() {
    String arrayOut = " ";
    for(int i = 0; i<IntArray.length; i++ ) {
    if(i%10 == 0 ) {
        arrayOut+="\n";
    }

    arrayOut += IntArray[i] + " " ;
    }

    return arrayOut;
}

}
</code>```

I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?

答:
You did not initialize your arrSize

You can modify your constructor to initialize arrSize

    public  IntegerList(int size) {
    arrSize = size;
    }

Also, in you toStrng method, you can just make use of arrSize instead of IntArray.length

Body:
// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input;
    char userChoice;
    int newVal, index;
    IntegerList intList = null;

    printMenu();

    do {
        System.out.print("Please enter a command or type? ");
        input = scan.nextLine();
        if (input.length() != 0)
            userChoice = input.charAt(0);
        else
            userChoice = ' ';
        switch (userChoice) {
        case 'a':
            System.out.print("How big should the list be? ");
            intList = new IntegerList(scan.nextInt());
            scan.nextLine();
            System.out.print("What is range of the values for each random draw? ");
            intList.randomize(scan.nextInt());
            scan.nextLine();
            break;
        case 'b':
            System.out.println(intList.toStrng());
            break;

The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.

// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {

private int arrSize;

public  IntegerList(int size) {
    size = arrSize;
}

private int[] IntArray = new int[arrSize];

public void randomize (int num) {
    for(int i = 0;i<IntArray.length;i++) {
        IntArray[i] =(int) (Math.random()*(num+1));
    }

}

public void addElement(int newVal, int index) {
    for(int i = index;i<IntArray.length;i++) {
        int temp = IntArray[i];
        IntArray[i]=newVal;
        IntArray[i+1]=temp;
        if(i == IntArray.length){
            increaseSize(IntArray);
        }
    }

}

private static void increaseSize(int[] x) {
    int[] temp = new int[2*x.length];
    for(int i = 0; i<x.length;i++) {
        temp[i]=x[i];
    }
    x = temp;
}

public void removeFirst(int nextInt) {
    // TODO Auto-generated method stub

}

public String range() {
    // TODO Auto-generated method stub
    return null;
}

public String toStrng() {
    String arrayOut = " ";
    for(int i = 0; i<IntArray.length; i++ ) {
    if(i%10 == 0 ) {
        arrayOut+="\n";
    }

    arrayOut += IntArray[i] + " " ;
    }

    return arrayOut;
}

}

I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?


问:
Open only one activity, without the main activity
I have an application that has one service and 2 activities.One activity (the main one) is a preferences activity and the other one is a dialog themed activity. The service from time to time needs to open only the dialog themed activity (using FLAG_ACTIVITY_NEW_TASK).
The problem is that when the preferences activity is opened in background (for example the user pressed HOME key instead of BACK, so the activity is OnPause) and the service tries to open the dialog themed activity, also the main activity is opened (comes in foreground).
I don't want this. So, how can I open only the themed activity from the service, without the main activity pop up ?

Android Manifest .xml

```<code>    <service android:name=".SimpleService"> </service>
<activity
    android:name=".Preferences" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

           <activity android:name=".popup_activity" android:theme="@android:style/Theme.Dialog" android:label="@string/app_name">
           <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.SAMPLE_CODE" />
           </intent-filter>
           <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="screenon.popup.activity" />
                    <category android:name="android.intent.category.DEFAULT" />
           </intent-filter>
            </activity>
</code>```

And from the service :

```<code>           Intent intent = new Intent(Intent.ACTION_VIEW);
               intent.addCategory("screenon.popup.activity");
               intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

               startActivity(intent);
</code>```

答: I believe you're looking for the android:launchMode attribute. </p>

ContentLicense: CC BY-SA 2.5

Body:
I have an application that has one service and 2 activities.One activity (the main one) is a preferences activity and the other one is a dialog themed activity. The service from time to time needs to open only the dialog themed activity (using FLAG_ACTIVITY_NEW_TASK).
The problem is that when the preferences activity is opened in background (for example the user pressed HOME key instead of BACK, so the activity is OnPause) and the service tries to open the dialog themed activity, also the main activity is opened (comes in foreground).
I don't want this. So, how can I open only the themed activity from the service, without the main activity pop up ?

Android Manifest .xml

    <service android:name=".SimpleService"> </service>
<activity
    android:name=".Preferences" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

           <activity android:name=".popup_activity" android:theme="@android:style/Theme.Dialog" android:label="@string/app_name">
           <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.SAMPLE_CODE" />
           </intent-filter>
           <intent-filter>
                    <action android:name="android.intent.action.VIEW" />
                    <category android:name="screenon.popup.activity" />
                    <category android:name="android.intent.category.DEFAULT" />
           </intent-filter>
            </activity>

And from the service :

           Intent intent = new Intent(Intent.ACTION_VIEW);
               intent.addCategory("screenon.popup.activity");
               intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

               startActivity(intent);


问:
MongoShell: SyntaxError: missing : after property id @(shell):1:137 mongo
Tried to insert in mongoshell from mac terminal:

```<code>    db.recipe.insert({ "_Title": "newname", "_Ingredients":
    "newingredients" , "_Instructions": "newinstructions" ,"
    _Time":1,"_Category": "newcategory", "_Author": "newauthor" ,
    "_RecipeVersion": 1})
</code>```

Gave error:

SyntaxError: missing : after property id @(shell):1:137

Not sure what I'm missing here...

答:
There seems to be unusual spacing in your JSON object - I just formatted this in my code editor, cleaned up the spacing and it worked: </p>

```<code>db.recipe.insert({
  "_Title": "newname",
  "_Ingredients": "newingredients" ,
  "_Instructions": "newinstructions" ,
  "_Time":1,
  "_Category": "newcategory",
  "_Author": "newauthor",
  "_RecipeVersion": 1
})
</code>```

Body:
Tried to insert in mongoshell from mac terminal:

    db.recipe.insert({ "_Title": "newname", "_Ingredients":
    "newingredients" , "_Instructions": "newinstructions" ,"
    _Time":1,"_Category": "newcategory", "_Author": "newauthor" ,
    "_RecipeVersion": 1})

Gave error:

SyntaxError: missing : after property id @(shell):1:137

Not sure what I'm missing here...

Body:
There seems to be unusual spacing in your JSON object - I just formatted this in my code editor, cleaned up the spacing and it worked:

db.recipe.insert({
  "_Title": "newname",
  "_Ingredients": "newingredients" ,
  "_Instructions": "newinstructions" ,
  "_Time":1,
  "_Category": "newcategory",
  "_Author": "newauthor",
  "_RecipeVersion": 1
})


问:
Install opencv on Google App Engine Python 2.7
Hi I installed on a Google App Engine Python 2.7, opencv using

```<code>pip install -t lib -r requirements.txt
</code>```

requirements.txt is:

```<code>Flask==0.12.1
Werkzeug==0.12.2
Opencv_python==3.3.0.10
</code>```

Install worked, I can use other libraries, but when I try to import opencv on code, it throws the next exception:

```<code>  File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "/home/tcarrillof/python-docs-hello-world/main.py", line 23, in <module>
    import cv2
  File "/home/tcarrillof/python-docs-hello-world/lib/cv2/__init__.py", line 6, in <module>
    os.environ["PATH"] += os.pathsep + os.path.dirname(os.path.realpath(__file__))
  File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/request_environment.py", line 126, in __getitem__
    return self._request.environ[key]
KeyError: 'PATH'
</code>```

Is it there something I need to configure?, Any help is welcome in advance :)

Note:

app.yaml is:

```<code>runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /static
  static_dir: static
- url: /.*
  script: main.app
</code>```

and appengine_config.py is:

```<code>import os
from google.appengine.ext import vendor

vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))
</code>```

答:
This is less something you need to configure, and more something to abandon. OpenCV won't run in the standard App Engine environment. OpenCV is a big chunk of C++ (with Python wrappers). App Engine only supports libraries that are pure Python unless they're on the list in  https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27

If you need OpenCV, consider using the Flex environment.

Body:
Hi I installed on a Google App Engine Python 2.7, opencv using

pip install -t lib -r requirements.txt

requirements.txt is:

Flask==0.12.1
Werkzeug==0.12.2
Opencv_python==3.3.0.10

Install worked, I can use other libraries, but when I try to import opencv on code, it throws the next exception:

  File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "/home/tcarrillof/python-docs-hello-world/main.py", line 23, in <module>
    import cv2
  File "/home/tcarrillof/python-docs-hello-world/lib/cv2/__init__.py", line 6, in <module>
    os.environ["PATH"] += os.pathsep + os.path.dirname(os.path.realpath(__file__))
  File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/request_environment.py", line 126, in __getitem__
    return self._request.environ[key]
KeyError: 'PATH'

Is it there something I need to configure?, Any help is welcome in advance :)

Note:

app.yaml is:

runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /static
  static_dir: static
- url: /.*
  script: main.app

and appengine_config.py is:

import os
from google.appengine.ext import vendor

vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'lib'))


问:
DB2 SQL point in time data on a transactional table
I am trying to extract point in time information from a history table.  The table contains fld_nbr which maps to attributes such as job codes, employee status, work location, etc.  How can I find what an employee's status is as of a particular date.  The data might show

```<code>Employee# fld_nbr beg_date value
1234      19      10/1/16  AA
1234      14      10/1/16  40
1234      14      1/6/17   46
1234      19      9/15/17  LA
</code>```

I need to find what the status (fld_nbr 19) and location (fld_nbr 14) was on 1/1/17.  I would expect my result set to be fld_nbr 19 = AA and fld_nbr 14 = 40.

EDIT Here is what I ended up with:

```<code>WITH MO1 AS
(SELECT AFF.AFFILIATE, COUNT(HIS.EMPLOYEE) AS MO1_HC
 FROM
(SELECT HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN A_VALUE END) AS PROCESS_LEVEL,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN BEG_DATE END) AS PL_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN A_VALUE END) AS DEPARTMENT,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN BEG_DATE END) AS DEPT_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN A_VALUE END) AS EMP_STATUS,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN BEG_DATE END) AS STATUS_DATE,
DAYS(DATE('2017-10-31')) - DAYS(EMP.ANNIVERS_DATE) AS DOS
FROM DATAMGMT.VW_GCHRHRHISTORY HIST
INNER JOIN (SELECT EMPLOYEE, FLD_NBR, MAX(BEG_DATE) AS MostRecent
                     FROM DATAMGMT.VW_GCHRHRHISTORY
                     WHERE BEG_DATE < DATE('2017-10-31')
                     AND COMPANY = 207
                     AND FLD_NBR IN (14, 15, 20)
                     GROUP BY EMPLOYEE, FLD_NBR) AS tA ON HIST.EMPLOYEE = tA.EMPLOYEE
                                                           AND HIST.FLD_NBR = tA.FLD_NBR
                                                           AND HIST.BEG_DATE = tA.MostRecent
INNER JOIN DATAMGMT.VW_GCHREMPLOYEE EMP ON HIST.EMPLOYEE = EMP.EMPLOYEE
WHERE EMP.ANNIVERS_DATE BETWEEN DATE('2017-10-31') - 365 DAYS AND DATE('2017-10-31')
AND SUBSTR(HIST.A_VALUE, 1, 1) NOT IN ('T', 'Z')
GROUP BY HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE) AS HIS
INNER JOIN DATAMGMT.VW_GCHRAFFILIATE AFF ON AFF.COMPANY = HIS.COMPANY AND AFF.PROCESS_LEVEL = HIS.PROCESS_LEVEL AND AFF.DEPARTMENT = HIS.DEPARTMENT
WHERE HIS.EMP_STATUS IS NOT NULL
GROUP BY AFF.AFFILIATE),
MO2 AS
(SELECT AFF.AFFILIATE, COUNT(HIS.EMPLOYEE) AS MO2_HC
 FROM
(SELECT HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN A_VALUE END) AS PROCESS_LEVEL,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN BEG_DATE END) AS PL_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN A_VALUE END) AS DEPARTMENT,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN BEG_DATE END) AS DEPT_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN A_VALUE END) AS EMP_STATUS,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN BEG_DATE END) AS STATUS_DATE,
DAYS(DATE('2017-10-31') - 1 MONTH) - DAYS(EMP.ANNIVERS_DATE) AS DOS
FROM DATAMGMT.VW_GCHRHRHISTORY HIST
INNER JOIN (SELECT EMPLOYEE, FLD_NBR, MAX(BEG_DATE) AS MostRecent
                     FROM DATAMGMT.VW_GCHRHRHISTORY
                     WHERE BEG_DATE < DATE('2017-10-31') - 1 MONTH
                     AND COMPANY = 207
                     AND FLD_NBR IN (14, 15, 20)
                     GROUP BY EMPLOYEE, FLD_NBR) AS tA ON HIST.EMPLOYEE = tA.EMPLOYEE
                                                           AND HIST.FLD_NBR = tA.FLD_NBR
                                                           AND HIST.BEG_DATE = tA.MostRecent
INNER JOIN DATAMGMT.VW_GCHREMPLOYEE EMP ON HIST.EMPLOYEE = EMP.EMPLOYEE
WHERE EMP.ANNIVERS_DATE BETWEEN DATE('2017-10-31') - 1 MONTH - 365 DAYS AND DATE('2017-10-31') - 1 MONTH
AND SUBSTR(HIST.A_VALUE, 1, 1) NOT IN ('T', 'Z')
GROUP BY HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE) AS HIS
INNER JOIN DATAMGMT.VW_GCHRAFFILIATE AFF ON AFF.COMPANY = HIS.COMPANY AND AFF.PROCESS_LEVEL = HIS.PROCESS_LEVEL AND AFF.DEPARTMENT = HIS.DEPARTMENT
WHERE HIS.EMP_STATUS IS NOT NULL
GROUP BY AFF.AFFILIATE)
SELECT MO1.AFFILIATE, MO1.MO1_HC, MO2.MO2_HC
FROM MO1
INNER JOIN MO2 ON MO2.AFFILIATE = MO1.AFFILIATE
</code>```

答:
You could try something like this, which will give you the point in time record for each employee/fld_nbr combination (I forget the syntax for DB2 date literals, you might need to play with that):</p>

```<code>SELECT *
FROM tbl INNER JOIN (SELECT Employee#, fld_nbr, MAX(beg_date) AS MostRecent
                     FROM tbl
                     WHERE beg_date < #1/1/17#
                     GROUP BY Employee#, fld_nbr) AS tA ON tbl.Employee# = tA.Employee#
                                                           AND tbl.fld_nbr = tA.fld_nbr
                                                           AND tbl.beg_date = tA.MostRecent
</code>```

Body:
I am trying to extract point in time information from a history table.  The table contains fld_nbr which maps to attributes such as job codes, employee status, work location, etc.  How can I find what an employee's status is as of a particular date.  The data might show

Employee# fld_nbr beg_date value
1234      19      10/1/16  AA
1234      14      10/1/16  40
1234      14      1/6/17   46
1234      19      9/15/17  LA

I need to find what the status (fld_nbr 19) and location (fld_nbr 14) was on 1/1/17.  I would expect my result set to be fld_nbr 19 = AA and fld_nbr 14 = 40.

EDIT Here is what I ended up with:

WITH MO1 AS
(SELECT AFF.AFFILIATE, COUNT(HIS.EMPLOYEE) AS MO1_HC
 FROM
(SELECT HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN A_VALUE END) AS PROCESS_LEVEL,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN BEG_DATE END) AS PL_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN A_VALUE END) AS DEPARTMENT,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN BEG_DATE END) AS DEPT_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN A_VALUE END) AS EMP_STATUS,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN BEG_DATE END) AS STATUS_DATE,
DAYS(DATE('2017-10-31')) - DAYS(EMP.ANNIVERS_DATE) AS DOS
FROM DATAMGMT.VW_GCHRHRHISTORY HIST
INNER JOIN (SELECT EMPLOYEE, FLD_NBR, MAX(BEG_DATE) AS MostRecent
                     FROM DATAMGMT.VW_GCHRHRHISTORY
                     WHERE BEG_DATE < DATE('2017-10-31')
                     AND COMPANY = 207
                     AND FLD_NBR IN (14, 15, 20)
                     GROUP BY EMPLOYEE, FLD_NBR) AS tA ON HIST.EMPLOYEE = tA.EMPLOYEE
                                                           AND HIST.FLD_NBR = tA.FLD_NBR
                                                           AND HIST.BEG_DATE = tA.MostRecent
INNER JOIN DATAMGMT.VW_GCHREMPLOYEE EMP ON HIST.EMPLOYEE = EMP.EMPLOYEE
WHERE EMP.ANNIVERS_DATE BETWEEN DATE('2017-10-31') - 365 DAYS AND DATE('2017-10-31')
AND SUBSTR(HIST.A_VALUE, 1, 1) NOT IN ('T', 'Z')
GROUP BY HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE) AS HIS
INNER JOIN DATAMGMT.VW_GCHRAFFILIATE AFF ON AFF.COMPANY = HIS.COMPANY AND AFF.PROCESS_LEVEL = HIS.PROCESS_LEVEL AND AFF.DEPARTMENT = HIS.DEPARTMENT
WHERE HIS.EMP_STATUS IS NOT NULL
GROUP BY AFF.AFFILIATE),
MO2 AS
(SELECT AFF.AFFILIATE, COUNT(HIS.EMPLOYEE) AS MO2_HC
 FROM
(SELECT HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN A_VALUE END) AS PROCESS_LEVEL,
MAX(CASE WHEN HIST.FLD_NBR = 14 THEN BEG_DATE END) AS PL_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN A_VALUE END) AS DEPARTMENT,
MAX(CASE WHEN HIST.FLD_NBR = 15 THEN BEG_DATE END) AS DEPT_DATE,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN A_VALUE END) AS EMP_STATUS,
MAX(CASE WHEN HIST.FLD_NBR = 20 THEN BEG_DATE END) AS STATUS_DATE,
DAYS(DATE('2017-10-31') - 1 MONTH) - DAYS(EMP.ANNIVERS_DATE) AS DOS
FROM DATAMGMT.VW_GCHRHRHISTORY HIST
INNER JOIN (SELECT EMPLOYEE, FLD_NBR, MAX(BEG_DATE) AS MostRecent
                     FROM DATAMGMT.VW_GCHRHRHISTORY
                     WHERE BEG_DATE < DATE('2017-10-31') - 1 MONTH
                     AND COMPANY = 207
                     AND FLD_NBR IN (14, 15, 20)
                     GROUP BY EMPLOYEE, FLD_NBR) AS tA ON HIST.EMPLOYEE = tA.EMPLOYEE
                                                           AND HIST.FLD_NBR = tA.FLD_NBR
                                                           AND HIST.BEG_DATE = tA.MostRecent
INNER JOIN DATAMGMT.VW_GCHREMPLOYEE EMP ON HIST.EMPLOYEE = EMP.EMPLOYEE
WHERE EMP.ANNIVERS_DATE BETWEEN DATE('2017-10-31') - 1 MONTH - 365 DAYS AND DATE('2017-10-31') - 1 MONTH
AND SUBSTR(HIST.A_VALUE, 1, 1) NOT IN ('T', 'Z')
GROUP BY HIST.COMPANY, HIST.EMPLOYEE, EMP.ANNIVERS_DATE, EMP.TERM_DATE) AS HIS
INNER JOIN DATAMGMT.VW_GCHRAFFILIATE AFF ON AFF.COMPANY = HIS.COMPANY AND AFF.PROCESS_LEVEL = HIS.PROCESS_LEVEL AND AFF.DEPARTMENT = HIS.DEPARTMENT
WHERE HIS.EMP_STATUS IS NOT NULL
GROUP BY AFF.AFFILIATE)
SELECT MO1.AFFILIATE, MO1.MO1_HC, MO2.MO2_HC
FROM MO1
INNER JOIN MO2 ON MO2.AFFILIATE = MO1.AFFILIATE

Body:
You could try something like this, which will give you the point in time record for each employee/fld_nbr combination (I forget the syntax for DB2 date literals, you might need to play with that):

SELECT *
FROM tbl INNER JOIN (SELECT Employee#, fld_nbr, MAX(beg_date) AS MostRecent
                     FROM tbl
                     WHERE beg_date < #1/1/17#
                     GROUP BY Employee#, fld_nbr) AS tA ON tbl.Employee# = tA.Employee#
                                                           AND tbl.fld_nbr = tA.fld_nbr
                                                           AND tbl.beg_date = tA.MostRecent


问:
Is it possible to add a wordpress function call inside another function call?
So I don't know if this is possible, or if there is a workaround, but I need to add a shortcode to my single.php template. However, inside the shortcode, I ideally need to call author meta data so that the shortcode renders the correct information...

It is something like this:

<? php do_shortcode('[form id="<? php the_author_meta( 'authorspecificformid' ); ?>"]') ?>```

I know this doesn't work, but is there a workaround I can do?

答:
you can construct this shortcode like this : </p>

```<code><?php
$authorId = get_the_author_meta("authorspecificformid");
echo do_shortcode("[form id=\"$authorId\"]");
</code>```

Body:
So I don't know if this is possible, or if there is a workaround, but I need to add a shortcode to my single.php template. However, inside the shortcode, I ideally need to call author meta data so that the shortcode renders the correct information...

It is something like this:

<? php do_shortcode('[form id="<? php the_author_meta( 'authorspecificformid' ); ?>"]') ?>

I know this doesn't work, but is there a workaround I can do?

Body:
you can construct this shortcode like this :

<?php
$authorId = get_the_author_meta("authorspecificformid");
echo do_shortcode("[form id=\"$authorId\"]");


问:
Entity Framework CTP5 and Ninject as my IOC
Is it possible in Entity Framework CTP5 to construct retrieved persisted entities via an IOC container?

I'm using Ninject and it's tied in fine with MVC, but I need to inject some services into my domain objects when they are constructed for some business rules.

I'd rather do this using constructor injection than method or property injections.

答:
I'm not sure what, exactly, you're trying to accomplish here, but EF has almost no extensbility points.  The best you can do is hook into the ObjectMaterialized event fired by ObjectContext.  In CTP5, you need to cast your DbContext like so in the constructor for your DbContext:

```<code>((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
    this.ObjectContext_OnObjectMaterialized;
</code>```

And then implement your function ObjectContext_OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e).  You will be able to access your object, which unfortunately has already been materialized.  Depending on your needs, you might be able to hack in some interesting behavior here.

BTW, this sentence makes no sense to me:

I need to inject some repositories into my domain objects when they are constructed for some business rules.

Doesn't this go against Persistence Ignorant Domain Objects?

Body:
I'm not sure what, exactly, you're trying to accomplish here, but EF has almost no extensbility points.  The best you can do is hook into the ObjectMaterialized event fired by ObjectContext.  In CTP5, you need to cast your DbContext like so in the constructor for your DbContext:

((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
    this.ObjectContext_OnObjectMaterialized;

And then implement your function ObjectContext_OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e).  You will be able to access your object, which unfortunately has already been materialized.  Depending on your needs, you might be able to hack in some interesting behavior here.

BTW, this sentence makes no sense to me:

I need to inject some repositories into my domain objects when they are constructed for some business rules.

Doesn't this go against Persistence Ignorant Domain Objects?


问:
How to adjust alpha parameter in gensim LdaModel
I have trained an topic model using a symmetric alpha in my lda distibution:

```<code>model = gensim.models.ldamodel.LdaModel(bows, num_topics = 20, id2word = dictionary, passes = 100)
</code>```

I can see that:

```<code>model.alpha
array([ 0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,
    0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,
    0.05,  0.05])
</code>```

where

```<code>numpy.sum(model.alpha)
1.0000000000000002
</code>```

I can't quite understand how gensim allows for lowering alpha parameter to allow each document to be a mixture of fewer topics?

答:
Looking as the docs

It seems like gensim.models.ldamodel.LdaModel takes an alpha parameter that defaults to 'symmetric'. You can either explicitly provide it an array of alphas, or set it to 'auto' and it will learn the priors from your data.

I suggest trying it with alpha='auto' to let it learn the priors.

Body:
I have trained an topic model using a symmetric alpha in my lda distibution:

model = gensim.models.ldamodel.LdaModel(bows, num_topics = 20, id2word = dictionary, passes = 100)

I can see that:

model.alpha
array([ 0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,
    0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,  0.05,
    0.05,  0.05])

where

numpy.sum(model.alpha)
1.0000000000000002

I can't quite understand how gensim allows for lowering alpha parameter to allow each document to be a mixture of fewer topics?


问:
Accessing an iframe with nightwatch without a fixed id
I have

```<code><div class="ap-content" id="office-addon">
  <div class="ap-iframe-container iframe-init" id="office-addon__5e83ed1">
    <iframe id="office-addon__5e83ed1">
      <!-- As it appears in the dev console: -->
      #document
      <!DOCTYPE html>
        <html>
          <head></head>
          <body>
            <div id="addon"></div>
          </body>
        </html>
    </iframe>
  <div>
<div>
</code>```

I want to access it with nightwatch like so:

```<code>browser
  .waitForElementPresent('#office-addon', 20000);
  .frame('#office-addon iframe')
  .waitForElementPresent('#addon', 1000)
  .end();
</code>```

But it times out waiting for #addon, though #addon is in the browser. How do I have to write the frame() parameters? The iframe id changes with every page build.

答:
If you want to select it by id, you probably ought to try a starts with selector like:

```<code>.frame("iframe[id^='office-addon']")
</code>```

If it's always the nth iframe you can index in

```<code>// select the first iframe
.frame(0)
// go back to the original html content
.frame()
</code>```

Body:
I have

      #document
      <!DOCTYPE html>

I want to access it with nightwatch like so:

browser
  .waitForElementPresent('#office-addon', 20000);
  .frame('#office-addon iframe')
  .waitForElementPresent('#addon', 1000)
  .end();

But it times out waiting for #addon, though #addon is in the browser. How do I have to write the frame() parameters? The iframe id changes with every page build.

Body:
If you want to select it by id, you probably ought to try a starts with selector like:

.frame("iframe[id^='office-addon']")

If it's always the nth iframe you can index in

// select the first iframe
.frame(0)
// go back to the original html content
.frame()


问:
How to compare if a char* is greater than or equal to another string/number?
I'm using scanf to input numbers and +,-,/ operators into a stack.

```<code>int scan = 1;
char * p = malloc(sizeof(char)*5);
while (scan = 1) {
    scanf("%1s", p);
    if(p>='0' && p<='9'){
        push(stack, p);
        print(stack);
    }
}
</code>```

Why does it never meet the condition? How can you compare strings?

答:
Well, if what you want to do is test whether the first character of the string is between '0' and '9', you should do:

```<code>(*p >= '0' && *p <= '9')
</code>```

But if you want to compare strings as strings, the old school C library function for that is strcmp.  I'm sure these days there are lots of other libraries that may offer more functionality.

Body:
I'm using scanf to input numbers and +,-,/ operators into a stack.

int scan = 1;
char * p = malloc(sizeof(char)*5);
while (scan = 1) {
    scanf("%1s", p);
    if(p>='0' && p<='9'){
        push(stack, p);
        print(stack);
    }
}

Why does it never meet the condition? How can you compare strings?

Body:
Well, if what you want to do is test whether the first character of the string is between '0' and '9', you should do:

(*p >= '0' && *p <= '9')

But if you want to compare strings as strings, the old school C library function for that is strcmp.  I'm sure these days there are lots of other libraries that may offer more functionality.


问:
Do Kubernetes pods still receive requests after receiving SIGTERM?
I want to implement graceful shutdown in a Kubernetes Pod. I know I need to listen for SIGTERM, which indicates the start of the shutdown procedure. But what exactly do I do when I receive it?

At the very least I must wait for all running request to finish before exiting. But can the pod still receive new requests after receiving the SIGTERM? (It's exposed using a service.) I can't find any explicit documentation on this.

The docs state:

Pod is removed from endpoints list for service, and are no longer considered part of the set of running pods for replication controllers. Pods that shutdown slowly can continue to serve traffic as load balancers (like the service proxy) remove them from their rotations.

So that seems to imply that new requests can still come in. So how long should I continue to expect new requests before graceful termination? Do I simply ignore the SIGTERM, continue to serve requests as usual and wait for the eventual SIGKILL?

I suppose ensuring future readiness checks fail and then waiting longer than the period with which they occur before terminating might work?

I'm on Kubernetes 1.2.5, if that makes any difference, and am talking about rolling updates in particular, but also scaling replication controllers down generally.

答:
I recently faced similar problem, I used simple preStop hook, which introduces some delay(sleep) between start of termination and receiving SIGTERM to underlying process

```<code>lifecycle:
        preStop:
          exec:
            command:
              - "sleep"
              - "60"
</code>```

This delay helps,

Load balancer to remove(sync) the pod being terminated

Gives chance to terminating pod to complete requests received before termination

Fulfill the requests received by terminating pod between termination and load balancer update(sync)

PreStop can be made more intelligent for pod with unpredictable time of serving

Body:
I recently faced similar problem, I used simple preStop hook, which introduces some delay(sleep) between start of termination and receiving SIGTERM to underlying process

lifecycle:
        preStop:
          exec:
            command:
              - "sleep"
              - "60"

This delay helps,

Load balancer to remove(sync) the pod being terminated

Gives chance to terminating pod to complete requests received before termination

Fulfill the requests received by terminating pod between termination and load balancer update(sync)

PreStop can be made more intelligent for pod with unpredictable time of serving


答:
if(p>='0' && p<='9'){

p is a char*, '0' is a char. Your compiler should have warned you about comparing incompatible types. Use *p  instead (same applies to '9' obviously). In my head *p gets read as "contents of p" (in this context)

In the more general case, use strcmp() to compare strings.

If your compiler did warn you about the bad compare: take it on board, most compiler warnings should be listened to and not ignored. If your compiler didn't warn you look up how to enable all the warnings.

Title: How to compare if a char* is greater than or equal to another string/number?


问:
mysql many-to-one and group by giving unusual results
im having difficulty with the following fairly simple setup:

```<code>CREATE TABLE IF NOT EXISTS invoices (
id int(11) NOT NULL auto_increment,
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_items (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
description text NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_payments (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);
</code>```

some data:

```<code>INSERT INTO invoices (id) VALUES (1);

INSERT INTO invoices_items (id, invoice_id, description, amount) VALUES
(1, 1, 'Item 1', '750.00'),
(2, 1, 'Item 2', '750.00'),
(3, 1, 'Item 3', '50.00'),
(4, 1, 'Item 4', '150.00');

INSERT INTO invoices_payments (id, invoice_id, amount) VALUES
(1, 1, '50.00'),
(2, 1, '1650.00');
</code>```

and the sql yielding unusual results:

```<code>select  invoices.id,
        ifnull(sum(invoices_payments.amount),0) as payments_total,
        ifnull(count(invoices_items.id),0) as item_count
from    invoices
            left join invoices_items on invoices_items.invoice_id=invoices.id
            left join invoices_payments on invoices_payments.invoice_id=invoices.id
group by invoices.id
</code>```

results in the (erroneous) output

```<code>id  payments_total  item_count
1   6800.00     8
</code>```

now, as evidenced by there being infact only four 'invoice_item' rows, i dont understand why mysql is not grouping properly.

EDIT

i know i can do something like this:

```<code>select x.*, ifnull(sum(invoices_payments.amount),0) as payments_total from (
    select  invoices.id,
            ifnull(count(invoices_items.id),0) as item_count
    from    invoices
                left join invoices_items on invoices_items.invoice_id=invoices.id
    group by invoices.id
) as x left join invoices_payments on invoices_payments.invoice_id=x.id
group by x.id
</code>```

but i want to know if im doing something wrong in the first query - i cant immediately see why the first query is giving incorrect results! :(

答:
There are two tables with a many:one relationship with invoices. Your count is the cartesian product.

The payments should be applied to the invoice, not the invoice items.  Get the invoice total first, then join the payments to it.

This may be similar to what you are looking for:

```<code>SELECT
    invoice_total.invoice_id,
    invoice_total.amount as invoice_amount,
    payments_total.amount as total_paid
FROM
    (
        SELECT
            invoice_id,
            SUM(amount) as amount
        FROM
            invoices_items
        GROUP BY
                invoice_id
        ) invoice_total
    INNER JOIN
            (
            SELECT
                invoice_id,
                SUM(amount) as amount
            FROM
                invoices_payments
            GROUP BY
                invoice_id
            ) payments_total
    ON invoice_total.invoice_id  = payments_total.invoice_id;
</code>```

Body:
im having difficulty with the following fairly simple setup:

CREATE TABLE IF NOT EXISTS invoices (
id int(11) NOT NULL auto_increment,
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_items (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
description text NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_payments (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);

some data:

INSERT INTO invoices (id) VALUES (1);

INSERT INTO invoices_items (id, invoice_id, description, amount) VALUES
(1, 1, 'Item 1', '750.00'),
(2, 1, 'Item 2', '750.00'),
(3, 1, 'Item 3', '50.00'),
(4, 1, 'Item 4', '150.00');

INSERT INTO invoices_payments (id, invoice_id, amount) VALUES
(1, 1, '50.00'),
(2, 1, '1650.00');

and the sql yielding unusual results:

select  invoices.id,
        ifnull(sum(invoices_payments.amount),0) as payments_total,
        ifnull(count(invoices_items.id),0) as item_count
from    invoices
            left join invoices_items on invoices_items.invoice_id=invoices.id
            left join invoices_payments on invoices_payments.invoice_id=invoices.id
group by invoices.id

results in the (erroneous) output

id  payments_total  item_count
1   6800.00     8

now, as evidenced by there being infact only four 'invoice_item' rows, i dont understand why mysql is not grouping properly.

EDIT

i know i can do something like this:

select x.*, ifnull(sum(invoices_payments.amount),0) as payments_total from (
    select  invoices.id,
            ifnull(count(invoices_items.id),0) as item_count
    from    invoices
                left join invoices_items on invoices_items.invoice_id=invoices.id
    group by invoices.id
) as x left join invoices_payments on invoices_payments.invoice_id=x.id
group by x.id

but i want to know if im doing something wrong in the first query - i cant immediately see why the first query is giving incorrect results! :(

Body:
There are two tables with a many:one relationship with invoices. Your count is the cartesian product.

The payments should be applied to the invoice, not the invoice items.  Get the invoice total first, then join the payments to it.

This may be similar to what you are looking for:

SELECT
    invoice_total.invoice_id,
    invoice_total.amount as invoice_amount,
    payments_total.amount as total_paid
FROM
    (
        SELECT
            invoice_id,
            SUM(amount) as amount
        FROM
            invoices_items
        GROUP BY
                invoice_id
        ) invoice_total
    INNER JOIN
            (
            SELECT
                invoice_id,
                SUM(amount) as amount
            FROM
                invoices_payments
            GROUP BY
                invoice_id
            ) payments_total
    ON invoice_total.invoice_id  = payments_total.invoice_id;


问:
Unusual error in code igniter system file when deployed to a VPS server
I recently finished building my site using code igniter on WAMP local server and tested it on a shared hosting server (from Namecheap). Then I got VPS hosting plan (from iPage) and uploaded the files and did the necessary configs. However, I got this error when I tried accessing the site:

An uncaught Exception was encountered

Type: Error

Message: Call to undefined function ctype_digit()

Filename: /home/eastngco/public_html/system/core/Security.php

Line Number: 600

Problem is, the suspect file, Security.php, is a code igniter system file which I never messed with (everything I wrote was within the application folder). Below is a code snippet around the line in Security.php causing the error:

```<code>/**
 * Get random bytes
 *
 * @param   int $length Output length
 * @return  string
 */
public function get_random_bytes($length)
{
    if (empty($length) OR ! ctype_digit((string) $length))
    {
        return FALSE;
    }

    if (function_exists('random_bytes'))
    {
        try
        {
            // The cast is required to avoid TypeError
            return random_bytes((int) $length);
        }
        catch (Exception $e)
        {
            // If random_bytes() can't do the job, we can't either ...
            // There's no point in using fallbacks.
            log_message('error', $e->getMessage());
            return FALSE;
        }
    }

    // Unfortunately, none of the following PRNGs is guaranteed to exist ...
    if (defined('MCRYPT_DEV_URANDOM') && ($output = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)) !== FALSE)
    {
        return $output;
    }

    if (is_readable('/dev/urandom') && ($fp = fopen('/dev/urandom', 'rb')) !== FALSE)
    {
        // Try not to waste entropy ...
        is_php('5.4') && stream_set_chunk_size($fp, $length);
        $output = fread($fp, $length);
        fclose($fp);
        if ($output !== FALSE)
        {
            return $output;
        }
    }

    if (function_exists('openssl_random_pseudo_bytes'))
    {
        return openssl_random_pseudo_bytes($length);
    }

    return FALSE;
}
</code>```

I have no idea what random bytes or ctype_digit() means!

I did some digging on the web to see if a similar problem (and its solution) would pop, but nothing did. I need help fixing this please.
If it means anything, the PHP version that comes with my hosting plan is version 7, and I have SSL.

答:
Looks like your provider might have explicitly disabled those types of functions. It should be enabled by default. Try contacting your provider for some support on enabling these, or reinstalling PHP without that flag turned off.

http://us2.php.net/manual/en/ctype.installation.php

Additionally, you could try and inspect a phpinfo() page to confirm whether ctypes are enabled or not. It seems weird that they would turn it off, so this would help figure out if this is part of the issue.

Body:
I recently finished building my site using code igniter on WAMP local server and tested it on a shared hosting server (from Namecheap). Then I got VPS hosting plan (from iPage) and uploaded the files and did the necessary configs. However, I got this error when I tried accessing the site:

An uncaught Exception was encountered

Type: Error

Message: Call to undefined function ctype_digit()

Filename: /home/eastngco/public_html/system/core/Security.php

Line Number: 600

Problem is, the suspect file, Security.php, is a code igniter system file which I never messed with (everything I wrote was within the application folder). Below is a code snippet around the line in Security.php causing the error:

/**
 * Get random bytes
 *
 * @param   int $length Output length
 * @return  string
 */
public function get_random_bytes($length)
{
    if (empty($length) OR ! ctype_digit((string) $length))
    {
        return FALSE;
    }

    if (function_exists('random_bytes'))
    {
        try
        {
            // The cast is required to avoid TypeError
            return random_bytes((int) $length);
        }
        catch (Exception $e)
        {
            // If random_bytes() can't do the job, we can't either ...
            // There's no point in using fallbacks.
            log_message('error', $e->getMessage());
            return FALSE;
        }
    }

    // Unfortunately, none of the following PRNGs is guaranteed to exist ...
    if (defined('MCRYPT_DEV_URANDOM') && ($output = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)) !== FALSE)
    {
        return $output;
    }

    if (is_readable('/dev/urandom') && ($fp = fopen('/dev/urandom', 'rb')) !== FALSE)
    {
        // Try not to waste entropy ...
        is_php('5.4') && stream_set_chunk_size($fp, $length);
        $output = fread($fp, $length);
        fclose($fp);
        if ($output !== FALSE)
        {
            return $output;
        }
    }

    if (function_exists('openssl_random_pseudo_bytes'))
    {
        return openssl_random_pseudo_bytes($length);
    }

    return FALSE;
}

I have no idea what random bytes or ctype_digit() means!

I did some digging on the web to see if a similar problem (and its solution) would pop, but nothing did. I need help fixing this please.
If it means anything, the PHP version that comes with my hosting plan is version 7, and I have SSL.


问:
C++ how to format a pointer to an array of classes?
I want to read information from a file and put that information in an pointer to an array of classes. it keeps throwing an exception at us->setUserName(name); but if I change it to us[i]->setUserName(name); it says "expression must have pointer type". How can I fix this?

```<code>    const int SIZE = 100;
    User *us = new User[SIZE];

    input.open("Account.txt", ios::in);

    if (input)
    {
       input >> size;

       for (int i = 0; i < size; i++)
       {
          us = new User[i];
          getline(input, uName);
          us->setUserName(uName);

          getline(input, password);
          us->setPassword(password);

          getline(input, name);
          us->setName(name);
       }
    else
       cout << "Error opening file" << endl;
</code>```

here is the user class:

```<code>    class User
    {
    public:
      User();
      ~User();

      void setName(string);
      string getName();

      void setUserName(string);
      string getUserName();

      void setPassword(string);
      string getPassword();

      void setFollower(vector<User*>*);
      vector<User*>* getFollower();

      void setFollowing(vector<User*>*);
      vector<User*>* getFollowing();

    protected:
      string name;
      string userName;
      string password;

      vector <User*>* followers;
      vector <User*>* following;

  };
</code>```

答:
if you want to continue to use an array do this</p>

```<code>  if (input)
    {
       input >> size;

       for (int i = 0; i < size; i++)
       {
          getline(input, uName);
          us[i].setUserName(uName);
.....
</code>```

Body:
I want to read information from a file and put that information in an pointer to an array of classes. it keeps throwing an exception at us->setUserName(name); but if I change it to us[i]->setUserName(name); it says "expression must have pointer type". How can I fix this?

    const int SIZE = 100;
    User *us = new User[SIZE];

    input.open("Account.txt", ios::in);

    if (input)
    {
       input >> size;

       for (int i = 0; i < size; i++)
       {
          us = new User[i];
          getline(input, uName);
          us->setUserName(uName);

          getline(input, password);
          us->setPassword(password);

          getline(input, name);
          us->setName(name);
       }
    else
       cout << "Error opening file" << endl;

here is the user class:

    class User
    {
    public:
      User();
      ~User();

      void setName(string);
      string getName();

      void setUserName(string);
      string getUserName();

      void setPassword(string);
      string getPassword();

      void setFollower(vector<User*>*);
      vector<User*>* getFollower();

      void setFollowing(vector<User*>*);
      vector<User*>* getFollowing();

    protected:
      string name;
      string userName;
      string password;

      vector <User*>* followers;
      vector <User*>* following;

  };

Body:
if you want to continue to use an array do this

  if (input)
    {
       input >> size;

       for (int i = 0; i < size; i++)
       {
          getline(input, uName);
          us[i].setUserName(uName);
.....


问:
Two digit string number Assembly
So I have to strings s1 and s2 and I have two obtain the string d that contains the maximum numbers for each of the positions of s1 and s2.

For example:

```<code>S1: 1, 3, 6, 2, 3, 10

S2: 6, 3, 11, 1, 2, 5

D: 6, 3, 11, 2, 3, 10
</code>```

So this is the code

```<code>bits 32
global start
extern exit,printf
import exit msvcrt.dll
import printf msvcrt.dll
segment data use32 class=data
    format db "%s",0
    s1 db "1","3","6","2","3","10"
    l equ $-s1
    s2 db "6","3" ,"11","1","2", "5"
    d times l db 0

segment code use32 class=code
start:
    mov esi,0
    mov edi,0
    cld
    Repeta:
        mov al,[s1+esi]
        mov bl,[s2+esi]
        cmp al,bl
        jg et1
        mov[d+edi],bl
        inc edi
        inc esi
        jmp et2
        et1:
            mov[d+edi],al
            inc edi
            inc esi
        et2:
    cmp esi,l
    jne Repeta
    push d
    push format
    call[printf]
    add esp,4*2

push dword 0
call [exit]
</code>```

The problem is that when it reaches a double digit element(10 or 11) it takes only the first digit(1) and compares it with the number from the other string on the same position and after that it takes the second digit and compares it with the next number from the other string.
How can I solve this?

答:
it says that it should be a string of bytes

The phrase "of bytes" very strongly implies array to me.  Ask your instructor for clarification, but I think s1: db 1, 3, 6, 2, 3, 10 is what you're supposed to be working with, so the elements are fixed width single byte integers.  (And not ASCII strings at all).

This means you can use a simple pairwise max like SSE2 pmaxub (for unsigned bytes) or SSE4.1 pmaxsb (for signed bytes).

```<code>segment data use32 class=data
    format db "%s",0
    s1 db 1, 3, 6, 2, 3, 10
    l equ $-s1
    s2 db 6, 3, 11, 1, 2, 5

    d times l db 0

start:
    movq   xmm1, [s1]       ; load all 6 elements, plus 2 bytes past the end but that's ok.  We ignore those bytes
    movq   xmm2, [s2]
    pmaxub xmm1, xmm2       ; element-wise vertical max

    ;but avoid storing outside of 6-byte d
    movd   [d], xmm1        ; store first 4 bytes of the result
    pextrw [d+4], xmm1, 2   ; store bytes 4 and 5 (word 2 of xmm1 = 3rd word)

    ...  ; the result isn't a string, you can't print it with printf.
</code>```

For byte counts that aren't a multiple of 2, e.g. if l was 7, you could use this instead of pextrw:

```<code>psrldq  xmm1, 3                ; bring the data you want to store down into the low 4 bytes of the register
movd    [d+4], xmm1            ; 4-byte store that overlaps by 1
</code>```

BTW, I realize that you're intended to loop over the elements 1 byte at a time.  Maybe use cmp cl, al  / cmovg  eax, ecx  / mov [edi], al to store what was originally in cl if cl > al (signed), otherwise store what was originally in al.

I think your loop structure is a bit broken, because you have one path that doesn't store to d.  You always need to store to d, regardless of which source was greater.

Title: Two digit string number Assembly

Body:
So I have to strings s1 and s2 and I have two obtain the string d that contains the maximum numbers for each of the positions of s1 and s2.

For example:

S1: 1, 3, 6, 2, 3, 10

S2: 6, 3, 11, 1, 2, 5

D: 6, 3, 11, 2, 3, 10

So this is the code

bits 32
global start
extern exit,printf
import exit msvcrt.dll
import printf msvcrt.dll
segment data use32 class=data
    format db "%s",0
    s1 db "1","3","6","2","3","10"
    l equ $-s1
    s2 db "6","3" ,"11","1","2", "5"
    d times l db 0

segment code use32 class=code
start:
    mov esi,0
    mov edi,0
    cld
    Repeta:
        mov al,[s1+esi]
        mov bl,[s2+esi]
        cmp al,bl
        jg et1
        mov[d+edi],bl
        inc edi
        inc esi
        jmp et2
        et1:
            mov[d+edi],al
            inc edi
            inc esi
        et2:
    cmp esi,l
    jne Repeta
    push d
    push format
    call[printf]
    add esp,4*2

push dword 0
call [exit]

The problem is that when it reaches a double digit element(10 or 11) it takes only the first digit(1) and compares it with the number from the other string on the same position and after that it takes the second digit and compares it with the next number from the other string.
How can I solve this?

Body:
it says that it should be a string of bytes

The phrase "of bytes" very strongly implies array to me.  Ask your instructor for clarification, but I think s1: db 1, 3, 6, 2, 3, 10 is what you're supposed to be working with, so the elements are fixed width single byte integers.  (And not ASCII strings at all).

This means you can use a simple pairwise max like SSE2 pmaxub (for unsigned bytes) or SSE4.1 pmaxsb (for signed bytes).

segment data use32 class=data
    format db "%s",0
    s1 db 1, 3, 6, 2, 3, 10
    l equ $-s1
    s2 db 6, 3, 11, 1, 2, 5

    d times l db 0

start:
    movq   xmm1, [s1]       ; load all 6 elements, plus 2 bytes past the end but that's ok.  We ignore those bytes
    movq   xmm2, [s2]
    pmaxub xmm1, xmm2       ; element-wise vertical max

    ;but avoid storing outside of 6-byte d
    movd   [d], xmm1        ; store first 4 bytes of the result
    pextrw [d+4], xmm1, 2   ; store bytes 4 and 5 (word 2 of xmm1 = 3rd word)

    ...  ; the result isn't a string, you can't print it with printf.

For byte counts that aren't a multiple of 2, e.g. if l was 7, you could use this instead of pextrw:

psrldq  xmm1, 3                ; bring the data you want to store down into the low 4 bytes of the register
movd    [d+4], xmm1            ; 4-byte store that overlaps by 1

BTW, I realize that you're intended to loop over the elements 1 byte at a time.  Maybe use cmp cl, al  / cmovg  eax, ecx  / mov [edi], al to store what was originally in cl if cl > al (signed), otherwise store what was originally in al.

I think your loop structure is a bit broken, because you have one path that doesn't store to d.  You always need to store to d, regardless of which source was greater.


问:
How to deal with library of images in android?
I'm rewriting existing Windows application to android.

My application is a kind of customizeable picture communicator for people with disabilities. It uses about 300 categorized images and this number is growing. They take 100-300kB each.

In Windows version I just have a folder with subfolders and I'm copying it to Program files\My application in installer. During runtime I just read images and folder tree from filesystem.

Now I want to re-use this folder structure with images in Android application, but my knowledge about Android development is poor.

My question:

How can I "include" whole folder of images in apk file and make it "expand" to somewhere in filesystem during installation?

My minSdkVersion is 21.

答:
If you are loading all the images "programmatically only", then you can dump all your directory tree into the assets folder. The assets folder maintains the hierarchy.

You will be using AssetManager for accessing the files. Note that files read from assets are simply stream of bytes.

As per the AssetManager docs

Provides access to an application's raw asset files. This class presents a lower-level API that allows you to open and read raw files that have been bundled with the application as a simple stream of bytes.

Check this tutorial for a head-start.


问:
Creating Reports with BIRT
I checked out basic tutorials for BIRT and I felt that BIRT is highly database-centric. I have a totally different situation.

I have to generate reports from a different kind of data source. The data to be published is created on the fly (that's the work of another module) and I have complicated data structures holding the data (like List of Maps). I can't have a template, as it all depends on user interaction. But the data structure contains all the data that is required to create each report, namely column names, number of rows, and values of a row.

I'm really confused how to create reports from this kind of data source. BIRT only supports POJOs. Is there any way that I can specify a map as a dataset and a Java class as a data source? Or if not, what are the alternatives?

答:
What you may need to do is build your report from code based on your data. You did not describe your situation in enough detail to say so for sure. And building from code should be the done only in rare cases because it requires a program change for any change. But if your needs for control are outside of any reporting tool, then look at that approach. If you do take this approach, then you can use iText for PDF generation, OpenXML for DOCX/XLSX/PPTX, etc.

With that said, can you create an XML file from your POJOs? It is an extra step, but if you can, then you can feed that to most any reporting system, as long as the schema of your XML is constant. This would be a much better approach as you would keep the reporting layout, formatting, and logic in the reporting tool. Saves you a boatload of time and makes revisions a lot easier.

If you do go the XML route, please take a look at Windward Reports. (Disclaimer, I'm the CTO at Windward.) With Windward you design the reports in Microsoft Word, Excel, or PowerPoint - which makes report design and editing fast & easy.

For general information, I suggest java-reports and reporting-software. The key to a system that works well for you is one where the design tool is a natural fit for your style - so try several.

Title: Creating Reports with BIRT


问:
I can load data from database with ajax and show in modal include ckeditor but i can't edit/save those data. I used Codeigniter 3

I can Load data with ajax but, I can't save data with ajax in ckeditor

Here's my ajax in view

```<code>$.ajax({

    url : "<?php echo base_url('admin/perusahaan_baik/edit_narasi_gcg')?>/" + id,
    type: "GET",
    dataType: "JSON",
    success: function(data)
    {

        $('[name="id"]').val(data.id);
        $('[name="posting_date"]').val(data.posting_date);
        $('[name="description"]').val(CKEDITOR.instances.description.setData(data.description));
</code>```

$('#modal_narasi').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Perusahaan Baik'); // Set title to Bootstrap modal title
},
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });

Here's my controller

```<code>    $data = array(

            'posting_date' => $this->input->post('posting_date'),
            'description' => $this->input->post('description')
        );

    $this->narasi_model->update_narasi_gcg(array('id' => $this->input->post('id')), $data);

    echo json_encode(array("status" => TRUE));
</code>```

Here's my model

```<code>    public function get_by_id($id)
    {
        $this->db->from($this->table);
        $this->db->where('id',$id);
        $query = $this->db->get();

        return $query->row();
    }

    public function update_narasi_gcg($where, $data)
    {
        $this->db->update($this->table, $data, $where);
        return $this->db->affected_rows();
    }
</code>```

Here's my div

```<code>                    <div class="form-group">
                        <label class="control-label col-md-3">Posisi ID</label>
                        <div class="col-md-9">
                            <textarea name="description" id="description" rows="10" cols="80">

                      </textarea>
                        </div>
                    </div>
</code>```

答:
Add also id and posting_date </p>

```<code><div class="form-group">
<label class="control-label col-md-3">Posisi ID</label>
<div class="col-md-9">
<textarea name="description" id="description" rows="10" cols="80"></textarea>
<input type="hidden" name="posting_date" id="posting_date">
<input type="hidden" name="id" id="id">
</div>
</div>
</code>```

Body:
I can Load data with ajax but, I can't save data with ajax in ckeditor

Here's my ajax in view

$.ajax({

    url : "<?php echo base_url('admin/perusahaan_baik/edit_narasi_gcg')?>/" + id,
    type: "GET",
    dataType: "JSON",
    success: function(data)
    {

        $('[name="id"]').val(data.id);
        $('[name="posting_date"]').val(data.posting_date);
        $('[name="description"]').val(CKEDITOR.instances.description.setData(data.description));

$('#modal_narasi').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Perusahaan Baik'); // Set title to Bootstrap modal title
},
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });

Here's my controller

    $data = array(

            'posting_date' => $this->input->post('posting_date'),
            'description' => $this->input->post('description')
        );

    $this->narasi_model->update_narasi_gcg(array('id' => $this->input->post('id')), $data);

    echo json_encode(array("status" => TRUE));

Here's my model

    public function get_by_id($id)
    {
        $this->db->from($this->table);
        $this->db->where('id',$id);
        $query = $this->db->get();

        return $query->row();
    }

    public function update_narasi_gcg($where, $data)
    {
        $this->db->update($this->table, $data, $where);
        return $this->db->affected_rows();
    }

Here's my div

                        Posisi ID

                            <textarea name="description" id="description" rows="10" cols="80">

                      </textarea>

Body:
Add also id and posting_date

<div class="form-group">
<label class="control-label col-md-3">Posisi ID</label>
<div class="col-md-9">
<textarea name="description" id="description" rows="10" cols="80"></textarea>
<input type="hidden" name="posting_date" id="posting_date">
<input type="hidden" name="id" id="id">
</div>
</div>


问:
Converting Binary to Decimal in python (without built in binary function)
Alrighty, first post here, so please forgive and ignore if the question is not workable;

Background:
I'm in computer science 160.  I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced.  We have been working in Python and each week we are prompted to write a program.

I have been working with this problem for over a week and am having a hard time even starting.

The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent.  Now, I have gotten some tips from a classmate and it sent me at least in a direction.

Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.

I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.

```<code>setbitval = 0
counter = 0

user = int(input("enter a binary value. "))

if user % 2 == 1:
        user = (user/10) - .1
        setbitval += 1
</code>```

This is all I've got so far.. My thinking is getting in the way.  I've searched and searched, even through these forums.

Any information or thoughts are extremely appreciated,

T

Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.

```<code>for i in reversed(bits):
decimal += 2**counter * int(i)

counter += 1
</code>```

This is the formula someone here gave me and I've been trying different iterations of "for i in bits:  if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".

Any thoughts?

答:
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number

The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.

Hopefully, this code clarifies things a bit.

```<code>x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
    decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)
</code>```

This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:

1st element of binary number * 2^(length of binary number - 1)

2nd element of binary number * 2^(length of binary number - 2)

and so on till we get to the last element and ...2^0

If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.

This code, however, assumes that the binary number is valid. Let me know if it helps.

Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.

```<code>x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
    decimal += int(x[index]) * 2**exp
    index += 1
    exp -= 1
print(decimal)
</code>```

In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.

Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:

```<code>def is_binary(x):
    """ Returns True if number x is binary and False otherwise.

    input: x as a string
    """
    for i in list(x):
        if i not in ["1", "0"]:
            return False
    return True

def binary_decimal(x):
    """ Converts binary to decimal.
    input: binary number x as a string
    output: decimal number as int
    """
    if not is_binary(x):
        return "Number is invalid"
    decimal = 0
    for i in range(len(x)):
        decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
    return decimal
</code>```

The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.

Of course, you can implement this solution without any functions.

Body:
Alrighty, first post here, so please forgive and ignore if the question is not workable;

Background:
I'm in computer science 160.  I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced.  We have been working in Python and each week we are prompted to write a program.

I have been working with this problem for over a week and am having a hard time even starting.

The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent.  Now, I have gotten some tips from a classmate and it sent me at least in a direction.

Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.

I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.

setbitval = 0
counter = 0

user = int(input("enter a binary value. "))

if user % 2 == 1:
        user = (user/10) - .1
        setbitval += 1

This is all I've got so far.. My thinking is getting in the way.  I've searched and searched, even through these forums.

Any information or thoughts are extremely appreciated,

T

Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.

for i in reversed(bits):
decimal += 2**counter * int(i)

counter += 1

This is the formula someone here gave me and I've been trying different iterations of "for i in bits:  if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".

Any thoughts?

Body:
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number

The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.

Hopefully, this code clarifies things a bit.

x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
    decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)

This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:

1st element of binary number * 2^(length of binary number - 1)

2nd element of binary number * 2^(length of binary number - 2)

and so on till we get to the last element and ...2^0

If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.

This code, however, assumes that the binary number is valid. Let me know if it helps.

Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.

x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
    decimal += int(x[index]) * 2**exp
    index += 1
    exp -= 1
print(decimal)

In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.

Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:

def is_binary(x):
    """ Returns True if number x is binary and False otherwise.

    input: x as a string
    """
    for i in list(x):
        if i not in ["1", "0"]:
            return False
    return True

def binary_decimal(x):
    """ Converts binary to decimal.
    input: binary number x as a string
    output: decimal number as int
    """
    if not is_binary(x):
        return "Number is invalid"
    decimal = 0
    for i in range(len(x)):
        decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
    return decimal

The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.

Of course, you can implement this solution without any functions.


问:
Why isn't 'false' equal to 'nil'?
false is not equal to nil, for example:

```<code>false == nil # => false
</code>```

The same goes for false and 0:

```<code>false == 0 # => false
</code>```

You get the same result for nil and 0:

```<code>nil == 0 # => false
</code>```

Why does Ruby act like this?

答:
In Ruby, the only time nil will return true on a == comparison is when you do: nil == nil

You can read more about nil here:

https://ruby-doc.org/core-2.2.3/NilClass.html

nil is the equivalent of undefined in JavaScript  or None in Python

Consider in JavaScript:

```<code>>> (undefined === false)
=> false
</code>```

Or Python:

```<code>>> (None == False)
=> False
</code>```

Title: Why isn't 'false' equal to 'nil'?

Body:
false is not equal to nil, for example:

false == nil # => false

The same goes for false and 0:

false == 0 # => false

You get the same result for nil and 0:

nil == 0 # => false

Why does Ruby act like this?

Body:
In Ruby, the only time nil will return true on a == comparison is when you do: nil == nil

You can read more about nil here:

https://ruby-doc.org/core-2.2.3/NilClass.html

nil is the equivalent of undefined in JavaScript  or None in Python

Consider in JavaScript:

>> (undefined === false)
=> false

Or Python:

>> (None == False)
=> False


问:
Can i use my hosted WEB API (created in ASP.NET) in Mulesoft API manger?
I am trying to learn mulesoft AnyPoint Platform, and trying to host an API using API Manager.

I already have an API created in asp.net, can i use it in API manager, or i need to create new API.

Please help

答:
Yes its possible if you are using Cloud based API Manager where below are the steps -

Click on the "Add New API" button.

Enter the API name of  Mythical

Mobile Experience API (Replace Mythical with your preferred company
name)

Enter Version name of 1.0 Leave the the API Endpoint blank for
now.

Enter a description.

You should see the API administration page for your newly created API.  From this page, you can Define API in API designer using RAML, publish an API portal, and Configure endpoint for the API.

Note, If you are using on-prem API Gateway then you need to develop a proxy Mule application which then need to be deployed using auto discovery component so that it will register under api manager then You should see the API administration page for your newly created API.  From this page, you can Define API in API designer using RAML, publish an API portal, and Configure endpoint for the API.


问:
How to place and center text in an SVG rectangle
I have the following rectangle:

```<code><rect x="0px" y="0px" width="60px" height="20px"/>
</code>```

I would like to center the word "Fiction" inside of it. For other rectangles, does SVG word wrap to stay within them? I can't seem to find anything specifically about inserting text within shapes that are centered both horizontally and vertically and word wrap. Also, the text can not leave the rectangle.

Looking at the https://www.w3.org/TR/SVG/text.html#TextElement example doesn't help since the text element's x and y are different from the rectangle's x and y. There doesn't seem to be width and height for text elements. I am not sure of the math here.

(My HTML table is just not going to work.)

答:
Full detail blog: https://web.archive.org/web/20180717015233/http://blog.techhysahil.com:80/svg/how-to-center-text-in-svg-shapes/

<svg width="600" height="600">

  <g transform="translate(50,40)">
    <circle cx="0" cy="0" r="35" stroke="#aaa" stroke-width="2" fill="#fff"></circle>
    <text x="0" y="0" alignment-baseline="middle" font-size="12" stroke-width="0" stroke="#000" text-anchor="middle">HueLink</text>
  </g>

  <g transform="translate(150,20)">
    <rect width="150" height="40" stroke="#aaa" stroke-width="2" fill="#fff"></rect>
    <text x="75" y="20" alignment-baseline="middle" font-size="12" stroke-width="0" stroke="#000" text-anchor="middle">HueLink</text>
  </g>

  <g transform="translate(120,140)">
    <ellipse cx="0" cy="0" rx="100" ry="50" stroke="#aaa" stroke-width="2" fill="#fff"></ellipse>
    <text x="0" y="0" alignment-baseline="middle" font-size="12" stroke-width="0" stroke="#000" text-anchor="middle">HueLink</text>
  </g>

</svg>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following rectangle:

<rect x="0px" y="0px" width="60px" height="20px"/>

I would like to center the word "Fiction" inside of it. For other rectangles, does SVG word wrap to stay within them? I can't seem to find anything specifically about inserting text within shapes that are centered both horizontally and vertically and word wrap. Also, the text can not leave the rectangle.

Looking at the https://www.w3.org/TR/SVG/text.html#TextElement example doesn't help since the text element's x and y are different from the rectangle's x and y. There doesn't seem to be width and height for text elements. I am not sure of the math here.

(My HTML table is just not going to work.)

Body:
Full detail blog: https://web.archive.org/web/20180717015233/http://blog.techhysahil.com:80/svg/how-to-center-text-in-svg-shapes/

<svg width="600" height="600">
  <!--   Circle -->
  <g transform="translate(50,40)">
    <circle cx="0" cy="0" r="35" stroke="#aaa" stroke-width="2" fill="#fff"></circle>
    <text x="0" y="0" alignment-baseline="middle" font-size="12" stroke-width="0" stroke="#000" text-anchor="middle">HueLink</text>
  </g>

  <!--   In Rectangle text position needs to be given half of width and height of rectangle respectively -->
  <!--   Rectangle -->
  <g transform="translate(150,20)">
    <rect width="150" height="40" stroke="#aaa" stroke-width="2" fill="#fff"></rect>
    <text x="75" y="20" alignment-baseline="middle" font-size="12" stroke-width="0" stroke="#000" text-anchor="middle">HueLink</text>
  </g>

  <!--   Rectangle -->
  <g transform="translate(120,140)">
    <ellipse cx="0" cy="0" rx="100" ry="50" stroke="#aaa" stroke-width="2" fill="#fff"></ellipse>
    <text x="0" y="0" alignment-baseline="middle" font-size="12" stroke-width="0" stroke="#000" text-anchor="middle">HueLink</text>
  </g>

</svg>


问:
match words containing at least one letter and at least one digit
I am new to regex but I have spent the last two days researching and I have also tried many of the similar queries in this and other sites.

I am trying to come up with an expression (POSIX ERE) that will find whole words that contain at least one letter and at least one digit. Specifically, I would like to capture all of these:

B/DIN/37/1
DU/32.Abb.31
P/NA.17
O/DIN/2017/8
22/N.Abb.2

I have tried many things and managed to crash my software a couple of times in the process, but still no go. One of my issues is I don't know how to phrase my string so it will find whole words that meet the criterion, not just a string within a word.

Thank you very much to anyone that can help me out!

答:
I'm assuming words are separated by whitespace. In that case, a word that has a digit and a letter can be separated into two regex expressions:

0 or more non-whitespace characters, followed by a letter, followed by 0 or more non-whitespace characters, followed by a digit, followed by 0 or more non-whitespace characters

The above, but with digit and letter swapped.

The non-whitespace character matches make sure the entire word is captured.

Those translate into the following regexes:

\S*[A-Za-z]\S*[0-9]\S*

\S*[0-9]\S*[A-Za-z]\S*

Combining them yields this final expression:

(\S*[A-Za-z]\S*[0-9]\S*|\S*[0-9]\S*[A-Za-z]\S*)