问:
Using interp2 to make number of points smaller
This is what my code looks like now

```<code>b=load('filenamehere');
b=b(46:285,51:170);

x=1:size(b,1);
y=1:size(b,2);

xq=1:size(b,1)/4;
yq=1:size(b,2)/4;

B=interp2(x,y,b,xq,yq);
</code>```

b is 240x120 matrix, and I'm trying to have it be a 60x30 matrix so that my computer can handle the later computations I have to make. not sure what I have to do to make it work, I've also tried using [X,Y]=meshgrid(x,y) and the same for xq, yq. any help is appreciated.

答:
I see several problem in your code.

```<code>b=load('filenamehere');
</code>```

will return a struct, rather than a matrix. Let's ignore this for now, and suppose you have matrix b with 240x120 size.

Your xq and yq take the first 1/4 of b. I guess you want to take one point from every four. If so, you can do

```<code>B = b(1:4:end, 1:4:end);
</code>```

or use downsample if you have Signal processing toolbox:

```<code>B = downsample(b, 4);
</code>```

If you really need interpolation, xq and yq, if they are vector, should have different orientations:

```<code>B = interp2(b, 1:4:120, (1:4:240).');
</code>```

Body:
This is what my code looks like now

b=load('filenamehere');
b=b(46:285,51:170);

x=1:size(b,1);
y=1:size(b,2);

xq=1:size(b,1)/4;
yq=1:size(b,2)/4;

B=interp2(x,y,b,xq,yq);

b is 240x120 matrix, and I'm trying to have it be a 60x30 matrix so that my computer can handle the later computations I have to make. not sure what I have to do to make it work, I've also tried using [X,Y]=meshgrid(x,y) and the same for xq, yq. any help is appreciated.

Body:
I see several problem in your code.

b=load('filenamehere');

will return a struct, rather than a matrix. Let's ignore this for now, and suppose you have matrix b with 240x120 size.

Your xq and yq take the first 1/4 of b. I guess you want to take one point from every four. If so, you can do

B = b(1:4:end, 1:4:end);

or use downsample if you have Signal processing toolbox:

B = downsample(b, 4);

If you really need interpolation, xq and yq, if they are vector, should have different orientations:

B = interp2(b, 1:4:120, (1:4:240).');


来源: stackexchange

问:
spring data hive integration with hive template
I am trying to use spring data hadoop to integrate hive into my application and running into some issues. First thing I am not sure about is <hdp:hive-server host="some-other-host" port="10001" /> is this to connect to an existing hive server or to something like create a new hive server to then be able to connect to it. Secondly my configuration does not throws any errors so it does seems ok and even the hiveTemplate autowiring works fine too but when I execute a query I dont seem to get any response back. The application sort of gets stuck at that point.

here is the configuration

```<code><hive-client-factory host="${hive-${env}.server}" port="${hive-${env}.port}" />

<hive-template />
</code>```

and here is how im using it

```<code>log.debug("before hive query");

for(String result : hiveTemplate.query("show tables;")){
    log.debug("=> " + result);
}

log.debug("after hive query");
</code>```

all I see in log output is before hive query .. nothing happens after that. I would appreciate any help. Any ideas what I could be doing wrong.

答:
If we are using with spring,please make sure all your dependency is compatible with spring version.After that give read and write permission using below commands.

```<code>hadoop fs -mkdir /tmp
hadoop fs -chmod a+w /tmp
hadoop fs -mkdir -p /user/hive/warehouse
hadoop fs -chmod a+w /user/hive/warehouse
</code>```

I have used following version of dependency in pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-hadoop-samples-hive</artifactId>

    <name>Spring Hadoop Samples - Hive</name>

    <parent>
        <groupId>org.springframework.samples</groupId>
        <artifactId>spring-hadoop-samples</artifactId>
        <version>1.0.0.BUILD-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.hadoop.version>2.3.0.M1</spring.hadoop.version>
        <hadoop.version>2.7.1</hadoop.version>
        <hive.version>1.2.1</hive.version>
        <!-- <hive.version>2.1.1</hive.version> -->
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-hadoop</artifactId>
            <version>${spring.hadoop.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context-support</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>${hadoop.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-metastore</artifactId>
            <version>${hive.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-service</artifactId>
            <version>${hive.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libfb303</artifactId>
            <version>0.9.1</version>
        </dependency>

        <!-- runtime Hive deps start -->
        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-common</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-jdbc</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-shims</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-serde</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-contrib</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- runtime Hive deps end -->

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
            <version>1.8.5</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestone</id>
            <url>http://repo.spring.io/libs-milestone</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>appassembler-maven-plugin</artifactId>
                <version>1.2.2</version>
                <configuration>
                    <repositoryLayout>flat</repositoryLayout>
                    <configurationSourceDirectory>src/main/config</configurationSourceDirectory>
                    <copyConfigurationDirectory>true</copyConfigurationDirectory>
                    <!-- Extra JVM arguments that will be included in the bin scripts -->
                    <extraJvmArguments>-Xms512m -Xmx1024m -Dhive.version=${hive.version}</extraJvmArguments>
                    <programs>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveApp</mainClass>
                            <name>hiveApp</name>
                        </program>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveClientApp</mainClass>
                            <name>hiveClientApp</name>
                        </program>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveAppWithApacheLogs</mainClass>
                            <name>hiveAppWithApacheLogs</name>
                        </program>
                    </programs>
                </configuration>
                <executions>
                    <execution>
                        <id>package</id>
                        <goals>
                            <goal>assemble</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>config</id>
                        <phase>package</phase>
                        <configuration>
                            <tasks>
                                <copy todir="target/appassembler/data">
                                    <fileset dir="data"/>
                                </copy>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use spring data hadoop to integrate hive into my application and running into some issues. First thing I am not sure about is <hdp:hive-server host="some-other-host" port="10001" /> is this to connect to an existing hive server or to something like create a new hive server to then be able to connect to it. Secondly my configuration does not throws any errors so it does seems ok and even the hiveTemplate autowiring works fine too but when I execute a query I dont seem to get any response back. The application sort of gets stuck at that point.

here is the configuration

<hive-client-factory host="${hive-${env}.server}" port="${hive-${env}.port}" />

<hive-template />

and here is how im using it

log.debug("before hive query");

for(String result : hiveTemplate.query("show tables;")){
    log.debug("=> " + result);
}

log.debug("after hive query");

all I see in log output is before hive query .. nothing happens after that. I would appreciate any help. Any ideas what I could be doing wrong.

Body:
If we are using with spring,please make sure all your dependency is compatible with spring version.After that give read and write permission using below commands.

hadoop fs -mkdir /tmp
hadoop fs -chmod a+w /tmp
hadoop fs -mkdir -p /user/hive/warehouse
hadoop fs -chmod a+w /user/hive/warehouse

I have used following version of dependency in pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-hadoop-samples-hive</artifactId>

    <name>Spring Hadoop Samples - Hive</name>

    <parent>
        <groupId>org.springframework.samples</groupId>
        <artifactId>spring-hadoop-samples</artifactId>
        <version>1.0.0.BUILD-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.hadoop.version>2.3.0.M1</spring.hadoop.version>
        <hadoop.version>2.7.1</hadoop.version>
        <hive.version>1.2.1</hive.version>
        <!-- <hive.version>2.1.1</hive.version> -->
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-hadoop</artifactId>
            <version>${spring.hadoop.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context-support</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>${hadoop.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-metastore</artifactId>
            <version>${hive.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-service</artifactId>
            <version>${hive.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libfb303</artifactId>
            <version>0.9.1</version>
        </dependency>

        <!-- runtime Hive deps start -->
        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-common</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-jdbc</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-shims</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-serde</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.hive</groupId>
            <artifactId>hive-contrib</artifactId>
            <version>${hive.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- runtime Hive deps end -->

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
            <version>1.8.5</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestone</id>
            <url>http://repo.spring.io/libs-milestone</url>
        </repository>
    </repositories>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>appassembler-maven-plugin</artifactId>
                <version>1.2.2</version>
                <configuration>
                    <repositoryLayout>flat</repositoryLayout>
                    <configurationSourceDirectory>src/main/config</configurationSourceDirectory>
                    <copyConfigurationDirectory>true</copyConfigurationDirectory>
                    <!-- Extra JVM arguments that will be included in the bin scripts -->
                    <extraJvmArguments>-Xms512m -Xmx1024m -Dhive.version=${hive.version}</extraJvmArguments>
                    <programs>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveApp</mainClass>
                            <name>hiveApp</name>
                        </program>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveClientApp</mainClass>
                            <name>hiveClientApp</name>
                        </program>
                        <program>
                            <mainClass>org.springframework.samples.hadoop.hive.HiveAppWithApacheLogs</mainClass>
                            <name>hiveAppWithApacheLogs</name>
                        </program>
                    </programs>
                </configuration>
                <executions>
                    <execution>
                        <id>package</id>
                        <goals>
                            <goal>assemble</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>config</id>
                        <phase>package</phase>
                        <configuration>
                            <tasks>
                                <copy todir="target/appassembler/data">
                                    <fileset dir="data"/>
                                </copy>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


问:
C#: .NET based webbrowser doesn't show image
I am new in C# language and I have been trying to automate a website using .NET based webbrowser for ONLY personal use in Visual Studio 2015.

I have done document parsing, used Timer, used DocumentCompleted event properly to wait for the webpage to load completely and then parse the content, tried to make async events to behave like sync events (in order to load HTML content generated by clicking a link in a fully loaded webpage), etc to go through the phases in webpage automation: login -> get trains between stations -> click the Book now link -> go to the next page and fill in the passenger details.

Everything works fine but I am now stuck at the last phase, i.e., "go to the next page and fill in the passenger details" has a captcha image that must be resolved to go to the payment page. Don't get me wrong because I am not trying to get this captcha resolved automatically. The problem here is that I do not see the captch image which turned to be loaded only when this javascript call is invoked $(document).ready.

I thought my project has some buggy code which is stopping to load the captcha and therefore, I created a very basic new project, only added below code and navigated through different phases myself to see if the captcha really loads but unfortunately it would not load.

```<code>namespace TestWebBrowser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webBrowser1.Navigate("https://www.irctc.co.in/eticketing/loginHome.jsf");
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }
    }
}
</code>```

Please see below. The highlighted part is where I am expecting a captcha.

I must tell you that I am not a web designer and therefore I only understand very basic of how websites work.

I went through several questions on this forum and nothing helped me.

Internet explorer is also using .NET browser from behind but while using IE, I can see the captcha is getting loaded. So, why is this javascript call $(document).ready is not getting invoked in .NET browser. Please see below:

I have later tried to use CefSharp in a fresh new project and I can see the captcha is getting loaded in its chromium based webbrowser. But I have done so much coding with .NET based webbrowser already and therefore I want to stick to the latter at this moment in order to get this resolved.

Is this happening because .NET webbrowser is using some very old IE version configurations?

Please help me to understand.

UPDATE 1: Adding the javascript

```<code><script type="text/javascript">
        $(document).ready(function(){
            var isJsBlocked=0;
            if (typeof(nlpLoadCaptchaAsync) == 'function'){
                nlpLoadCaptchaAsync();
            }else{
                isJsBlocked=1;
            }
            setTimeout(function(){
                var isNLPCaptcha = document.getElementById('nlpIdentifier');
                if(isNLPCaptcha == null || isNLPCaptcha=='' ) {
                    var nlptrack = new Image();
                    nlptrack.src="http://irctclive.nlpcaptcha.in/temp_redirect_count/irctc_timeout.php?ref=f2c5d744485b0b4251461454db791111&isJsBlocked="+isJsBlocked+"&dynamicParameter="+Date.now();
                    nlpCaptchaTimeOut(true);

                }

            }, 5000 );

        });
        </script>
</code>```

答:
The answer shared here: Use latest version of Internet Explorer in the webbrowser control solved my issue.

I basically had to change the version of IE version used by my webbrowser control.

Thanks to Matthias herrmann

Body:
I am new in C# language and I have been trying to automate a website using .NET based webbrowser for ONLY personal use in Visual Studio 2015.

I have done document parsing, used Timer, used DocumentCompleted event properly to wait for the webpage to load completely and then parse the content, tried to make async events to behave like sync events (in order to load HTML content generated by clicking a link in a fully loaded webpage), etc to go through the phases in webpage automation: login -> get trains between stations -> click the Book now link -> go to the next page and fill in the passenger details.

Everything works fine but I am now stuck at the last phase, i.e., "go to the next page and fill in the passenger details" has a captcha image that must be resolved to go to the payment page. Don't get me wrong because I am not trying to get this captcha resolved automatically. The problem here is that I do not see the captch image which turned to be loaded only when this javascript call is invoked $(document).ready.

I thought my project has some buggy code which is stopping to load the captcha and therefore, I created a very basic new project, only added below code and navigated through different phases myself to see if the captcha really loads but unfortunately it would not load.

namespace TestWebBrowser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            webBrowser1.Navigate("https://www.irctc.co.in/eticketing/loginHome.jsf");
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }
    }
}

Please see below. The highlighted part is where I am expecting a captcha.

I must tell you that I am not a web designer and therefore I only understand very basic of how websites work.

I went through several questions on this forum and nothing helped me.

Internet explorer is also using .NET browser from behind but while using IE, I can see the captcha is getting loaded. So, why is this javascript call $(document).ready is not getting invoked in .NET browser. Please see below:

I have later tried to use CefSharp in a fresh new project and I can see the captcha is getting loaded in its chromium based webbrowser. But I have done so much coding with .NET based webbrowser already and therefore I want to stick to the latter at this moment in order to get this resolved.

Is this happening because .NET webbrowser is using some very old IE version configurations?

Please help me to understand.

UPDATE 1: Adding the javascript


问:
SQL - Table waiting for Commit/Rollback after closing session
I have a large table without any indexes on it, about 27.5m rows.
I tried to delete about half of those using using BEGIN TRAN.
I then tried canceling the querie, but because it was taking long I decided to just close the Management Studio.

Now when I try to look into that table, it does not return anything, just keeps running.

When I run SELECT TOP 10 * FROM Tbl it just executes without returning anything.

But when I run SELECT TOP 10 * FROM Tbl(NOLOCK) it return 10 rows.

This tells me that it is waiting on a Rollback/Commit from my BEGIN TRAN.

I thought it would rollback automatically after closing the session and Management Studio.

 How do I fix this issue?

Thanks.

答:
Apparently, this worked:

Terminate/Close connection to the database would solve this. To close connection you can try terminating sqlserver.exe from Task Manager or Activity Monitor if you have a Mac.


问:
doctrine save method update/insert based on unique field
I read so many post and I found many variations about how to get save to insert vs update but couldn't find something that would work for me.

I am guessing that preSave would be the way to go if preSave() is being executed automaticly by save() if present.

```<code>columns:
  email:
    type: string(255)
    unique: true
    email: true
</code>```

I need save() to check if a filed is set to be unique
if so, to check if field data in this case email address is unique.
Based on that info decide to insert or update posted fields that have changed.

答:
I guess Vladimir's answer right, you just need to add the update logic before skipOperation.

```<code>public function preSave($event)
{
    if (!$this->isUniqueEmail()) {
        // update logic

        $event->skipOperation();
    }
}
</code>```

Sorry, but I can't comment on Vladimir's answer.

ContentLicense: CC BY-SA 2.5

Body:
I read so many post and I found many variations about how to get save to insert vs update but couldn't find something that would work for me.

I am guessing that preSave would be the way to go if preSave() is being executed automaticly by save() if present.

columns:
  email:
    type: string(255)
    unique: true
    email: true

I need save() to check if a filed is set to be unique
if so, to check if field data in this case email address is unique.
Based on that info decide to insert or update posted fields that have changed.

Body:
I guess Vladimir's answer right, you just need to add the update logic before skipOperation.

public function preSave($event)
{
    if (!$this->isUniqueEmail()) {
        // update logic

        $event->skipOperation();
    }
}

Sorry, but I can't comment on Vladimir's answer.


问:
Fail to send the PATCH request to set the extended property in MAC outlook client
I am developing an Office Add-in for MAC outlook client. I am trying to send the PATCH request to set the extended property in MAC outlook client but it does not work. There is no response after executing the code below.  The code snippet below works in MAC Safari browser and windows desktop/browser. Do you have any idea? </p>

<p>Note:Replace the XXXX with your email ID. The email ID can be retrieved by the outlook rest api sandbox. https://oauthplay.azurewebsites.net/ or via the Office.js Office.Context.Mailbox.Item.itemId https://dev.office.com/reference/add-ins/outlook/1.5/Office.context.mailbox.item?product=outlook&version=v1.5 </p>

```<code>        function setFlag() {
           var options = {
           isRest: true,
           };
           Office.context.mailbox.getCallbackTokenAsync(options, cb);
        }

        function cb(asyncResult) {
           var token = asyncResult.value;
           setEmailFlagByToken(token);
        }
        function setEmailFlagByToken(accessToken) {
         var getMessageUrl = 'https://outlook.com/api/beta/me/messages/XXXX'
          $.ajax({
          url: getMessageUrl,
          dataType: 'json',
          contentType:"application/json",
          type:'PATCH',
          data: "{'Flag':{'FlagStatus':'Flagged'}}",
          headers: { 'Authorization': 'Bearer ' + accessToken }
          }).done(function(data){
             //Succeeded

          }).fail(function(error){
            // Handle error
          });
        }

 Updated XML Manifest file:
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="MailApp">
  <Id>47837963-11df-469e-a84e-661070c8217c</Id>
  <Version>1.0.0.0</Version>
  <ProviderName>[Provider name]</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="OfficeAddIn" />
  <Description DefaultValue="OfficeAddIn"/>
  <Hosts>
    <Host Name="Mailbox" />
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="MailBox" MinVersion="1.1" />
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemRead">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://mailapppoc2.azurewebsites.net/AddInRead/Home/Home.html"/>
        <RequestedHeight>250</RequestedHeight>
      </DesktopSettings>
    </Form>
  </FormSettings>
  <Permissions>ReadWriteMailbox</Permissions>
  <Rule xsi:type="RuleCollection" Mode="Or">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Read" />
  </Rule>
  <DisableEntityHighlighting>false</DisableEntityHighlighting>
</OfficeApp>
</code>```

答: Rest token for making rest calls is supported in mac outlook client as part of 1.5 APIs. Please make sure you are using the latest outlook binary while making the request. In older binaries this support is not present. Earlier, it would only provide EWS token, which will enable you to make only ews requests. Insider fast program user get binaries which support this feature.</p>

Body:
I am developing an Office Add-in for MAC outlook client. I am trying to send the PATCH request to set the extended property in MAC outlook client but it does not work. There is no response after executing the code below.  The code snippet below works in MAC Safari browser and windows desktop/browser. Do you have any idea?

Note:Replace the XXXX with your email ID. The email ID can be retrieved by the outlook rest api sandbox. https://oauthplay.azurewebsites.net/ or via the Office.js Office.Context.Mailbox.Item.itemId https://dev.office.com/reference/add-ins/outlook/1.5/Office.context.mailbox.item?product=outlook&version=v1.5

        function setFlag() {
           var options = {
           isRest: true,
           };
           Office.context.mailbox.getCallbackTokenAsync(options, cb);
        }

        function cb(asyncResult) {
           var token = asyncResult.value;
           setEmailFlagByToken(token);
        }
        function setEmailFlagByToken(accessToken) {
         var getMessageUrl = 'https://outlook.com/api/beta/me/messages/XXXX'
          $.ajax({
          url: getMessageUrl,
          dataType: 'json',
          contentType:"application/json",
          type:'PATCH',
          data: "{'Flag':{'FlagStatus':'Flagged'}}",
          headers: { 'Authorization': 'Bearer ' + accessToken }
          }).done(function(data){
             //Succeeded

          }).fail(function(error){
            // Handle error
          });
        }

 Updated XML Manifest file:
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="MailApp">
  <Id>47837963-11df-469e-a84e-661070c8217c</Id>
  <Version>1.0.0.0</Version>
  <ProviderName>[Provider name]</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="OfficeAddIn" />
  <Description DefaultValue="OfficeAddIn"/>
  <Hosts>
    <Host Name="Mailbox" />
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="MailBox" MinVersion="1.1" />
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemRead">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://mailapppoc2.azurewebsites.net/AddInRead/Home/Home.html"/>
        <RequestedHeight>250</RequestedHeight>
      </DesktopSettings>
    </Form>
  </FormSettings>
  <Permissions>ReadWriteMailbox</Permissions>
  <Rule xsi:type="RuleCollection" Mode="Or">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Read" />
  </Rule>
  <DisableEntityHighlighting>false</DisableEntityHighlighting>
</OfficeApp>


问:
chmod(): No such file or directory
this might be a duplicate but dont know the reason why i got this error.. this code is fine when im using another laptop which the php version is 5.6 but when im using a laptop with php version 5.4 i got an error..
here is the code that im using..

```<code>        public function uploadImg($file, $newname){

            $path = "../valenciamd/captured_images/";
            $fileparts = pathinfo($file["name"]);
            $name =  $newname . $fileparts["extension"];

            if( is_dir($path) === false ){
                mkdir($path);
            }

            $i = 0;
            $parts = pathinfo($name);
            // while (file_exists($path . $name)) {
            //     $i++;
            //     $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
            // }
            $name = $parts["filename"]. "." . $parts["extension"];
            $success = move_uploaded_file($file["tmp_name"],
                $path . $name);

            chmod($path . $name, 0777);

            return $path . $name;
        }
</code>```

$img = $reg->uploadImg( $_FILES['image'], $patientID.'.');

答:
Are you sure that your php version is 5.4, maybe it's below 5.2  $path_parts['filename'] is only added since php 5.2 so you will get nothing. This is not an error, just update your php version.

Or if you do not want to update your php version, you can use
$parts['basename'] instead of $parts["filename"]. "." . $parts["extension"]

Title: chmod(): No such file or directory

Body:
this might be a duplicate but dont know the reason why i got this error.. this code is fine when im using another laptop which the php version is 5.6 but when im using a laptop with php version 5.4 i got an error..
here is the code that im using..

        public function uploadImg($file, $newname){

            $path = "../valenciamd/captured_images/";
            $fileparts = pathinfo($file["name"]);
            $name =  $newname . $fileparts["extension"];

            if( is_dir($path) === false ){
                mkdir($path);
            }

            $i = 0;
            $parts = pathinfo($name);
            // while (file_exists($path . $name)) {
            //     $i++;
            //     $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
            // }
            $name = $parts["filename"]. "." . $parts["extension"];
            $success = move_uploaded_file($file["tmp_name"],
                $path . $name);

            chmod($path . $name, 0777);

            return $path . $name;
        }

$img = $reg->uploadImg( $_FILES['image'], $patientID.'.');


问:
NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()'
```<code>public class CategoryAdapter extends BaseAdapter {
Context context;
ArrayList<ModelCategory> model;
LayoutInflater layoutInflater;

public CategoryAdapter(Activity activity, ArrayList<ModelCategory> model) {
    this.model = model;
    this.context = activity;
}

@Override
public int getCount() {
    return model.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder viewHolder = null;
    layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = layoutInflater.inflate(R.layout.category_adapter, parent, false);
        viewHolder.imageView = (ImageView) convertView.findViewById(R.id.category_grid_image);
        viewHolder.textView = (TextView) convertView.findViewById(R.id.get_category_title);
        convertView.setTag(viewHolder);

    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.textView.setText(model.get(position).getCategoryName());
    if(position<=3){
        viewHolder.imageView.setImageBitmap(StringToBitMap(model.get(position).getCategoryImage()));
    }
    else {
        viewHolder.imageView.setImageBitmap(getBitmap(model.get(position).getCategoryImage()));
    }
    return convertView;
}

private class ViewHolder {
    public ImageView imageView;
    public TextView textView;
}

private Bitmap getBitmap(String path) {

    BitmapFactory.Options option = new BitmapFactory.Options();
    option.inSampleSize = 8;
    Bitmap bitmap = BitmapFactory.decodeFile(path, option);
    Matrix matrix = new Matrix();
    matrix.postRotate(getImageOrientation(path));
    Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    Bitmap resized = Bitmap.createScaledBitmap(rotatedBitmap, 150, 150, true);
    return resized;
}

private static int getImageOrientation(String imagePath) {
    int rotate = 0;
    try {
        File imageFile = new File(imagePath);
        ExifInterface exif = new ExifInterface(
                imageFile.getAbsolutePath());
        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return rotate;
}

public Bitmap StringToBitMap(String encodedString){
    try {
        byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
        Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    } catch(Exception e) {
        e.getMessage();
        return null;
    }
}
</code>```

}

I am getting error like below..

java.lang.NullPointerException: Attempt to invoke virtual method 'int
  android.graphics.Bitmap.getWidth()' on a null object reference
              at com.adapter.CategoryAdapter.getBitmap(CategoryAdapter.java:92)
              at com.adapter.CategoryAdapter.getView(CategoryAdapter.java:75)
              at android.widget.AbsListView.obtainView(AbsListView.java:2896)
              at android.widget.GridView.makeAndAddView(GridView.java:1456)
              at android.widget.GridView.makeRow(GridView.java:361)
              at android.widget.GridView.fillDown(GridView.java:302)
              at android.widget.GridView.fillFromTop(GridView.java:437)
              at android.widget.GridView.layoutChildren(GridView.java:1284)
              at android.widget.AbsListView.onLayout(AbsListView.java:2700)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1043)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1702)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1556)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1465)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1702)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1556)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1465)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1702)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1556)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1465)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)

How can I solve this?

答: The problem in my case was that I was calling 'decodeFile' in background thread which was returning null. Moving that code to main thread fixed the problem.</p>

Body:
public class CategoryAdapter extends BaseAdapter {
Context context;
ArrayList<ModelCategory> model;
LayoutInflater layoutInflater;

public CategoryAdapter(Activity activity, ArrayList<ModelCategory> model) {
    this.model = model;
    this.context = activity;
}

@Override
public int getCount() {
    return model.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    ViewHolder viewHolder = null;
    layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = layoutInflater.inflate(R.layout.category_adapter, parent, false);
        viewHolder.imageView = (ImageView) convertView.findViewById(R.id.category_grid_image);
        viewHolder.textView = (TextView) convertView.findViewById(R.id.get_category_title);
        convertView.setTag(viewHolder);

    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.textView.setText(model.get(position).getCategoryName());
    if(position<=3){
        viewHolder.imageView.setImageBitmap(StringToBitMap(model.get(position).getCategoryImage()));
    }
    else {
        viewHolder.imageView.setImageBitmap(getBitmap(model.get(position).getCategoryImage()));
    }
    return convertView;
}

private class ViewHolder {
    public ImageView imageView;
    public TextView textView;
}

private Bitmap getBitmap(String path) {

    BitmapFactory.Options option = new BitmapFactory.Options();
    option.inSampleSize = 8;
    Bitmap bitmap = BitmapFactory.decodeFile(path, option);
    Matrix matrix = new Matrix();
    matrix.postRotate(getImageOrientation(path));
    Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    Bitmap resized = Bitmap.createScaledBitmap(rotatedBitmap, 150, 150, true);
    return resized;
}

private static int getImageOrientation(String imagePath) {
    int rotate = 0;
    try {
        File imageFile = new File(imagePath);
        ExifInterface exif = new ExifInterface(
                imageFile.getAbsolutePath());
        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_270:
                rotate = 270;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                rotate = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                rotate = 90;
                break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return rotate;
}

public Bitmap StringToBitMap(String encodedString){
    try {
        byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
        Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    } catch(Exception e) {
        e.getMessage();
        return null;
    }
}

}

I am getting error like below..

java.lang.NullPointerException: Attempt to invoke virtual method 'int
  android.graphics.Bitmap.getWidth()' on a null object reference
              at com.adapter.CategoryAdapter.getBitmap(CategoryAdapter.java:92)
              at com.adapter.CategoryAdapter.getView(CategoryAdapter.java:75)
              at android.widget.AbsListView.obtainView(AbsListView.java:2896)
              at android.widget.GridView.makeAndAddView(GridView.java:1456)
              at android.widget.GridView.makeRow(GridView.java:361)
              at android.widget.GridView.fillDown(GridView.java:302)
              at android.widget.GridView.fillFromTop(GridView.java:437)
              at android.widget.GridView.layoutChildren(GridView.java:1284)
              at android.widget.AbsListView.onLayout(AbsListView.java:2700)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1043)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1702)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1556)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1465)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1702)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1556)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1465)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1702)
              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1556)
              at android.widget.LinearLayout.onLayout(LinearLayout.java:1465)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)
              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
              at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
              at android.view.View.layout(View.java:16899)
              at android.view.ViewGroup.layout(ViewGroup.java:5405)

How can I solve this?


问:
Python: select only folders in a directory
I am wondering about a good way to isolate just the folders in any given directory. Right now I have a folder with both, folders and random files in it and I want to isolate just the folders and ignore the files, whatever they may be called. Is there a quick way to do this in python?

Cheers

答:
This may be a duplicate question. Please check out this link and see if it serves your purpose :

How to list only top level directories in Python?


问:
creating a new pandas dataframe based on groups
The csv (sample below) shows the absolute error for an item for a given week (week_end_date). As the csv shows, an item belongs to a department, and a department has multiple items:

What I want to do is to create a new dataframe which has the following fields:

```<code>mdse_dept_ref_i     week_end_date      average_ABSError      num_items_in_department
</code>```

Here is what I am able to do:

```<code>new_df = df.loc[df['mdse_dept_ref_i'] == 47]
num_items = new_df.groupby('week_end_date').size()

avg_abs_error = new_df.groupby(['week_end_date'])['ABSError'].mean()
new_df = num_items.to_frame().join(avg_abs_error.to_frame())
</code>```

But, I don't know how to do this automatically for all the departments to create a single dataframe, because eventually I want to see how the number of items in a department is affecting the average error, and also be able to see the worst performing departments. Also, when I do a groupby('week_end_date'), the week_end_date becomes an index, whereas I would like it to be a field in the new dataframe, so that I can use it while plotting. Can someone please help me?

答:
Pandas' groupby allows you to group by more than one field:

```<code>g = df.groupby(['mdse_dept_ref_i','week_end_date'])
num_items = g.size().to_frame('num_items')
avg_abs_error = g['ABSError'].mean()
df0 = pd.concat((num_items,avg_abs_error), axis = 1).reset_index()
df.merge(df0)
</code>```

You can actually pass the argument as_index = False to the .groupby, but this has no effect when using .size(), so we have to reset the index later.

Body:
The csv (sample below) shows the absolute error for an item for a given week (week_end_date). As the csv shows, an item belongs to a department, and a department has multiple items:

What I want to do is to create a new dataframe which has the following fields:

mdse_dept_ref_i     week_end_date      average_ABSError      num_items_in_department

Here is what I am able to do:

new_df = df.loc[df['mdse_dept_ref_i'] == 47]
num_items = new_df.groupby('week_end_date').size()

avg_abs_error = new_df.groupby(['week_end_date'])['ABSError'].mean()
new_df = num_items.to_frame().join(avg_abs_error.to_frame())

But, I don't know how to do this automatically for all the departments to create a single dataframe, because eventually I want to see how the number of items in a department is affecting the average error, and also be able to see the worst performing departments. Also, when I do a groupby('week_end_date'), the week_end_date becomes an index, whereas I would like it to be a field in the new dataframe, so that I can use it while plotting. Can someone please help me?

Body:
Pandas' groupby allows you to group by more than one field:

g = df.groupby(['mdse_dept_ref_i','week_end_date'])
num_items = g.size().to_frame('num_items')
avg_abs_error = g['ABSError'].mean()
df0 = pd.concat((num_items,avg_abs_error), axis = 1).reset_index()
df.merge(df0)

You can actually pass the argument as_index = False to the .groupby, but this has no effect when using .size(), so we have to reset the index later.


问:
Coldfusion ORM: delete in cascade
I'm not an expert in coldfusion orm and I call your help because I'm pulling my hair!

I'm excepting to delete an entity 'Action' that has 2 relationship one-to-many, 'Texts' and 'Bonus'.

When I try to delete an Action that has only Texts but no Bonus, everything is fine. Hibernate deletes the Action record and the children Texts. It's what I want!

But when the Action has both Texts and Bonus, I got this error :

```<code>Column 'bonus_actionId' cannot be null
Root cause :java.sql.BatchUpdateException: Column 'bonus_actionId' cannot be null
</code>```

Why Hibernate does not delete the Bonus before deleting the Action ? Like it is done for Texts ?

Thanks

Action Entity:

```<code>component {
    property name="id"      column="action_id" type="numeric" fieldtype="id" generator="native";

    /* ... */

    property name="texts" type="array"
             fieldtype="one-to-many" cfc="Text" fkcolumn="text_actionId" singularname="text"
             cascade="all-delete-orphan" lazy="true";

    /* ... */

    property name="bonus" type="array"
             fieldtype="one-to-many" cfc="Bonus" fkcolumn="bonus_actionId" singularname="bonus"
             cascade="all-delete-orphan" lazy="true";
}
</code>```

Text Entity:

```<code>component {
    property name="id"      column="text_id" type="numeric" fieldtype="id" generator="native";

    /* ... (properties without relationships */

    property name="action" fieldtype="many-to-one" fkcolumn="text_actionId" cfc="Action" notnull="false" lazy="true";
}
</code>```

Bonus Entity:

```<code>component  {
    property name="id"      column="bonus_id" type="numeric" fieldtype="id" generator="native";

    /* ... (properties WITH relationships */

    // Parent
    property name="action" fieldtype="many-to-one" fkcolumn="bonus_actionId" cfc="Action" notnull="true" lazy="true";

}
</code>```

答:
You can keep your notnull="true" and have cascades work correctly by adding inverse="true" to the foreign key–owning side of the relationship.

In your case, this would be on the Action entity:

```<code>component {

    property name="id"
             column="action_id"
             type="numeric"
             fieldtype="id"
             generator="native";

    /* ... */

    property name="texts"
             type="array"
             fieldtype="one-to-many"
             cfc="Text"
             fkcolumn="text_actionId"
             singularname="text"
             cascade="all-delete-orphan"
             inverse="true"
             lazy="true";

    /* ... */

    property name="bonus"
             type="array"
             fieldtype="one-to-many"
             cfc="Bonus"
             fkcolumn="bonus_actionId"
             singularname="bonus"
             cascade="all-delete-orphan"
             inverse="true"
             lazy="true";
}
</code>```

Here's a write-up on how inverse works in Hibernate.

Title: Coldfusion ORM: delete in cascade

Body:
I'm not an expert in coldfusion orm and I call your help because I'm pulling my hair!

I'm excepting to delete an entity 'Action' that has 2 relationship one-to-many, 'Texts' and 'Bonus'.

When I try to delete an Action that has only Texts but no Bonus, everything is fine. Hibernate deletes the Action record and the children Texts. It's what I want!

But when the Action has both Texts and Bonus, I got this error :

Column 'bonus_actionId' cannot be null
Root cause :java.sql.BatchUpdateException: Column 'bonus_actionId' cannot be null

Why Hibernate does not delete the Bonus before deleting the Action ? Like it is done for Texts ?

Thanks

Action Entity:

component {
    property name="id"      column="action_id" type="numeric" fieldtype="id" generator="native";

    /* ... */

    property name="texts" type="array"
             fieldtype="one-to-many" cfc="Text" fkcolumn="text_actionId" singularname="text"
             cascade="all-delete-orphan" lazy="true";

    /* ... */

    property name="bonus" type="array"
             fieldtype="one-to-many" cfc="Bonus" fkcolumn="bonus_actionId" singularname="bonus"
             cascade="all-delete-orphan" lazy="true";
}

Text Entity:

component {
    property name="id"      column="text_id" type="numeric" fieldtype="id" generator="native";

    /* ... (properties without relationships */

    property name="action" fieldtype="many-to-one" fkcolumn="text_actionId" cfc="Action" notnull="false" lazy="true";
}

Bonus Entity:

component  {
    property name="id"      column="bonus_id" type="numeric" fieldtype="id" generator="native";

    /* ... (properties WITH relationships */

    // Parent
    property name="action" fieldtype="many-to-one" fkcolumn="bonus_actionId" cfc="Action" notnull="true" lazy="true";

}

Body:
You can keep your notnull="true" and have cascades work correctly by adding inverse="true" to the foreign key–owning side of the relationship.

In your case, this would be on the Action entity:

component {

    property name="id"
             column="action_id"
             type="numeric"
             fieldtype="id"
             generator="native";

    /* ... */

    property name="texts"
             type="array"
             fieldtype="one-to-many"
             cfc="Text"
             fkcolumn="text_actionId"
             singularname="text"
             cascade="all-delete-orphan"
             inverse="true"
             lazy="true";

    /* ... */

    property name="bonus"
             type="array"
             fieldtype="one-to-many"
             cfc="Bonus"
             fkcolumn="bonus_actionId"
             singularname="bonus"
             cascade="all-delete-orphan"
             inverse="true"
             lazy="true";
}

Here's a write-up on how inverse works in Hibernate.


问:
How to manage large MySQL databases (backup)
We have a production MySQL database of about 320GB on disk.

We need to perform regular backups of the dataset but, either mysqldump or "copying table files" are taking hours to complete; moreover, both commands lock the database leading to an unusable website.

At the moment out tables are InnoDB and we have no replication, clustering, master&slave in place.

Is there any way we can perform daily backups without having to take down the website?

答:
Option 1: Have you tried mysqldump --single-transaction? This does not lock the database server, if you only back up InnoDB tables.

Option 2: Percona XtraBackup, but this software is not available for Windows.

Option 3: Percona XtraBackup on Windows. Read this blog that describes a way to use Docker to run Percona XtraBackup on Windows: https://www.percona.com/blog/2017/03/20/running-percona-xtrabackup-windows-docker/

Option 4: Create a replication slave.


问:
Operator overloading in c (not c++) is it possible?
This question arises from my need to "convert" std::string to char* form.

Preferably I would like to maintain as much code as possible and that includes plenty of "=" initialization/assignment operators.

standard c operators exist for the basic data types (int, char, float, pointers to, etc...).

Is it even possible to overload the assignment operator in c? I suppose that each data type as it's own operator so messing with one wouldn't mess with others.

Anyhow, this is just something that intrigued me as I can't find much references on how C operators are implemented.

Cheers

well, some examples are in order

```<code>std::string a_string;
a_string = "bla"
</code>```

or using standard C

```<code>char a_char_array[10];
strcpy(a_char_array,"bla");
</code>```

or

```<code>char *a_char_pointer = "bla";
</code>```

what I'm thinking about is a wa to replace these 3 use cases with a single one where I can (through a #define) switch between using char* or std::string.

I guess that everyone that really cares about performance vs coding speed has already thought about the implications of using std::string instead of char*. All of the advantages of using stl are usually often offseted (is this even a word!?) by lower performance (you can't always get what you want right??).

As I said, I have a large project and I want to see for myself what are the changes in using one method or the other.

My post title was purposely misleading as I didn't want this to become a char* vs string battle, but I guess I can't really explain what I want without some more details.

Cheers

答: No, you cannot overload operators in C, you need to explicitly call a function to do the conversion. The compiler will only do some conversions for you (ints <-> floats, some pointer stuff, etc), but never more intricate stuff.</p>

Body:
This question arises from my need to "convert" std::string to char* form.

Preferably I would like to maintain as much code as possible and that includes plenty of "=" initialization/assignment operators.

standard c operators exist for the basic data types (int, char, float, pointers to, etc...).

Is it even possible to overload the assignment operator in c? I suppose that each data type as it's own operator so messing with one wouldn't mess with others.

Anyhow, this is just something that intrigued me as I can't find much references on how C operators are implemented.

Cheers

well, some examples are in order

std::string a_string;
a_string = "bla"

or using standard C

char a_char_array[10];
strcpy(a_char_array,"bla");

or

char *a_char_pointer = "bla";

what I'm thinking about is a wa to replace these 3 use cases with a single one where I can (through a #define) switch between using char* or std::string.

I guess that everyone that really cares about performance vs coding speed has already thought about the implications of using std::string instead of char*. All of the advantages of using stl are usually often offseted (is this even a word!?) by lower performance (you can't always get what you want right??).

As I said, I have a large project and I want to see for myself what are the changes in using one method or the other.

My post title was purposely misleading as I didn't want this to become a char* vs string battle, but I guess I can't really explain what I want without some more details.

Cheers


问:
Running a single node Elasticsearch on a remote computer for development
I am trying to run elasticsearch in development mode on a remote machine. Is it possible to by pass the bootstrap checks and have it run in development mode on a remote computer but accessible to other computers?

In the documentation, it said that I should set discovery.type to single-node but I don't know where to add that.

I tried adding it to my config file but it gave me an error saying that discovery.type: single-node is an invalid configuration

```<code>org.elasticsearch.bootstrap.StartupException: java.lang.IllegalArgumentException: Unknown discovery type [single-node]
</code>```

答:
For future reference, just make this changes:</p>

```<code>transport.host: localhost
network.host: _site_
</code>```

Body:
I am trying to run elasticsearch in development mode on a remote machine. Is it possible to by pass the bootstrap checks and have it run in development mode on a remote computer but accessible to other computers?

In the documentation, it said that I should set discovery.type to single-node but I don't know where to add that.

I tried adding it to my config file but it gave me an error saying that discovery.type: single-node is an invalid configuration

org.elasticsearch.bootstrap.StartupException: java.lang.IllegalArgumentException: Unknown discovery type [single-node]

Body:
For future reference, just make this changes:

transport.host: localhost
network.host: _site_


问:
Shell cmd in access vba returns error 5 - invalid procedure call or argument
I have used the Shell command in MS Access for several years in multiple databases in various versions.  Most recently, I have received this Run-Time error 5 - invalid procedure call or argument on a Shell command I have used for many years.  Can anyone tell me if there was a recent Windows update or possibly MS Office update that has caused this error to appear?  I am currently using Office 2010 and Office 2013 and receiving the same error in both version on multiple computers.  I have even tried creating a simple empty database and gone straight to the vba window and in the immediate window tried a simple Shell command as such:

```<code>Shell "C:\Notepad.bat", vbNormalFocus
</code>```

Notepad.bat is a simple command inside it:

```<code>cmd /C "Notepad.exe"
</code>```

The code:

```<code>Shell "Notepad.exe", vbNormalFocus
</code>```

does work, but:

```<code>Shell "Cmd.exe", vbNormalFocus
</code>```

still gives the same Error 5 message on every machine I test it on.   Running the batch files from the Windows explorer works just fine.  Any help is much appreciated.

答: After a lot more investigation, I happened on a new software installed by our network software engineers that maintain our McAfee protection.  Last week, there was a blind install of a new app called Adaptive Threat Protection and is set to check for MS office apps running shell commands, especially the CMD type.  This is set to automatically block all of these such commands.  I finally came to a conclusion to look in anything recently installed or updated on my computer and happen to find a few different things installed within the last week date range.  Thank you for your assistance and answers so far.  The answer provided by thx1138v2 were something I also tried prior to my post but I figured for my 1st question I tried to keep my post to a bit of a minimum.</p>

Body:
I have used the Shell command in MS Access for several years in multiple databases in various versions.  Most recently, I have received this Run-Time error 5 - invalid procedure call or argument on a Shell command I have used for many years.  Can anyone tell me if there was a recent Windows update or possibly MS Office update that has caused this error to appear?  I am currently using Office 2010 and Office 2013 and receiving the same error in both version on multiple computers.  I have even tried creating a simple empty database and gone straight to the vba window and in the immediate window tried a simple Shell command as such:

Shell "C:\Notepad.bat", vbNormalFocus

Notepad.bat is a simple command inside it:

cmd /C "Notepad.exe"

The code:

Shell "Notepad.exe", vbNormalFocus

does work, but:

Shell "Cmd.exe", vbNormalFocus

still gives the same Error 5 message on every machine I test it on.   Running the batch files from the Windows explorer works just fine.  Any help is much appreciated.


问:
eLisp. check if return value of (read-event) is a graphical character
I'm trying to check if the return value of (read-event) is a graphical character. Example: a (97) is a graphical character. return is not a graphical character. f1 is not a graphical character and so on. I tried a lot of ways to do that, but nothing works.

答:
Did you try char-displayable-p? C-h f tells you:

char-displayable-p is an autoloaded Lisp function in mule-util.el.

(char-displayable-p CHAR)

Return non-nil if we should be able to display CHAR.

On a multi-font display, the test is only whether there is an
  appropriate font from the selected frame's fontset to display
  CHAR's charset in general.  Since fonts may be specified on a
  per-character basis, this may not be accurate.

But that says that it expects CHAR to be a character.  So you might want to also test to make sure that it is, using characterp.

(In fact, characterp might be all you need: (characterp (read-event)). It depends on whether you care if a given character is displayable in your environment, i.e., given the fonts you have.)

You can often find a function with a name like char-displayable-p using apropos. Try, for instance:

M-x apropos RET char display RET

That shows you something like this:

Type RET on a type label to view its full documentation.

char-displayable-p

Function: Return non-nil if we should be able to display CHAR.

Properties: autoload

glyphless-char-display

Variable: Char-table defining glyphless characters.

Properties: char-table-extra-slots variable-documentation

glyphless-char-display-control

User option: List of directives to control display of glyphless characters.

Properties: standard-value custom-version custom-type custom-options custom-set custom-requests variable-documentation

nobreak-char-display

Variable: Control highlighting of non-ASCII space and hyphen chars.

Properties: variable-documentation

tabulated-list-glyphless-char-display

Variable: The glyphless-char-display table in Tabulated List buffers.

Properties: variable-documentation

update-glyphless-char-display

Function: Make the setting of glyphless-char-display-control take effect.


答:
C does not allow any kind of overloading, operators are built-in (direct translation to assembly code).

There may be some possible tricks using macros depending of your actual code base, but I would discourage it anyway. It is likely to introduce bugs. Just go with plain functions.

Title: Operator overloading in c (not c++) is it possible?


问:
How to run kafka on different machines
From last 10 days i am trying to set Kafka on different machine:

Server32

Server56

Below are the list of task which i have done so far

Configured Zookeeper and started on both server  with

server.1=Server32_IP:2888:3888

server.2=Server56_IP:2888:3888

I also changed server and server-1 properties as below

broker.id=0   port=9092   log.dir=/tmp/kafka0-logs

  host.name=Server32

  zookeeper.connect=Server32_IP:9092,Server56_IP:9062

& server-1

broker.id=1   port=9062   log.dir=/tmp/kafka1-logs

  host.name=Server56

  zookeeper.connect=Server32_IP:9092,Server56_IP:9062

Server.property i ran in Server32

Server-1.property i ran in Server56

The Problem is : when i start producer in both the servers and if i try to consume from any one then it is working BUT

  When i stop any one server then another one is not able to send the details

Please help me in explaining the process

答:
Running 2 zookeepers is not fault tolerant. If one of the zookeepers is stopped, then the system will not work. Unlike Kafka brokers, zookeeper needs a quorum (or majority) of the configured nodes in order to work. This is why zookeeper is typically deployed with an odd number of instances (nodes). Since 1 of 2 nodes is not a majority it really is no better than running a single zookeeper. You need at least 3 zookeepers to tolerate a failure because 2 of 3 is a majority so the system will stay up.

Kafka is different so you can have any number of Kafka brokers and if they are configured correctly and you create your topics with a replication factor of 2 or greater, then the Kafka cluster can continue if you take any one of the broker nodes down , even if it's just 1 of 2.

Title: How to run kafka on different machines


问:
Which stdio.h was included for the hello.c?
The source code.

```<code>#include<stdio.h>
#include<stdlib.h>
int main(int argc,char **argv)
{

    printf("Hello,Linux.\n");
    exit(0);
}
</code>```

To compile it with gcc.

```<code>gcc -o hello hello.c
</code>```

To run it with hello.

```<code>sudo find / -name 'stdio.h'
/usr/include/stdio.h
/usr/include/x86_64-linux-gnu/bits/stdio.h
/usr/include/c++/4.9/tr1/stdio.h
</code>```

For the statement #include<stdio.h>, Which file ,/usr/include/stdio.h or/usr/include/x86_64-linux-gnu/bits/stdio.h , used ?

The os:

```<code>uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u2 (2017-03-07) x86_64 GNU/Linux

gcc -o -H  hello hello.c
hello: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
hello: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
hello: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/4.9/crtbegin.o:(.data+0x0): first defined here
hello:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
hello: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here
hello: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/tmp/ccNhnGzH.o: In function `main':
hello.c:(.text+0x0): multiple definition of `main'
hello:(.text+0xf6): first defined here
/usr/lib/gcc/x86_64-linux-gnu/4.9/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__'
hello:(.data+0x10): first defined here
/usr/bin/ld: error in hello(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status

gcc -H -o hello hello.c
. /usr/include/stdio.h
.. /usr/include/features.h
... /usr/include/x86_64-linux-gnu/sys/cdefs.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/gnu/stubs.h
.... /usr/include/x86_64-linux-gnu/gnu/stubs-64.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/types.h
... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/bits/typesizes.h
.. /usr/include/libio.h
... /usr/include/_G_config.h
.... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.... /usr/include/wchar.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stdarg.h
.. /usr/include/x86_64-linux-gnu/bits/stdio_lim.h
.. /usr/include/x86_64-linux-gnu/bits/sys_errlist.h
. /usr/include/stdlib.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/waitflags.h
.. /usr/include/x86_64-linux-gnu/bits/waitstatus.h
... /usr/include/endian.h
.... /usr/include/x86_64-linux-gnu/bits/endian.h
.... /usr/include/x86_64-linux-gnu/bits/byteswap.h
..... /usr/include/x86_64-linux-gnu/bits/wordsize.h
..... /usr/include/x86_64-linux-gnu/bits/byteswap-16.h
.. /usr/include/x86_64-linux-gnu/sys/types.h
... /usr/include/time.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
... /usr/include/x86_64-linux-gnu/sys/select.h
.... /usr/include/x86_64-linux-gnu/bits/select.h
..... /usr/include/x86_64-linux-gnu/bits/wordsize.h
.... /usr/include/x86_64-linux-gnu/bits/sigset.h
.... /usr/include/time.h
.... /usr/include/x86_64-linux-gnu/bits/time.h
... /usr/include/x86_64-linux-gnu/sys/sysmacros.h
... /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
.. /usr/include/alloca.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/stdlib-float.h
Multiple include guards may be useful for:
/usr/include/wchar.h
/usr/include/x86_64-linux-gnu/bits/byteswap-16.h
/usr/include/x86_64-linux-gnu/bits/byteswap.h
/usr/include/x86_64-linux-gnu/bits/endian.h
/usr/include/x86_64-linux-gnu/bits/select.h
/usr/include/x86_64-linux-gnu/bits/sigset.h
/usr/include/x86_64-linux-gnu/bits/stdio_lim.h
/usr/include/x86_64-linux-gnu/bits/stdlib-float.h
/usr/include/x86_64-linux-gnu/bits/sys_errlist.h
/usr/include/x86_64-linux-gnu/bits/time.h
/usr/include/x86_64-linux-gnu/bits/typesizes.h
/usr/include/x86_64-linux-gnu/bits/waitflags.h
/usr/include/x86_64-linux-gnu/bits/waitstatus.h
/usr/include/x86_64-linux-gnu/gnu/stubs-64.h
/usr/include/x86_64-linux-gnu/gnu/stubs.h
</code>```

答:
The short answer is: /usr/include/stdio.h

The correct answer is: more than one of them

The solution depends on the following premises:

The search for C preprocessor include files is guided by the INCLUDE directory list. You can use the command cpp -v to print the search list (Assuming cpp is your preprocessor, which is likely true. Determining which preprocessor is being used just adds another level of indirection)

On my SUSE linux system I get the following output

```<code>$ cpp -v
  ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/lib64/gcc/x86_64-suse-linux/4.8/include
 /usr/local/include
 /usr/lib64/gcc/x86_64-suse-linux/4.8/include-fixed
 /usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../x86_64-suse-linux/include
 /usr/include
End of search list.
</code>```

Header files often include other header files.

E.g. /usr/include/stdio.h contains the following code

/* If we are compiling with optimizing read this file.  It contains
   several optimizing inline functions and macros.  */
#ifdef __USE_EXTERN_INLINES
# include <bits/stdio.h>
#endif
```

<p>That means that after reading in the file the preprocessor also reads in <code>/usr/include/bits/stdio.h</code> if <code>__USE_EXTERN_INLINES</code> is defined.</p>

<ol start="3">
<li>The <code>bits/stdio.h</code> is supplementary. When you look inside the file you will notice that it starts with a warning message straight after the license text:</li>
</ol>

```
#ifndef _STDIO_H
# error "Never include <bits/stdio.h> directly; use <stdio.h> instead."
#endif
```

That is this file is to be included only via the proper /usr/include/stdio.h file

Body:
The source code.

#include<stdio.h>
#include<stdlib.h>
int main(int argc,char **argv)
{

    printf("Hello,Linux.\n");
    exit(0);
}

To compile it with gcc.

gcc -o hello hello.c

To run it with hello.

sudo find / -name 'stdio.h'
/usr/include/stdio.h
/usr/include/x86_64-linux-gnu/bits/stdio.h
/usr/include/c++/4.9/tr1/stdio.h

For the statement #include<stdio.h>, Which file ,/usr/include/stdio.h or/usr/include/x86_64-linux-gnu/bits/stdio.h , used ?

The os:

uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u2 (2017-03-07) x86_64 GNU/Linux

gcc -o -H  hello hello.c
hello: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
hello: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
hello: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/4.9/crtbegin.o:(.data+0x0): first defined here
hello:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
hello: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here
hello: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/4.9/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/tmp/ccNhnGzH.o: In function `main':
hello.c:(.text+0x0): multiple definition of `main'
hello:(.text+0xf6): first defined here
/usr/lib/gcc/x86_64-linux-gnu/4.9/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__'
hello:(.data+0x10): first defined here
/usr/bin/ld: error in hello(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status

gcc -H -o hello hello.c
. /usr/include/stdio.h
.. /usr/include/features.h
... /usr/include/x86_64-linux-gnu/sys/cdefs.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/gnu/stubs.h
.... /usr/include/x86_64-linux-gnu/gnu/stubs-64.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/types.h
... /usr/include/x86_64-linux-gnu/bits/wordsize.h
... /usr/include/x86_64-linux-gnu/bits/typesizes.h
.. /usr/include/libio.h
... /usr/include/_G_config.h
.... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.... /usr/include/wchar.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stdarg.h
.. /usr/include/x86_64-linux-gnu/bits/stdio_lim.h
.. /usr/include/x86_64-linux-gnu/bits/sys_errlist.h
. /usr/include/stdlib.h
.. /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/waitflags.h
.. /usr/include/x86_64-linux-gnu/bits/waitstatus.h
... /usr/include/endian.h
.... /usr/include/x86_64-linux-gnu/bits/endian.h
.... /usr/include/x86_64-linux-gnu/bits/byteswap.h
..... /usr/include/x86_64-linux-gnu/bits/wordsize.h
..... /usr/include/x86_64-linux-gnu/bits/byteswap-16.h
.. /usr/include/x86_64-linux-gnu/sys/types.h
... /usr/include/time.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
... /usr/include/x86_64-linux-gnu/sys/select.h
.... /usr/include/x86_64-linux-gnu/bits/select.h
..... /usr/include/x86_64-linux-gnu/bits/wordsize.h
.... /usr/include/x86_64-linux-gnu/bits/sigset.h
.... /usr/include/time.h
.... /usr/include/x86_64-linux-gnu/bits/time.h
... /usr/include/x86_64-linux-gnu/sys/sysmacros.h
... /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h
.... /usr/include/x86_64-linux-gnu/bits/wordsize.h
.. /usr/include/alloca.h
... /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stddef.h
.. /usr/include/x86_64-linux-gnu/bits/stdlib-float.h
Multiple include guards may be useful for:
/usr/include/wchar.h
/usr/include/x86_64-linux-gnu/bits/byteswap-16.h
/usr/include/x86_64-linux-gnu/bits/byteswap.h
/usr/include/x86_64-linux-gnu/bits/endian.h
/usr/include/x86_64-linux-gnu/bits/select.h
/usr/include/x86_64-linux-gnu/bits/sigset.h
/usr/include/x86_64-linux-gnu/bits/stdio_lim.h
/usr/include/x86_64-linux-gnu/bits/stdlib-float.h
/usr/include/x86_64-linux-gnu/bits/sys_errlist.h
/usr/include/x86_64-linux-gnu/bits/time.h
/usr/include/x86_64-linux-gnu/bits/typesizes.h
/usr/include/x86_64-linux-gnu/bits/waitflags.h
/usr/include/x86_64-linux-gnu/bits/waitstatus.h
/usr/include/x86_64-linux-gnu/gnu/stubs-64.h
/usr/include/x86_64-linux-gnu/gnu/stubs.h

Body:
The short answer is: /usr/include/stdio.h

The correct answer is: more than one of them

The solution depends on the following premises:

The search for C preprocessor include files is guided by the INCLUDE directory list. You can use the command cpp -v to print the search list (Assuming cpp is your preprocessor, which is likely true. Determining which preprocessor is being used just adds another level of indirection)

On my SUSE linux system I get the following output

$ cpp -v
  ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/lib64/gcc/x86_64-suse-linux/4.8/include
 /usr/local/include
 /usr/lib64/gcc/x86_64-suse-linux/4.8/include-fixed
 /usr/lib64/gcc/x86_64-suse-linux/4.8/../../../../x86_64-suse-linux/include
 /usr/include
End of search list.

Header files often include other header files.

E.g. /usr/include/stdio.h contains the following code

/* If we are compiling with optimizing read this file.  It contains
   several optimizing inline functions and macros.  */
#ifdef __USE_EXTERN_INLINES
# include <bits/stdio.h>
#endif

That means that after reading in the file the preprocessor also reads in /usr/include/bits/stdio.h if __USE_EXTERN_INLINES is defined.

The bits/stdio.h is supplementary. When you look inside the file you will notice that it starts with a warning message straight after the license text:

#ifndef _STDIO_H
# error "Never include <bits/stdio.h> directly; use <stdio.h> instead."
#endif

That is this file is to be included only via the proper /usr/include/stdio.h file


问:
xcode The document "..." could not be saved
I use xcode 3.2.4 on snow leopard. Today when I tried to save a file on my project I get an error message saying: The document "nameOfFile.m" could not be saved. I tried reinstalling xcode but no luck. The file can be edited with other editors and I see the same behavior on all my projects as well as newly created projects. Any ideas?

答:
Hey........... even i faced the same problem..... But got the answer......
 steps:

reveal in folder  the project.

select the file that is locked

select 'GEt Info'

deselect ie uncheck the label 'LOCKED' in the Info.


答: If you compile just with -E it will give you preprocessed output for hello.c, it will include path for header files that were expanded during preprocessing, you can see which stdio.h is used there</p>

Title: Which stdio.h was included for the hello.c?


问:
Amazon RDS Endpoint internal
How can I make ec2 instance communicate with rds instance on aws by internal ip address or dns?
I only see public dns like xxx.cehmrvc73g1g.eu-west-1.rds.amazonaws.com:3306
Will internal ipaddress will be faster than public dns?

Thanks

答:
A note for posterity, ensure that you enable DNS on the VPC Peering link!

Enabling DNS Resolution Support for a VPC Peering Connection

To enable a VPC to resolve public IPv4 DNS hostnames to private IPv4
addresses when queried from instances in the peer VPC, you must modify
the peering connection.

Both VPCs must be enabled for DNS hostnames and DNS resolution.

To enable DNS resolution support for the peering connection

Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.

In the navigation pane, choose Peering Connections.

Select the VPC peering connection, and choose Actions, Edit DNS
Settings.

To ensure that queries from the peer VPC resolve to private IP
addresses in your local VPC, choose the option to enable DNS
resolution for queries from the peer VPC.

If the peer VPC is in the same AWS account, you can choose the option
to enable DNS resolution for queries from the local VPC. This ensures
that queries from the local VPC resolve to private IP addresses in the
peer VPC. This option is not available if the peer VPC is in a
different AWS account.

Choose Save.

If the peer VPC is in a different AWS account, the owner of the peer
VPC must sign into the VPC console, perform steps 2 through 4, and
choose Save.

Title: Amazon RDS Endpoint internal


问:
Modify tick label text
I want to make some modifications to a few selected tick labels in a plot.

For example, if I do:

```<code>label = axes.yaxis.get_major_ticks()[2].label
label.set_fontsize(size)
label.set_rotation('vertical')
</code>```

the font size and the orientation of the tick label is changed.

However, if try:

```<code>label.set_text('Foo')
</code>```

the tick label is not modified. Also if I do:

```<code>print label.get_text()
</code>```

nothing is printed.

Here's some more strangeness. When I tried this:

import matplotlib.pyplot as plt
import numpy as np

axes = plt.figure().add_subplot(111)
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
axes.plot(t, s)
for ticklabel in axes.get_xticklabels():
    print(ticklabel.get_text())
```

Only empty strings are printed, but the plot contains ticks labeled as '0.0', '0.5', '1.0', '1.5', and '2.0'.

答:
This works:

```<code>import matplotlib.pyplot as plt

fig, ax1 = plt.subplots(1,1)

x1 = [0,1,2,3]
squad = ['Fultz','Embiid','Dario','Simmons']

ax1.set_xticks(x1)
ax1.set_xticklabels(squad, minor=False, rotation=45)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Modify tick label text

Body:
I want to make some modifications to a few selected tick labels in a plot.

For example, if I do:

label = axes.yaxis.get_major_ticks()[2].label
label.set_fontsize(size)
label.set_rotation('vertical')

the font size and the orientation of the tick label is changed.

However, if try:

label.set_text('Foo')

the tick label is not modified. Also if I do:

print label.get_text()

nothing is printed.

Here's some more strangeness. When I tried this:

import matplotlib.pyplot as plt
import numpy as np

axes = plt.figure().add_subplot(111)
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
axes.plot(t, s)
for ticklabel in axes.get_xticklabels():
    print(ticklabel.get_text())

Only empty strings are printed, but the plot contains ticks labeled as '0.0', '0.5', '1.0', '1.5', and '2.0'.

Body:
This works:

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots(1,1)

x1 = [0,1,2,3]
squad = ['Fultz','Embiid','Dario','Simmons']

ax1.set_xticks(x1)
ax1.set_xticklabels(squad, minor=False, rotation=45)