问:
Specifying input/output nodes to run inference in TensorFlow 1.0+ on a model loaded with the C++ API
I'm loading a V2 checkpoint with the TensorFlow 1.4 C++ API, which is fairly straightforward following this answer: https://stackoverflow.com/a/43639305/9015277 . However, this answer does not specify the how the inputs can be fed to the loaded network.

In TF 1.4 inputs for ClientSession::Run() can be specified using a FeedType object, which is defined as:

```<code>std::unordered_map< Output, Input::Initializer, OutputHash > FeedType
</code>```

Here  each Output key represents a tensor value produced by an OP. With a graph built in the C++ API I guess it is fairly simple to just pass the input placeholder, but how can I do the same with a graph loaded from a V2 checkpoint?

In this example (which using the r0.12 api I believe) https://github.com/tensorflow/tensorflow/blob/ab0fcaceda001825654424bf18e8a8e0f8d39df2/tensorflow/examples/label_image/main.cc#L346 it is straightforward again, the layers are just given with their names. But how can I do the same with the new API?

答:
Well, I was not getting any useful answers, so finally I ended up just using the old C++ API instead (which BTW still works in r1.4). I'm still looking for an answer how this should be done with the new API.

In the old TF API Session::Run is as follows:

```<code>virtual Status Run(
  const std::vector< std::pair< string, Tensor > > & inputs,
  const std::vector< string > & output_tensor_names,
  const std::vector< string > & target_node_names,
  std::vector< Tensor > *outputs
)=0
</code>```

The string in the inputs vector allows for specifying inputs in the network with their names from the python graph definition, similar to how feed_dict is used on python. Here is the graph definition of my input placeholders in python:

```<code>with tf.variable_scope('global'):
    velocity_state = tf.placeholder(shape=[None, 1],
                                    dtype=tf.float32,
                                    name='velocity_state')
</code>```

Feeding this particular placeholder in C++ with some dummy data, and running inference:

```<code>using namespace tensorflow;

// specifying input node name and creating tensor to feed it
string velocity_state_placeholder = "global/velocity_state";
Tensor velocity_state = Input::Initializer((float)0.0, TensorShape({1, 1})).tensor;

// collecting all inputs
std::vector<std::pair<string, Tensor>> input_feed;
input_feed.push_back(std::make_pair(velocity_state_placeholder, velocity_state));

// output node name
string action_distribution = "global/fully_connected_1/Softmax";

// tensor for results
std::vector<Tensor> output_tensors;

// running inference
Status run_status = session->Run(input_feed,
                                {action_distribution},
                                {},
                                &output_tensors);
</code>```

Body:
I'm loading a V2 checkpoint with the TensorFlow 1.4 C++ API, which is fairly straightforward following this answer: https://stackoverflow.com/a/43639305/9015277 . However, this answer does not specify the how the inputs can be fed to the loaded network.

In TF 1.4 inputs for ClientSession::Run() can be specified using a FeedType object, which is defined as:

std::unordered_map< Output, Input::Initializer, OutputHash > FeedType

Here  each Output key represents a tensor value produced by an OP. With a graph built in the C++ API I guess it is fairly simple to just pass the input placeholder, but how can I do the same with a graph loaded from a V2 checkpoint?

In this example (which using the r0.12 api I believe) https://github.com/tensorflow/tensorflow/blob/ab0fcaceda001825654424bf18e8a8e0f8d39df2/tensorflow/examples/label_image/main.cc#L346 it is straightforward again, the layers are just given with their names. But how can I do the same with the new API?

Body:
Well, I was not getting any useful answers, so finally I ended up just using the old C++ API instead (which BTW still works in r1.4). I'm still looking for an answer how this should be done with the new API.

In the old TF API Session::Run is as follows:

virtual Status Run(
  const std::vector< std::pair< string, Tensor > > & inputs,
  const std::vector< string > & output_tensor_names,
  const std::vector< string > & target_node_names,
  std::vector< Tensor > *outputs
)=0

The string in the inputs vector allows for specifying inputs in the network with their names from the python graph definition, similar to how feed_dict is used on python. Here is the graph definition of my input placeholders in python:

with tf.variable_scope('global'):
    velocity_state = tf.placeholder(shape=[None, 1],
                                    dtype=tf.float32,
                                    name='velocity_state')

Feeding this particular placeholder in C++ with some dummy data, and running inference:

using namespace tensorflow;

// specifying input node name and creating tensor to feed it
string velocity_state_placeholder = "global/velocity_state";
Tensor velocity_state = Input::Initializer((float)0.0, TensorShape({1, 1})).tensor;

// collecting all inputs
std::vector<std::pair<string, Tensor>> input_feed;
input_feed.push_back(std::make_pair(velocity_state_placeholder, velocity_state));

// output node name
string action_distribution = "global/fully_connected_1/Softmax";

// tensor for results
std::vector<Tensor> output_tensors;

// running inference
Status run_status = session->Run(input_feed,
                                {action_distribution},
                                {},
                                &output_tensors);


来源: stackexchange

问:
What is the difference between a pod and a deployment?
I have been creating pods with type:deployment but I see that some documentation uses type:pod, more specifically the documentation for multi-container pods:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: ""
  labels:
    name: ""
  namespace: ""
  annotations: []
  generateName: ""
spec:
  ? "// See 'The spec schema' for details."
  : ~
</code>```

But to create pods I can just use a deployment type:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: ""
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: ""
    spec:
      containers:
        etc
</code>```

I noticed the pod documentation says:

The create command can be used to create a pod directly, or it can
  create a pod or pods through a Deployment. It is highly recommended
  that you use a Deployment to create your pods. It watches for failed
  pods and will start up new pods as required to maintain the specified
  number. If you don’t want a Deployment to monitor your pod (e.g. your
  pod is writing non-persistent data which won’t survive a restart, or
  your pod is intended to be very short-lived), you can create a pod
  directly with the create command.

Note: We recommend using a Deployment to create pods. You should use
  the instructions below only if you don’t want to create a Deployment.

But this raises the question of what kind:pod is good for? Can you somehow reference pods in a deployment? I didn't see a way. It looks like what you get with pods is some extra metadata but none of the deployment options such as replica or a restart policy. What good is a pod that doesn't persist data, survives a restart? I think I'd be able to create a multi-container pod with a deployment as well.

答:
Radek's answer is very good, but I would like to pitch in from my experience, you will almost never use an object with the kind pod, because that doesn't make any sense in practice.

Because you need a deployment object - or other Kubernetes API objects like a replication controller or replicaset - that needs to keep the replicas (pods) alive (that's kind of the point of using kubernetes).

What you will use in practice for a typical application are:

Deployment object (where you will specify your apps container/containers) that will host your app's container with some other specifications.

Service object (that is like a grouping object and gives it a so-called virtual IP (cluster IP) for the pods that have a certain label - and those pods are basically the app containers that you deployed with the former deployment object).

You need to have the service object because the pods from the deployment object can be killed, scaled up and down, and you can't rely on their IP addresses because they will not be persistent.

So you need an object like a service, that gives those pods a stable IP.

Just wanted to give you some context around pods, so you know how things work together.

Hope that clears a few things for you, not long ago I was in your shoes :)

ContentLicense: CC BY-SA 4.0

Body:
I have been creating pods with type:deployment but I see that some documentation uses type:pod, more specifically the documentation for multi-container pods:

apiVersion: v1
kind: Pod
metadata:
  name: ""
  labels:
    name: ""
  namespace: ""
  annotations: []
  generateName: ""
spec:
  ? "// See 'The spec schema' for details."
  : ~

But to create pods I can just use a deployment type:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: ""
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: ""
    spec:
      containers:
        etc

I noticed the pod documentation says:

The create command can be used to create a pod directly, or it can
  create a pod or pods through a Deployment. It is highly recommended
  that you use a Deployment to create your pods. It watches for failed
  pods and will start up new pods as required to maintain the specified
  number. If you don’t want a Deployment to monitor your pod (e.g. your
  pod is writing non-persistent data which won’t survive a restart, or
  your pod is intended to be very short-lived), you can create a pod
  directly with the create command.

Note: We recommend using a Deployment to create pods. You should use
  the instructions below only if you don’t want to create a Deployment.

But this raises the question of what kind:pod is good for? Can you somehow reference pods in a deployment? I didn't see a way. It looks like what you get with pods is some extra metadata but none of the deployment options such as replica or a restart policy. What good is a pod that doesn't persist data, survives a restart? I think I'd be able to create a multi-container pod with a deployment as well.

ContentLicense: CC BY-SA 3.0


问:
Tips/Tricks for DataFlex
Is anyone out there still using DataFlex? If so, what are you favorite tips and tricks for this venerable 4GL?</p>

答: Another good new site for VDF/DF tips is VDF Wiki.</p>

OwnerDisplayName: Steven A. Lowe

ContentLicense: CC BY-SA 2.5

Title: Tips/Tricks for DataFlex

OwnerDisplayName: Dennis


问:
how do I only show the user data in angular
What can I do to make it so that user can only see their own information rather than the whole database?

I have tried to use an if else statement to get the data I want like in the example below but it doesn't work.

history.component.html

```<code><div class="container">
  <div class="row" *ngFor="let histories of history">
    <div class="card card-block">
      <h4 class="card-title">{{ histories.email }}</h4>
      <p class="card-text">{{histories.amount}}</p>
    </div>
  </div>
</div>
</code>```

history.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { PostsService } from '../posts.service';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-history',
  templateUrl: './history.component.html',
  styleUrls: ['./history.component.css']
})
export class HistoryComponent implements OnInit {
  history: any;
  histories: any;
  public userEmail: string;

  constructor(private postsService: PostsService, private auth: AuthService) { }

  ngOnInit() {
    this.auth.currentEmail.subscribe(email => this.userEmail = email);

    this.postsService.getAllHistory().subscribe(history => {
      if(history.email == this.userEmail){
        this.history = history;
      }
    });
  }
}
</code>```

答:
Yes you should do it on the angular side, according to your code, you should not check the validation here

```<code>  this.postsService.getAllHistory().subscribe(history => {
 //remove this line  if(history.email==this.userEmail){
         this.history = history;
      }
  });
</code>```

instead do it here

```<code><div class="row" *ngFor="let histories of history">
      <div *ngIf="histories.email === userEmail" class="card card-block">
        <h4 class="card-title">{{ histories.email }}</h4>
        <p class="card-text">{{histories.amount}}</p>
      </div>
</div>
</code>```

Body:
What can I do to make it so that user can only see their own information rather than the whole database?

I have tried to use an if else statement to get the data I want like in the example below but it doesn't work.

history.component.html

{{ histories.email }}

{{histories.amount}}

history.component.ts

import { Component, OnInit } from '@angular/core';
import { PostsService } from '../posts.service';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-history',
  templateUrl: './history.component.html',
  styleUrls: ['./history.component.css']
})
export class HistoryComponent implements OnInit {
  history: any;
  histories: any;
  public userEmail: string;

  constructor(private postsService: PostsService, private auth: AuthService) { }

  ngOnInit() {
    this.auth.currentEmail.subscribe(email => this.userEmail = email);

    this.postsService.getAllHistory().subscribe(history => {
      if(history.email == this.userEmail){
        this.history = history;
      }
    });
  }
}

Body:
Yes you should do it on the angular side, according to your code, you should not check the validation here

  this.postsService.getAllHistory().subscribe(history => {
 //remove this line  if(history.email==this.userEmail){
         this.history = history;
      }
  });

instead do it here

<div class="row" *ngFor="let histories of history">
      <div *ngIf="histories.email === userEmail" class="card card-block">
        <h4 class="card-title">{{ histories.email }}</h4>
        <p class="card-text">{{histories.amount}}</p>
      </div>
</div>


问:
Spring Boot 404 not found error
I am trying to run the spring boot application but getting the 404 not found error.

Project structure:

```<code>src/
 +- main/
     +- java/
     |   + com/
         |   + demo/
             |    SpringBootDemo.java
             |    + controller/
                  |    HomeController.java
     +- resources/
             |   application.yml

src/
 +- main/
     +- webapp/
        +- WEB-INF/
           +- pages/
              | home.jsp
</code>```

HomeController.java

```<code>package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String getHome() {
        System.out.println("Controller");
        return "home";
    }
}
</code>```

application.yml

```<code>server:
  port: 8080
spring:
  mvc:
    view:
      prefix: /WEB-INF/pages/
      suffix: .jsp
</code>```

build.gradle

```<code>buildscript {
    ext {
        springBootVersion = '1.5.6.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'application'
mainClassName = 'com.demo.SpringBootDemo'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

// In this section you declare where to find the dependencies of your project
repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    compile('org.springframework.boot:spring-boot-starter-parent')
    compile('javax.servlet.jsp.jstl:javax.servlet.jsp.jstl-api')
}

jar {
  manifest {
    attributes(
      'Main-Class': 'com.demo.SpringBootDemo'
    )
  }
}
</code>```

SpringBootDemo.java

```<code>package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication(scanBasePackages="com.demo")
public class SpringBootDemo {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemo.class, args);
    }
}
</code>```

home.jsp

```<code><!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
    Hello World
</body>
</html>
</code>```

When I try to execute the code, it shows in the output as

```<code>Controller
</code>```

But it gives the Whitelabel Error Page when I visit http://localhost:8080/

答:
UPDATE
Ok I'll try to do better. It was not my intention to do you wrong...

I think you need to extend the SpringBootApplication class from  SpringBootServletInitializer to get servlet functionality in your Spring Boot application

```<code>@SpringBootApplication
public class WebApplication extends SpringBootServletInitializer {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(WebApplication.class, args);
    }
}
</code>```

In order to be able to resolve the view you have to define these properties:

```<code>spring.mvc.view.prefix: /WEB-INF/pages
spring.mvc.view.suffix: .jsp
</code>```

or of course the yaml variant of them. The actual jsp pages need then be placed in src/main/webapp/WEB-INF/pages

These are the dependencies in my pom

```<code>   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
</code>```

I hope you can translate this to gradle yourself?

My sample controller looks like this:

```<code>@Controller
public class HelloController {
    @RequestMapping("/")
    public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="World") String name) {
        model.addAttribute("name", name);
        return "hello";
    }
}
</code>```

Hope this will help you with getting your app working...

Title: Spring Boot 404 not found error

Body:
I am trying to run the spring boot application but getting the 404 not found error.

Project structure:

src/
 +- main/
     +- java/
     |   + com/
         |   + demo/
             |    SpringBootDemo.java
             |    + controller/
                  |    HomeController.java
     +- resources/
             |   application.yml

src/
 +- main/
     +- webapp/
        +- WEB-INF/
           +- pages/
              | home.jsp

HomeController.java

package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String getHome() {
        System.out.println("Controller");
        return "home";
    }
}

application.yml

server:
  port: 8080
spring:
  mvc:
    view:
      prefix: /WEB-INF/pages/
      suffix: .jsp

build.gradle

buildscript {
    ext {
        springBootVersion = '1.5.6.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'application'
mainClassName = 'com.demo.SpringBootDemo'

version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

// In this section you declare where to find the dependencies of your project
repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    compile('org.springframework.boot:spring-boot-starter-parent')
    compile('javax.servlet.jsp.jstl:javax.servlet.jsp.jstl-api')
}

jar {
  manifest {
    attributes(
      'Main-Class': 'com.demo.SpringBootDemo'
    )
  }
}

SpringBootDemo.java

package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication(scanBasePackages="com.demo")
public class SpringBootDemo {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemo.class, args);
    }
}

home.jsp

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello</title>

    Hello World

When I try to execute the code, it shows in the output as

Controller

But it gives the Whitelabel Error Page when I visit http://localhost:8080/

Body:
UPDATE
Ok I'll try to do better. It was not my intention to do you wrong...

I think you need to extend the SpringBootApplication class from  SpringBootServletInitializer to get servlet functionality in your Spring Boot application

@SpringBootApplication
public class WebApplication extends SpringBootServletInitializer {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(WebApplication.class, args);
    }
}

In order to be able to resolve the view you have to define these properties:

spring.mvc.view.prefix: /WEB-INF/pages
spring.mvc.view.suffix: .jsp

or of course the yaml variant of them. The actual jsp pages need then be placed in src/main/webapp/WEB-INF/pages

These are the dependencies in my pom

   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>

I hope you can translate this to gradle yourself?

My sample controller looks like this:

@Controller
public class HelloController {
    @RequestMapping("/")
    public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="World") String name) {
        model.addAttribute("name", name);
        return "hello";
    }
}

Hope this will help you with getting your app working...


问:
django combine to query result and perform query on the combined query result on postgres
I am trying to accomplish a query to determine the number of checkout and checkin in a day for an attendance that is unique to the employee without duplication of checkin and checkout, and picking the latest to be distinct.

In essence is combine 2 query result, and perform a query on the result.

Its much easier explained below.

I have 2 models:

```<code>class Employee(models.Model):
    fullname = models.CharField(max_length=30, blank=False)

class Attendance(models.Model):
    CHECKIN = 1
    CHECKOUT = 2
    ATTENDANCE_TYPE_CHOICES = (
        (CHECKIN, "Check In"),
        (CHECKOUT, "Check Out"),
    )
    employee = models.ForeignKey(Employee)
    activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN)
    timestamp = models.DateTimeField(auto_now_add=True)
</code>```

And I have this 2 queries to obtain the unique CheckIn and CheckOut of the employee in the attendance.

```<code>unique_employee_attendance_checkin_today = Attendance.objects.filter(company=auth_employee.employee.company.id,
                                    activity_type=Attendance.CHECKIN,
                                    timestamp__date = today).order_by(
                                    'employee_id','-timestamp').distinct('employee_id')

unique_employee_attendance_checkout_today = Attendance.objects.filter(company=auth_employee.employee.company.id,
                                    activity_type=Attendance.CHECKOUT,
                                    timestamp__date = today).order_by(
                                    'employee_id','-timestamp').distinct('employee_id')
</code>```

Assuming I have these records

```<code>Employee
{"id":1, "employee":"michael jackson",
"id":2, "fullname":"mariah carey",
"id":3, "fullname":"taylor swift"}

Attendance
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13",
"id":3, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 11:30",
"id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13",
"id":7, "employee": 1,"activity_type": 2, timestamp: "2017-12-06 08:08"}
</code>```

unique_employee_attendance_checkin_today - will output this result

```<code>{"id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30"}
</code>```

unique_employee_attendance_checkout_today - will output this result

```<code>{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13"}
</code>```

Question no.1 is here:

I want to combine these 2 queries

```<code>unique_employee_attendance_checkin_today + unique_employee_attendance_checkout_today
</code>```

and

I want to create a distinct for the employee, it will remove 2 of the records, so the output result will be like this.

```<code>{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30"
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13"}
</code>```

Question no.2 is here:

and then do a query based on the result for activity_type = 1 (CHECKIN) and another for activity_type = 2 (CHECKOUT)

The question is above, which is how can i combine 2 queries result, and perform query on the combine queries based on the above requirements.

答:
The combined query (latest attendance per employee/date regardless of type) could just leave the activity_type out completely:

```<code>unique_employee_attendance_today = Attendance.objects.filter(
    company=auth_employee.employee.company.id,
    timestamp__date = today).order_by(
        'employee_id','-timestamp'
    ).distinct('employee_id')
</code>```

Now you can filter checkins out of that set in a nested query like:

```<code>Attendance.objects.filter(
    id__in=unique_employee_attendance_today,
    activity_type=Attendance.CHECKIN
)
</code>```

This will only result in a single database query.

Body:
I am trying to accomplish a query to determine the number of checkout and checkin in a day for an attendance that is unique to the employee without duplication of checkin and checkout, and picking the latest to be distinct.

In essence is combine 2 query result, and perform a query on the result.

Its much easier explained below.

I have 2 models:

class Employee(models.Model):
    fullname = models.CharField(max_length=30, blank=False)

class Attendance(models.Model):
    CHECKIN = 1
    CHECKOUT = 2
    ATTENDANCE_TYPE_CHOICES = (
        (CHECKIN, "Check In"),
        (CHECKOUT, "Check Out"),
    )
    employee = models.ForeignKey(Employee)
    activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN)
    timestamp = models.DateTimeField(auto_now_add=True)

And I have this 2 queries to obtain the unique CheckIn and CheckOut of the employee in the attendance.

unique_employee_attendance_checkin_today = Attendance.objects.filter(company=auth_employee.employee.company.id,
                                    activity_type=Attendance.CHECKIN,
                                    timestamp__date = today).order_by(
                                    'employee_id','-timestamp').distinct('employee_id')

unique_employee_attendance_checkout_today = Attendance.objects.filter(company=auth_employee.employee.company.id,
                                    activity_type=Attendance.CHECKOUT,
                                    timestamp__date = today).order_by(
                                    'employee_id','-timestamp').distinct('employee_id')

Assuming I have these records

Employee
{"id":1, "employee":"michael jackson",
"id":2, "fullname":"mariah carey",
"id":3, "fullname":"taylor swift"}

Attendance
{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13",
"id":3, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 11:30",
"id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13",
"id":7, "employee": 1,"activity_type": 2, timestamp: "2017-12-06 08:08"}

unique_employee_attendance_checkin_today - will output this result

{"id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13",
"id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30"}

unique_employee_attendance_checkout_today - will output this result

{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13"}

Question no.1 is here:

I want to combine these 2 queries

unique_employee_attendance_checkin_today + unique_employee_attendance_checkout_today

and

I want to create a distinct for the employee, it will remove 2 of the records, so the output result will be like this.

{"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08",
"id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30"
"id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13"}

Question no.2 is here:

and then do a query based on the result for activity_type = 1 (CHECKIN) and another for activity_type = 2 (CHECKOUT)

The question is above, which is how can i combine 2 queries result, and perform query on the combine queries based on the above requirements.

Body:
The combined query (latest attendance per employee/date regardless of type) could just leave the activity_type out completely:

unique_employee_attendance_today = Attendance.objects.filter(
    company=auth_employee.employee.company.id,
    timestamp__date = today).order_by(
        'employee_id','-timestamp'
    ).distinct('employee_id')

Now you can filter checkins out of that set in a nested query like:

Attendance.objects.filter(
    id__in=unique_employee_attendance_today,
    activity_type=Attendance.CHECKIN
)

This will only result in a single database query.


问:
How to use confirm in JavaScript with PHP
```<code>   <?php
 mysql_connect("localhost","root","");
 mysql_select_db("lastasignment");
if(isset($_GET['act'])){
 $nid=$_GET['i']; ?>
<script type="text/javascript">
 if(confirm("you want to delete "+" <?php echo $nid ?>")){
<?php $i=$_GET['i'];
mysql_query("delete from testings where id=$i");
 ?> ;
 }else {
alert("cancelled");
}
</script>
</code>```

The data in the table is deleted whether i click ok or cancel?

答:
You are trying to alert the user whether to continue or not. Here is that code

```<code>if (confirm('Are you sure you want to do this thing into the database?')) {
    // operation to execute
} else {
    // operation on false
}
</code>```

call the function by onclick event in edit e.g(onclick="showUser(this.value)")

AJAX:

```<code><script>
function showUser(str) {
    if (confirm('Are you sure you want to do this thing into the database?')) {
        // operation to execute
        if (str == "") {
            document.getElementById("txtHint").innerHTML="";
            return;
        }

        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function() {
            if (this.readyState==4 && this.status==200) {
              document.getElementById("txtHint").innerHTML = this.responseText;
            }
        }
        xmlhttp.open("GET","linktophp.php?q="+str,true);
        xmlhttp.send();
    } else {
        alert("cancelled");
    }
}
</script>
</code>```

PHP FILE:

```<code><?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','****','abc123','my_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="DELETE FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
?>
</code>```

Body:
   <?php
 mysql_connect("localhost","root","");
 mysql_select_db("lastasignment");
if(isset($_GET['act'])){
 $nid=$_GET['i']; ?>

The data in the table is deleted whether i click ok or cancel?

Body:
You are trying to alert the user whether to continue or not. Here is that code

if (confirm('Are you sure you want to do this thing into the database?')) {
    // operation to execute
} else {
    // operation on false
}

call the function by onclick event in edit e.g(onclick="showUser(this.value)")

AJAX:

<script>
function showUser(str) {
    if (confirm('Are you sure you want to do this thing into the database?')) {
        // operation to execute
        if (str == "") {
            document.getElementById("txtHint").innerHTML="";
            return;
        }

        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function() {
            if (this.readyState==4 && this.status==200) {
              document.getElementById("txtHint").innerHTML = this.responseText;
            }
        }
        xmlhttp.open("GET","linktophp.php?q="+str,true);
        xmlhttp.send();
    } else {
        alert("cancelled");
    }
}
</script>

PHP FILE:

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','****','abc123','my_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="DELETE FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
?>


问:
Pascal, convert string to palindrome
I must check if string can be changed to palindrome, fo example:

Input: AABBCC, ABCD

Output: Yes (ABCCBA), No

I come out with this code:

```<code>program test;
var
 x, y: string;
 i: integer;
begin
 readln(x);
  for i:= length(x) downto 1 do
  y := y + x[i];

 writeln(y);
 readln
end.
</code>```

But this program only write text from back.

I will be gratefull for any answer

答:
What you can do is following:

Create array of integers indexed with characters like this: chars:array['A'..'Z'] of integer

Go through every char in string and increase its array element. For example string is 'ABBCBBA'. You would increase counter on 'A' twice, on 'C' once and on 'B' 4 times.

Then go through array and have one test boolean. If every index has value that is even or has ONLY one odd value, than string can be become palindrome. Else I cant become palindrome. Boolean starts as 'true' and will become false once you find odd value more than once. Above given example would return true because every character repeats even number of times, expect 'C' and 'C' is only uneven value. Something like 'ABBC' returns false.

Very simple algorithm. Good luck with implementation.

With this you can just output boolean value once you are done.

Title: Pascal, convert string to palindrome

Body:
I must check if string can be changed to palindrome, fo example:

Input: AABBCC, ABCD

Output: Yes (ABCCBA), No

I come out with this code:

program test;
var
 x, y: string;
 i: integer;
begin
 readln(x);
  for i:= length(x) downto 1 do
  y := y + x[i];

 writeln(y);
 readln
end.

But this program only write text from back.

I will be gratefull for any answer


问:
Bash alias: command not found
I'm trying to setup a simple alias to move me into my Developer folder on my machine. However, after setting it up, I get a weird error:

```<code>-bash: dv: command not found
</code>```

I setup my alias in .bashrc like so:

```<code>alias dv='cd Developer/'
</code>```

I use it by just typing dv, and then get that error. Does anyone see any syntax errors or something I'm missing here for aliases?

答:
Make sure the following line is present inside .bash_profile

test -f ~/.bashrc && . ~/.bashrc

If not then add it to the beginning. This code is used by .bash_profile to load up .bashrc.
If this line is not present inside .bash_profile then anything you type inside .bashrc will not be loaded.

Title: Bash alias: command not found

Body:
I'm trying to setup a simple alias to move me into my Developer folder on my machine. However, after setting it up, I get a weird error:

-bash: dv: command not found

I setup my alias in .bashrc like so:

alias dv='cd Developer/'

I use it by just typing dv, and then get that error. Does anyone see any syntax errors or something I'm missing here for aliases?


问:
Styling Feed Content returned in XML Format
I have this code that is pulling info from my database and then checking it against an API. I'm trying to customize the return information into a table. I'll include a picture to show what I would like. I've searched everywhere and I don't know how to code this. Don't worry about the CSS it's just getting the information to fill a table.

```<code><?php
        $key = "********************";
        $address = urlencode($CustomFields->field('jr_address',$listing,false,false));
        $city = $listing['Category']['title'];
        $zip = $CustomFields->field('jr_zipcode',$listing,false,false);
        $url = "http://api.greatschools.org/schools/nearby?key={$key}&address={$address}&city={$city}&state=MI&zip={$zip}&schoolType=public-charter&levelCode=elementary-schools&minimumSchools=50&radius=10&limit=5";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);
        curl_close($curl);
        print_r($response);
?><style type='text/css'>gsId{display:none;}name{color:#9BB055; font-size:18px;}type{display:none;}gradeRange{}enrollment{}gsRating{}city{display:none;}state{display:none;}district{}districtNCESId{display:none;}address{display:none;}phone{display:none; }fax{display:none;}ncesId{display:none;}lat{display:none;}lon{display:none;}</style>
</code>```

The Return Code:

```<code>    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<schools>
<school>
<gsId>6350</gsId>
<name>Chinese Education Center</name>
<type>public</type>
<gradeRange>K-5</gradeRange>
<enrollment>63</enrollment>
<gsRating>3</gsRating>
<city>San Francisco</city>
<state>CA</state>
<district>San Francisco Unified School District</district>
<districtNCESId>0634410</districtNCESId>
<address>657 Merchant St., San Francisco, CA  94111</address>
<phone>(415) 291-7918</phone>
<fax>(415) 291-7965</fax>
<ncesId>063441005596</ncesId>
<lat>37.795</lat>
<lon>-122.4042</lon>
<overviewLink>http://www.greatschools.org/california/san-francisco/6350-Chinese-Education-Center/?s_cid=gsapi</overviewLink>
<ratingsLink>http://www.greatschools.org/school/rating.page?state=CA&id=6350&s_cid=gsapi</ratingsLink>
<reviewsLink>http://www.greatschools.org/school/parentReviews.page?state=CA&id=6350&s_cid=gsapi</reviewsLink>
</school>
<school>
<gsId>6389</gsId>
<name>Gordon J. Lau Elementary School</name>
<type>public</type>
<gradeRange>K-5</gradeRange>
<enrollment>667</enrollment>
<gsRating>7</gsRating>
<city>San Francisco</city>
<state>CA</state>
<district>San Francisco Unified School District</district>
<districtNCESId>0634410</districtNCESId>
<address>950 Clay St., San Francisco, CA  94108</address>
<phone>(415) 291-7921</phone>
<fax>(415) 291-7952</fax>
<website>http://www.gjles.org/</website>
<ncesId>063441005599</ncesId>
<lat>37.794</lat>
<lon>-122.4086</lon>
<overviewLink>http://www.greatschools.org/california/san-francisco/6389-Gordon-J.-Lau-Elementary-School/?s_cid=gsapi</overviewLink>
<ratingsLink>http://www.greatschools.org/school/rating.page?state=CA&id=6389&s_cid=gsapi</ratingsLink>
<reviewsLink>http://www.greatschools.org/school/parentReviews.page?state=CA&id=6389&s_cid=gsapi</reviewsLink>
</school>
</schools>
</code>```

I don't know how to write the script to make it look like this:
Link to image:
link text

So the new file looks like this?

```<code><?php
    $key = "xxxxxxxxxxxxxxxxxxxxxxxx";
    $address = urlencode($CustomFields->field('jr_address',$listing,false,false));
    $city = $listing['Category']['title'];
    $zip = $CustomFields->field('jr_zipcode',$listing,false,false);
    $url = "http://api.greatschools.org/schools/nearby?key={$key}&address={$address}&city={$city}&state=MI&zip={$zip}&schoolType=public-charter&levelCode=elementary-schools&minimumSchools=50&radius=10&limit=5";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curl);
    curl_close($curl);
    echo (xml2html($response, "/xslt/schools.xsl");
</code>```

?>

I get an error on the echo line.

Where does this go?

```<code><?php
function xml2html($xmldata, $xslPath)
{
    /* $xmldata -> your XML */
    /* $xsl -> XSLT file */

    $arguments = array('/_xml' => $xmldata);
    $xsltproc = xslt_create();
    xslt_set_encoding($xsltproc, 'ISO-8859-1');
    $html =
        xslt_process($xsltproc, 'arg:/_xml', $xslPath, NULL, $arguments);

    if (empty($html)) {
       die('XSLT processing error: '. xslt_error($xsltproc));
    }
    xslt_free($xsltproc);
    return $html;
}
?>
</code>```

答:
Browsers are unable to visualize custom XML (i.e. your schools xml).
So you should manually transform it to HTML. I know 2 solutions:

Parse XML with xml parser functions

Transform XML by XSLT sheet (as for me, better approach).

For offerred XML I've written next XSLT: link text (sorry for external link, I  have unexplainable troubles with pasting XSLT code here)

Transformation could be applied by the function xslt_process. (You should store xsl file somewhere in your server's folder (for example "xslt/schools.xsl") and convert xml response):

```<code><?php
function xml2html($xmldata, $xslPath)
{
    /* $xmldata -> your XML */
    /* $xsl -> XSLT file */

    $arguments = array('/_xml' => $xmldata);
    $xsltproc = xslt_create();
    xslt_set_encoding($xsltproc, 'ISO-8859-1');
    $html =
        xslt_process($xsltproc, 'arg:/_xml', $xslPath, NULL, $arguments);

    if (empty($html)) {
       die('XSLT processing error: '. xslt_error($xsltproc));
    }
    xslt_free($xsltproc);
    return $html;
}

// making request...
$response = curl_exec($curl);
curl_close($curl);
echo(xml2html($response, "/xslt/schools.xsl"));
</code>```

?>

Body:
I have this code that is pulling info from my database and then checking it against an API. I'm trying to customize the return information into a table. I'll include a picture to show what I would like. I've searched everywhere and I don't know how to code this. Don't worry about the CSS it's just getting the information to fill a table.

<?php
        $key = "********************";
        $address = urlencode($CustomFields->field('jr_address',$listing,false,false));
        $city = $listing['Category']['title'];
        $zip = $CustomFields->field('jr_zipcode',$listing,false,false);
        $url = "http://api.greatschools.org/schools/nearby?key={$key}&address={$address}&city={$city}&state=MI&zip={$zip}&schoolType=public-charter&levelCode=elementary-schools&minimumSchools=50&radius=10&limit=5";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($curl);
        curl_close($curl);
        print_r($response);
?>

The Return Code:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<schools>
<school>
<gsId>6350</gsId>
<name>Chinese Education Center</name>
<type>public</type>
<gradeRange>K-5</gradeRange>
<enrollment>63</enrollment>
<gsRating>3</gsRating>
<city>San Francisco</city>
<state>CA</state>
<district>San Francisco Unified School District</district>
<districtNCESId>0634410</districtNCESId>
<address>657 Merchant St., San Francisco, CA  94111</address>
<phone>(415) 291-7918</phone>
<fax>(415) 291-7965</fax>
<ncesId>063441005596</ncesId>
<lat>37.795</lat>
<lon>-122.4042</lon>
<overviewLink>http://www.greatschools.org/california/san-francisco/6350-Chinese-Education-Center/?s_cid=gsapi</overviewLink>
<ratingsLink>http://www.greatschools.org/school/rating.page?state=CA&id=6350&s_cid=gsapi</ratingsLink>
<reviewsLink>http://www.greatschools.org/school/parentReviews.page?state=CA&id=6350&s_cid=gsapi</reviewsLink>
</school>
<school>
<gsId>6389</gsId>
<name>Gordon J. Lau Elementary School</name>
<type>public</type>
<gradeRange>K-5</gradeRange>
<enrollment>667</enrollment>
<gsRating>7</gsRating>
<city>San Francisco</city>
<state>CA</state>
<district>San Francisco Unified School District</district>
<districtNCESId>0634410</districtNCESId>
<address>950 Clay St., San Francisco, CA  94108</address>
<phone>(415) 291-7921</phone>
<fax>(415) 291-7952</fax>
<website>http://www.gjles.org/</website>
<ncesId>063441005599</ncesId>
<lat>37.794</lat>
<lon>-122.4086</lon>
<overviewLink>http://www.greatschools.org/california/san-francisco/6389-Gordon-J.-Lau-Elementary-School/?s_cid=gsapi</overviewLink>
<ratingsLink>http://www.greatschools.org/school/rating.page?state=CA&id=6389&s_cid=gsapi</ratingsLink>
<reviewsLink>http://www.greatschools.org/school/parentReviews.page?state=CA&id=6389&s_cid=gsapi</reviewsLink>
</school>
</schools>

I don't know how to write the script to make it look like this:
Link to image:
link text

So the new file looks like this?

<?php
    $key = "xxxxxxxxxxxxxxxxxxxxxxxx";
    $address = urlencode($CustomFields->field('jr_address',$listing,false,false));
    $city = $listing['Category']['title'];
    $zip = $CustomFields->field('jr_zipcode',$listing,false,false);
    $url = "http://api.greatschools.org/schools/nearby?key={$key}&address={$address}&city={$city}&state=MI&zip={$zip}&schoolType=public-charter&levelCode=elementary-schools&minimumSchools=50&radius=10&limit=5";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curl);
    curl_close($curl);
    echo (xml2html($response, "/xslt/schools.xsl");

?>

I get an error on the echo line.

Where does this go?

<?php
function xml2html($xmldata, $xslPath)
{
    /* $xmldata -> your XML */
    /* $xsl -> XSLT file */

    $arguments = array('/_xml' => $xmldata);
    $xsltproc = xslt_create();
    xslt_set_encoding($xsltproc, 'ISO-8859-1');
    $html =
        xslt_process($xsltproc, 'arg:/_xml', $xslPath, NULL, $arguments);

    if (empty($html)) {
       die('XSLT processing error: '. xslt_error($xsltproc));
    }
    xslt_free($xsltproc);
    return $html;
}
?>

Body:
Browsers are unable to visualize custom XML (i.e. your schools xml).
So you should manually transform it to HTML. I know 2 solutions:

Parse XML with xml parser functions

Transform XML by XSLT sheet (as for me, better approach).

For offerred XML I've written next XSLT: link text (sorry for external link, I  have unexplainable troubles with pasting XSLT code here)

Transformation could be applied by the function xslt_process. (You should store xsl file somewhere in your server's folder (for example "xslt/schools.xsl") and convert xml response):

<?php
function xml2html($xmldata, $xslPath)
{
    /* $xmldata -> your XML */
    /* $xsl -> XSLT file */

    $arguments = array('/_xml' => $xmldata);
    $xsltproc = xslt_create();
    xslt_set_encoding($xsltproc, 'ISO-8859-1');
    $html =
        xslt_process($xsltproc, 'arg:/_xml', $xslPath, NULL, $arguments);

    if (empty($html)) {
       die('XSLT processing error: '. xslt_error($xsltproc));
    }
    xslt_free($xsltproc);
    return $html;
}

// making request...
$response = curl_exec($curl);
curl_close($curl);
echo(xml2html($response, "/xslt/schools.xsl"));

?>


问:
Cannot display image in webpage
I have problem displaying my image after I upload my coding to online web hosting. When I do in  my localhost, I the image manage to retrieve out and manage to move to the accessory folder. But when I try in online, the image  upload do not move to the accessory folder that store the image and cannot be retrieve out. Below is my code:

adminadd.php

```<code><?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "db_name");

if(isset($_POST['submit'])){
    $name=$_POST['name'];
    $description=$_POST['description'];
    $image = $_FILES['image']['name'];
    $image_temp = $_FILES['image']['tmp_name'];
    move_uploaded_file($image_temp,"accessory/".$image);
    $price=$_POST['price'];
    $category=$_POST['category'];

    $query="INSERT INTO product (name,product_description,price,catid,image) VALUES ('$name','$description','$price','$category','$image')";

    if(mysqli_query($connect, $query)){
        echo "<script>alert('Successfully inserted')</script>";

    }
}
?>
</code>```

Can someone enlighten me with my problem. Appreciate alot.

答:
The destination needs to be a filename, not a URL.

Typically, it is not possible to write to HTTP URLs (it requires the server to be set up to allow it, and for you to make a PUT request with appropriate authentication … move_uploaded_file can't do that).

Change http://fypesystem.com/Shineacc/accessory/ to a directory path on your server's filesystem.

Title: Cannot display image in webpage

Body:
I have problem displaying my image after I upload my coding to online web hosting. When I do in  my localhost, I the image manage to retrieve out and manage to move to the accessory folder. But when I try in online, the image  upload do not move to the accessory folder that store the image and cannot be retrieve out. Below is my code:

adminadd.php

<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "db_name");

if(isset($_POST['submit'])){
    $name=$_POST['name'];
    $description=$_POST['description'];
    $image = $_FILES['image']['name'];
    $image_temp = $_FILES['image']['tmp_name'];
    move_uploaded_file($image_temp,"accessory/".$image);
    $price=$_POST['price'];
    $category=$_POST['category'];

    $query="INSERT INTO product (name,product_description,price,catid,image) VALUES ('$name','$description','$price','$category','$image')";

    if(mysqli_query($connect, $query)){
        echo "";

    }
}
?>

Can someone enlighten me with my problem. Appreciate alot.


问:
Mate not listening to events - Flex
I am working on a simple project involving flex 4 and Mate framework. When I am including Mate event map in fx:declarations tag in mxml file, and when I fire up an event, Mate event handlers listen to events and act upon it.

The issue is this, in action script based project, when I instantiate the eventmap class(this is in mxml file only) and keep it in top and fireup an event, instantiated eventmap is not listening to event fired up from action script class.

What do you think is going wrong?

Thanks in advance.

答:
Antony. Just a suggestion, getting an example  CafeTownSend http://mate.asfusion.com/page/examples/cafe-townsend is not a bad idea.

Build your application using that example will be much more easy. You can learn the event handling of MATE from that project too.

Title: Mate not listening to events - Flex


问:
Writing a big text file fast
How can I write a big text file very fast on Android?

I made some tests using a PrintWriter, a BufferedWriter and a FileWriter, but there are no significative time difference, and writing takes about three times the time of reading.

答:
For faster file read/write take a look at java.nio package.

This is a good article about java NIO, here you can find comparison with IO package

Title: Writing a big text file fast


问:
How to make the path to songs in pygame relative
Im working on a simple Snake game in python, and its working as intended here at home, but when I put the code on github, it doesn't find the path to the songs, I want to make this path relative, intead of absolute so it works on every computer.

Here is the part of the code for the song files -

```<code> def game_sound(s):
        """ Include the game sfx and music"""
        if s == 0:
            pygame.mixer.music.load("background.ogg")
            pygame.mixer.music.play(-1)
        elif s == 1:
            pygame.mixer.Sound("eating.wav").play()
        elif s == 2:
            pygame.mixer.Sound("game-over.wav").play()
</code>```

TL - DR- It works here at home and nowhere else, Im trying to find a way to fix that by making the path relative I just dont know how. Can someone help?

答:
Standard method is to find real path to folder with application

```<code>import os, sys

APP_FOLDER = os.path.dirname(os.path.realpath(sys.argv[0]))
</code>```

And later use it to create real path to file

```<code>full_path = os.path.join(APP_FOLDER, "eating.wav")

pygame.mixer.Sound(full_path).play()
</code>```

Or you have to change "current working directory" (CWD) to application folder.

```<code>os.chdir(APP_FOLDER)

pygame.mixer.Sound("eating.wav").play()
</code>```

You can check current working directory with

```<code>print(os.getcwd())
</code>```

BTW: without this method problem is not only when you run on different computer but also when you run from different folder on the same computer - so it makes problem when you create shortcut/icon on desktop which executes program as python game_folder/game.py

Body:
Im working on a simple Snake game in python, and its working as intended here at home, but when I put the code on github, it doesn't find the path to the songs, I want to make this path relative, intead of absolute so it works on every computer.

Here is the part of the code for the song files -

 def game_sound(s):
        """ Include the game sfx and music"""
        if s == 0:
            pygame.mixer.music.load("background.ogg")
            pygame.mixer.music.play(-1)
        elif s == 1:
            pygame.mixer.Sound("eating.wav").play()
        elif s == 2:
            pygame.mixer.Sound("game-over.wav").play()

TL - DR- It works here at home and nowhere else, Im trying to find a way to fix that by making the path relative I just dont know how. Can someone help?

Body:
Standard method is to find real path to folder with application

import os, sys

APP_FOLDER = os.path.dirname(os.path.realpath(sys.argv[0]))

And later use it to create real path to file

full_path = os.path.join(APP_FOLDER, "eating.wav")

pygame.mixer.Sound(full_path).play()

Or you have to change "current working directory" (CWD) to application folder.

os.chdir(APP_FOLDER)

pygame.mixer.Sound("eating.wav").play()

You can check current working directory with

print(os.getcwd())

BTW: without this method problem is not only when you run on different computer but also when you run from different folder on the same computer - so it makes problem when you create shortcut/icon on desktop which executes program as python game_folder/game.py


问:
CronJob not able to start docker container
I am trying to run a container using cronjob however my cron is not able to run container.

I have a cron task to invoke orchestrate.sh which starts a container

crontab -l

```<code>27 22 08 * * /tmp/compose/orchestrate.sh >> /var/log/composeerr.log
#have a newline
</code>```

orchestrate.sh

```<code>#!/bin/bash -v
/usr/bin/docker run -d hello/helloworld:latest >> /somerror.log
</code>```

somerror.log has a container id , however docker ps on host is not showing it.

If I run the command /usr/bin/docker run -d hello/helloworld:latest >> /somerror.log  on host its bringing the container up.

What am I missing?

答: The user the cronjob is running under must be able to start a docker container. On linux this is often the root user or a user added to that group.</p>

Body:
I am trying to run a container using cronjob however my cron is not able to run container.

I have a cron task to invoke orchestrate.sh which starts a container

crontab -l

27 22 08 * * /tmp/compose/orchestrate.sh >> /var/log/composeerr.log
#have a newline

orchestrate.sh

#!/bin/bash -v
/usr/bin/docker run -d hello/helloworld:latest >> /somerror.log

somerror.log has a container id , however docker ps on host is not showing it.

If I run the command /usr/bin/docker run -d hello/helloworld:latest >> /somerror.log  on host its bringing the container up.

What am I missing?


问:
How to mix Mp3 files
I would like to mix MP3 files with Delphi 2010.

Is this possible? Does anyone know of a component(set) I could use to get this done? Or maybe a runtime library? Any tips from someone with experience mixing MP3 files?

答:
you can do this using bass ,Bassenc and lame encoder .

download lame encoder from http://www.rarewares.org/mp3-lame-bundle.php
and bass  from http://www.un4seen.com/
put bass.dll ,bass.pas,Bassenc.dll,bassenc.pas and lime.exe in same folder as your project exe file.
to use sample code put a listbox ,opendialog and two buttons on form

```<code>unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, bass, bassenc,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    OpenDialog1: TOpenDialog;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  //
  if OpenDialog1.Execute then
    ListBox1.items.add(OpenDialog1.FileName);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  decoder, encoder, newdecoder: dword;
  I, R: Integer;
  buf: array [1 .. 204800] of byte;

begin
  for I := 0 to ListBox1.items.count - 1 do
  begin
    if I = 0 then
    begin
      decoder := BASS_StreamCreateFile(FALSE, PChar(ListBox1.items.strings[0]),
        0, 0, BASS_STREAM_DECODE or BASS_UNICODE);
      encoder := BASS_Encode_Start(decoder,
        'lame.exe --alt-preset standard - fulltrack.mp3',
        BASS_ENCODE_AUTOFREE or BASS_UNICODE, nil, nil);

    end
    else
    begin
      newdecoder := BASS_StreamCreateFile(FALSE, PChar(ListBox1.items.strings[I]
        ), 0, 0, BASS_STREAM_DECODE or BASS_UNICODE);

      if not BASS_Encode_SetChannel(encoder, newdecoder) then
      begin
        showmessage(inttostr(BASS_ErrorGetCode));
        BASS_StreamFree(decoder);
        continue;
      end;
      BASS_StreamFree(decoder);

   // free the old decoder
      decoder := newdecoder;
    end;

    R := 1;
    while R > 0 do
    begin
      R := BASS_ChannelGetData(decoder, @buf, sizeof(buf));
    end;

  end;

  BASS_StreamFree(decoder); // free the decoder
  BASS_Encode_Stop(encoder); // stop the encoder
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  if not BASS_Init(-1, 44100, 0, handle, nil) then
    showmessage('Error initializing audio!');
end;

end.
</code>```

Title: How to mix Mp3 files

Body:
you can do this using bass ,Bassenc and lame encoder .

download lame encoder from http://www.rarewares.org/mp3-lame-bundle.php
and bass  from http://www.un4seen.com/
put bass.dll ,bass.pas,Bassenc.dll,bassenc.pas and lime.exe in same folder as your project exe file.
to use sample code put a listbox ,opendialog and two buttons on form

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics, bass, bassenc,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    OpenDialog1: TOpenDialog;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  //
  if OpenDialog1.Execute then
    ListBox1.items.add(OpenDialog1.FileName);
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  decoder, encoder, newdecoder: dword;
  I, R: Integer;
  buf: array [1 .. 204800] of byte;

begin
  for I := 0 to ListBox1.items.count - 1 do
  begin
    if I = 0 then
    begin
      decoder := BASS_StreamCreateFile(FALSE, PChar(ListBox1.items.strings[0]),
        0, 0, BASS_STREAM_DECODE or BASS_UNICODE);
      encoder := BASS_Encode_Start(decoder,
        'lame.exe --alt-preset standard - fulltrack.mp3',
        BASS_ENCODE_AUTOFREE or BASS_UNICODE, nil, nil);

    end
    else
    begin
      newdecoder := BASS_StreamCreateFile(FALSE, PChar(ListBox1.items.strings[I]
        ), 0, 0, BASS_STREAM_DECODE or BASS_UNICODE);

      if not BASS_Encode_SetChannel(encoder, newdecoder) then
      begin
        showmessage(inttostr(BASS_ErrorGetCode));
        BASS_StreamFree(decoder);
        continue;
      end;
      BASS_StreamFree(decoder);

   // free the old decoder
      decoder := newdecoder;
    end;

    R := 1;
    while R > 0 do
    begin
      R := BASS_ChannelGetData(decoder, @buf, sizeof(buf));
    end;

  end;

  BASS_StreamFree(decoder); // free the decoder
  BASS_Encode_Stop(encoder); // stop the encoder
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  if not BASS_Init(-1, 44100, 0, handle, nil) then
    showmessage('Error initializing audio!');
end;

end.


问:
Complete command from history in ipython
For reasons outside of my control I'm stuck using python 2.6.6 and IPython 0.10.2. I also normally use the tcsh shell, and have gotten quite used to completing a command from the history using  (i.e. pressing the ALT key and p). However, this doesn't work in IPython. I know I can press <C-r> and then start typing a command, but what inevitably is happening is that I start a command, press , get a colon indicating some weird state, then exit out of that state, delete my command, press <C-r> then search for my command. It's getting rather irritating. Is there any way to make  complete my already started command by relying on the history?

答:
Ouch, this is an old version of IPython, Python (and pip). The bad news is I don't have much experience with such an old version of IPython, the good new is; it was way simpler at that time.

Most of the shortcut and feature are provided using readline, and the python bindings of stdlib. Meaning that most likely what you are trying to configure is readline itself and not only IPython; so you can  find more information on that outside of IPython !

The secret is to grep in the source-code for parse_and_bind, then you'll find the following example configuration, leading me to change the ~/.ipython/ipy_user_conf.py to be like so at around line 99 (all indented an extra 4 space to be in the main() function):

```<code>import readline
readline.parse_and_bind('set completion-query-items 1000')
readline.parse_and_bind('set page-completions no')
rlopts = """\
tab: complete
"\C-l": possible-completions
set show-all-if-ambiguous on
"\C-o": tab-insert
"\M-i": "    "
"\M-o": "\d\d\d\d"
"\M-I": "\d\d\d\d"
"\C-r": reverse-search-history
"\C-s": forward-search-history
"\C-p": history-search-backward
"\C-n": history-search-forward
"\e[A": history-search-backward
"\e[B": history-search-forward
"\C-k": kill-line
"\C-u": unix-line-discard"""

for cmd in rlopts.split('\n'):
    readline.parse_and_bind(cmd)
</code>```

The repetition of commands make me think that what \C,\M or [e mean  might be system dependant. I would bet on \C being Control, and \M being Meta (Alt, Opt), but at least one of these line did the trick for me (and also now tab allows to complete). See also man readline for the list of commands you can bind to what, and enjoy! Hoping you can upgrade to Python 3 and IPython 6 at some point.

[Edit]

See Eric Carlsen second comment under this answer for how it was resolved.

Body:
Ouch, this is an old version of IPython, Python (and pip). The bad news is I don't have much experience with such an old version of IPython, the good new is; it was way simpler at that time.

Most of the shortcut and feature are provided using readline, and the python bindings of stdlib. Meaning that most likely what you are trying to configure is readline itself and not only IPython; so you can  find more information on that outside of IPython !

The secret is to grep in the source-code for parse_and_bind, then you'll find the following example configuration, leading me to change the ~/.ipython/ipy_user_conf.py to be like so at around line 99 (all indented an extra 4 space to be in the main() function):

import readline
readline.parse_and_bind('set completion-query-items 1000')
readline.parse_and_bind('set page-completions no')
rlopts = """\
tab: complete
"\C-l": possible-completions
set show-all-if-ambiguous on
"\C-o": tab-insert
"\M-i": "    "
"\M-o": "\d\d\d\d"
"\M-I": "\d\d\d\d"
"\C-r": reverse-search-history
"\C-s": forward-search-history
"\C-p": history-search-backward
"\C-n": history-search-forward
"\e[A": history-search-backward
"\e[B": history-search-forward
"\C-k": kill-line
"\C-u": unix-line-discard"""

for cmd in rlopts.split('\n'):
    readline.parse_and_bind(cmd)

The repetition of commands make me think that what \C,\M or [e mean  might be system dependant. I would bet on \C being Control, and \M being Meta (Alt, Opt), but at least one of these line did the trick for me (and also now tab allows to complete). See also man readline for the list of commands you can bind to what, and enjoy! Hoping you can upgrade to Python 3 and IPython 6 at some point.

[Edit]

See Eric Carlsen second comment under this answer for how it was resolved.


问:
ERROR in ./src/main.ts Module not found(ng build --prod)
I'm working on angular-cli. I got following errors.

ERROR in ./src/main.ts
  Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in 'D:\material\matapp\src'
   @ ./src/main.ts 3:0-74
   @ multi ./src/main.ts

My main.ts file:

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

if (environment.production) {
    enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

Kindly help me to resolve the issue.PFA

答: I had same issue and fixed it by deleting node_module and run npm install.</p>

Body:
I'm working on angular-cli. I got following errors.

ERROR in ./src/main.ts
  Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in 'D:\material\matapp\src'
   @ ./src/main.ts 3:0-74
   @ multi ./src/main.ts

My main.ts file:

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

if (environment.production) {
    enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);

Kindly help me to resolve the issue.PFA


问:
Bitbucket webhook to run jenkins job

Update:

I succesfuly sent a post request from curl to trigger jenkins job:

```<code>curl -I -X POST http://jenkinsAccountUserName:jenkinsAccountPassword@JenkinsIp:8080/job/projecty_ci/build -H "Jenkins-Crumb:a4fb99fbdb252fda3cc69ee575bedabc"
</code>```

I don't understand how to convert this to a url: Problem accessing /job/projecty_ci/build. Reason: No valid crumb was included in the request.

```<code>http://jenkinsAccountUserName:jenkinsAccountPassword@JenkinsIp:8080/job/projecty_ci/build?Jenkins-Crumb:a4fb99fbdb252fda3cc69ee575bedabc
</code>```

this works fine from chrome but not from bitbucket webhooks.

What is the problem?

I created a job in jenkins which I can successfuly trigger by url.

When I'm triggering the same job from bitbucket's webhook, I get the error: Problem accessing /job/projecty_ci/build. Reason: No valid crumb was included in the request.

答:
I may not be directly solving your issue here but wanted to share that we have managed to trigger a Jenkins job successfully by following the instructions on https://support.cloudbees.com/hc/en-us/articles/226568007-How-to-Trigger-Non-Multibranch-Jobs-from-BitBucket-Server-

The plugin that we use on BitBucket server is https://marketplace.atlassian.com/plugins/com.nerdwin15.stash-stash-webhook-jenkins/server/overview

Title: Bitbucket webhook to run jenkins job

Body:
Update:

I succesfuly sent a post request from curl to trigger jenkins job:

curl -I -X POST http://jenkinsAccountUserName:jenkinsAccountPassword@JenkinsIp:8080/job/projecty_ci/build -H "Jenkins-Crumb:a4fb99fbdb252fda3cc69ee575bedabc"

I don't understand how to convert this to a url: Problem accessing /job/projecty_ci/build. Reason: No valid crumb was included in the request.

http://jenkinsAccountUserName:jenkinsAccountPassword@JenkinsIp:8080/job/projecty_ci/build?Jenkins-Crumb:a4fb99fbdb252fda3cc69ee575bedabc

this works fine from chrome but not from bitbucket webhooks.

What is the problem?

I created a job in jenkins which I can successfuly trigger by url.

When I'm triggering the same job from bitbucket's webhook, I get the error: Problem accessing /job/projecty_ci/build. Reason: No valid crumb was included in the request.


问:
How to get bitmap transparancy without the need to paint first?
A newly created bitmap seems to have a (white) background by default. At least, a query on the Pixels property confirms. But why is that background color not used as the transparent color when Transparent is set true?

Consider this simple test code:

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
  Bmp: TBitmap;
begin
  Bmp := TBitmap.Create;
  try
    Bmp.Width := 100;
    Bmp.Height := 100;
    Bmp.Transparent := True;
    Canvas.Draw(0, 0, Bmp);                              // A white block is drawn
    Bmp.Canvas.Brush.Color := Bmp.Canvas.Pixels[0, 99];  // = 'clWhite'
    Bmp.Canvas.FillRect(Rect(0, 0, 100, 100));
    Canvas.Draw(0, 100, Bmp);                            // "Nothing" is drawn
  finally
    Bmp.Free;
  end;
end;
</code>```

For some reason, the entire bitmap surface has to be painted before it can appear transparent, which sounds kind of odd.

The following variations are tried to eliminate the call to FillRect, all with the same outcome (no transparancy):

Only setting Brush.Color,

Brush.Handle := CreateSolidBrush(clWhite),

PixelFormat := pf32Bit,

IgnorePalette := True,

TransparantColor := clWhite,

TransparantMode := tmFixed,

Canvas.Pixels[0, 99] := clWhite which makes only thát pixel transparent,

Modified := True.

So, the wish is to paint only a portion of a newly created bitmap and get the remaining surface transparent.

Using: Delphi 7, Win 7/64.

答:
I really needed to be able to create a completely transparent (and otherwise empty/blank) TBitmap of an arbitrary size in 32bit RGBA format. Many times. Lazarus is able to load such a bitmap into TBitmap and after it's loaded, you can manipulate it with scanline and what not using RGBA format. But it just doesn't work when you create TBitmap yourself. Pixel format seems to be completely ignored. So what I did is so out-of-the box, and simple, that it's almost AMUZING (!). But it is practical, works super nice, and is completely independent of LCL and any 3rd party libraries. Even does not depend on Graphics unit, becasue it generates the actual 32bit RGBA BMP file (I generate it to TMemoryStream, you can generate differently). Then once you have it, elsewhere in your code you can just load it using TBitmap.LoadFrom source or TPicture.LoadFrom source.

The background story
I initially wanted to generate properly formatted BMP file following the format as described here: http://www.fileformat.info/format/bmp/egff.htm
But there were few variants of BMP format, and I was not clear on which one I was supposed to follow. So I decided to go with a reverse engineering approach, but the format description helped me later on. I used a graphical editor (I used GIMP) to create an empty 1x1 pixel 32 RGBA BMP file, and called it alpha1p.bmp, it only contained transparency nothing else.
Then I resized the canvas to 10x10 pixels, and saved as alpha10p.bmp file.
Then I compared the two files:
compating two bmp files in vbindiff on Ubuntu
So I found out that the only differences were the added pixels (every one was 4 bytes all zeros RGBA), and few other bytes in the header. Because of the format documentation at the linked I shared, I figured out that these were: FileSize (in bytes), BitmapWidth (in pixels), BitmapHeight (in pixels) and BitmapDataSize (in bytes). The last one was BitmapWidth*BitmapHeight*4, because each pixel in RGBA is 4 bytes. So now, I could just generate that entire sequence of bytes as seen inside alpha1p.bmp files, minus 4 bytes from the end (the 1st of the BitmapData), then add 4 bytes (all zeroes) of RGBA data for each pixel of the BMP I want to generate, then come back to the initial sequence and update the variable parts: FileSize, width, height and BMP data size. And it works flawlessly! I just had to add test for BigEndian and would swap word and dword numbers before writting. That would become issue on ARM platforms working in BigEndian.

The code

```<code>const
  C_BLANK_ALPHA_BMP32_PREFIX : array[0..137]of byte
  = ($42, $4D, $00, $00, $00, $00, $00, $00,    $00, $00, $8A, $00, $00, $00, $7C, $00,
     $00, $00, $0A, $00, $00, $00, $0A, $00,    $00, $00, $01, $00, $20, $00, $03, $00,
     $00, $00, $90, $01, $00, $00, $13, $0B,    $00, $00, $13, $0B, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $FF, $00, $00, $FF, $00, $00, $FF,
     $00, $00, $FF, $00, $00, $00, $42, $47,    $52, $73, $00, $00, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $00, $00, $00, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $00, $00, $00, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $00, $02, $00, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $00 );

(...)

  Function  RenderEmptyAlphaBitmap(AWidth,AHeight: integer): TMemoryStream;
   var
     buf : array[1..4096]of byte;
     i,p : int64;
     w   : word;
     dw  : dword;
     BE  : Boolean;
   begin
     buf[low(buf)] := $00; //this is jyst to prevent compiler warning about not initializing buf variable
     Result := TMemoryStream.Create;
     if(AWidth <1)then AWidth  := 1;
     if(AHeight<1)then AHeight := 1;
   //Write File Header:
     Result.Write(C_BLANK_ALPHA_BMP32_PREFIX, SizeOf(C_BLANK_ALPHA_BMP32_PREFIX));
   //Now start writing the pixels:
     FillChar(buf[Low(buf)],Length(buf),$00);
     p := Result.Position;
     Result.Size := Result.Size+int64(AWidth)*int64(AHeight)*4;
     Result.Position := p;
     i := int64(AWidth)*int64(AHeight)*4; //4 because RGBA has 4 bytes
     while(i>0)do
       begin
         if(i>Length(buf))
           then w := Length(buf)
           else w := i;
         Result.Write(buf[Low(buf)], w);
         dec(i,w);
       end;
   //Go back to the original header and update FileSize, Width, Height, and offset fields:
     BE := IsBigEndian;
     Result.Position :=  2; dw := Result.Size;
     if BE then SwapEndian(dw); Result.Write(dw, SizeOf(dw));
     Result.Position := 18; dw := AWidth;
     if BE then SwapEndian(dw); Result.Write(dw, SizeOf(dw));
     Result.Position := 22; dw := AHeight;
     if BE then SwapEndian(dw); Result.Write(dw, SizeOf(dw));
     Result.Position := 34; dw := AWidth*AHeight*4;
     if BE then SwapEndian(dw); Result.Write(dw, SizeOf(dw));
   //Done:
     Result.Position := 0;
   end;
</code>```

Notice how C_BLANK_ALPHA_BMP32_PREFIX constant is basically the copy of byte sequence from my sample alpha1p.bmp file, minus last 4 bytes, which were the RGBA pixel. :D

Also, I am using IsBigEndian function which goes like this:

```<code>  Function  IsBigEndian: Boolean;
   type
    Q = record case Boolean of
          True  : (i: Integer);
          False : (p: array[1..4] of Byte);
        end;
   var
     x : ^Q;
   begin
     New(x);
     x^.i := 5;
     Result := (x^.p[4]=5);
     Dispose(x);
   end;
</code>```

This is copied from Lazarus Wiki: http://wiki.freepascal.org/Writing_portable_code_regarding_the_processor_architecture you can skip this part if you don't deal with BigEndian platforms, or you can use a compilers IFDEF directive. The thing is that if you use {$IFDEF ENDIAN_BIG} then it is what compiler things is the case, whereas the function actually tests the system. This is explained in the linked wiki.

Sample usage

```<code>Procedure TForm1.Button1Click(Sender: TObject);
var
  MS  : TMemoryStream;
begin
  MS := RenderEmptyAlphaBitmap(Image1.Width, Image1.Height);
  try
    if Assigned(MS)then Image1.Picture.LoadFromStream(MS);
  //you can also MS.SaveToFile('my_file.bmp'); if you want
  finally
    FreeAndNil(MS);
  end;
end;
</code>```

Body:
A newly created bitmap seems to have a (white) background by default. At least, a query on the Pixels property confirms. But why is that background color not used as the transparent color when Transparent is set true?

Consider this simple test code:

procedure TForm1.Button1Click(Sender: TObject);
var
  Bmp: TBitmap;
begin
  Bmp := TBitmap.Create;
  try
    Bmp.Width := 100;
    Bmp.Height := 100;
    Bmp.Transparent := True;
    Canvas.Draw(0, 0, Bmp);                              // A white block is drawn
    Bmp.Canvas.Brush.Color := Bmp.Canvas.Pixels[0, 99];  // = 'clWhite'
    Bmp.Canvas.FillRect(Rect(0, 0, 100, 100));
    Canvas.Draw(0, 100, Bmp);                            // "Nothing" is drawn
  finally
    Bmp.Free;
  end;
end;

For some reason, the entire bitmap surface has to be painted before it can appear transparent, which sounds kind of odd.

The following variations are tried to eliminate the call to FillRect, all with the same outcome (no transparancy):

Only setting Brush.Color,

Brush.Handle := CreateSolidBrush(clWhite),

PixelFormat := pf32Bit,

IgnorePalette := True,

TransparantColor := clWhite,

TransparantMode := tmFixed,

Canvas.Pixels[0, 99] := clWhite which makes only thát pixel transparent,

Modified := True.

So, the wish is to paint only a portion of a newly created bitmap and get the remaining surface transparent.

Using: Delphi 7, Win 7/64.

Body:
I really needed to be able to create a completely transparent (and otherwise empty/blank) TBitmap of an arbitrary size in 32bit RGBA format. Many times. Lazarus is able to load such a bitmap into TBitmap and after it's loaded, you can manipulate it with scanline and what not using RGBA format. But it just doesn't work when you create TBitmap yourself. Pixel format seems to be completely ignored. So what I did is so out-of-the box, and simple, that it's almost AMUZING (!). But it is practical, works super nice, and is completely independent of LCL and any 3rd party libraries. Even does not depend on Graphics unit, becasue it generates the actual 32bit RGBA BMP file (I generate it to TMemoryStream, you can generate differently). Then once you have it, elsewhere in your code you can just load it using TBitmap.LoadFrom source or TPicture.LoadFrom source.

The background story
I initially wanted to generate properly formatted BMP file following the format as described here: http://www.fileformat.info/format/bmp/egff.htm
But there were few variants of BMP format, and I was not clear on which one I was supposed to follow. So I decided to go with a reverse engineering approach, but the format description helped me later on. I used a graphical editor (I used GIMP) to create an empty 1x1 pixel 32 RGBA BMP file, and called it alpha1p.bmp, it only contained transparency nothing else.
Then I resized the canvas to 10x10 pixels, and saved as alpha10p.bmp file.
Then I compared the two files:
compating two bmp files in vbindiff on Ubuntu
So I found out that the only differences were the added pixels (every one was 4 bytes all zeros RGBA), and few other bytes in the header. Because of the format documentation at the linked I shared, I figured out that these were: FileSize (in bytes), BitmapWidth (in pixels), BitmapHeight (in pixels) and BitmapDataSize (in bytes). The last one was BitmapWidth*BitmapHeight*4, because each pixel in RGBA is 4 bytes. So now, I could just generate that entire sequence of bytes as seen inside alpha1p.bmp files, minus 4 bytes from the end (the 1st of the BitmapData), then add 4 bytes (all zeroes) of RGBA data for each pixel of the BMP I want to generate, then come back to the initial sequence and update the variable parts: FileSize, width, height and BMP data size. And it works flawlessly! I just had to add test for BigEndian and would swap word and dword numbers before writting. That would become issue on ARM platforms working in BigEndian.

The code

const
  C_BLANK_ALPHA_BMP32_PREFIX : array[0..137]of byte
  = ($42, $4D, $00, $00, $00, $00, $00, $00,    $00, $00, $8A, $00, $00, $00, $7C, $00,
     $00, $00, $0A, $00, $00, $00, $0A, $00,    $00, $00, $01, $00, $20, $00, $03, $00,
     $00, $00, $90, $01, $00, $00, $13, $0B,    $00, $00, $13, $0B, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $FF, $00, $00, $FF, $00, $00, $FF,
     $00, $00, $FF, $00, $00, $00, $42, $47,    $52, $73, $00, $00, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $00, $00, $00, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $00, $00, $00, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $00, $02, $00, $00, $00, $00, $00,
     $00, $00, $00, $00, $00, $00, $00, $00,    $00, $00 );

(...)

  Function  RenderEmptyAlphaBitmap(AWidth,AHeight: integer): TMemoryStream;
   var
     buf : array[1..4096]of byte;
     i,p : int64;
     w   : word;
     dw  : dword;
     BE  : Boolean;
   begin
     buf[low(buf)] := $00; //this is jyst to prevent compiler warning about not initializing buf variable
     Result := TMemoryStream.Create;
     if(AWidth <1)then AWidth  := 1;
     if(AHeight<1)then AHeight := 1;
   //Write File Header:
     Result.Write(C_BLANK_ALPHA_BMP32_PREFIX, SizeOf(C_BLANK_ALPHA_BMP32_PREFIX));
   //Now start writing the pixels:
     FillChar(buf[Low(buf)],Length(buf),$00);
     p := Result.Position;
     Result.Size := Result.Size+int64(AWidth)*int64(AHeight)*4;
     Result.Position := p;
     i := int64(AWidth)*int64(AHeight)*4; //4 because RGBA has 4 bytes
     while(i>0)do
       begin
         if(i>Length(buf))
           then w := Length(buf)
           else w := i;
         Result.Write(buf[Low(buf)], w);
         dec(i,w);
       end;
   //Go back to the original header and update FileSize, Width, Height, and offset fields:
     BE := IsBigEndian;
     Result.Position :=  2; dw := Result.Size;
     if BE then SwapEndian(dw); Result.Write(dw, SizeOf(dw));
     Result.Position := 18; dw := AWidth;
     if BE then SwapEndian(dw); Result.Write(dw, SizeOf(dw));
     Result.Position := 22; dw := AHeight;
     if BE then SwapEndian(dw); Result.Write(dw, SizeOf(dw));
     Result.Position := 34; dw := AWidth*AHeight*4;
     if BE then SwapEndian(dw); Result.Write(dw, SizeOf(dw));
   //Done:
     Result.Position := 0;
   end;

Notice how C_BLANK_ALPHA_BMP32_PREFIX constant is basically the copy of byte sequence from my sample alpha1p.bmp file, minus last 4 bytes, which were the RGBA pixel. :D

Also, I am using IsBigEndian function which goes like this:

  Function  IsBigEndian: Boolean;
   type
    Q = record case Boolean of
          True  : (i: Integer);
          False : (p: array[1..4] of Byte);
        end;
   var
     x : ^Q;
   begin
     New(x);
     x^.i := 5;
     Result := (x^.p[4]=5);
     Dispose(x);
   end;

This is copied from Lazarus Wiki: http://wiki.freepascal.org/Writing_portable_code_regarding_the_processor_architecture you can skip this part if you don't deal with BigEndian platforms, or you can use a compilers IFDEF directive. The thing is that if you use {$IFDEF ENDIAN_BIG} then it is what compiler things is the case, whereas the function actually tests the system. This is explained in the linked wiki.

Sample usage

Procedure TForm1.Button1Click(Sender: TObject);
var
  MS  : TMemoryStream;
begin
  MS := RenderEmptyAlphaBitmap(Image1.Width, Image1.Height);
  try
    if Assigned(MS)then Image1.Picture.LoadFromStream(MS);
  //you can also MS.SaveToFile('my_file.bmp'); if you want
  finally
    FreeAndNil(MS);
  end;
end;