问:
Unable to create cmis:document inside custom alfresco folder
I'm using open cmis to create folder (custom type) with attachments in Alfresco repository (5.1e). Folder is successfully created, but for creation of document (cmis:document - cm:content) as attachment I'm getting following exception:

Caused by: org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException: Objects of type 'cmis:document' cannot be added to this folder!
                  at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:514) [chemistry-opencmis-client-bindings-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.post(AbstractAtomPubService.java:717) [chemistry-opencmis-client-bindings-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.bindings.spi.atompub.ObjectServiceImpl.createDocument(ObjectServiceImpl.java:122) [chemistry-opencmis-client-bindings-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.runtime.SessionImpl.createDocument(SessionImpl.java:1197) [chemistry-opencmis-client-impl-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.runtime.FolderImpl.createDocument(FolderImpl.java:88) [chemistry-opencmis-client-impl-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.runtime.FolderImpl.createDocument(FolderImpl.java:471) [chemistry-opencmis-client-impl-1.0.0.jar:1.0.0]
                  at com.salviol.frops.common.ejbs.DcmIntegrationEJB.createDocument(DcmIntegrationEJB.java:208) [frops-common-ejb-0.0.1.jar:]
                  at com.salviol.frops.common.ejbs.DcmIntegrationEJB.createCase(DcmIntegrationEJB.java:67) [frops-common-ejb-0.0.1.jar:]
                  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_40]
                  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_40]
                  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_40]
                  at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_40]
                  at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
                  at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:407)
                  at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:82) [wildfly-weld-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:93) [wildfly-weld-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
                  at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43) [wildfly-ejb3-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47) [wildfly-jpa-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:407)
                  at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
                  at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:83) [wildfly-weld-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation(ConcurrentContextInterceptor.java:45) [wildfly-ee-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
                  at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:53)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.ejb3.component.interceptors.NonPooledEJBComponentInstanceAssociatingInterceptor.processInvocation(NonPooledEJBComponentInstanceAssociatingInterceptor.java:59) [wildfly-ejb3-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:251) [wildfly-ejb3-8.1.0.Final.jar:8.1.0.Final]
                  ... 174 more

Here is the source code  (method) for adding document to folder:

```<code>private Document createDocument(Session cmisSession, Folder parentFolder, byte[] file, String fileName, String fileType) {

Document document = null;

try {

Map<String, Object> docProperties = new HashMap<String, Object>();
docProperties.put(PropertyIds.OBJECT_TYPE_ID,  "cmis:document");
docProperties.put(PropertyIds.NAME, fileName);

    ContentStream contentStream = cmisSession.getObjectFactory().createContentStream(fileName, file.length, fileType, new ByteArrayInputStream(file));

        document = parentFolder.createDocument(docProperties, contentStream, null);

    } catch (CmisContentAlreadyExistsException ccaee) {
        document = (Document) cmisSession.getObjectByPath(parentFolder.getPath() + "/" + fileName);
    }

    return document;
}
</code>```

I tried with versioning (state MAJOR and NONE), but the problem is still there. Created folder has standard permissions (inherit = "true" and for each site user appropriate permission).

Did anyone have the same problem with Cmis constraint?

答:
It's about your folder, not about your document.
Take a look at the code that is causing the error, and the cause will become aparent. There's a property named cmis:allowedChildObjectTypeIds, and it's what you're after.

How is your model defined?

```<code>public void checkChildObjectType(CMISNodeInfo folderInfo, String childType)
    {
        TypeDefinitionWrapper targetType = folderInfo.getType();
        PropertyDefinitionWrapper allowableChildObjectTypeProperty = targetType
                .getPropertyById(PropertyIds.ALLOWED_CHILD_OBJECT_TYPE_IDS);
        List<String> childTypes = (List<String>) allowableChildObjectTypeProperty.getPropertyAccessor().getValue(
                folderInfo);

        if ((childTypes == null) || childTypes.isEmpty())
        {
            return;
        }

        if (!childTypes.contains(childType))
        {
            throw new CmisConstraintException("Objects of type '" + childType + "' cannot be added to this folder!");
        }
    }
</code>```

Body:
I'm using open cmis to create folder (custom type) with attachments in Alfresco repository (5.1e). Folder is successfully created, but for creation of document (cmis:document - cm:content) as attachment I'm getting following exception:

Caused by: org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException: Objects of type 'cmis:document' cannot be added to this folder!
                  at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:514) [chemistry-opencmis-client-bindings-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.post(AbstractAtomPubService.java:717) [chemistry-opencmis-client-bindings-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.bindings.spi.atompub.ObjectServiceImpl.createDocument(ObjectServiceImpl.java:122) [chemistry-opencmis-client-bindings-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.runtime.SessionImpl.createDocument(SessionImpl.java:1197) [chemistry-opencmis-client-impl-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.runtime.FolderImpl.createDocument(FolderImpl.java:88) [chemistry-opencmis-client-impl-1.0.0.jar:1.0.0]
                  at org.apache.chemistry.opencmis.client.runtime.FolderImpl.createDocument(FolderImpl.java:471) [chemistry-opencmis-client-impl-1.0.0.jar:1.0.0]
                  at com.salviol.frops.common.ejbs.DcmIntegrationEJB.createDocument(DcmIntegrationEJB.java:208) [frops-common-ejb-0.0.1.jar:]
                  at com.salviol.frops.common.ejbs.DcmIntegrationEJB.createCase(DcmIntegrationEJB.java:67) [frops-common-ejb-0.0.1.jar:]
                  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_40]
                  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_40]
                  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_40]
                  at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_40]
                  at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
                  at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:407)
                  at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:82) [wildfly-weld-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:93) [wildfly-weld-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
                  at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43) [wildfly-ejb3-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47) [wildfly-jpa-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:407)
                  at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:46) [weld-core-impl-2.1.2.Final.jar:2014-01-09 09:23]
                  at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:83) [wildfly-weld-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation(ConcurrentContextInterceptor.java:45) [wildfly-ee-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
                  at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:53)
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.ejb3.component.interceptors.NonPooledEJBComponentInstanceAssociatingInterceptor.processInvocation(NonPooledEJBComponentInstanceAssociatingInterceptor.java:59) [wildfly-ejb3-8.1.0.Final.jar:8.1.0.Final]
                  at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:309)
                  at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:251) [wildfly-ejb3-8.1.0.Final.jar:8.1.0.Final]
                  ... 174 more

Here is the source code  (method) for adding document to folder:

private Document createDocument(Session cmisSession, Folder parentFolder, byte[] file, String fileName, String fileType) {

Document document = null;

try {

Map<String, Object> docProperties = new HashMap<String, Object>();
docProperties.put(PropertyIds.OBJECT_TYPE_ID,  "cmis:document");
docProperties.put(PropertyIds.NAME, fileName);

    ContentStream contentStream = cmisSession.getObjectFactory().createContentStream(fileName, file.length, fileType, new ByteArrayInputStream(file));

        document = parentFolder.createDocument(docProperties, contentStream, null);

    } catch (CmisContentAlreadyExistsException ccaee) {
        document = (Document) cmisSession.getObjectByPath(parentFolder.getPath() + "/" + fileName);
    }

    return document;
}

I tried with versioning (state MAJOR and NONE), but the problem is still there. Created folder has standard permissions (inherit = "true" and for each site user appropriate permission).

Did anyone have the same problem with Cmis constraint?

Body:
It's about your folder, not about your document.
Take a look at the code that is causing the error, and the cause will become aparent. There's a property named cmis:allowedChildObjectTypeIds, and it's what you're after.

How is your model defined?

public void checkChildObjectType(CMISNodeInfo folderInfo, String childType)
    {
        TypeDefinitionWrapper targetType = folderInfo.getType();
        PropertyDefinitionWrapper allowableChildObjectTypeProperty = targetType
                .getPropertyById(PropertyIds.ALLOWED_CHILD_OBJECT_TYPE_IDS);
        List<String> childTypes = (List<String>) allowableChildObjectTypeProperty.getPropertyAccessor().getValue(
                folderInfo);

        if ((childTypes == null) || childTypes.isEmpty())
        {
            return;
        }

        if (!childTypes.contains(childType))
        {
            throw new CmisConstraintException("Objects of type '" + childType + "' cannot be added to this folder!");
        }
    }


来源: stackexchange

问:
Laravel Query Relationship on One Model Instance
I am aware that I can use count() to query for Eloquent relationships in Laravel, like so:

```<code>if(count($question->answers()))
</code>```

Where answers() is a hasMany relationship:

```<code> public function answers()
    {
        return $this->hasMany('App\Models\Answer', 'question_id');
    }
</code>```

My question is, how do I do this when $question is not an entire collection but one Model instance?

```<code>$question = Question::where('id',$key)->first();
</code>```

How do I query the above question, and only that question, for a potential relationship using count()?

I always am getting a count() of greater than zero, even when the selected question has no associated answers, which means my if block always runs and returns unwarranted null values:

```<code>if(count($question->answers()))
   {
   //returns nulls
   }
</code>```

答:
As already pointed count($question->answers()) has no meaning because $question->answers() is a Relation instance, you can call dynamic query method on that but if you want to count elements you need a collection, i.e $question->answers.

So you have two choice:

count the collection: count($question->answers)

ask the database to do the count: $question->answers()->count()

Parentheses matters

ContentLicense: CC BY-SA 3.0

Body:
I am aware that I can use count() to query for Eloquent relationships in Laravel, like so:

if(count($question->answers()))

Where answers() is a hasMany relationship:

 public function answers()
    {
        return $this->hasMany('App\Models\Answer', 'question_id');
    }

My question is, how do I do this when $question is not an entire collection but one Model instance?

$question = Question::where('id',$key)->first();

How do I query the above question, and only that question, for a potential relationship using count()?

I always am getting a count() of greater than zero, even when the selected question has no associated answers, which means my if block always runs and returns unwarranted null values:

if(count($question->answers()))
   {
   //returns nulls
   }


问:
Error setting a default null value for an annotation's field
Why am I getting an error "Attribute value must be constant". Isn't null constant???

```<code>@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SomeInterface {
    Class<? extends Foo> bar() default null;// this doesn't compile
}
</code>```

答:
```<code>Class<? extends Foo> bar() default null;// this doesn't compile
</code>```

As mentioned, the Java language specification does not allow null values in the annotations defaults.

What I tend to do is to do is to define DEFAULT_VALUE constants at the top of the annotation definition.  Something like:

```<code>public @interface MyAnnotation {
    public static final String DEFAULT_PREFIX = "__class-name-here__ default";
    ...
    public String prefix() default DEFAULT_PREFIX;
}
</code>```

Then in my code I do something like:

```<code>if (myAnnotation.prefix().equals(MyAnnotation.DEFAULT_PREFIX)) { ... }
</code>```

In your case with a class, I would just define a marker class.  Unfortunately you can't have a constant for this so instead you need to do something like:

```<code>public @interface MyAnnotation {
    public static Class<? extends Foo> DEFAULT_BAR = DefaultBar.class;
    ...
    Class<? extends Foo> bar() default DEFAULT_BAR;
}
</code>```

Your DefaultFoo class would just an empty implementation so that the code can do:

```<code>if (myAnnotation.bar() == MyAnnotation.DEFAULT_BAR) { ... }
</code>```

Hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
Why am I getting an error "Attribute value must be constant". Isn't null constant???

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SomeInterface {
    Class<? extends Foo> bar() default null;// this doesn't compile
}

Body:
Class<? extends Foo> bar() default null;// this doesn't compile

As mentioned, the Java language specification does not allow null values in the annotations defaults.

What I tend to do is to do is to define DEFAULT_VALUE constants at the top of the annotation definition.  Something like:

public @interface MyAnnotation {
    public static final String DEFAULT_PREFIX = "__class-name-here__ default";
    ...
    public String prefix() default DEFAULT_PREFIX;
}

Then in my code I do something like:

if (myAnnotation.prefix().equals(MyAnnotation.DEFAULT_PREFIX)) { ... }

In your case with a class, I would just define a marker class.  Unfortunately you can't have a constant for this so instead you need to do something like:

public @interface MyAnnotation {
    public static Class<? extends Foo> DEFAULT_BAR = DefaultBar.class;
    ...
    Class<? extends Foo> bar() default DEFAULT_BAR;
}

Your DefaultFoo class would just an empty implementation so that the code can do:

if (myAnnotation.bar() == MyAnnotation.DEFAULT_BAR) { ... }

Hope this helps.

ContentLicense: CC BY-SA 4.0


问:
Methods .text() and .html() in jQuery strip trailing whitespace in IE7?
I'm using jQuery to insert text inside a HTML tag. The HTML code looks like this:

```<code><h5>Do you want to send a message to <span id='firstName'></span> right now?</h5>
</code>```

The jQuery code for inserting the text inside the span tag looks like this:

```<code>var myFirstName = "Thomas";
$("h5 span.firstName").html(myFirstName);
</code>```

When I run this code in Firefox, Chrome, Safari or IE8 the result is this:

```<code><h5>Do you want to send a message to <span id='firstName'>Thomas</span> right now?</h5>
</code>```

But in Internet Explorer 7, the result is this:

```<code><h5>Do you want to send a message to <span id='firstName'>Thomas</span>right now?</h5>
</code>```

The trailing white space after the span tag is stripped resulting in a text on-screen that reads: "Do you want to send a message to Thomasright now?".

I've tried using both .html() and .text() but there is no difference in the result.

Is there a way to fix this bug? Is it a known bug in jQuery/IE7?

Thanks in advance!

/Thomas Kahn

答:
making  to   will fixed the problem. ^^

simple demo page

 ^ open this on IE 7

Body:
I'm using jQuery to insert text inside a HTML tag. The HTML code looks like this:

Do you want to send a message to  right now?

The jQuery code for inserting the text inside the span tag looks like this:

var myFirstName = "Thomas";
$("h5 span.firstName").html(myFirstName);

When I run this code in Firefox, Chrome, Safari or IE8 the result is this:

Do you want to send a message to Thomas right now?

But in Internet Explorer 7, the result is this:

Do you want to send a message to Thomasright now?

The trailing white space after the span tag is stripped resulting in a text on-screen that reads: "Do you want to send a message to Thomasright now?".

I've tried using both .html() and .text() but there is no difference in the result.

Is there a way to fix this bug? Is it a known bug in jQuery/IE7?

Thanks in advance!

/Thomas Kahn

Body:
making <span id='firstName'></span> to <span id='firstName'>&nbsp;</span> will fixed the problem. ^^

simple demo page

 ^ open this on IE 7


问:
Calling a class in a different sub-project using eclipse
I have a project where I am trying to call a class that is in another sub-project but it is resulting in a compile error.

This is how my project structure looks:

I am trying to call a class DownLoadFactory from the utilcmrujar sub-project to a class B that is under the crmuwar sub-project.

This is how I imported the package in class B under the crmuwar sub-project but it produces a compile error:

Would I actually have to sub-project utilcmrujar into a jar file and call it as a dependency?

答:
It looks like you're using Eclipse.  Simply add the utilcmrujar folder to your classpath by right clicking on the older and selecting Build Path > Use as Source Folder:

Repeat the same step for each of your source folders.

Inside of your utilcmrujar source folders, you should have com/south/smdw/crm/webutils and com/south/smdw/crm/data folders, based on your package and import statements.  DownloadFactory.java should be in com/south/smdw/crm/data (based on the import statement) and the file you are editing should be in com/south/smdw/crm/webutils (based on your package declaration).


问:
putting binary data python sharemy3d
I'm working with ShareMy3D API and came across a problem.

I have a file upload link and need to execute

```<code>curl -X PUT -T - "[UPLOAD_URL]" < PATH_TO_LOCAL_FILE
</code>```

My specific CURL command:

```<code>curl -X PUT -T - https://storage.googleapis.com/sharemy3d-central-us-1-production/alotofstuff < /home/max/Documents/file.obj
</code>```

After I execute it I always get:

```<code>curl: (6) Could not resolve host: <
curl: (3) <url> malformed
</code>```

Are there other ways to PUT binary files?

答:
All I had to do was execute curl -T file.obj https://example.com.
 With -T (same as --upload-file) curl will use PUT for HTTP

Title: putting binary data python sharemy3d

Body:
I'm working with ShareMy3D API and came across a problem.

I have a file upload link and need to execute

curl -X PUT -T - "[UPLOAD_URL]" < PATH_TO_LOCAL_FILE

My specific CURL command:

curl -X PUT -T - https://storage.googleapis.com/sharemy3d-central-us-1-production/alotofstuff < /home/max/Documents/file.obj

After I execute it I always get:

curl: (6) Could not resolve host: <
curl: (3) <url> malformed

Are there other ways to PUT binary files?


问:
Node.js create folder or use existing
I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdir(). As you can see in the documentation, it's not very much.

Currently, I have this code, which tries to create a folder or use an existing one instead:

```<code>fs.mkdir(path,function(e){
    if(!e || (e && e.code === 'EEXIST')){
        //do something with contents
    } else {
        //debug
        console.log(e);
    }
});
</code>```

But I wonder is this the right way to do it? Is checking for the code EEXIST the right way to know that the folder already exists? I know I can do fs.stat() before making the directory, but that would already be two hits to the filesystem.

Secondly, is there a complete or at least a more detailed documentation of Node.js that contains details as to what error objects contain, what parameters signify etc.

答:
I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :

LAST UPDATE :

In v10.12.0, NodeJS impletement recursive options :

```<code>// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });
</code>```

UPDATE :

```<code>// Get modules node
const fs   = require('fs');
const path = require('path');

// Create
function mkdirpath(dirPath)
{
    if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
    {
        try
        {
            fs.mkdirSync(dirPath);
        }
        catch(e)
        {
            mkdirpath(path.dirname(dirPath));
            mkdirpath(dirPath);
        }
    }
}

// Create folder path
mkdirpath('my/new/folder/create');
</code>```

Title: Node.js create folder or use existing

Body:
I already have read the documentation of Node.js and, unless if I missed something, it does not tell what the parameters contain in certain operations, in particular fs.mkdir(). As you can see in the documentation, it's not very much.

Currently, I have this code, which tries to create a folder or use an existing one instead:

fs.mkdir(path,function(e){
    if(!e || (e && e.code === 'EEXIST')){
        //do something with contents
    } else {
        //debug
        console.log(e);
    }
});

But I wonder is this the right way to do it? Is checking for the code EEXIST the right way to know that the folder already exists? I know I can do fs.stat() before making the directory, but that would already be two hits to the filesystem.

Secondly, is there a complete or at least a more detailed documentation of Node.js that contains details as to what error objects contain, what parameters signify etc.

Body:
I propose a solution without modules (accumulate modules is never recommended for maintainability especially for small functions that can be written in a few lines...) :

LAST UPDATE :

In v10.12.0, NodeJS impletement recursive options :

// Create recursive folder
fs.mkdir('my/new/folder/create', { recursive: true }, (err) => { if (err) throw err; });

UPDATE :

// Get modules node
const fs   = require('fs');
const path = require('path');

// Create
function mkdirpath(dirPath)
{
    if(!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK))
    {
        try
        {
            fs.mkdirSync(dirPath);
        }
        catch(e)
        {
            mkdirpath(path.dirname(dirPath));
            mkdirpath(dirPath);
        }
    }
}

// Create folder path
mkdirpath('my/new/folder/create');


问:
Doxygen : skip some classes / structs
I use Doxygen to generate my documentation but it adds documentation for the structs that does not have any documentation.

I use HIDE_UNDOC_CLASSES in my Doxyfile.in, but I still see some documentation.

Is there another way to explain to Doxygen to not generate any documentation for a class/struct ?

答:
You can use the EXCLUDE_SYMBOLS tag.

The documentation says:

```<code>The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
(namespaces, classes, functions, etc.) that should be excluded from the
output. The symbol name can be a fully qualified name, a word, or if the
wildcard * is used, a substring. Examples: ANamespace, AClass,
AClass::ANamespace, ANamespace::*Test

Note that the wildcards are matched against the file with absolute path, so to
exclude all test directories use the pattern */test/*
</code>```

Title: Doxygen : skip some classes / structs

Body:
You can use the EXCLUDE_SYMBOLS tag.

The documentation says:

The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
(namespaces, classes, functions, etc.) that should be excluded from the
output. The symbol name can be a fully qualified name, a word, or if the
wildcard * is used, a substring. Examples: ANamespace, AClass,
AClass::ANamespace, ANamespace::*Test

Note that the wildcards are matched against the file with absolute path, so to
exclude all test directories use the pattern */test/*


问:
Microsoft SQL Server Management Studio says that RowVersion is invalid type
Is there a way when creating a tables through Microsoft SQL Server Management Studio, to specify a field as RowVersion rather than Timestamp?

This is what I get when I try to use rowversion as a type of a field:

I am on Windows 7 64bit, SQL Server 2014 Express, and Microsoft SQL Server Management Studio 17.1

答:
Don't have enough reputation to post a comment. This has been asked before. below is the link

if you are using GUI,then use TimeStamp' which is howrowversion` is stored under the hoods

```<code>CREATE TABLE dbo.x(y ROWVERSION);
</code>```

even the above ddl under the hoods will be stored as Timestamp,you can verify the same using below

```<code>SELECT t.name
  FROM sys.types AS t
  INNER JOIN sys.columns AS c
    ON c.system_type_id = t.system_type_id
  INNER JOIN sys.tables AS st
    ON c.[object_id] = st.[object_id]
  INNER JOIN sys.schemas AS s
    ON st.[schema_id] = s.[schema_id]
  WHERE st.name = N'x'
    AND s.name = N'dbo'
    AND c.name = N'y';
</code>```

References:

https://dba.stackexchange.com/questions/86523/microsoft-recommends-using-rowversion-over-timestamp-but-i-can-not-find-rowve

Body:
Don't have enough reputation to post a comment. This has been asked before. below is the link

if you are using GUI,then use TimeStamp' which is howrowversion` is stored under the hoods

CREATE TABLE dbo.x(y ROWVERSION);

even the above ddl under the hoods will be stored as Timestamp,you can verify the same using below

SELECT t.name
  FROM sys.types AS t
  INNER JOIN sys.columns AS c
    ON c.system_type_id = t.system_type_id
  INNER JOIN sys.tables AS st
    ON c.[object_id] = st.[object_id]
  INNER JOIN sys.schemas AS s
    ON st.[schema_id] = s.[schema_id]
  WHERE st.name = N'x'
    AND s.name = N'dbo'
    AND c.name = N'y';

References:

https://dba.stackexchange.com/questions/86523/microsoft-recommends-using-rowversion-over-timestamp-but-i-can-not-find-rowve


问:
Odd/even html in php loop not alternating properly
I've been searching through questions/answers on here, but can't seem to find something that works with my code.

Most of the solutions I've found cause the whole page to get a 500 error. They're generally just snippets of the odd/even php, and aren't working for me to easily integrate with the custom post type loop php I have. I'm probably just not putting it in the right place, but nothing seem to be working.

I'm not super great with php, but this is the one thing I've always had an issue getting to work.

Goal:
Odd posts have the headshot on the left, bio info on the right.
Even posts have the headshot on the right, bio info on the left.

Below is my code, which does load on the page (no 500 error), but doesn't output the alternating layout, just outputs the same layout as if I didn't have the odd/even code.

```<code><?php // theloop
    if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php $loop = new WP_Query( array( 'post_type' => 'team', 'posts_per_page' => -1, 'order' => 'ASC') ); ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <?php if ($wp_query->current_post % 2 == 0): ?>

        <div class="row team-member"> <!--ODD LAYOUT // HEADSHOT LEFT - BIO RIGHT-->
            <div class="container">
                <div class="row is-table-row">
                    <div class="col-sm-6 headshot" style="background-image:url(<?php the_field('bio_photo'); ?>);">
                        <div class="box">
                        </div>
                    </div>
                    <div class="col-sm-6 bio cream-bg">
                        <div class="box">
                            <?php if( get_field('additional_logo') ): ?>
                                    <div class="additional-logo"><img src="<?php the_field('additional_logo'); ?>"></div>
                            <?php endif; ?>
                            <h2><?php the_field('name'); ?></h2>
                            <div class="bio-content"><?php the_field('bio'); ?></div>

                           <div class="contact-container">
                               <h4>Contact me!</h4>
                                <?php if( get_field('phone_number') ): ?>
                                    <p><i class="fa fa-phone" aria-hidden="true"></i> <?php the_field('phone_number'); ?></p>
                                <?php endif; ?>
                                <p><i class="fa fa-envelope" aria-hidden="true"></i> <a href="mailto:<?php the_field('email'); ?>" target="_top"><?php the_field('email'); ?></a></p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    <?php else: ?>

        <div class="row team-member"> <!--EVEN LAYOUT // HEADSHOT RIGHT - BIO LEFT-->
            <div class="container">
                <div class="row is-table-row">
                    <div class="col-sm-6 bio cream-bg">
                        <div class="box">
                            <?php if( get_field('additional_logo') ): ?>
                                    <div class="additional-logo"><img src="<?php the_field('additional_logo'); ?>"></div>
                               <?php endif; ?>
                            <h2><?php the_field('name'); ?></h2>
                            <div class="bio-content"><?php the_field('bio'); ?></div>

                           <div class="contact-container">
                               <h4>Contact me!</h4>
                               <?php if( get_field('phone_number') ): ?>
                                    <p><i class="fa fa-phone" aria-hidden="true"></i> <?php the_field('phone_number'); ?></p>
                               <?php endif; ?>
                               <p><i class="fa fa-envelope" aria-hidden="true"></i> <a href="mailto:<?php the_field('email'); ?>" target="_top"><?php the_field('email'); ?></a></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 headshot" style="background-image:url(<?php the_field('bio_photo'); ?>);">
                        <div class="box">
                        </div>
                    </div>

                </div>
            </div>
        </div>

<?php endif ?>
<?php endwhile; wp_reset_query(); ?>
</code>```

Is there anything I've done wrong here, or a better solution to this? I'm frustrated that this is theoretically a simple request that I just can't seem to make work properly. Any help is much appreciated!

答:
OK, pro tip: programmers are lazy.  We like the DRY principle. We don't like to duplicate code, nor do we like to maintain giant blocks of duplicated code.

So, below is a modified version of your loop that is somewhat simpler, with less duplication.  I would encourage you to consider other ways to reduce duplication, for example, using CSS classes (floats, possibly) to alternate which is on the left or right, and only render one version of the HTML one time.

The specific problem is that you're not accessing the $current_post property of the correct query object.  You should be using $loop->current_post instead of $wpdb->current_post.  However, to be super clear / explicit, I would manually set a counter, and use that instead:

```<code><?php // theloop
    if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php $loop = new WP_Query( array( 'post_type' => 'team', 'posts_per_page' => -1, 'order' => 'ASC') ); ?>
    <?php
        // initialize the counter here
        $post_count = 0;
        while ( $loop->have_posts() ) : $loop->the_post(); ?>
        <div class="row team-member">
            <div class="container">
                <div class="row is-table-row">
                   <?php
                    // move the if condition here to reduce / simplify code
                    // reference (and increment) the counter
                    if ($post_count++ % 2 == 0): ?>
                    <div class="col-sm-6 headshot" style="background-image:url(<?php the_field('bio_photo'); ?>);">
                        <div class="box">
                        </div>
                    </div>
                    <div class="col-sm-6 bio cream-bg">
                        <div class="box">
                            <?php if( get_field('additional_logo') ): ?>
                                    <div class="additional-logo"><img src="<?php the_field('additional_logo'); ?>"></div>
                            <?php endif; ?>
                            <h2><?php the_field('name'); ?></h2>
                            <div class="bio-content"><?php the_field('bio'); ?></div>
                           <div class="contact-container">
                               <h4>Contact me!</h4>
                                <?php if( get_field('phone_number') ): ?>
                                    <p><i class="fa fa-phone" aria-hidden="true"></i> <?php the_field('phone_number'); ?></p>
                                <?php endif; ?>
                                <p><i class="fa fa-envelope" aria-hidden="true"></i> <a href="mailto:<?php the_field('email'); ?>" target="_top"><?php the_field('email'); ?></a></p>
                            </div>
                        </div>
                    </div>
                 <?php else: ?>
                    <div class="col-sm-6 bio cream-bg">
                        <div class="box">
                            <?php if( get_field('additional_logo') ): ?>
                                    <div class="additional-logo"><img src="<?php the_field('additional_logo'); ?>"></div>
                               <?php endif; ?>
                            <h2><?php the_field('name'); ?></h2>
                            <div class="bio-content"><?php the_field('bio'); ?></div>

                           <div class="contact-container">
                               <h4>Contact me!</h4>
                               <?php if( get_field('phone_number') ): ?>
                                    <p><i class="fa fa-phone" aria-hidden="true"></i> <?php the_field('phone_number'); ?></p>
                               <?php endif; ?>
                               <p><i class="fa fa-envelope" aria-hidden="true"></i> <a href="mailto:<?php the_field('email'); ?>" target="_top"><?php the_field('email'); ?></a></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 headshot" style="background-image:url(<?php the_field('bio_photo'); ?>);">
                        <div class="box">
                        </div>
                    </div>
                   <?php endif; ?>
                </div>
            </div>
        </div>
<?php endwhile; wp_reset_query(); ?>
</code>```

Body:
I've been searching through questions/answers on here, but can't seem to find something that works with my code.

Most of the solutions I've found cause the whole page to get a 500 error. They're generally just snippets of the odd/even php, and aren't working for me to easily integrate with the custom post type loop php I have. I'm probably just not putting it in the right place, but nothing seem to be working.

I'm not super great with php, but this is the one thing I've always had an issue getting to work.

Goal:
Odd posts have the headshot on the left, bio info on the right.
Even posts have the headshot on the right, bio info on the left.

Below is my code, which does load on the page (no 500 error), but doesn't output the alternating layout, just outputs the same layout as if I didn't have the odd/even code.

<?php // theloop
    if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php $loop = new WP_Query( array( 'post_type' => 'team', 'posts_per_page' => -1, 'order' => 'ASC') ); ?>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <?php if ($wp_query->current_post % 2 == 0): ?>

                    <div class="col-sm-6 headshot" style="background-image:url(<?php the_field('bio_photo'); ?>);">

                            <?php if( get_field('additional_logo') ): ?>

<img src="<?php the_field('additional_logo'); ?>">

                            <?php endif; ?>

<?php the_field('name'); ?>

<?php the_field('bio'); ?>

Contact me!

                                <?php if( get_field('phone_number') ): ?>

 <?php the_field('phone_number'); ?>

                                <?php endif; ?>

 <a href="mailto:<?php the_field('email'); ?>" target="_top"><?php the_field('email'); ?>

    <?php else: ?>

                            <?php if( get_field('additional_logo') ): ?>

<img src="<?php the_field('additional_logo'); ?>">

                               <?php endif; ?>

<?php the_field('name'); ?>

<?php the_field('bio'); ?>

Contact me!

                               <?php if( get_field('phone_number') ): ?>

 <?php the_field('phone_number'); ?>

                               <?php endif; ?>

 <a href="mailto:<?php the_field('email'); ?>" target="_top"><?php the_field('email'); ?>

                    <div class="col-sm-6 headshot" style="background-image:url(<?php the_field('bio_photo'); ?>);">

<?php endif ?>
<?php endwhile; wp_reset_query(); ?>

Is there anything I've done wrong here, or a better solution to this? I'm frustrated that this is theoretically a simple request that I just can't seem to make work properly. Any help is much appreciated!

Body:
OK, pro tip: programmers are lazy.  We like the DRY principle. We don't like to duplicate code, nor do we like to maintain giant blocks of duplicated code.

So, below is a modified version of your loop that is somewhat simpler, with less duplication.  I would encourage you to consider other ways to reduce duplication, for example, using CSS classes (floats, possibly) to alternate which is on the left or right, and only render one version of the HTML one time.

The specific problem is that you're not accessing the $current_post property of the correct query object.  You should be using $loop->current_post instead of $wpdb->current_post.  However, to be super clear / explicit, I would manually set a counter, and use that instead:

<?php // theloop
    if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php $loop = new WP_Query( array( 'post_type' => 'team', 'posts_per_page' => -1, 'order' => 'ASC') ); ?>
    <?php
        // initialize the counter here
        $post_count = 0;
        while ( $loop->have_posts() ) : $loop->the_post(); ?>
        <div class="row team-member">
            <div class="container">
                <div class="row is-table-row">
                   <?php
                    // move the if condition here to reduce / simplify code
                    // reference (and increment) the counter
                    if ($post_count++ % 2 == 0): ?>
                    <div class="col-sm-6 headshot" style="background-image:url(<?php the_field('bio_photo'); ?>);">
                        <div class="box">
                        </div>
                    </div>
                    <div class="col-sm-6 bio cream-bg">
                        <div class="box">
                            <?php if( get_field('additional_logo') ): ?>
                                    <div class="additional-logo"><img src="<?php the_field('additional_logo'); ?>"></div>
                            <?php endif; ?>
                            <h2><?php the_field('name'); ?></h2>
                            <div class="bio-content"><?php the_field('bio'); ?></div>
                           <div class="contact-container">
                               <h4>Contact me!</h4>
                                <?php if( get_field('phone_number') ): ?>
                                    <p><i class="fa fa-phone" aria-hidden="true"></i> <?php the_field('phone_number'); ?></p>
                                <?php endif; ?>
                                <p><i class="fa fa-envelope" aria-hidden="true"></i> <a href="mailto:<?php the_field('email'); ?>" target="_top"><?php the_field('email'); ?></a></p>
                            </div>
                        </div>
                    </div>
                 <?php else: ?>
                    <div class="col-sm-6 bio cream-bg">
                        <div class="box">
                            <?php if( get_field('additional_logo') ): ?>
                                    <div class="additional-logo"><img src="<?php the_field('additional_logo'); ?>"></div>
                               <?php endif; ?>
                            <h2><?php the_field('name'); ?></h2>
                            <div class="bio-content"><?php the_field('bio'); ?></div>

                           <div class="contact-container">
                               <h4>Contact me!</h4>
                               <?php if( get_field('phone_number') ): ?>
                                    <p><i class="fa fa-phone" aria-hidden="true"></i> <?php the_field('phone_number'); ?></p>
                               <?php endif; ?>
                               <p><i class="fa fa-envelope" aria-hidden="true"></i> <a href="mailto:<?php the_field('email'); ?>" target="_top"><?php the_field('email'); ?></a></p>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-6 headshot" style="background-image:url(<?php the_field('bio_photo'); ?>);">
                        <div class="box">
                        </div>
                    </div>
                   <?php endif; ?>
                </div>
            </div>
        </div>
<?php endwhile; wp_reset_query(); ?>


问:
How can I determine the Windows version from a VB 6 app?
I want to detect any Windows versions from 95 to Win 7.

I also would like to display if the OS is 32-bit or 64-bit.

That's it; it's that simple. :) What code could I use to do this from within a VB 6 application?

答:
WORK on WINDOWS 10
VB6 - not work in debug mode - work only on runtime

```<code>Private Declare Function RtlGetVersion Lib "ntdll" (ByRef lpVersionInformation As RTL_OSVERSIONINFOEX) As Long

Private Type RTL_OSVERSIONINFOEX
        dwOSVersionInfoSize As Long
        dwMajorVersion As Long
        dwMinorVersion As Long
        dwBuildNumber As Long
        dwPlatformId As Long
        szCSDVersion As String * 128
End Type
</code>```

call

```<code>Dim lpVersionInformation As RTL_OSVERSIONINFOEX
lpVersionInformation.dwOSVersionInfoSize = Len(lpVersionInformation)
RtlGetVersion(lpVersionInformation)
</code>```

Body:
WORK on WINDOWS 10
VB6 - not work in debug mode - work only on runtime

Private Declare Function RtlGetVersion Lib "ntdll" (ByRef lpVersionInformation As RTL_OSVERSIONINFOEX) As Long

Private Type RTL_OSVERSIONINFOEX
        dwOSVersionInfoSize As Long
        dwMajorVersion As Long
        dwMinorVersion As Long
        dwBuildNumber As Long
        dwPlatformId As Long
        szCSDVersion As String * 128
End Type

call

Dim lpVersionInformation As RTL_OSVERSIONINFOEX
lpVersionInformation.dwOSVersionInfoSize = Len(lpVersionInformation)
RtlGetVersion(lpVersionInformation)


问:
HTML - refresh page after inactivity
I am having a touch screen with some very basic html pages. But if there is no activity for maybe 5 minutes, it should reload the main page again.

So it is not just a refresh of the site, but a load of the main page if there is no activity

just a question Where does the script know which site is the main page ?. If someone goes to "site B" - it should after some minutes without any movement move back to "site A"

答:
Assuming no activity means you do not get click, scroll and movement events. You need to listen to these events in the body element of your page and set a range that calls the page refresh method.

```<code>var timeOut = null;
var activityMade = function(){

clearInterval(timeOut); //first clears the interval
  timeOut = setInterval(function(){ console.log("Page Refreshed"); }, 3000); //logs to the console at every 3 seconds of inactivity
}

var bindEvents = function(){
  var body = document.getElementById("app");
  // bind click move and scroll event to body
  body.addEventListener('click', activityMade);
  body.addEventListener('mousemove', activityMade);
  body.addEventListener('scroll', activityMade);
  activityMade(); // assume activivity has done at page init
}

bindEvents();
</code>```

You can bind as may events as you wish to ajust it to your needs.

Here is an working example https://jsfiddle.net/fspayfqt/
Please note that for this to work perfectly the body element will cover the whole window of the navigator and this can be solved with css using fixed position with height and width of 100%

Title: HTML - refresh page after inactivity

Body:
Assuming no activity means you do not get click, scroll and movement events. You need to listen to these events in the body element of your page and set a range that calls the page refresh method.

var timeOut = null;
var activityMade = function(){

clearInterval(timeOut); //first clears the interval
  timeOut = setInterval(function(){ console.log("Page Refreshed"); }, 3000); //logs to the console at every 3 seconds of inactivity
}

var bindEvents = function(){
  var body = document.getElementById("app");
  // bind click move and scroll event to body
  body.addEventListener('click', activityMade);
  body.addEventListener('mousemove', activityMade);
  body.addEventListener('scroll', activityMade);
  activityMade(); // assume activivity has done at page init
}

bindEvents();

You can bind as may events as you wish to ajust it to your needs.

Here is an working example https://jsfiddle.net/fspayfqt/
Please note that for this to work perfectly the body element will cover the whole window of the navigator and this can be solved with css using fixed position with height and width of 100%


问:
ios - Error when hiding button through code Objective-c
I'm trying to hide a button through code, but the program crashes every time I try to hide it.

The error I get:

```<code>'NSInvalidArgumentException', reason: '-[UIBarButtonItem setHidden:]: unrecognized selector sent to instance 0x14ef8f30'
</code>```

.h file code:

```<code>@property (strong) UIButton *takeAll;
</code>```

.m code:

```<code>    @synthesize takeAll;

// function

   [self.takeAll setHidden:YES];
</code>```

答:
Error is clearly saying 'You are trying to set hidden value of UIBarButtonItem

You created a UIButton object and allocation as UIBarButtonItem. This is wrong. It suppose to be

```<code>self.takeAll = [UIButton buttonWithType:UIButtonTypeCustom]
</code>```

If you need UIBarButtonItem then

```<code>@property (strong) UIBarButtonItem *takeAll;
</code>```

And if you want hide UIBarButtonItem.

```<code> self.takeAll.enabled = false
 self.takeAll.tintColor = UIColor.clearColor
</code>```

Enable the bar button item

```<code> self.takeAll.enabled = true
 self.takeAll.tintColor = UIColor.blueColor
</code>```

Body:
I'm trying to hide a button through code, but the program crashes every time I try to hide it.

The error I get:

'NSInvalidArgumentException', reason: '-[UIBarButtonItem setHidden:]: unrecognized selector sent to instance 0x14ef8f30'

.h file code:

@property (strong) UIButton *takeAll;

.m code:

    @synthesize takeAll;

// function

   [self.takeAll setHidden:YES];

Body:
Error is clearly saying 'You are trying to set hidden value of UIBarButtonItem

You created a UIButton object and allocation as UIBarButtonItem. This is wrong. It suppose to be

self.takeAll = [UIButton buttonWithType:UIButtonTypeCustom]

If you need UIBarButtonItem then

@property (strong) UIBarButtonItem *takeAll;

And if you want hide UIBarButtonItem.

 self.takeAll.enabled = false
 self.takeAll.tintColor = UIColor.clearColor

Enable the bar button item

 self.takeAll.enabled = true
 self.takeAll.tintColor = UIColor.blueColor


问:
Why can’t variables be declared in a switch statement?
I want to know more about "Why can’t variables be declared in a switch statement?"

I read the post but i am not getting it exactly.
You can just declare variable inside switch but to decalre and initialize a variable or to declare object of class it gives complie time error.

Please explain me....

答:
Essentially because the initialisation of the variable would be skipped if the label containing the variable initialisation was not hit. This would be bad because the compiler would then have to emit code that would destroy said variable if and only if the initialisation code had run.

For example:

```<code>class A
{
  // has some non-trivial constructor and destructor
};

switch (x)
{
  case 1:
    A a;
    break;
  default:
    // do something else
}
</code>```

If the code had hit the default, then a would not have been initialised. The compiler would have to have been able to figure this out in advance. Probably for performance reasons, this was disallowed.

The simple fix is to introduce a new layer of scope:

```<code>class A
{
  // has some non-trivial constructor and destructor
};

switch (x)
{
  case 1:
    {
      A a;
    }
    break;
  default:
    // do something else
}
</code>```

This makes it ok, the destruction of a is now well defined.

OwnerDisplayName: Omi

LastEditorDisplayName: mark

Body:
Essentially because the initialisation of the variable would be skipped if the label containing the variable initialisation was not hit. This would be bad because the compiler would then have to emit code that would destroy said variable if and only if the initialisation code had run.

For example:

class A
{
  // has some non-trivial constructor and destructor
};

switch (x)
{
  case 1:
    A a;
    break;
  default:
    // do something else
}

If the code had hit the default, then a would not have been initialised. The compiler would have to have been able to figure this out in advance. Probably for performance reasons, this was disallowed.

The simple fix is to introduce a new layer of scope:

class A
{
  // has some non-trivial constructor and destructor
};

switch (x)
{
  case 1:
    {
      A a;
    }
    break;
  default:
    // do something else
}

This makes it ok, the destruction of a is now well defined.

OwnerDisplayName: 1800 INFORMATION


问:
Recover cleared file content
I was working on a report using typora markdown editor, which is a beta version now.

After finishing the report and saving it, I have opened it to review and correct typos. While I was editing, the program hangs and I killed its process.

when I tried to open the file again, I've found it a clean file. So is there any way to recover the last saved content of the file?

答:
You could open preference panel, under “Editor” section, click the “Recover Unsaved Drafts” button to find some writing drafts auto saved by Typora.

Source -> http://support.typora.io/Version-Control/

Title: Recover cleared file content


问:
Concern about having lots of redux-aware components
I'm currently writing a component for comments that is Redux-aware and stateless. My concern is that if say each comment is connected to a user-post, and say there are 100 posts, will that slow down my app?

So for example.

```<code>class Comments extends Component {
  doThis() {
    const props = this.props;
    props.dispatch(someAction(props.data.id));
  }
  render(){
    <Button onPress={()=> this.doThis()}
  }
}

export default connect()(Comments);
</code>```

Then in some other component:

```<code>arr.map((item) => {
  return <Comment data={item} />
})
</code>```

Is this the proper way to use Redux?

答:
Generally speaking, having more connected components leads to better performance, as each component will only re-render when the data it needs changes.  The cost of having to notify more subscribers to the Redux store is usually less than the cost of "wasted" re-renders by your components.

For more information, see:

My blog post Practical Redux, Part 6: Connected Lists, Forms, and Performance

the Redux FAQ on performance and scaling

the Redux FAQ on connecting multiple components

a chat log where I describe the benefits of connecting each item in a large list

and the Redux Performance section of my React/Redux links list.

Body:
I'm currently writing a component for comments that is Redux-aware and stateless. My concern is that if say each comment is connected to a user-post, and say there are 100 posts, will that slow down my app?

So for example.

class Comments extends Component {
  doThis() {
    const props = this.props;
    props.dispatch(someAction(props.data.id));
  }
  render(){
    <Button onPress={()=> this.doThis()}
  }
}

export default connect()(Comments);

Then in some other component:

arr.map((item) => {
  return <Comment data={item} />
})

Is this the proper way to use Redux?


问:
I want to copy 2 Excel Worksheets at the same time to a new workbook
To explain, I currently have like 90 different files that I need to, after processing, separate the first two tabs of the file and copy paste to a new workbook and save that workbook, with the name of the person who the report will go to (name is in each of the files) and email them out.

I need help for 2 things.  I'm unable to save the file using the cell as a reference for the name and copy two (2) sheets at the same time (sheet1 is dependent on sheet2, copy/pasting separately breaks the connection).

Can anyone help with this?

UPDATE:
I've been able to make the save as work :), but still need help in being able to copy two worksheets at the same time.

Here is my UPDATED code:

```<code>$Files = GCI '\\networkfolder\workingfolder' | ?{$_.Extension -Match "xlsx?"} | select -ExpandProperty FullName

#Launch Excel, and make it do as its told (supress confirmations)
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
$Excel.DisplayAlerts = $False

#Loop through files and perform tasks
ForEach($File in $Files[0..4]){
$Source = $Excel.Workbooks.Open($File,$true,$true) #Open's source
$NewWorkBook = $Excel.Workbooks.Add() # open target (New Workbook)

$sh1_wb1 = $NewWorkBook.sheets.item(1) # first sheet in destination workbook

$sheetToCopy2 = $Source.sheets.item(2) # Alias for 2nd Sheet
$sheetToCopy = $Source.sheets.item(1) # Alias for 1st Sheet
$SheetsToCopy = ($sheetToCopy, $sheetToCopy2) # Selects sheets 1 and 2
#I think the fix to copy both sheets at the same time would be in this step

$SheetsToCopy.copy($sh1_wb1) # copy source sheet 1 & 2 to destination workbook

$ws1 = $NewWorkBook.worksheets | where {$_.name -eq "Charts Data Tab"} #Selects Sheet2
$ws2 = $NewWorkBook.worksheets | where {$_.name -eq "Dashboard"} #Selects Sheet1

$range = $ws1.Rows.Item("1:5000")
[void]$range.select()
$range.Copy();
$range.PasteSpecial(-4163)
$Source.close($false) # close source workbook w/o saving

$Name = $ws1.Cells.Item.Invoke(2,4).Value2  #Registers contents of D2 of Sheet2

$FName = "\\networkfolder\Testing\$Name.xlsx"

$NewWorkBook.SaveAs($FName)
Start-Sleep 50000
}
$xl.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
</code>```

答:
You should have a look at the PSExcel library. It provides a lot of functions for working with Excel.

http://ramblingcookiemonster.github.io/PSExcel-Intro/

Body:
To explain, I currently have like 90 different files that I need to, after processing, separate the first two tabs of the file and copy paste to a new workbook and save that workbook, with the name of the person who the report will go to (name is in each of the files) and email them out.

I need help for 2 things.  I'm unable to save the file using the cell as a reference for the name and copy two (2) sheets at the same time (sheet1 is dependent on sheet2, copy/pasting separately breaks the connection).

Can anyone help with this?

UPDATE:
I've been able to make the save as work :), but still need help in being able to copy two worksheets at the same time.

Here is my UPDATED code:

$Files = GCI '\\networkfolder\workingfolder' | ?{$_.Extension -Match "xlsx?"} | select -ExpandProperty FullName

#Launch Excel, and make it do as its told (supress confirmations)
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
$Excel.DisplayAlerts = $False

#Loop through files and perform tasks
ForEach($File in $Files[0..4]){
$Source = $Excel.Workbooks.Open($File,$true,$true) #Open's source
$NewWorkBook = $Excel.Workbooks.Add() # open target (New Workbook)

$sh1_wb1 = $NewWorkBook.sheets.item(1) # first sheet in destination workbook

$sheetToCopy2 = $Source.sheets.item(2) # Alias for 2nd Sheet
$sheetToCopy = $Source.sheets.item(1) # Alias for 1st Sheet
$SheetsToCopy = ($sheetToCopy, $sheetToCopy2) # Selects sheets 1 and 2
#I think the fix to copy both sheets at the same time would be in this step

$SheetsToCopy.copy($sh1_wb1) # copy source sheet 1 & 2 to destination workbook

$ws1 = $NewWorkBook.worksheets | where {$_.name -eq "Charts Data Tab"} #Selects Sheet2
$ws2 = $NewWorkBook.worksheets | where {$_.name -eq "Dashboard"} #Selects Sheet1

$range = $ws1.Rows.Item("1:5000")
[void]$range.select()
$range.Copy();
$range.PasteSpecial(-4163)
$Source.close($false) # close source workbook w/o saving

$Name = $ws1.Cells.Item.Invoke(2,4).Value2  #Registers contents of D2 of Sheet2

$FName = "\\networkfolder\Testing\$Name.xlsx"

$NewWorkBook.SaveAs($FName)
Start-Sleep 50000
}
$xl.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)


问:
Using global variables in Celery: What's the best approach?
Im writing an app using Django 1.10 and Celery.
Im trying to create a loop in celery that can be started and stopped through Django.

My idea looks something like this (very simple):

```<code>_run = False

def do_work():
  global _run
  while _run:
    # Do something

@app.task
def start():
  global _run
  _run = True
  do_work()

@app.task
def stop():
  global _run
  _run = False
</code>```

The problem is that celery is typically run in >1 working thread, and _run is not accessable between threads.

Question: What's the best approach to achieve the functionality?
Im thinking about setting a database variable, but I'm afraid its not the best approach.

答:
One of possible approaches is to create task which will run forever and then stop it on request.

```<code>from proj.celery import app
app.control.revoke(task_id)
</code>```

http://docs.celeryproject.org/en/latest/faq.html#can-i-cancel-the-execution-of-a-task

Body:
Im writing an app using Django 1.10 and Celery.
Im trying to create a loop in celery that can be started and stopped through Django.

My idea looks something like this (very simple):

_run = False

def do_work():
  global _run
  while _run:
    # Do something

@app.task
def start():
  global _run
  _run = True
  do_work()

@app.task
def stop():
  global _run
  _run = False

The problem is that celery is typically run in >1 working thread, and _run is not accessable between threads.

Question: What's the best approach to achieve the functionality?
Im thinking about setting a database variable, but I'm afraid its not the best approach.

Body:
One of possible approaches is to create task which will run forever and then stop it on request.

from proj.celery import app
app.control.revoke(task_id)

http://docs.celeryproject.org/en/latest/faq.html#can-i-cancel-the-execution-of-a-task


问:
How do I split an array into smaller arrays bsaed on a condition?
Ruby 2.4.  I have an array of strings

```<code>2.4.0 :007 > arr = ["a", "b", "g", "e", "f", "i"]
 => ["a", "b", "g", "e", "f", "h", "i"]
</code>```

How do I split my array into smaller arrays based on a condition?  I have a function -- "contains_vowel," which returns true if a string contains "a", "e", "i", "o", or "u".  How would I take an array of strings and split it into smaller arrays, using a divider function of "contains_vowel"?  That is, for the above, the resulting array of smaller arrays would be

```<code>[["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]
</code>```

If an element of the larger array satisfies the condition, it would become an array of one element.

答:
I might use chunk which splits an array everytime the value of its block changes. Chunk returns a list of [block_value, [elements]] pairs, I used .map(&:last) to only get the sub-lists of elements.

```<code>arr = ["a", "b", "g", "e", "f", "h", "i"]

def vowel?(x); %w(a e i o u).include?(x); end

arr.chunk{|x| vowel?(x)}.map(&:last)

=> [["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]
</code>```

Body:
Ruby 2.4.  I have an array of strings

2.4.0 :007 > arr = ["a", "b", "g", "e", "f", "i"]
 => ["a", "b", "g", "e", "f", "h", "i"]

How do I split my array into smaller arrays based on a condition?  I have a function -- "contains_vowel," which returns true if a string contains "a", "e", "i", "o", or "u".  How would I take an array of strings and split it into smaller arrays, using a divider function of "contains_vowel"?  That is, for the above, the resulting array of smaller arrays would be

[["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]

If an element of the larger array satisfies the condition, it would become an array of one element.

Body:
I might use chunk which splits an array everytime the value of its block changes. Chunk returns a list of [block_value, [elements]] pairs, I used .map(&:last) to only get the sub-lists of elements.

arr = ["a", "b", "g", "e", "f", "h", "i"]

def vowel?(x); %w(a e i o u).include?(x); end

arr.chunk{|x| vowel?(x)}.map(&:last)

=> [["a"], ["b", "g"], ["e"], ["f", "h"], ["i"]]


问:
How can I view an Azure CosmosDb using Pycharms or IntelliJ?

I can see loads of drivers, but nothing for DocumentDB.
I did try searching for an appropriate driver, but I found nothing.

My DocumentDb is in Azure, so I have a URL and primary key, but I was unable to see how to connect via Pycharm using the "Data Source from URL" option.

How can I connect my DocumentDb to Pycharm (or IntelliJ) database explorer?

答:
Cosmos DB is not a relational database, and you cannot simply connect to it as such.

It supports several NoSQL protocol variants: DocumentDB (native document store), MongoDB API, Gremlin graph api, and Azure Table API. Not possible to connect via a relational database driver.

If a tool doesn't explicitly support one of the above-mentioned protocols, you simply won't be able to use it, and will need to work with a different tool. And which tool you choose is really up to you (tool recommendation questions are off-topic).


问:
How to implement some code in many actions of many controllers
I have controllers with actions, which works with some entity (Driver). Also, each Driver linked with identity profile.

```<code>        public async Task<ActionResult> Details(int? id)
        {
            if ((id == null))
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DriverDetailVM model = mapper.Map<DriverDetailVM>(db.Drivers.Find(id));
            if ((model == null))
            {
                return HttpNotFound();
            }
            return View(model);
        }

        public async Task<ActionResult> Edit(int? id = null, bool isNewUser = false)
        {
/////////
        }
</code>```

If user has role "Superadmin" then he has access to pages with any id value. If user has role "Driver" then we should have access only if id value is the same, as his profile. I try to implement it on ActionFilter:

```<code>public class DriverAccessActionFilterAttribute : ActionFilterAttribute
{
    public string IdParamName { get; set; }
    public int DriverID { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.User.IsInRole("Driver"))
        {
            if (filterContext.ActionParameters.ContainsKey(IdParamName))
            {
                var id = filterContext.ActionParameters[IdParamName] as Int32;
                if (id != DriverID)
                    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }
            else
                filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        else
            base.OnActionExecuting(filterContext);
    }
}
</code>```

but when I try to use this code:

```<code>    [DriverAccessActionFilter(DriverID = currentUser.DriverId, IdParamName = "id")]
    public async Task<ActionResult> Details(int? id)
    {
</code>```

it does not want to be compiled, because

An object reference is required for the non-static field, method, or
  property

how to implement it?

答:
Attribute parameters are evaluated at compile-time, not at runtime. So they have to be compile time constants. You can't pass a value to an action attribute at run-time. i.e in [DriverAccessActionFilter(DriverID = currentUser.DriverId, IdParamName = "id")] you are passing DriverID = currentUser.DriverId. An attribute is used as controller/action metadata and metadata needs to be compiled in assembly. This is why attributes can take only constant values.

You have to change your attribute as follows:

Use Dependency Injection to Inject your service which returns logged in user.

Or Implement a custom Principal and assign it current request principal.

You can modify your attribute as follow in case you implement CustomPrinicpal:

```<code>public class DriverAccessActionFilterAttribute : ActionFilterAttribute
    {
        public string IdParamName { get; set; }
        private int DriverID { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.IsInRole("Driver"))
            {
                var customPrincipal = filterContext.HttpContext.User as CustomPrincipal;
                DriverID = customPrincipal.Id;
                // Rest of you logic
            }
            else
                base.OnActionExecuting(filterContext);
        }
    }
</code>```

In case you choose DI path then you can use the following snippet:

```<code>public class DriverAccessActionFilterAttribute : ActionFilterAttribute
{
    public string IdParamName { get; set; }
    private int DriverID { get; set; }

    public DriverAccessActionFilterAttribute(IYourIdentityProvider provider)
    {
        DriverID = provider.LoggedInUserID;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Your logic
    }
}
</code>```

and then use your attribute as [DriverAccessActionFilter(IdParamName = "id")]

Body:
I have controllers with actions, which works with some entity (Driver). Also, each Driver linked with identity profile.

        public async Task<ActionResult> Details(int? id)
        {
            if ((id == null))
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            DriverDetailVM model = mapper.Map<DriverDetailVM>(db.Drivers.Find(id));
            if ((model == null))
            {
                return HttpNotFound();
            }
            return View(model);
        }

        public async Task<ActionResult> Edit(int? id = null, bool isNewUser = false)
        {
/////////
        }

If user has role "Superadmin" then he has access to pages with any id value. If user has role "Driver" then we should have access only if id value is the same, as his profile. I try to implement it on ActionFilter:

public class DriverAccessActionFilterAttribute : ActionFilterAttribute
{
    public string IdParamName { get; set; }
    public int DriverID { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.User.IsInRole("Driver"))
        {
            if (filterContext.ActionParameters.ContainsKey(IdParamName))
            {
                var id = filterContext.ActionParameters[IdParamName] as Int32;
                if (id != DriverID)
                    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }
            else
                filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        else
            base.OnActionExecuting(filterContext);
    }
}

but when I try to use this code:

    [DriverAccessActionFilter(DriverID = currentUser.DriverId, IdParamName = "id")]
    public async Task<ActionResult> Details(int? id)
    {

it does not want to be compiled, because

An object reference is required for the non-static field, method, or
  property

how to implement it?

Body:
Attribute parameters are evaluated at compile-time, not at runtime. So they have to be compile time constants. You can't pass a value to an action attribute at run-time. i.e in [DriverAccessActionFilter(DriverID = currentUser.DriverId, IdParamName = "id")] you are passing DriverID = currentUser.DriverId. An attribute is used as controller/action metadata and metadata needs to be compiled in assembly. This is why attributes can take only constant values.

You have to change your attribute as follows:

Use Dependency Injection to Inject your service which returns logged in user.

Or Implement a custom Principal and assign it current request principal.

You can modify your attribute as follow in case you implement CustomPrinicpal:

public class DriverAccessActionFilterAttribute : ActionFilterAttribute
    {
        public string IdParamName { get; set; }
        private int DriverID { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.User.IsInRole("Driver"))
            {
                var customPrincipal = filterContext.HttpContext.User as CustomPrincipal;
                DriverID = customPrincipal.Id;
                // Rest of you logic
            }
            else
                base.OnActionExecuting(filterContext);
        }
    }

In case you choose DI path then you can use the following snippet:

public class DriverAccessActionFilterAttribute : ActionFilterAttribute
{
    public string IdParamName { get; set; }
    private int DriverID { get; set; }

    public DriverAccessActionFilterAttribute(IYourIdentityProvider provider)
    {
        DriverID = provider.LoggedInUserID;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Your logic
    }
}

and then use your attribute as [DriverAccessActionFilter(IdParamName = "id")]


问:
Bash script to run Python Tkinter GUI
I am trying to write a Bash script so that I can run my program on a double click. The program uses tkinter and the GUI is the only thing I need to see. My bat file is the following:

```<code>python BudgetGUI.py &
</code>```

This runs the code and successfully prints any print statements I have throughout my code but it never opens up the GUI. It simply runs through and closes immediately.

How can I modify the bash script to run the GUI?

Thanks in advance!

Edit Solutions for both mac and pc would be great, though at the moment I am on PC. I am working in Python3.

答:
Make the window made with tkinter stay out of IDLE*

if you have

```<code>root = Tk()
</code>```

at the end put

```<code>root.mainloop()
</code>```

if you have another name for that like:

```<code>window1 = Tk()
</code>```

then, at the end put

```<code>window1.mainloop()
</code>```

and so for any name you gave to the istance of Tk()

A little example

```<code>import tkinter as tk

class Window:
    root = tk.Tk()
    label = tk.Label(root, text = "Ciao").pack()

app = Window()
app.root.mainloop()
</code>```

Python 2

The code above is for python 3.
For python 2 you just need to change the first line (Tkinter with T, not t)

```<code>import Tkinter as tk
</code>```

Title: Bash script to run Python Tkinter GUI

Body:
I am trying to write a Bash script so that I can run my program on a double click. The program uses tkinter and the GUI is the only thing I need to see. My bat file is the following:

python BudgetGUI.py &

This runs the code and successfully prints any print statements I have throughout my code but it never opens up the GUI. It simply runs through and closes immediately.

How can I modify the bash script to run the GUI?

Thanks in advance!

Edit Solutions for both mac and pc would be great, though at the moment I am on PC. I am working in Python3.

Body:
Make the window made with tkinter stay out of IDLE*

if you have

root = Tk()

at the end put

root.mainloop()

if you have another name for that like:

window1 = Tk()

then, at the end put

window1.mainloop()

and so for any name you gave to the istance of Tk()

A little example

import tkinter as tk

class Window:
    root = tk.Tk()
    label = tk.Label(root, text = "Ciao").pack()

app = Window()
app.root.mainloop()

Python 2

The code above is for python 3.
For python 2 you just need to change the first line (Tkinter with T, not t)

import Tkinter as tk


问:
Automatic reconnect to internet
How can I programatically force system (Windows 7) to reconnect to internet? I need IP changed. I'm using USB Modem Huawei E1750</p>

答:
There's a good chance you'll get the same external IP even if you do reconnect, that is up to your ISP.  As for your internal (on your router if you have one) IP, you can change that by changing your IP address in the Windows 7 settings.

Why do you want this ability - sounds like you're trying to get around an IP filter/limit of a website?

EDIT:
Well, not sure if this will help, but a simple Google search turned this up: http://bytes.com/topic/c-sharp/answers/260772-enable-disable-lan-connection

Title: Automatic reconnect to internet


问:
How to remove space between span elements using inline style only?
I would like to display a single word "WorldWide" in two colors(red and blue).

I've tried using span elements as below.

```<code><span style="color:red">World</span><span style="color:blue">Wide</span>
</code>```

but the issue is that the email clients format the html as below so the text ends-up displayed in two words (World Wide instead of WordWide) due the new lines added in the html.

```<code><span style="color:red">World
</span>
<span style="color:blue">Wide
</span>
</code>```

So my question is: How can I display a single word in two colors considering that the html clients format/add new lines to span elements? Please note that only inline styling is allowed in email clients so I can't use  tags.

答:
You can float the first element.

World
Wide```

Body:
I would like to display a single word "WorldWide" in two colors(red and blue).

I've tried using span elements as below.

WorldWide

but the issue is that the email clients format the html as below so the text ends-up displayed in two words (World Wide instead of WordWide) due the new lines added in the html.

World

Wide

So my question is: How can I display a single word in two colors considering that the html clients format/add new lines to span elements? Please note that only inline styling is allowed in email clients so I can't use  tags.

Body:
You can float the first element.

<span style="color:red; float: left;">World</span>
<span style="color:blue">Wide</span>


问:
Subversion (svn) update to source tree containing nested checkouts (like clang/llvm)
I've building clang/llvm frequently on various systems following the "Getting Started" instructions (http://clang.llvm.org/get_started.html). The SVN folks are really into modularity but don't seem to use the SVN "externals" mechanism, so they require three separate checkouts (llvm, clang, compiler-rt) into a single source tree (with one optional: extra).

Every now and then I build an updated version by doing "svn up" in the source tree root ("llvm") and then rebuilding.

Today, for the first time, I wondered if I should be doing an "svn up" in each separate checkout sub-directory or whether SVN is smart enough to do "recursive updates for nested checkouts". Couldn't find an answer after searching a bit so I am here now.

Thanks!

答:
```<code>find . -name ".svn" -type d | xargs dirname | xargs svn update
</code>```


问:
Python: Requests won't POST if I have punctuation in my data
I have a small_file.txt file that contains:

```<code>1asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
2asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
3asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf
4asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
</code>```

Notice the colons at the end, they are just regular strings.

When I try to send it using python requests it doesn't work. For some reason, it waits for the first line with a colon and then sends all the lines starting from there. So for example, in the file above, it will POST only:

```<code>3asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf
4asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
</code>```

How can I fix this issue? I'm not sure what is going on.

Here is a simple version of my code:

```<code>import requests
import sys
import json
import os

token                    = 'nVQowAng0c'
url                      = "https://api.hipchat.com/v2/room/test_room/share/file"
headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
headers['Authorization'] = "Bearer " + token

filepath = 'small_file.csv'
data     = open(filepath, 'rb').read()

payload = """\
--boundary123456
Content-Type: application/json; charset=UTF-8
Content-Disposition: attachment; name="metadata"
--boundary123456
Content-Disposition: attachment; name="file"; filename="{0}"
{1}
--boundary123456--\
""".format(os.path.basename(filepath), data)

r = requests.post(url, headers=headers, data=payload)
r.raise_for_status()
</code>```

When I try to send something like a .csv file with a timestamp on every row, nothing will get sent because each row has a colon.

答:
Here is the combined code from @Martijn Pieters:</p>

```<code># do this:
#     pip install requests_toolbelt

from os                import path
from sys               import exit, stderr
from requests          import post
from requests_toolbelt import MultipartEncoder

class MultipartRelatedEncoder(MultipartEncoder):
    """A multipart/related encoder"""
    @property
    def content_type(self):
        return str('multipart/related; boundary={0}'.format(self.boundary_value))

    def _iter_fields(self):
        # change content-disposition from form-data to attachment
        for field in super(MultipartRelatedEncoder, self)._iter_fields():
            content_type = field.headers['Content-Type']
            field.make_multipart(content_disposition = 'attachment',
                                 content_type        = content_type)
            yield field

def hipchat_file(token, room, filepath, host='api.hipchat.com'):

    if not path.isfile(filepath):
        raise ValueError("File '{0}' does not exist".format(filepath))

    url                      = "https://{0}/v2/room/{1}/share/file".format(host, room)
    headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
    headers['Authorization'] = "Bearer " + token

    m = MultipartRelatedEncoder(fields={'metadata' : (None, '', 'application/json; charset=UTF-8'),
                                        'file'     : (path.basename(filepath), open(filepath, 'rb'), 'text/csv')})

    headers['Content-type'] = m.content_type

    r = post(url, data=m, headers=headers)

if __name__ == '__main__:

    my_token = <my token>
    my_room  = <room name>
    my_file  = <filepath>

    try:
        hipchat_file(my_token, my_room, my_file)
    except Exception as e:
        msg = "[ERROR] HipChat file failed: '{0}'".format(e)
        print(msg, file=stderr)
        exit(1)
</code>```

Body:
I have a small_file.txt file that contains:

1asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
2asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:
3asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf
4asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:

Notice the colons at the end, they are just regular strings.

When I try to send it using python requests it doesn't work. For some reason, it waits for the first line with a colon and then sends all the lines starting from there. So for example, in the file above, it will POST only:

3asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf
4asdfaksdjfhlaksjdhflkjashdflkjhasldkjfhlaksdfhasdf:

How can I fix this issue? I'm not sure what is going on.

Here is a simple version of my code:

import requests
import sys
import json
import os

token                    = 'nVQowAng0c'
url                      = "https://api.hipchat.com/v2/room/test_room/share/file"
headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
headers['Authorization'] = "Bearer " + token

filepath = 'small_file.csv'
data     = open(filepath, 'rb').read()

payload = """\
--boundary123456
Content-Type: application/json; charset=UTF-8
Content-Disposition: attachment; name="metadata"
--boundary123456
Content-Disposition: attachment; name="file"; filename="{0}"
{1}
--boundary123456--\
""".format(os.path.basename(filepath), data)

r = requests.post(url, headers=headers, data=payload)
r.raise_for_status()

When I try to send something like a .csv file with a timestamp on every row, nothing will get sent because each row has a colon.

Body:
Here is the combined code from @Martijn Pieters:

# do this:
#     pip install requests_toolbelt

from os                import path
from sys               import exit, stderr
from requests          import post
from requests_toolbelt import MultipartEncoder

class MultipartRelatedEncoder(MultipartEncoder):
    """A multipart/related encoder"""
    @property
    def content_type(self):
        return str('multipart/related; boundary={0}'.format(self.boundary_value))

    def _iter_fields(self):
        # change content-disposition from form-data to attachment
        for field in super(MultipartRelatedEncoder, self)._iter_fields():
            content_type = field.headers['Content-Type']
            field.make_multipart(content_disposition = 'attachment',
                                 content_type        = content_type)
            yield field

def hipchat_file(token, room, filepath, host='api.hipchat.com'):

    if not path.isfile(filepath):
        raise ValueError("File '{0}' does not exist".format(filepath))

    url                      = "https://{0}/v2/room/{1}/share/file".format(host, room)
    headers                  = {'Content-type': 'multipart/related; boundary=boundary123456'}
    headers['Authorization'] = "Bearer " + token

    m = MultipartRelatedEncoder(fields={'metadata' : (None, '', 'application/json; charset=UTF-8'),
                                        'file'     : (path.basename(filepath), open(filepath, 'rb'), 'text/csv')})

    headers['Content-type'] = m.content_type

    r = post(url, data=m, headers=headers)

if __name__ == '__main__:

    my_token = <my token>
    my_room  = <room name>
    my_file  = <filepath>

    try:
        hipchat_file(my_token, my_room, my_file)
    except Exception as e:
        msg = "[ERROR] HipChat file failed: '{0}'".format(e)
        print(msg, file=stderr)
        exit(1)


问:
Bootstrap Popover inside of a link in a table cell does not display
I have a link within a table cell that on the hover action, I would like a Bootstrap Popover to appear.  As of now, I cannot get this to work correctly.

Here is the code snippet:

```<code><table style="background: transparent; border: 0; outline: 0; border-collapse: collapse;">
 <tr style="background: transparent; border: 0; outline: 0;">
  <td style="background: transparent; border: 0; outline: 0; text-align:left; width:100px">
   <a href="#" id="lastBACommentCell" tabindex="0" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-template="<div class='mainViewPopover' role='tooltip'><div class='arrow'></div><div class='popover-content' style='color: #FFFFFF;'></div></div>" data-content="Here is my popover">
    Hover here for the popover to appear...
   </a>
  </td>
 </tr>
</table>
...
    <script type="text/javascript" language="javascript">
     $(document).ready(function() {
      $('#lastBACommentCell').popover();
     });
    </script>
</code>```

I have tried putting a  inside the  tag, but it still will not display the popover.

Here is the JSFiddle - https://jsfiddle.net/dzeller44/swnbdjaq/

答:
You are using the wrong data-template syntax. The outermost wrapper element should have the .popover class. You are also using style='color: #FFFFFF on an element with a white background.

Bootstrap Popover Options

...The outermost wrapper element should have the .popover class.

So in the data-template attribute change this:

```<code><div class='mainViewPopover' role='tooltip'>
  <div class='arrow'></div>
  <div class='popover-content' style='color: #FFFFFF;'></div>
</div>
</code>```

To this:

```<code><div class='mainViewPopover popover' role='tooltip'>
  <div class='arrow'></div>
  <div class='popover-content'></div>
</div>
</code>```

$(document).ready(function() {
  $('#lastBACommentCell').popover()
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<table style="background: transparent; border: 0; outline: 0; border-collapse: collapse;">
  <tr style="background: transparent; border: 0; outline: 0;">
    <td style="background: transparent; border: 0; outline: 0; text-align:left; width:100px">
      <div class='arrow'></div><div class='popover-content'></div></div>" >
        Hover here for the popover to appear...

    </td>
  </tr>
</table></code>```

Body:
I have a link within a table cell that on the hover action, I would like a Bootstrap Popover to appear.  As of now, I cannot get this to work correctly.

Here is the code snippet:

    Hover here for the popover to appear...

...

I have tried putting a  inside the  tag, but it still will not display the popover.

Here is the JSFiddle - https://jsfiddle.net/dzeller44/swnbdjaq/

Body:
You are using the wrong data-template syntax. The outermost wrapper element should have the .popover class. You are also using style='color: #FFFFFF on an element with a white background.

Bootstrap Popover Options

...The outermost wrapper element should have the .popover class.

So in the data-template attribute change this:

<div class='mainViewPopover' role='tooltip'>
  <div class='arrow'></div>
  <div class='popover-content' style='color: #FFFFFF;'></div>
</div>

To this:

<div class='mainViewPopover popover' role='tooltip'>
  <div class='arrow'></div>
  <div class='popover-content'></div>
</div>

$(document).ready(function() {
  $('#lastBACommentCell').popover()
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<table style="background: transparent; border: 0; outline: 0; border-collapse: collapse;">
  <tr style="background: transparent; border: 0; outline: 0;">
    <td style="background: transparent; border: 0; outline: 0; text-align:left; width:100px">
      <a href="#" id="lastBACommentCell"
        tabindex="0"
        data-toggle="popover"
        role="button"
        data-trigger="hover"
        data-placement="bottom"
        data-content="Here is my popover"
        data-template="<div class='mainViewPopover popover' role='tooltip'><div class='arrow'></div><div class='popover-content'></div></div>" >
        Hover here for the popover to appear...
      </a>
    </td>
  </tr>
</table>


问:
What is the SLA for Azure Graph API
I've been seeing long latency recently (up to 30-50 secs) calling Azure Graph API from its SDK client. Including query account, add account, adding group members and get account photo. Is there a SLA document for Graph API?</p>

答:
There is no SLA at this time for the either the Azure AD Graph nor the Microsoft Graph.

You can always ask for this via the Microsoft Graph feedback forum.

Title: What is the SLA for Azure Graph API


问:
Is there a way to put columns of a table in divs using DataTable?
So what I'm trying to do is make it so that the user can choose which columns of a table to display after it has already been generated. I already have functionality that does this, after the user changes their options it destroys the current table and then reinitializes it with different visibility settings for certain columns. While this works, it's sorta slow and doesn't look as pretty as say, the columns just disappearing. I think if I put the columns in uniquely id'd divs and then edited their css to say display: none; using jquery when the user deselects them it would work quicker and more attractively, but I haven't been able to find a way to put the columns in divs.

答:
You shouldn't need to put the columns in divs.

```<code>myFunction = function(){
  $('.first').css('display','none')
}
</code>```

codepen

Body:
You shouldn't need to put the columns in divs.

myFunction = function(){
  $('.first').css('display','none')
}

codepen