问:
unable to find attribute android:font for v7 support
I've been developing a Linphone application but got stuck in below point. I've changed the app name and refactored all relative packages. The application was ok until I upgraded gradle to 3.0.0.

```<code>AGPBI: {"kind":"error","text":"error: resource android:attr/fontStyle not found.","sources":[{"file":"~/.gradle/caches/transforms-1/files-1.1/support-compat-27.0.0.aar/61646c6d4479aff22f7047873e2edd7d/res/values/values.xml","position":{"startLine":20,"startColumn":4,"startOffset":1254,"endColumn":69,"endOffset":1319}}],"original":"","tool":"AAPT"}
AGPBI: {"kind":"error","text":"error: resource android:attr/font not found.","sources":[{"file":"~/.gradle/caches/transforms-1/files-1.1/support-compat-27.0.0.aar/61646c6d4479aff22f7047873e2edd7d/res/values/values.xml","position":{"startLine":20,"startColumn":4,"startOffset":1254,"endColumn":69,"endOffset":1319}}],"original":"","tool":"AAPT"}
AGPBI: {"kind":"error","text":"error: resource android:attr/fontWeight not found.","sources":[{"file":"~/.gradle/caches/transforms-1/files-1.1/support-compat-27.0.0.aar/61646c6d4479aff22f7047873e2edd7d/res/values/values.xml","position":{"startLine":20,"startColumn":4,"startOffset":1254,"endColumn":69,"endOffset":1319}}],"original":"","tool":"AAPT"}
~/app-name/bin/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml:149: error: resource android:attr/fontStyle not found.
~/appname/bin/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml:149: error: resource android:attr/font not found.
~/appname/bin/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml:149: error: resource android:attr/fontWeight not found.
error: failed linking references.
</code>```

I've read other questions about unabling to find attribute error but could not find an answer. I've tried below methods but none of them worked:

delete bin/ directory of the app

clean cache and rebuild the app again

Invalidate cache and restart (every options in it)

Changing sdk version (api)

multiDexEnabled true/false

Below is detail log :

```<code>Failed to execute aapt
com.android.ide.common.process.ProcessException: Failed to execute aapt
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:793)
    at com.android.build.gradle.tasks.ProcessAndroidResources.invokeAaptForSplit(ProcessAndroidResources.java:566)
    at com.android.build.gradle.tasks.ProcessAndroidResources.doFullTaskAction(ProcessAndroidResources.java:293)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:482)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:791)
    ... 48 more
Caused by: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:462)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
    at com.android.builder.internal.aapt.v2.QueueableAapt2.lambda$makeValidatedPackage$1(QueueableAapt2.java:179)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more
Caused by: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    at com.android.builder.png.AaptProcess$NotifierProcessOutput.handleOutput(AaptProcess.java:454)
    at com.android.builder.png.AaptProcess$NotifierProcessOutput.err(AaptProcess.java:411)
    at com.android.builder.png.AaptProcess$ProcessOutputFacade.err(AaptProcess.java:332)
    at com.android.utils.GrabProcessOutput$1.run(GrabProcessOutput.java:104)
</code>```

答:
To solve this problem you should:

Install the mathching SDK version (27)

In module's build.gradle you should set compileSdkVersion to 27 and change the com.android.support:appcompat-v7 version to match the com.android.support:recyclerview-v7: (or the other support library component that you use) version (27.0.0)

UPD:

If for some reason it doesn't help you, please look at the comment below by @madu

Body:
I've been developing a Linphone application but got stuck in below point. I've changed the app name and refactored all relative packages. The application was ok until I upgraded gradle to 3.0.0.

AGPBI: {"kind":"error","text":"error: resource android:attr/fontStyle not found.","sources":[{"file":"~/.gradle/caches/transforms-1/files-1.1/support-compat-27.0.0.aar/61646c6d4479aff22f7047873e2edd7d/res/values/values.xml","position":{"startLine":20,"startColumn":4,"startOffset":1254,"endColumn":69,"endOffset":1319}}],"original":"","tool":"AAPT"}
AGPBI: {"kind":"error","text":"error: resource android:attr/font not found.","sources":[{"file":"~/.gradle/caches/transforms-1/files-1.1/support-compat-27.0.0.aar/61646c6d4479aff22f7047873e2edd7d/res/values/values.xml","position":{"startLine":20,"startColumn":4,"startOffset":1254,"endColumn":69,"endOffset":1319}}],"original":"","tool":"AAPT"}
AGPBI: {"kind":"error","text":"error: resource android:attr/fontWeight not found.","sources":[{"file":"~/.gradle/caches/transforms-1/files-1.1/support-compat-27.0.0.aar/61646c6d4479aff22f7047873e2edd7d/res/values/values.xml","position":{"startLine":20,"startColumn":4,"startOffset":1254,"endColumn":69,"endOffset":1319}}],"original":"","tool":"AAPT"}
~/app-name/bin/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml:149: error: resource android:attr/fontStyle not found.
~/appname/bin/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml:149: error: resource android:attr/font not found.
~/appname/bin/intermediates/incremental/mergeDebugResources/merged.dir/values/values.xml:149: error: resource android:attr/fontWeight not found.
error: failed linking references.

I've read other questions about unabling to find attribute error but could not find an answer. I've tried below methods but none of them worked:

delete bin/ directory of the app

clean cache and rebuild the app again

Invalidate cache and restart (every options in it)

Changing sdk version (api)

multiDexEnabled true/false

Below is detail log :

Failed to execute aapt
com.android.ide.common.process.ProcessException: Failed to execute aapt
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:793)
    at com.android.build.gradle.tasks.ProcessAndroidResources.invokeAaptForSplit(ProcessAndroidResources.java:566)
    at com.android.build.gradle.tasks.ProcessAndroidResources.doFullTaskAction(ProcessAndroidResources.java:293)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
    at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:482)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
    at com.android.builder.core.AndroidBuilder.processResources(AndroidBuilder.java:791)
    ... 48 more
Caused by: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:462)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
    at com.android.builder.internal.aapt.v2.QueueableAapt2.lambda$makeValidatedPackage$1(QueueableAapt2.java:179)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more
Caused by: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    at com.android.builder.png.AaptProcess$NotifierProcessOutput.handleOutput(AaptProcess.java:454)
    at com.android.builder.png.AaptProcess$NotifierProcessOutput.err(AaptProcess.java:411)
    at com.android.builder.png.AaptProcess$ProcessOutputFacade.err(AaptProcess.java:332)
    at com.android.utils.GrabProcessOutput$1.run(GrabProcessOutput.java:104)


来源: stackexchange

问:
Electron packaging errors
I am new to Electron and love it.  Just finished writing a wonderful little app for the entertainment industry and am having trouble packaging it.  Also notice that there is an electron compiler and a packager.  Which one do you use that is most convenient for a windows end user ?  I work with mostly windows people in a certain segment of the entertainment biz, so being a Linux user you get tons of flack if something does not work. Here is the problem :

```<code>package.json:

{
  "name": "Sick Bay Scanner by H.A. Hobson",
  "productName": "SickBayScanner",
  "version": "1.0.1",
  "main": "main.js",
  "devDependencies": {
    "electron-winstaller": "^2.6.3"
  }

}
</code>```

Packaging argument and outome :

```<code>me@debian:/$ electron-packager --electron-version=1.7.9 . sound/SickBayScanner --overwrite --asar=true --platform=win32 --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds
WARNING: --asar does not take any arguments, it only has sub-properties (see --help)
Downloading tmp-6742-0-electron-v1.7.9-win32-x64.zip
[============================================>] 100.0% of 53.89 MB (421.05 kB/s)
Packaging app for platform win32 x64 using electron v1.7.9
EPERM: operation not permitted, open '/dev/core'
</code>```

If you could explain how to create electron apps that are as easy possible for an end user to use, whether packaged or compiled, and point out my own packaging issue, would be very appreciative.  Thanks !

答:
Firstly I've had a lot of trouble packaging windows on linux so in the end I just made a virtual windows machine using virtual box and did it there. The only problem is it's tricky to get the right iso :(

Secondly I don't think there is much of an advantage to using asar because there are not many people who want to look at your source code and the ones who do mostly know how to unpack asar and get to your source code.

https://stackoverflow.com/a/38524534/6577664

All in all I think your best option is just to do it on a windows PC.

ContentLicense: CC BY-SA 3.0

Title: Electron packaging errors

Body:
I am new to Electron and love it.  Just finished writing a wonderful little app for the entertainment industry and am having trouble packaging it.  Also notice that there is an electron compiler and a packager.  Which one do you use that is most convenient for a windows end user ?  I work with mostly windows people in a certain segment of the entertainment biz, so being a Linux user you get tons of flack if something does not work. Here is the problem :

package.json:

{
  "name": "Sick Bay Scanner by H.A. Hobson",
  "productName": "SickBayScanner",
  "version": "1.0.1",
  "main": "main.js",
  "devDependencies": {
    "electron-winstaller": "^2.6.3"
  }

}

Packaging argument and outome :

me@debian:/$ electron-packager --electron-version=1.7.9 . sound/SickBayScanner --overwrite --asar=true --platform=win32 --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds
WARNING: --asar does not take any arguments, it only has sub-properties (see --help)
Downloading tmp-6742-0-electron-v1.7.9-win32-x64.zip
[============================================>] 100.0% of 53.89 MB (421.05 kB/s)
Packaging app for platform win32 x64 using electron v1.7.9
EPERM: operation not permitted, open '/dev/core'

If you could explain how to create electron apps that are as easy possible for an end user to use, whether packaged or compiled, and point out my own packaging issue, would be very appreciative.  Thanks !


问:
How do I avoid checking for nulls in Java?
I use x != null to avoid NullPointerException. Is there an alternative?

if (x != null) {
    // ...
}
```

答:
All in all to avoid statement

```<code>if (object != null) {
    ....
}
</code>```

since java 7 you can use Objects methods:

Objects.isNull(object)

Objects.nonNull(object)

Objects.requireNonNull(object)

Objects.equals(object1, object2)

since java 8 you can use Optional class (when to use)

object.ifPresent(obj -> ...); java 8

object.ifPresentOrElse(obj -> ..., () -> ...); java 9

rely on method contract (JSR 305) and use Find Bugs. Mark your code with annotations @javax.annotation.Nullable and @javax.annotation.Nonnnul. Also Preconditions are available.

Preconditions.checkNotNull(object);

In special cases (for example for Strings and Collections) you can use apache-commons (or Google guava) utility methods:

public static boolean isEmpty(CharSequence cs) //apache CollectionUtils

public static boolean isEmpty(Collection coll) //apache StringUtils

public static boolean isEmpty(Map map) //apache MapUtils

public static boolean isNullOrEmpty(@Nullable String string) //Guava Strings

When you need to assign default value when null use apache commons lang

public static Object defaultIfNull(Object object, Object defaultValue)

OwnerDisplayName: Goran Martinic

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: cletus

Body:
All in all to avoid statement

if (object != null) {
    ....
}

since java 7 you can use Objects methods:

Objects.isNull(object)

Objects.nonNull(object)

Objects.requireNonNull(object)

Objects.equals(object1, object2)

since java 8 you can use Optional class (when to use)

object.ifPresent(obj -> ...); java 8

object.ifPresentOrElse(obj -> ..., () -> ...); java 9

rely on method contract (JSR 305) and use Find Bugs. Mark your code with annotations @javax.annotation.Nullable and @javax.annotation.Nonnnul. Also Preconditions are available.

Preconditions.checkNotNull(object);

In special cases (for example for Strings and Collections) you can use apache-commons (or Google guava) utility methods:

public static boolean isEmpty(CharSequence cs) //apache CollectionUtils

public static boolean isEmpty(Collection coll) //apache StringUtils

public static boolean isEmpty(Map map) //apache MapUtils

public static boolean isNullOrEmpty(@Nullable String string) //Guava Strings

When you need to assign default value when null use apache commons lang

public static Object defaultIfNull(Object object, Object defaultValue)


问:
Cordova or ReactNative. Which should i prefer for this specific project?
I am working on a project that needs to be cross platform for web and mobile. Currently the website is being developed using ReactJS and cordova is being used to make it available on mobile.

But I was wondering if it would maybe be a better choice to use ReactNative for the mobile version because cordova might be more of a hassle than ReactNative is. I dont know if this is true tho.

I know this is kind of an open question that tends to be opinionated but i'd still like to hear some thoughts on this from you guys because its bugging me and I dont have the knowledge and experience of working on both these platforms (cordova and reactnative) to have an educated opinion.

答:
React Native is an abstraction to write native UIs for Android and iOS. Your JS code runs in a JS runtime on the OS, but the UI is rendered as native components. This makes it very different than Cordova.

With React Native, you can use the standard platform components such as UITabBar on iOS and Drawer on Android. This gives your app a consistent look and feel with the rest of the platform ecosystem, and keeps the quality bar high. These components are easily incorporated into your app using their React component counterparts, such as TabBarIOS and DrawerLayoutAndroid.

Also you can find differences here:

https://www.toptal.com/mobile/comparing-react-native-to-cordova

Phone gap vs React Native

http://noeticforce.com/mobile-app-development-cordova-vs-react-native-vs-xamarin


问:
ViewPager inside Fragment do not Showing ImageView
I'm trying to make carousel view using ViewPager which is in Fragment.

Fragment is also showed by another ViewPager which is in MainActivity.

However, ViewPager in Fragment do not showing ImageView.

I think ViewPager is ok, because when I change ViewPager's background and ImageView's background respectively, only ImageView's background was not showed.

Please help.

MainActivity.java

package com.rudolphriding.giftfriend.activity;

import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.rudolphriding.giftfriend.app.friend.FriendFragment;
import com.rudolphriding.giftfriend.base.BaseActivity;
import com.rudolphriding.giftfriend.app.home.HomeFragment;
import com.rudolphriding.giftfriend.R;
import com.rudolphriding.giftfriend.app.trend.TrendFragment;

public class MainActivity extends BaseActivity
{
    ViewPager viewPager;
    TabLayout tabLayout;
    DrawerLayout drawerLayout;
    View friendDrawer;
    ImageButton menuButton;
    ImageButton slidMenuBackButton;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //view custom action bar
        customActionbar();

        //initialize tab
        initTab();

        friendDrawer = (View) findViewById(R.id.drawer);
        drawerLayout = (DrawerLayout) findViewById(R.id.activity_main);
        menuButton = (ImageButton) findViewById(R.id.actionbar_button_menu);
        slidMenuBackButton = (ImageButton) findViewById(R.id.sidemenu_button_close);

        //set MainPagerAdapter
        viewPager = (ViewPager) findViewById(R.id.activity_main_veiwpager);
        MainPagerAdapter pagerAdapter = new MainPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        //drawer open by button on action bar
        draweOpnebyMenuButton();

        //drawer close by button on slide menu
        drawerClosebyBackButton();

    }

    /* /////////////////////////////////////////////////
    //                                                //
    //                    About UI                    //
    //                                                //
    ///////////////////////////////////////////////// */

    public void customActionbar()
    {
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.item_main_actionbar);
    }

    public void initTab()
    {
        tabLayout = (TabLayout) findViewById(R.id.activity_main_tablayout);
        tabLayout.addTab(tabLayout.newTab().setText("선물스토리"));
        tabLayout.addTab(tabLayout.newTab().setText("친구스토리"));
    }

    /* /////////////////////////////////////////////////
    //                                                //
    //                  About drawer                  //
    //                                                //
    ///////////////////////////////////////////////// */

    public void draweOpnebyMenuButton()
    {
        menuButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                drawerLayout.openDrawer(friendDrawer);
            }
        });
    }

    public void drawerClosebyBackButton()
    {
        slidMenuBackButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                drawerLayout.closeDrawer(friendDrawer);
            }
        });
    }

}
```

<p>BaseActivity is for convenient which extents AppCompatActivity.</p>

<h1>HomeFragment.java</h1>

<pre class="lang-java prettyprint-override"><code>package com.rudolphriding.giftfriend.app.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.rudolphriding.giftfriend.R;
import com.rudolphriding.giftfriend.model.HomeItem;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment
{
    ViewPager viewPager;
    VpAdapter adapter;
    TabLayout tabLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View hView = inflater.inflate(R.layout.fragment_home, container, false);

        viewPager = (ViewPager) hView.findViewById(R.id.home_viewPager);
        adapter = new VpAdapter(getChildFragmentManager());
        viewPager.setAdapter(adapter);

        tabLayout = (TabLayout) hView.findViewById(R.id.home_dotNavi_tabLayout);
        tabLayout.setupWithViewPager(viewPager, true);

        return hView;
    }

    public static HomeFragment newInstance()
    {
        Bundle args = new Bundle();

        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

}
</code>```

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/home_viewPager"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:background="@color/ut_std_main_mint_01">

    </android.support.v4.view.ViewPager>

    <android.support.design.widget.TabLayout
        android:id="@+id/home_dotNavi_tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/home_viewPager"
        app:tabBackground="@drawable/btn_homebanner_round_selector"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp">

    </android.support.design.widget.TabLayout>

    <TableLayout
        android:id="@+id/home_buttoncontainer_tableLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/home_viewPager"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="15dp"
        android:stretchColumns="*">
        <TableRow
            android:layout_weight="1"
            android:weightSum="4">
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1" />
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"/>
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"/>
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_weight="1"/>

        </TableRow>

        <TableRow>
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="기념일 별\n추천 선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="감정으로\n찾는 선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="브랜드\n선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_weight="1"
                android:text="선물 기획전"
                android:textAlignment="center"/>

        </TableRow>
    </TableLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="40dp"
        android:background="@drawable/btn_giftfindbg_roundrect_selector"
        style="?android:attr/borderlessButtonStyle"
        android:text="선물 준비 시작하기"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textAlignment="center"
        android:textColor="@color/ut_std_text_gray_01"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>
```

<h1>VpAdapter.java</h1>

<pre class="lang-java prettyprint-override"><code>package com.rudolphriding.giftfriend.app.home;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.View;
import com.rudolphriding.giftfriend.R;

public class VpAdapter extends FragmentStatePagerAdapter {

    private int[] sampleImg = new int[] { R.drawable.img_home_cardviewbg_01, R.drawable.img_home_cardviewbg_02 };

    public VpAdapter(FragmentManager fragmentManager)
    {
        super(fragmentManager);
    }

    @Override
    public int getCount() {
        return sampleImg.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Fragment getItem(int position) {
        return VpFragment.create(sampleImg[position]);
    }
}
</code>```

VpFragment.java

package com.rudolphriding.giftfriend.app.home;

import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.rudolphriding.giftfriend.R;

/**
 * Created by LeeJihye on 2017-11-09.
 */

public class VpFragment extends android.support.v4.app.Fragment
{
    private int image;
    private ViewGroup rootView;
    private ImageView imageView;
    private Bitmap bitmapImg;
    BitmapFactory.Options options;

    public static VpFragment create(int image)
    {
        VpFragment fragment = new VpFragment();
        Bundle args = new Bundle();
        args.putInt("image", image);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        image = getArguments().getInt("image");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        rootView = (ViewGroup) inflater.inflate(R.layout.item_home_viewpager, container, false);
        options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        bitmapImg = BitmapFactory.decodeResource(rootView.getResources(), image, options);

        imageView = (ImageView) rootView.findViewById(R.id.viewPager_ImageView);
        imageView.setImageBitmap(bitmapImg);

        return rootView;
    }
}
```

<h1>item_home_viewpager.xml</h1>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/viewPager_ImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/ut_std_text_gray_01"/>

</LinearLayout>
</code>```

答:
you need to set tablayout and viewpager in main activity is like this:

```<code>        ViewPager viewPager = (ViewPager) findViewById(R.id.container);
        viewPager.setAdapter(jobTitlePagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
</code>```

Hope this help..If you have doubt then pls ask me.

Body:
I'm trying to make carousel view using ViewPager which is in Fragment.

Fragment is also showed by another ViewPager which is in MainActivity.

However, ViewPager in Fragment do not showing ImageView.

I think ViewPager is ok, because when I change ViewPager's background and ImageView's background respectively, only ImageView's background was not showed.

Please help.

MainActivity.java

package com.rudolphriding.giftfriend.activity;

import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.rudolphriding.giftfriend.app.friend.FriendFragment;
import com.rudolphriding.giftfriend.base.BaseActivity;
import com.rudolphriding.giftfriend.app.home.HomeFragment;
import com.rudolphriding.giftfriend.R;
import com.rudolphriding.giftfriend.app.trend.TrendFragment;

public class MainActivity extends BaseActivity
{
    ViewPager viewPager;
    TabLayout tabLayout;
    DrawerLayout drawerLayout;
    View friendDrawer;
    ImageButton menuButton;
    ImageButton slidMenuBackButton;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //view custom action bar
        customActionbar();

        //initialize tab
        initTab();

        friendDrawer = (View) findViewById(R.id.drawer);
        drawerLayout = (DrawerLayout) findViewById(R.id.activity_main);
        menuButton = (ImageButton) findViewById(R.id.actionbar_button_menu);
        slidMenuBackButton = (ImageButton) findViewById(R.id.sidemenu_button_close);

        //set MainPagerAdapter
        viewPager = (ViewPager) findViewById(R.id.activity_main_veiwpager);
        MainPagerAdapter pagerAdapter = new MainPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        //drawer open by button on action bar
        draweOpnebyMenuButton();

        //drawer close by button on slide menu
        drawerClosebyBackButton();

    }

    /* /////////////////////////////////////////////////
    //                                                //
    //                    About UI                    //
    //                                                //
    ///////////////////////////////////////////////// */

    public void customActionbar()
    {
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.item_main_actionbar);
    }

    public void initTab()
    {
        tabLayout = (TabLayout) findViewById(R.id.activity_main_tablayout);
        tabLayout.addTab(tabLayout.newTab().setText("선물스토리"));
        tabLayout.addTab(tabLayout.newTab().setText("친구스토리"));
    }

    /* /////////////////////////////////////////////////
    //                                                //
    //                  About drawer                  //
    //                                                //
    ///////////////////////////////////////////////// */

    public void draweOpnebyMenuButton()
    {
        menuButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                drawerLayout.openDrawer(friendDrawer);
            }
        });
    }

    public void drawerClosebyBackButton()
    {
        slidMenuBackButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                drawerLayout.closeDrawer(friendDrawer);
            }
        });
    }

}

BaseActivity is for convenient which extents AppCompatActivity.

HomeFragment.java

package com.rudolphriding.giftfriend.app.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.rudolphriding.giftfriend.R;
import com.rudolphriding.giftfriend.model.HomeItem;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment
{
    ViewPager viewPager;
    VpAdapter adapter;
    TabLayout tabLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View hView = inflater.inflate(R.layout.fragment_home, container, false);

        viewPager = (ViewPager) hView.findViewById(R.id.home_viewPager);
        adapter = new VpAdapter(getChildFragmentManager());
        viewPager.setAdapter(adapter);

        tabLayout = (TabLayout) hView.findViewById(R.id.home_dotNavi_tabLayout);
        tabLayout.setupWithViewPager(viewPager, true);

        return hView;
    }

    public static HomeFragment newInstance()
    {
        Bundle args = new Bundle();

        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

}

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/home_viewPager"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:background="@color/ut_std_main_mint_01">

    </android.support.v4.view.ViewPager>

    <android.support.design.widget.TabLayout
        android:id="@+id/home_dotNavi_tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/home_viewPager"
        app:tabBackground="@drawable/btn_homebanner_round_selector"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp">

    </android.support.design.widget.TabLayout>

    <TableLayout
        android:id="@+id/home_buttoncontainer_tableLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/home_viewPager"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="15dp"
        android:stretchColumns="*">
        <TableRow
            android:layout_weight="1"
            android:weightSum="4">
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1" />
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"/>
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"/>
            <com.rudolphriding.giftfriend.widget.SquareButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_weight="1"/>

        </TableRow>

        <TableRow>
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="기념일 별\n추천 선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="감정으로\n찾는 선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="브랜드\n선물"
                android:textAlignment="center"/>

            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_weight="1"
                android:text="선물 기획전"
                android:textAlignment="center"/>

        </TableRow>
    </TableLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="40dp"
        android:background="@drawable/btn_giftfindbg_roundrect_selector"
        style="?android:attr/borderlessButtonStyle"
        android:text="선물 준비 시작하기"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textAlignment="center"
        android:textColor="@color/ut_std_text_gray_01"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

VpAdapter.java

package com.rudolphriding.giftfriend.app.home;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.View;
import com.rudolphriding.giftfriend.R;

public class VpAdapter extends FragmentStatePagerAdapter {

    private int[] sampleImg = new int[] { R.drawable.img_home_cardviewbg_01, R.drawable.img_home_cardviewbg_02 };

    public VpAdapter(FragmentManager fragmentManager)
    {
        super(fragmentManager);
    }

    @Override
    public int getCount() {
        return sampleImg.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Fragment getItem(int position) {
        return VpFragment.create(sampleImg[position]);
    }
}

VpFragment.java

package com.rudolphriding.giftfriend.app.home;

import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.rudolphriding.giftfriend.R;

/**
 * Created by LeeJihye on 2017-11-09.
 */

public class VpFragment extends android.support.v4.app.Fragment
{
    private int image;
    private ViewGroup rootView;
    private ImageView imageView;
    private Bitmap bitmapImg;
    BitmapFactory.Options options;

    public static VpFragment create(int image)
    {
        VpFragment fragment = new VpFragment();
        Bundle args = new Bundle();
        args.putInt("image", image);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        image = getArguments().getInt("image");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        rootView = (ViewGroup) inflater.inflate(R.layout.item_home_viewpager, container, false);
        options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        bitmapImg = BitmapFactory.decodeResource(rootView.getResources(), image, options);

        imageView = (ImageView) rootView.findViewById(R.id.viewPager_ImageView);
        imageView.setImageBitmap(bitmapImg);

        return rootView;
    }
}

item_home_viewpager.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/viewPager_ImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/ut_std_text_gray_01"/>

</LinearLayout>

Body:
you need to set tablayout and viewpager in main activity is like this:

        ViewPager viewPager = (ViewPager) findViewById(R.id.container);
        viewPager.setAdapter(jobTitlePagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

Hope this help..If you have doubt then pls ask me.


问:
receive var declaration string, save value only
I am trying to use a variable value that I get with an HTTP request, and what I get back is this:

```<code>var nums=["155","175","195","205","215","225","235","245","255","265","275","285","295","315","325"]
</code>```

Which is a string with the declaration of the variable. What I want is to collect ONLY the value, not the whole line. So, in this case, I'd save ["155","175","195","205","215","225","235","245","255","265","275","285","295","315","325"]

Is there any JQuery or JS library that can do this kind of operations with strings?? I'd want to implement an universal solution as I don't always know what will I receive in the HTTP request.

Thank you so much.

答:
var str = 'var nums=["155","175","195","205","215","225","235","245","255","265","275","285","295","315","325"]'
var resStr = str.split('=')[1];
var arr = JSON.parse(resStr);
console.log(arr);```

Split the string with = then get the value of second position. To get array representation use JSON.parse

Body:
I am trying to use a variable value that I get with an HTTP request, and what I get back is this:

var nums=["155","175","195","205","215","225","235","245","255","265","275","285","295","315","325"]

Which is a string with the declaration of the variable. What I want is to collect ONLY the value, not the whole line. So, in this case, I'd save ["155","175","195","205","215","225","235","245","255","265","275","285","295","315","325"]

Is there any JQuery or JS library that can do this kind of operations with strings?? I'd want to implement an universal solution as I don't always know what will I receive in the HTTP request.

Thank you so much.

Body:
var str = 'var nums=["155","175","195","205","215","225","235","245","255","265","275","285","295","315","325"]'
var resStr = str.split('=')[1];
var arr = JSON.parse(resStr);
console.log(arr);

Split the string with = then get the value of second position. To get array representation use JSON.parse


问:
How to return 2 values from a Java method?
I am trying to return 2 values from a Java method but I get these errors. Here is my code:

```<code>// Method code
public static int something(){
    int number1 = 1;
    int number2 = 2;

    return number1, number2;
}

// Main method code
public static void main(String[] args) {
    something();
    System.out.println(number1 + number2);
}
</code>```

Error:

```<code>Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
    at assignment.Main.something(Main.java:86)
    at assignment.Main.main(Main.java:53)
</code>```

Java Result: 1

答:
I'm curious as to why nobody has come up with the more elegant callback solution.  So instead of using a return type you use a handler passed into the method as an argument.  The example below has the two contrasting approaches.  I know which of the two is more elegant to me. :-)</p>

```<code>public class DiceExample {

    public interface Pair<T1, T2> {
        T1 getLeft();

        T2 getRight();
    }

    private Pair<Integer, Integer> rollDiceWithReturnType() {

        double dice1 = (Math.random() * 6);
        double dice2 = (Math.random() * 6);

        return new Pair<Integer, Integer>() {
            @Override
            public Integer getLeft() {
                return (int) Math.ceil(dice1);
            }

            @Override
            public Integer getRight() {
                return (int) Math.ceil(dice2);
            }
        };
    }

    @FunctionalInterface
    public interface ResultHandler {
        void handleDice(int ceil, int ceil2);
    }

    private void rollDiceWithResultHandler(ResultHandler resultHandler) {
        double dice1 = (Math.random() * 6);
        double dice2 = (Math.random() * 6);

        resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2));
    }

    public static void main(String[] args) {

        DiceExample object = new DiceExample();

        Pair<Integer, Integer> result = object.rollDiceWithReturnType();
        System.out.println("Dice 1: " + result.getLeft());
        System.out.println("Dice 2: " + result.getRight());

        object.rollDiceWithResultHandler((dice1, dice2) -> {
            System.out.println("Dice 1: " + dice1);
            System.out.println("Dice 2: " + dice2);
        });
    }
}
</code>```

Body:
I am trying to return 2 values from a Java method but I get these errors. Here is my code:

// Method code
public static int something(){
    int number1 = 1;
    int number2 = 2;

    return number1, number2;
}

// Main method code
public static void main(String[] args) {
    something();
    System.out.println(number1 + number2);
}

Error:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
    at assignment.Main.something(Main.java:86)
    at assignment.Main.main(Main.java:53)

Java Result: 1

Body:
I'm curious as to why nobody has come up with the more elegant callback solution.  So instead of using a return type you use a handler passed into the method as an argument.  The example below has the two contrasting approaches.  I know which of the two is more elegant to me. :-)

public class DiceExample {

    public interface Pair<T1, T2> {
        T1 getLeft();

        T2 getRight();
    }

    private Pair<Integer, Integer> rollDiceWithReturnType() {

        double dice1 = (Math.random() * 6);
        double dice2 = (Math.random() * 6);

        return new Pair<Integer, Integer>() {
            @Override
            public Integer getLeft() {
                return (int) Math.ceil(dice1);
            }

            @Override
            public Integer getRight() {
                return (int) Math.ceil(dice2);
            }
        };
    }

    @FunctionalInterface
    public interface ResultHandler {
        void handleDice(int ceil, int ceil2);
    }

    private void rollDiceWithResultHandler(ResultHandler resultHandler) {
        double dice1 = (Math.random() * 6);
        double dice2 = (Math.random() * 6);

        resultHandler.handleDice((int) Math.ceil(dice1), (int) Math.ceil(dice2));
    }

    public static void main(String[] args) {

        DiceExample object = new DiceExample();

        Pair<Integer, Integer> result = object.rollDiceWithReturnType();
        System.out.println("Dice 1: " + result.getLeft());
        System.out.println("Dice 2: " + result.getRight());

        object.rollDiceWithResultHandler((dice1, dice2) -> {
            System.out.println("Dice 1: " + dice1);
            System.out.println("Dice 2: " + dice2);
        });
    }
}


问:
Stuck with server.use()
Im stuck with server.use is node.js. everytime i take server.use(express.static('public')); before server.get , it won't run, then i change server.use(express.static('public')); after server.get() it working well like nothing happened.

can someone tell me what is the difference ?

here my script :

```<code>    // Depedencies / built-in
import express from 'express';
import { join } from 'path';
import nodeSass from 'node-sass-middleware';

// you can place anything here, except depedencies
import config from './config';
import apiRouter from './api/index';

const server = express();

// Including Middleware
server.use(nodeSass({
    src: join(__dirname + 'sass'),
    dest: join(__dirname + 'public'),
}));

// everytime i take this before Router, it running, but
// but, the index won't showing up
server.use(express.static('public'));

// Setting up view engine
server.set('view engine', 'ejs');

// Router
server.get('/', (req, res) => {
    res.render('index', {
        title: 'Hello EJs',
    });
});

// if i change after Route, it working well
// server.use(express.static('public'));

server.listen(config.port, () => {
    console.log('magic happen on port: ', config.port);
});
</code>```

答:
I will try to answer, by guesing what's wrong.

1) server.use(express.static('public')); This is just the way to tell your application where to look for static files like JS, CSS, images and other content that page will need to load. More info here . http://expressjs.com/en/api.html#express.static

2) When you use res.render('pathToRenderFile') It will try to find file name with specified engine server.set('view engine', 'ejs'); . If no engine is set you will need to add extension too. By default it will look in views directory. More info here http://expressjs.com/en/guide/using-template-engines.html

So in your case you need to put index.ejs inside views/index.ejs. Then all should work.

3) All of the middleware(middleware functions) like server.use or server.set should be set up before routes.

4) About middleware, and the point of it. Before or after any route you can perform some actions that you may require on request or response objects. For example you need this middleware https://github.com/expressjs/body-parser to have all post data inside req.body object. If you dont include it you will have to parse it yourself. That's why express gives you a good way to handle this cases, using build in or yourown middlewares.

Here is the list of all usefull middlewares https://expressjs.com/en/resources/middleware.html

Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

There is a good examples here https://expressjs.com/en/4x/api.html#app.use

Hope this helps.

Title: Stuck with server.use()

Body:
Im stuck with server.use is node.js. everytime i take server.use(express.static('public')); before server.get , it won't run, then i change server.use(express.static('public')); after server.get() it working well like nothing happened.

can someone tell me what is the difference ?

here my script :

    // Depedencies / built-in
import express from 'express';
import { join } from 'path';
import nodeSass from 'node-sass-middleware';

// you can place anything here, except depedencies
import config from './config';
import apiRouter from './api/index';

const server = express();

// Including Middleware
server.use(nodeSass({
    src: join(__dirname + 'sass'),
    dest: join(__dirname + 'public'),
}));

// everytime i take this before Router, it running, but
// but, the index won't showing up
server.use(express.static('public'));

// Setting up view engine
server.set('view engine', 'ejs');

// Router
server.get('/', (req, res) => {
    res.render('index', {
        title: 'Hello EJs',
    });
});

// if i change after Route, it working well
// server.use(express.static('public'));

server.listen(config.port, () => {
    console.log('magic happen on port: ', config.port);
});


问:
Javascript can't get element's value, value equals undefined
I would like some help please.

I've recently started learning javascript, and I came across an error I can't fix, it seems simple, yet I can't find a way to fix it.
So, I have a table:

And the point of the table is to give the squares with the value "X" when clicked, a red background (changing css class), and all others green, but to do that, I need to get the value of the square, and it is always returning "undefined".

The HTML table looks like this:

```<code><table>
    <tr>
        <td class="normal" id="11" value="0" onclick="alterar('11');">0</td>
        <td class="normal" id="12" value="1" onclick="alterar('12');">1</td>
        <td class="normal" id="13" value="2" onclick="alterar('13');">2</td>
        <td class="normal" id="14" value="X" onclick="alterar('14');">X</td>
        <td class="normal" id="15" value="1" onclick="alterar('15');">1</td>
        <td class="normal" id="16" value="0" onclick="alterar('16');">0</td>
        <td class="normal" id="17" value="0" onclick="alterar('17');">0</td>
    </tr>
        <td class="normal" id="21" value="0" onclick="alterar('21');">0</td>
        <td class="normal" id="22" value="1" onclick="alterar('22');">1</td>
        <td class="normal" id="23" value="2" onclick="alterar('23');">2</td>
        <td class="normal" id="24" value="X" onclick="alterar('24');">X</td>
        <td class="normal" id="25" value="1" onclick="alterar('25');">1</td>
        <td class="normal" id="26" value="0" onclick="alterar('26');">0</td>
        <td class="normal" id="27" value="0" onclick="alterar('27');">0</td>
    </tr>
        <td class="normal" id="31" value="0" onclick="alterar('31');">0</td>
        <td class="normal" id="32" value="1" onclick="alterar('32');">1</td>
        <td class="normal" id="33" value="2" onclick="alterar('33');">2</td>
        <td class="normal" id="34" value="X" onclick="alterar('34');">X</td>
        <td class="normal" id="35" value="1" onclick="alterar('35');">1</td>
        <td class="normal" id="36" value="0" onclick="alterar('36');">0</td>
        <td class="normal" id="37" value="0" onclick="alterar('37');">0</td>
    </tr>
        <td class="normal" id="41" value="0" onclick="alterar('41');">0</td>
        <td class="normal" id="42" value="1" onclick="alterar('42');">1</td>
        <td class="normal" id="43" value="2" onclick="alterar('43');">2</td>
        <td class="normal" id="44" value="X" onclick="alterar('44');">X</td>
        <td class="normal" id="45" value="1" onclick="alterar('45');">1</td>
        <td class="normal" id="46" value="0" onclick="alterar('46');">0</td>
        <td class="normal" id="47" value="0" onclick="alterar('47');">0</td>
    </tr>
</table>
</code>```

My javascript code looks like this:

```<code>function alterar(obj){

  var id = document.getElementById(obj).id;
  var value = document.getElementById(id).value;

  if (value == 'X'){
    obj.className='red';
  } else {
    obj.className='green';
    }
}

</script>
</code>```

And if for example, I'd use the square "44", which value is "X", it tells me that

```<code>    <td class="normal" id="44" value="X" onclick="alterar('44');">X</td>
</code>```

I'd like to thank everyone in advance for their times.

答:
Ok, so the problem is that td element cannot have value.

But you can leave value attribute and get it by function: getAttribute

```<code>var value = document.getElementById(id).getAttribute("value");
</code>```

Also I don't see a point of line:

```<code>var id = document.getElementById(obj).id;
</code>```

since variable obj is your id.

By the way if you try to get few attributes from one element it's a good practice to get element once and save it to variable, eg.

```<code>function alterar(obj){

    var element = document.getElementById(obj);
    var id = obj;
    var value = element.getAttribute("value");

    if (value == 'X') {
        element.className='red';
    } else {
        element.className='green';
    }
}
</code>```

Body:
I would like some help please.

I've recently started learning javascript, and I came across an error I can't fix, it seems simple, yet I can't find a way to fix it.
So, I have a table:

And the point of the table is to give the squares with the value "X" when clicked, a red background (changing css class), and all others green, but to do that, I need to get the value of the square, and it is always returning "undefined".

The HTML table looks like this:

        0
        1
        2
        X
        1
        0
        0

        0
        1
        2
        X
        1
        0
        0

        0
        1
        2
        X
        1
        0
        0

        0
        1
        2
        X
        1
        0
        0

My javascript code looks like this:

function alterar(obj){

  var id = document.getElementById(obj).id;
  var value = document.getElementById(id).value;

  if (value == 'X'){
    obj.className='red';
  } else {
    obj.className='green';
    }
}

</script>

And if for example, I'd use the square "44", which value is "X", it tells me that

    X

I'd like to thank everyone in advance for their times.

Body:
Ok, so the problem is that td element cannot have value.

But you can leave value attribute and get it by function: getAttribute

var value = document.getElementById(id).getAttribute("value");

Also I don't see a point of line:

var id = document.getElementById(obj).id;

since variable obj is your id.

By the way if you try to get few attributes from one element it's a good practice to get element once and save it to variable, eg.

function alterar(obj){

    var element = document.getElementById(obj);
    var id = obj;
    var value = element.getAttribute("value");

    if (value == 'X') {
        element.className='red';
    } else {
        element.className='green';
    }
}


问:
Pass eloquent method as a parameters
I trouble to pass eloquent methods as a parameter.

Here is my method,

```<code>public function getPayment($paymentId, $eloquentMethod)
{
    if (!empty($orderId)) {
        return DB::connection('my_db')->table('payment')->{$eloquentMethod}();
    }
    return null;
}
</code>```

It is working properly if i pass $this->getPayment('1', 'get')

But it is not working if i pass $this->getPayment('1', 'pluck("payment_id")')

Thanks in advance.

答:
How much possibilities do you have for $eloquentMethod ?
If many possibilities such as "get","first"..etc then you can make:

```<code>public function getPayment($paymentId, $eloquentMethod = 'get()')
{
    if (!empty($orderId)) {
        switch ($eloquentMethod) {
            case "get":
                return DB::connection('my_db')->table('payment')->get();
                break;
            case "first":
                return DB::connection('my_db')->table('payment')->first();
                break;
            case default:
                return null;
        }
    }
}
</code>```

Title: Pass eloquent method as a parameters

Body:
I trouble to pass eloquent methods as a parameter.

Here is my method,

public function getPayment($paymentId, $eloquentMethod)
{
    if (!empty($orderId)) {
        return DB::connection('my_db')->table('payment')->{$eloquentMethod}();
    }
    return null;
}

It is working properly if i pass $this->getPayment('1', 'get')

But it is not working if i pass $this->getPayment('1', 'pluck("payment_id")')

Thanks in advance.

Body:
How much possibilities do you have for $eloquentMethod ?
If many possibilities such as "get","first"..etc then you can make:

public function getPayment($paymentId, $eloquentMethod = 'get()')
{
    if (!empty($orderId)) {
        switch ($eloquentMethod) {
            case "get":
                return DB::connection('my_db')->table('payment')->get();
                break;
            case "first":
                return DB::connection('my_db')->table('payment')->first();
                break;
            case default:
                return null;
        }
    }
}


问:
VSI powerState stays ''HALTED' when I create by dedicatedAccountHostOnlyFlag: true
I used softlayer api to create VSI. And I met a problem when 'dedicatedAccountHostOnlyFlag' is true for dedicated VSI.

```<code>POST https://api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest.json
{
    "parameters": [
        {
            "blockDeviceTemplateGroup": {
                "globalIdentifier": "2aae2a36-76f3-4d2f-9881-e86fa15b040b"
            },
            "datacenter": {
                "name": "lon02"
            },
            "dedicatedAccountHostOnlyFlag": true,
            "domain": "softlayer.com",
            "hostname": "redis--031242-787",
            "hourlyBillingFlag": true,
            "localDiskFlag": false,
            "maxMemory": 8192,
            "networkComponents": [
                {
                    "maxSpeed": 100
                }
            ],
            "primaryBackendNetworkComponent": {
                "networkVlan": {
                    "id": 1292651,
                    "networkSpace": "PRIVATE"
                }
            },
            "privateNetworkOnlyFlag": true,
            "startCpus": 4
        }
    ]
}
</code>```

The VSI's trasaction is stuck with CLOUD_PROVISION_SETUP transaction and then powerState is still HALTED for long time.

Is it the virtual guest template incorrect? Or is something else the root cause?

答: Nope the template is fine otherwise the order would never had started the provision, the issue is at provisioning time, it may due to many reasons (e.g. the private network that you picked out does not have enough room or the datacenter is full), anyway in those cases a Softlayer Employee must review the provisioning process and fix it if he cannot do it he will contact you in order to let you know, So you can wait until the employee solve the problem or you can open a ticket and ask why you order is stuck.</p>

Body:
I used softlayer api to create VSI. And I met a problem when 'dedicatedAccountHostOnlyFlag' is true for dedicated VSI.

POST https://api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest.json
{
    "parameters": [
        {
            "blockDeviceTemplateGroup": {
                "globalIdentifier": "2aae2a36-76f3-4d2f-9881-e86fa15b040b"
            },
            "datacenter": {
                "name": "lon02"
            },
            "dedicatedAccountHostOnlyFlag": true,
            "domain": "softlayer.com",
            "hostname": "redis--031242-787",
            "hourlyBillingFlag": true,
            "localDiskFlag": false,
            "maxMemory": 8192,
            "networkComponents": [
                {
                    "maxSpeed": 100
                }
            ],
            "primaryBackendNetworkComponent": {
                "networkVlan": {
                    "id": 1292651,
                    "networkSpace": "PRIVATE"
                }
            },
            "privateNetworkOnlyFlag": true,
            "startCpus": 4
        }
    ]
}

The VSI's trasaction is stuck with CLOUD_PROVISION_SETUP transaction and then powerState is still HALTED for long time.

Is it the virtual guest template incorrect? Or is something else the root cause?


问:
Chrome extension that keeps running after window is deactivated(minimized)
I am trying to make some simple Chrome extension that continuously reloads each tab opened in current window.

Currently my extension runs only when a window is active.

How can I get it running even after the window is deactivated(minimized)?

```<code>{
  "manifest_version": 2,

  "name": "some name",
  "description": "some description",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "default.html",
    "default_title": "click here!"
  },
  "permissions": [
    "activeTab",
    "tabs",
    "cookies",
    "http://*.xxx.com/",
    "https://*.xxx.com/"
  ]
}
</code>```

Here is manifest.json I am using.

I am assuming that whether an extension can run in background has nothing to do with the extension script itself.

Am I right?

答:
The only piece of code your extension contains is a popup page (presumably, with scripts inside).

A popup page is only loaded while it's shown. As soon as the popup closes, the "tab" holding the page is torn down, and your code no longer executes.

For something that has to run at any time in the background there are, well, background pages. Their "tab" exists independently of the UI.

See documentation:

Architecture overview

Background pages

Event pages (more efficient in some scenarios, but harder to use)

Body:
I am trying to make some simple Chrome extension that continuously reloads each tab opened in current window.

Currently my extension runs only when a window is active.

How can I get it running even after the window is deactivated(minimized)?

{
  "manifest_version": 2,

  "name": "some name",
  "description": "some description",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "default.html",
    "default_title": "click here!"
  },
  "permissions": [
    "activeTab",
    "tabs",
    "cookies",
    "http://*.xxx.com/",
    "https://*.xxx.com/"
  ]
}

Here is manifest.json I am using.

I am assuming that whether an extension can run in background has nothing to do with the extension script itself.

Am I right?


问:
How to define calculations in a data frame depending on values from another data frame?
I have to calculate a coefficient based on a dataset stored in a data frame (A) of size 4936 obs. x 1025 var.

In a first row [1,] time in seconds is presented, each row is a sample collected from a different place. A sample of the data frame A:

```<code>#        V1   V2   V3   V4
# [1,] 26.4 26.5 26.6 26.7
# [2,]  -15   -5    2    3
# [3,]    6   -7    5    8
# [4,]    9    4    4   -2
</code>```

In another data frame (B) I stored the time from which I should start my calculations for each row in A. An example of the data frame B:

```<code>#      time
# [1,] 26.4
# [2,] 26.6
# [3,] 26.5
</code>```

Let's simplify that the coefficient is a sum of the data collected in one place (data frame A), depending on the time of their collection (data frame B). For the example above, the calculation should work like this:

```<code>sum1=-15+(-5)+2+3
sum2=5+8
sum3=4+4+(-2)
</code>```

The results of the calculations I would like to store in a new data frame, which would look like this:

```<code>#       Sum
# [1,]  -15
# [2,]   13
# [3,]    6
</code>```

How to link the calculations between the two data frames depending on a value stored in the second data frame?

答:
Solution using a simple for-loop:

```<code># recreate your data
V1 <- c(26.4, -15, 6, 9)
V2 <- c(26.5, -5, -7, 4)
V3 <- c(26.6, 2, 5, 4)
V4 <- c(26.7, 3, 8, -2)

A <- data.frame(V1, V2, V3, V4)
B <- data.frame(time = c(26.4, 26.6, 26.5))

#initialize empty variable to store sums in
sum_frame <- numeric()

# calculating sums
for (i in 1:NROW(B)) {
  sum_frame[i] <- sum(A[(i + 1), (which(A[1, ] == B$time[i])):NCOL(A)])
}

# turning sum-vector into a dataframe
sum_frame <- data.frame(sums = sum_frame)
</code>```

Output:

```<code>> sum_frame
  sum_frame
1       -15
2        13
3         6
</code>```

Body:
I have to calculate a coefficient based on a dataset stored in a data frame (A) of size 4936 obs. x 1025 var.

In a first row [1,] time in seconds is presented, each row is a sample collected from a different place. A sample of the data frame A:

#        V1   V2   V3   V4
# [1,] 26.4 26.5 26.6 26.7
# [2,]  -15   -5    2    3
# [3,]    6   -7    5    8
# [4,]    9    4    4   -2

In another data frame (B) I stored the time from which I should start my calculations for each row in A. An example of the data frame B:

#      time
# [1,] 26.4
# [2,] 26.6
# [3,] 26.5

Let's simplify that the coefficient is a sum of the data collected in one place (data frame A), depending on the time of their collection (data frame B). For the example above, the calculation should work like this:

sum1=-15+(-5)+2+3
sum2=5+8
sum3=4+4+(-2)

The results of the calculations I would like to store in a new data frame, which would look like this:

#       Sum
# [1,]  -15
# [2,]   13
# [3,]    6

How to link the calculations between the two data frames depending on a value stored in the second data frame?

Body:
Solution using a simple for-loop:

# recreate your data
V1 <- c(26.4, -15, 6, 9)
V2 <- c(26.5, -5, -7, 4)
V3 <- c(26.6, 2, 5, 4)
V4 <- c(26.7, 3, 8, -2)

A <- data.frame(V1, V2, V3, V4)
B <- data.frame(time = c(26.4, 26.6, 26.5))

#initialize empty variable to store sums in
sum_frame <- numeric()

# calculating sums
for (i in 1:NROW(B)) {
  sum_frame[i] <- sum(A[(i + 1), (which(A[1, ] == B$time[i])):NCOL(A)])
}

# turning sum-vector into a dataframe
sum_frame <- data.frame(sums = sum_frame)

Output:

> sum_frame
  sum_frame
1       -15
2        13
3         6


问:
finding the largest binary number from a range of cells
I have a data of some binary numbers in few range of cells, from A2 to A8, B2 to B8, and so on, till G column.
Now, I want to check the largest binary number from the above Rows and paste it to the cell, two row below the last used range. (i.e., Largest binary number from Row A to be paste in A10, and so on).
I am not finding any function which can find the value of binary numbers, and the code which I ran finds out the max number considering those as natural numbers.
Your help will be appreciated.
Thank You!</p>

答:
Okay first i made a function that converts binary to decimal and stored in a module. (You can store it wherever you want) This function handles any size binary

```<code>Function BinToDecConverter(BinaryString As String) As Variant
    Dim i As Integer
    For i = 0 To Len(BinaryString) - 1
        BinToDecConverter = CDec(BinToDecConverter) + Val(Mid(BinaryString, Len(BinaryString) - i, 1)) * 2 ^ i
    Next
End Function
</code>```

Afterwards i made the sub that loops through all binarys on sheet1 (Might need to change this for your sheet)

```<code>Sub FindLargestBinary()
On Error Resume Next
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Application.ThisWorkbook
Set ws = wb.Sheets("Sheet1")

Dim tempVal, tempRow As Integer
Dim iCoulmn, iRow As Integer

For iCoulmn = 1 To 7 'Run from A to G
    tempRow = 2
    tempVal = 0
    For iRow = 2 To 8 'Run from row 2 to 8
        If BinToDecConverter(ws.Cells(iRow, iCoulmn).Value) > tempVal Then tempVal = BinToDecConverter(ws.Cells(iRow, iCoulmn).Value): tempRow = iRow ' Check if current binary i higher then any previous

    Next iRow
    ws.Cells(iRow + 1, iCoulmn).Value = ws.Cells(tempRow, iCoulmn).Value 'Print highest binary
Next iCoulmn

End Sub
</code>```

Hope this helps you out..

Body:
Okay first i made a function that converts binary to decimal and stored in a module. (You can store it wherever you want) This function handles any size binary

Function BinToDecConverter(BinaryString As String) As Variant
    Dim i As Integer
    For i = 0 To Len(BinaryString) - 1
        BinToDecConverter = CDec(BinToDecConverter) + Val(Mid(BinaryString, Len(BinaryString) - i, 1)) * 2 ^ i
    Next
End Function

Afterwards i made the sub that loops through all binarys on sheet1 (Might need to change this for your sheet)

Sub FindLargestBinary()
On Error Resume Next
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Application.ThisWorkbook
Set ws = wb.Sheets("Sheet1")

Dim tempVal, tempRow As Integer
Dim iCoulmn, iRow As Integer

For iCoulmn = 1 To 7 'Run from A to G
    tempRow = 2
    tempVal = 0
    For iRow = 2 To 8 'Run from row 2 to 8
        If BinToDecConverter(ws.Cells(iRow, iCoulmn).Value) > tempVal Then tempVal = BinToDecConverter(ws.Cells(iRow, iCoulmn).Value): tempRow = iRow ' Check if current binary i higher then any previous

    Next iRow
    ws.Cells(iRow + 1, iCoulmn).Value = ws.Cells(tempRow, iCoulmn).Value 'Print highest binary
Next iCoulmn

End Sub

Hope this helps you out..


问:
Is there a way to figure out what is using a Linux kernel module?
If I load a kernel module and list the loaded modules with lsmod, I can get the "use count" of the module (number of other modules with a reference to the module). Is there a way to figure out what is using a module, though?

The issue is that a module I am developing insists its use count is 1 and thus I cannot use rmmod to unload it, but its "by" column is empty. This means that every time I want to re-compile and re-load the module, I have to reboot the machine (or, at least, I can't figure out any other way to unload it).

答: try kgdb and set breakpoint to your module</p>

OwnerDisplayName: mipadi

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: mipadi


问:
Where and Right/Left Join
I have the following code in SQL Server, when I use my filter on INNER JOIN condition, right join works fine, but if I change its position and create a where, it stops to working, my question is every time that I use RIGHT or LEFT JOIN I can't use WHERE?

```<code>SELECT pcm.clacta,
       pcm.descta,
       pcm.ctared,
       SUM(mcp.vlrliq)
  FROM e501tcp tcp
 INNER JOIN e501mcp mcp ON mcp.codemp = tcp.codemp
                       AND mcp.codfil = tcp.codfil
                       AND mcp.numtit = tcp.numtit
                       AND mcp.codtpt = tcp.codtpt
                       AND mcp.codfor = tcp.codfor
 RIGHT JOIN (SELECT pcm.clacta,
                    pcm.descta,
                    pcm.ctared
               FROM e043pcm pcm
              WHERE pcm.codmpc = 700) pcm ON pcm.ctared = tcp.ctafin
 WHERE tcp.codfil = 1
   AND tcp.numtit = '1/01'
 GROUP BY pcm.clacta,
          pcm.descta,
          pcm.ctared
 ORDER BY pcm.clacta;
</code>```

答:
I am not a fan of RIGHT JOIN. I think LEFT JOINs are much clearer (keep everything in the first table rather than the last table). In any case, your problem is that the WHERE clause is undoing the RIGHT JOIN.

I would write this as:

```<code>SELECT pcm.clacta,
       pcm.descta,
       pcm.ctared,
       SUM(mcp.vlrliq)
FROM e043pcm pcm LEFT JOIN
     e501tcp tcp
     ON pcm.ctared = tcp.ctafin AND
        tcp.codfil = 1 AND
        tcp.numtit = '1/01' LEFT JOIN
     e501mcp mcp
     ON mcp.codemp = tcp.codemp AND
        mcp.codfil = tcp.codfil AND
        mcp.numtit = tcp.numtit AND
        mcp.codtpt = tcp.codtpt AND
        mcp.codfor = tcp.codfor
 WHERE pcm.codmpc = 700
 GROUP BY pcm.clacta, pcm.descta, pcm.ctared
 ORDER BY pcm.clacta;
</code>```

Notes:

The condition on pcm can be in the WHERE clause.

No subquery is needed for pcm.

The original WHERE conditions are now in the ON clause.

The order of the JOINs is switched around, with the second conditions switched to a LEFT JOIN.

Also, this logic is not exactly the same as yours.  There are subtle differences based when there are matches in 2 of the 3 tables.  I doubt that this makes a difference for the results that you want.

Title: Where and Right/Left Join

Body:
I have the following code in SQL Server, when I use my filter on INNER JOIN condition, right join works fine, but if I change its position and create a where, it stops to working, my question is every time that I use RIGHT or LEFT JOIN I can't use WHERE?

SELECT pcm.clacta,
       pcm.descta,
       pcm.ctared,
       SUM(mcp.vlrliq)
  FROM e501tcp tcp
 INNER JOIN e501mcp mcp ON mcp.codemp = tcp.codemp
                       AND mcp.codfil = tcp.codfil
                       AND mcp.numtit = tcp.numtit
                       AND mcp.codtpt = tcp.codtpt
                       AND mcp.codfor = tcp.codfor
 RIGHT JOIN (SELECT pcm.clacta,
                    pcm.descta,
                    pcm.ctared
               FROM e043pcm pcm
              WHERE pcm.codmpc = 700) pcm ON pcm.ctared = tcp.ctafin
 WHERE tcp.codfil = 1
   AND tcp.numtit = '1/01'
 GROUP BY pcm.clacta,
          pcm.descta,
          pcm.ctared
 ORDER BY pcm.clacta;

Body:
I am not a fan of RIGHT JOIN. I think LEFT JOINs are much clearer (keep everything in the first table rather than the last table). In any case, your problem is that the WHERE clause is undoing the RIGHT JOIN.

I would write this as:

SELECT pcm.clacta,
       pcm.descta,
       pcm.ctared,
       SUM(mcp.vlrliq)
FROM e043pcm pcm LEFT JOIN
     e501tcp tcp
     ON pcm.ctared = tcp.ctafin AND
        tcp.codfil = 1 AND
        tcp.numtit = '1/01' LEFT JOIN
     e501mcp mcp
     ON mcp.codemp = tcp.codemp AND
        mcp.codfil = tcp.codfil AND
        mcp.numtit = tcp.numtit AND
        mcp.codtpt = tcp.codtpt AND
        mcp.codfor = tcp.codfor
 WHERE pcm.codmpc = 700
 GROUP BY pcm.clacta, pcm.descta, pcm.ctared
 ORDER BY pcm.clacta;

Notes:

The condition on pcm can be in the WHERE clause.

No subquery is needed for pcm.

The original WHERE conditions are now in the ON clause.

The order of the JOINs is switched around, with the second conditions switched to a LEFT JOIN.

Also, this logic is not exactly the same as yours.  There are subtle differences based when there are matches in 2 of the 3 tables.  I doubt that this makes a difference for the results that you want.