问:
Install Apache Ignite on EC2
I am trying to install Apache Ignite on EC2 (CentOS).
Downloaded latest Ignite src (2.0) and installed Java 1.8 and MVN.

Next tried to run (inside Ignite folder) MVN setup but is failing:

```<code>mvn clean package -DskipTests
[INFO] Scanning for projects...
Downloading: https://repo.maven.apache.org/maven2/org/apache/apache/16/apache-16.pom
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for org.apache.ignite:ignite-parent:1: Could not transfer artifact org.apache:apache:pom:16 from/to central (https://repo.maven.apache.org/maven2): Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101.32.215] failed: Connection timed out (Connection timed out) and 'parent.relativePath' points at no local POM @ org.apache.ignite:ignite-parent:1, /home/ec2-user/ignite/apache-ignite-2.0.0-src/parent/pom.xml, line 29, column 13
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project org.apache.ignite:apache-ignite:2.0.0 (/home/ec2-user/ignite/apache-ignite-2.0.0-src/pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for org.apache.ignite:ignite-parent:1: Could not transfer artifact org.apache:apache:pom:16 from/to central (https://repo.maven.apache.org/maven2): Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101.32.215] failed: Connection timed out (Connection timed out) and 'parent.relativePath' points at no local POM @ org.apache.ignite:ignite-parent:1, /home/ec2-user/ignite/apache-ignite-2.0.0-src/parent/pom.xml, line 29, column 13 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
</code>```

I am able to install same way on my Mac without this error. What could be a problem? Can MVN be set differently to avoid this error? Or is some issue with EC2/Apache Ignite compatibility? (I am not able to use AMI for Ignite since is not approved for usage within company network)

答:
It's a problem with connection to maven repository, check if this repo accessible from your EC2 machine:

Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101.32.215] failed: Connection timed out

It's not necessary to build Ignite from src on your server, you can download binaries and use them.

Title: Install Apache Ignite on EC2

Body:
I am trying to install Apache Ignite on EC2 (CentOS).
Downloaded latest Ignite src (2.0) and installed Java 1.8 and MVN.

Next tried to run (inside Ignite folder) MVN setup but is failing:

mvn clean package -DskipTests
[INFO] Scanning for projects...
Downloading: https://repo.maven.apache.org/maven2/org/apache/apache/16/apache-16.pom
[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[FATAL] Non-resolvable parent POM for org.apache.ignite:ignite-parent:1: Could not transfer artifact org.apache:apache:pom:16 from/to central (https://repo.maven.apache.org/maven2): Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101.32.215] failed: Connection timed out (Connection timed out) and 'parent.relativePath' points at no local POM @ org.apache.ignite:ignite-parent:1, /home/ec2-user/ignite/apache-ignite-2.0.0-src/parent/pom.xml, line 29, column 13
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project org.apache.ignite:apache-ignite:2.0.0 (/home/ec2-user/ignite/apache-ignite-2.0.0-src/pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM for org.apache.ignite:ignite-parent:1: Could not transfer artifact org.apache:apache:pom:16 from/to central (https://repo.maven.apache.org/maven2): Connect to repo.maven.apache.org:443 [repo.maven.apache.org/151.101.32.215] failed: Connection timed out (Connection timed out) and 'parent.relativePath' points at no local POM @ org.apache.ignite:ignite-parent:1, /home/ec2-user/ignite/apache-ignite-2.0.0-src/parent/pom.xml, line 29, column 13 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException

I am able to install same way on my Mac without this error. What could be a problem? Can MVN be set differently to avoid this error? Or is some issue with EC2/Apache Ignite compatibility? (I am not able to use AMI for Ignite since is not approved for usage within company network)


来源: stackexchange

问:
Hosting a Shiny app without Shiny Server
I am running a Shiny app through Rscript.exe on a server that hosts to my local network. If we were to port this online, we could do so through the server infrastructure we have set up.

Does Shiny Server add anything or is it just another type of hosting infrastructure?

答: I am doing the same thing via RStudio. Without knowing more about your business case, I don't think you would need Shiny Server.</p>

ContentLicense: CC BY-SA 3.0


问:
D3.js: Remove force.drag from a selection
I have a (rather simple) question: How to "un-call" force.drag on a selection made by D3.js? Let's say I created a set of elements and called "call" on it, giving it the drag-callback of a force-directed layout. That looked like this:

```<code>    d3.selectAll('rect').call(force.drag);
</code>```

Now it shall be possible to remove that behavior from some of the nodes later on. My approaches included resetting various listeners, such as 'click', 'drag' etc. using

```<code>    d3.select('rect#no-drag').on('click', null);
</code>```

None of them worked. Does anybody know how to remove the callback?

答:
This question isn't asking how to have fine grained control on the drag element, but I came here looking for how to toggle the drag on/off based on conditions, and the asker also asked how to get the drag back after removing it in the comments.

Thus, for anyone looking for how to conditionally allow the drag event, use drag.filter.

drag.filter takes a callback that needs to return a boolean. If the callback returns true, the drag happens, otherwise the drag doesn't trigger.

This is much cleaner than removing the drag from the selection and then trying to re-apply it.

Body:
I have a (rather simple) question: How to "un-call" force.drag on a selection made by D3.js? Let's say I created a set of elements and called "call" on it, giving it the drag-callback of a force-directed layout. That looked like this:

    d3.selectAll('rect').call(force.drag);

Now it shall be possible to remove that behavior from some of the nodes later on. My approaches included resetting various listeners, such as 'click', 'drag' etc. using

    d3.select('rect#no-drag').on('click', null);

None of them worked. Does anybody know how to remove the callback?


问:
Kotlin view variable is unexpectedly null in Activity onCreate method
I have a small Java Android Studio project, and I used the Kotlin converter in Android Studio 3.0 Canary 3 to convert all four source files to Kotlin. I then made some small modifications to get it to compile. I have only one activity with the following code:

```<code>package com.ebelinski.soundboard

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.AdapterView
import kotlinx.android.synthetic.main.activity_storyboard.gridview;

class StoryboardActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val itemManager = ItemManager(applicationContext)
        val items = itemManager.getItems().toTypedArray<Item>()

        setContentView(R.layout.activity_storyboard)
        val storyboardAdapter = StoryboardAdapter(this, items)
        gridview.adapter = storyboardAdapter

        gridview.onItemClickListener = AdapterView.OnItemClickListener { parent, v, position, id ->
            // todo
        }
    }

}
</code>```

When I run this I get the following error:

```<code>06-05 10:25:42.758 5668-5668/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.ebelinski.soundboard, PID: 5668
                                                 java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter convertView
                                                     at com.ebelinski.soundboard.StoryboardAdapter.getView(StoryboardAdapter.kt)
                                                     at android.widget.AbsListView.obtainView(AbsListView.java:2363)
                                                     at android.widget.GridView.onMeasure(GridView.java:1065)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                     at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                     at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at com.android.internal.policy.DecorView.onMeasure(DecorView.java:689)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
                                                     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
                                                     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1619)
                                                     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6337)
                                                     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                     at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                     at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:154)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

I'm not sure what the problem here is. Clearly gridview is null, but I don't know why. When I comment out the gridview.adapter and gridview.onItemClickListener lines, at least the program doesn't crash. I had the same error message before I used kotlin-android-extensions and defined the variable in question as val gridView = findViewById(R.id.gridview) as GridView.

The corresponding XML file has the following content:

```<code><?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:id="@+id/activity_storyboard"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.ebelinski.soundboard.StoryboardActivity">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:columnWidth="100dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="24dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="spacingWidthUniform"
        />
</RelativeLayout>
</code>```

My original Java code which worked just fine for this class was:

```<code>package com.ebelinski.soundboard;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

public class StoryboardActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ItemManager itemManager = new ItemManager(getApplicationContext());
        final Item[] items = itemManager.getItems().toArray(new Item[itemManager.getItems().size()]);

        setContentView(R.layout.activity_storyboard);
        GridView gridView = (GridView)findViewById(R.id.gridview);
        StoryboardAdapter storyboardAdapter = new StoryboardAdapter(this, items);
        gridView.setAdapter(storyboardAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                // todo
            }
        });
    }

}
</code>```

答: I think problem is in kotlin-android-extensions, your code looks good, just try to clean project and change grid view id. Also you can read great article about configuring kotlin-android-extensions, this is realy cool tool, you will forget about findViewById. Also please try it in stable version of studio and android plugin and make sure that you import it in main gradle file and apply in app gradle file.</p>

Body:
I have a small Java Android Studio project, and I used the Kotlin converter in Android Studio 3.0 Canary 3 to convert all four source files to Kotlin. I then made some small modifications to get it to compile. I have only one activity with the following code:

package com.ebelinski.soundboard

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.AdapterView
import kotlinx.android.synthetic.main.activity_storyboard.gridview;

class StoryboardActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val itemManager = ItemManager(applicationContext)
        val items = itemManager.getItems().toTypedArray<Item>()

        setContentView(R.layout.activity_storyboard)
        val storyboardAdapter = StoryboardAdapter(this, items)
        gridview.adapter = storyboardAdapter

        gridview.onItemClickListener = AdapterView.OnItemClickListener { parent, v, position, id ->
            // todo
        }
    }

}

When I run this I get the following error:

06-05 10:25:42.758 5668-5668/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.ebelinski.soundboard, PID: 5668
                                                 java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter convertView
                                                     at com.ebelinski.soundboard.StoryboardAdapter.getView(StoryboardAdapter.kt)
                                                     at android.widget.AbsListView.obtainView(AbsListView.java:2363)
                                                     at android.widget.GridView.onMeasure(GridView.java:1065)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                     at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                     at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                     at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                     at com.android.internal.policy.DecorView.onMeasure(DecorView.java:689)
                                                     at android.view.View.measure(View.java:19857)
                                                     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
                                                     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
                                                     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1619)
                                                     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6337)
                                                     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                     at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                     at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:154)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

I'm not sure what the problem here is. Clearly gridview is null, but I don't know why. When I comment out the gridview.adapter and gridview.onItemClickListener lines, at least the program doesn't crash. I had the same error message before I used kotlin-android-extensions and defined the variable in question as val gridView = findViewById(R.id.gridview) as GridView.

The corresponding XML file has the following content:

<?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:id="@+id/activity_storyboard"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.ebelinski.soundboard.StoryboardActivity">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:columnWidth="100dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="24dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="spacingWidthUniform"
        />
</RelativeLayout>

My original Java code which worked just fine for this class was:

package com.ebelinski.soundboard;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

public class StoryboardActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ItemManager itemManager = new ItemManager(getApplicationContext());
        final Item[] items = itemManager.getItems().toArray(new Item[itemManager.getItems().size()]);

        setContentView(R.layout.activity_storyboard);
        GridView gridView = (GridView)findViewById(R.id.gridview);
        StoryboardAdapter storyboardAdapter = new StoryboardAdapter(this, items);
        gridView.setAdapter(storyboardAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                // todo
            }
        });
    }

}


问:
ARM: How does VIC interact with flash vector table?
I have problems getting an interrupt-driven LED flasher going on an ARM LPC2138.  If I change to polling the timer, it works fine, so the problem seems to be the interrupts. The program is essentially a copy of demo code off the web, adapted for my IDE.

I’m prepared to keep trying things and failing repeatedly because that’s how you learn, but I would appreciate one specific clarification regarding how the VIC works, so I can eliminate one potential cause.

There’s an interrupt vector table in flash, starting at location 0x0. A MEMMAP register allows it to be mapped to the bottom of RAM, 0x4000000. However, there is also  code in setting up the VIC, as follows:

VICVectCntl4 = 0x20 | 4 ;     // 4 informs VIC which address register to use.

VICVectAddr4 = (unsigned) timerISR;  // ISR address

VICIntEnable |= 0x10 ;  // Enable tmr0 interrupt.

My code also contains the ISR function timerISR(), of course.

This suggests that the timer vector in the tables is not used, since the address of the (my) ISR is specified in the VIC vector address register.

Q:  Is there any interaction at all between my program and the flash/remapped timer vector address, or is it ignored in this case? If it is involved, how does this occur?

Thanks in advance for any assistance.

答:
Taking a look at page 13 of the datasheet for the LPC2138,
 (http://www.nxp.com/documents/user_manual/UM10120.pdf) it seems that the interrupts mapped at the beginning of flash (or RAM, if the bit you mentioned is set) are the core processor exception handlers. These interrupts are standard across all ARM7 processors. If you look at the particular interrupts that are made available there, you'll notice that there's nothing specific to a particular timer or peripheral.

The "VIC" peripheral on the chip is designed to easily handle miscellaneous interrupt sources, such as timers or external pin wakeups. It provides an additional facility for tying a particular interrupt directly to a function in code, which is what the snippet you call out seems to be configuring.

There's a dedicated reference manual for the VIC on the LPC2138 which can be found here: http://infocenter.arm.com/help/topic/com.arm.doc.ddi0181e/DDI0181.pdf . Section 2.2 Operation provides good information on how this operates.


问:
TypeError: list indices must be integers or slices, not str 'convert the chararter'
```<code>Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
      print(Number[n]+1\n)
InputNum3 = input()
Number[InputNum3] = ''.join(str('-'))
</code>```

want:

```<code>1       2
     3
     4
     .... 20
</code>```

input 2

want:

```<code>1
      -
      3
      4...20
</code>```

but the result is:

TypeError: list indices must be integers or slices, not str

答:
Do:

inputNum3 = int(input())

to get an Integer, you can't access lists by a String as index.

Your variable names should start with lowercase. Generally snakecase too, with all lowercase separated by underscore:

```<code>number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
input_num = int(input())
number[input_num] = "-"
</code>```

You don't need the .join() here because you want to have just a single character anyway.

You can also fill your number list like so:

number = [x for x in range(20)]

This is called a list comprehension.

Lastly, you can just do print(number) if you want to print the full list, no need for the for loop.

If you want to print all list elements from index x to y you can use list slicing:

number[3:15] for example.

See here for more examples of slices.

Body:
Number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
for n in range(0, 20):
      print(Number[n]+1\n)
InputNum3 = input()
Number[InputNum3] = ''.join(str('-'))

want:

1       2
     3
     4
     .... 20

input 2

want:

1
      -
      3
      4...20

but the result is:

TypeError: list indices must be integers or slices, not str

Body:
Do:

inputNum3 = int(input())

to get an Integer, you can't access lists by a String as index.

Your variable names should start with lowercase. Generally snakecase too, with all lowercase separated by underscore:

number = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
input_num = int(input())
number[input_num] = "-"

You don't need the .join() here because you want to have just a single character anyway.

You can also fill your number list like so:

number = [x for x in range(20)]

This is called a list comprehension.

Lastly, you can just do print(number) if you want to print the full list, no need for the for loop.

If you want to print all list elements from index x to y you can use list slicing:

number[3:15] for example.

See here for more examples of slices.


问:
Duplicate Output Destination Error in Access
I am using the following query. But when i run it, it gives error </p>

<blockquote>
  <p>"Duplicate Output Destination 'ShipmentID'.  </p>
</blockquote>

```<code>CurrentDb.Execute "INSERT INTO TmpContainersForPLReport " & _
                  "SELECT * FROM Containers INNER JOIN Shipments ON (Containers.ShipmentID = Shipments.ShipmentID)  WHERE Containers.PackinglistentryDate = #" & TxtEntryDate & "# and Containers.PONumber = '" & TxtPONumber & "'" & _
                  " OR Containers.PackinglistentryDate = #" & TxtEntryDate & "# and Containers.SalesOrderNumber = '" & txtSalesOrderNumber & "'"
</code>```

答:
From the join, one can see ShipmentID resides in two tables, Containers and Shipments, and hence the error. For this reason among others, always explicitly reference columns and not abbreviate with *. Even so explicitly reference the destination columns in INSERT clause.

And as another best practice, consider parameterization over string concatenation. You can so with DAO querydef parameters with PARAMETERS clause. See below example. Do replace the Cols.

```<code>Dim strSQL As String
Dim qdef As QueryDef

strSQL = "PARAMETERS TxtEntryDateParam Date, TxtPONumberParam Text(255), TxtSalesOrderNumberParam Text(255);" & _
         "INSERT INTO TmpContainersForPLReport (Col1, Col2, Col3) " & _
         "SELECT Col1, Col2, Col3 FROM Containers c " & _
         "INNER JOIN Shipments s ON (c.ShipmentID = s.ShipmentID) " & _
         "WHERE c.PackinglistentryDate = [TxtEntryDateParam] AND c.PONumber = [TxtPONumberParam]" & _
         "   OR c.PackinglistentryDate = [TxtEntryDateParam] AND c.SalesOrderNumber = [TxtSalesOrderNumberParam];"

Set qdef = CurrentDb.CreateQueryDef("", strSQL)

qdef!TxtEntryDateParam = TxtEntryDate
qdef!TxtPONumberParam = TxtPONumber
qdef!TxtSalesOrderNumberParam = txtSalesOrderNumber

qdef.Execute dbFailOnError

Set qdef = Nothing
</code>```

In fact, you can even save above SQL as a saved Access query which the Jet/ACE Engine caches for best optimized, execution path (i.e., more efficient than VBA string query):

```<code>Dim strSQL As String

Set qdef = CurrentDb.QueryDefs("myAppendQuery")

qdef!TxtEntryDateParam = TxtEntryDate
qdef!TxtPONumberParam = TxtPONumber
qdef!txtSalesOrderNumberParam = txtSalesOrderNumber

qdef.Execute dbFailOnError

Set qdef = Nothing
</code>```

Body:
I am using the following query. But when i run it, it gives error

"Duplicate Output Destination 'ShipmentID'.

CurrentDb.Execute "INSERT INTO TmpContainersForPLReport " & _
                  "SELECT * FROM Containers INNER JOIN Shipments ON (Containers.ShipmentID = Shipments.ShipmentID)  WHERE Containers.PackinglistentryDate = #" & TxtEntryDate & "# and Containers.PONumber = '" & TxtPONumber & "'" & _
                  " OR Containers.PackinglistentryDate = #" & TxtEntryDate & "# and Containers.SalesOrderNumber = '" & txtSalesOrderNumber & "'"

Body:
From the join, one can see ShipmentID resides in two tables, Containers and Shipments, and hence the error. For this reason among others, always explicitly reference columns and not abbreviate with *. Even so explicitly reference the destination columns in INSERT clause.

And as another best practice, consider parameterization over string concatenation. You can so with DAO querydef parameters with PARAMETERS clause. See below example. Do replace the Cols.

Dim strSQL As String
Dim qdef As QueryDef

strSQL = "PARAMETERS TxtEntryDateParam Date, TxtPONumberParam Text(255), TxtSalesOrderNumberParam Text(255);" & _
         "INSERT INTO TmpContainersForPLReport (Col1, Col2, Col3) " & _
         "SELECT Col1, Col2, Col3 FROM Containers c " & _
         "INNER JOIN Shipments s ON (c.ShipmentID = s.ShipmentID) " & _
         "WHERE c.PackinglistentryDate = [TxtEntryDateParam] AND c.PONumber = [TxtPONumberParam]" & _
         "   OR c.PackinglistentryDate = [TxtEntryDateParam] AND c.SalesOrderNumber = [TxtSalesOrderNumberParam];"

Set qdef = CurrentDb.CreateQueryDef("", strSQL)

qdef!TxtEntryDateParam = TxtEntryDate
qdef!TxtPONumberParam = TxtPONumber
qdef!TxtSalesOrderNumberParam = txtSalesOrderNumber

qdef.Execute dbFailOnError

Set qdef = Nothing

In fact, you can even save above SQL as a saved Access query which the Jet/ACE Engine caches for best optimized, execution path (i.e., more efficient than VBA string query):

Dim strSQL As String

Set qdef = CurrentDb.QueryDefs("myAppendQuery")

qdef!TxtEntryDateParam = TxtEntryDate
qdef!TxtPONumberParam = TxtPONumber
qdef!txtSalesOrderNumberParam = txtSalesOrderNumber

qdef.Execute dbFailOnError

Set qdef = Nothing


问:
BIML calling a stored procedure in C# using SSIS project parameter
I am new to BIML. I am stuck at the point where I want to call a SQL Server stored procedure in C# and want to pass SSIS project parameter in the stored procedure as a parameter.

For example -

```<code><# string sSQL1 = "Exec dbo.USP_ProcName 'p1'";#>

<# DataTable tbl1 = ExternalDataAccess.GetDataTable(DBConnectionStr,sSQL1); #>

<# foreach (DataRow row in tbl1.Rows){ #>
<Package PackageName="<#=row["PackageName"]#>" />
...
<# } #>
</code>```

In the above example I want to use SSIS project parameter say, @[Project::Param1] rather than the constant value p1, but I am not getting it right and keep getting syntax errors all the time.

Could someone please help? Thanks in advance

答:
It looks like you are using the results of your stored procedure to build a DataTable that is then used to create your SSIS packages via Biml.  As far as I am aware, this is not possible.

If you want to have a dynamic element within your actual Biml script, you need to have those values available to reference either in a metadata file or a database somewhere you can connect to and retrieve.

Body:
I am new to BIML. I am stuck at the point where I want to call a SQL Server stored procedure in C# and want to pass SSIS project parameter in the stored procedure as a parameter.

For example -

<# string sSQL1 = "Exec dbo.USP_ProcName 'p1'";#>

<# DataTable tbl1 = ExternalDataAccess.GetDataTable(DBConnectionStr,sSQL1); #>

<# foreach (DataRow row in tbl1.Rows){ #>
<Package PackageName="<#=row["PackageName"]#>" />
...
<# } #>

In the above example I want to use SSIS project parameter say, @[Project::Param1] rather than the constant value p1, but I am not getting it right and keep getting syntax errors all the time.

Could someone please help? Thanks in advance


问:
Retrieve content using two labels with Casperjs
I'm just starting with CasperJs and I'd like to retrieve the current page number which is stored in a list. I assume this can be done by combining the class and the aria-selected which must be true to indicate the current page.

I would appreciate if someone can point out how to do this programmatically.
Here's what I've got so far:

```<code>var casper = require("casper").create({
    pageSettings: {
        userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20130404 Firefox/23.0"
    }
});

var url = 'https://markets.ft.com/data/director-dealings';
var currentPage = 1;
var jobs = [];

casper.start(url, function() {
    this.waitForSelector('li[class="mod-ui-pagination__number"]');
});

casper.then(function() {

    var el = document.querySelectorAll('body > div.o-grid-container.mod-container > div:nth-child(2) > section > div:nth-child(1) > div > div > div.mod-ui-pagination__results-count > ul');//div[3] div[2] section div[1] div div div[3] ul li[2]');

    this.echo(JSON.stringify(el));
});

casper.run();
</code>```

HTML:

```<code><ul class="mod-ui-pagination">
    <li class="mod-ui-pagination__arrows" aria-disabled="false"><i class="o-ft-icons-icon o-ft-icons-icon--arrow-left"></i></li>
    <li class="mod-ui-pagination__number" aria-selected="false" data-mod-pagination-num="1">1</li>
    <li class="mod-ui-pagination__number" aria-selected="true" data-mod-pagination-num="2">2</li>
    <li class="mod-ui-pagination__number" aria-selected="false" data-mod-pagination-num="3">3</li>
    <li class="mod-ui-pagination__ellipsis"><i class="o-ft-icons-icon o-ft-icons-icon--more"></i></li>
    <li class="mod-ui-pagination__number" aria-selected="false" data-mod-pagination-num="739">739</li>
    <li class="mod-ui-pagination__number" aria-selected="false" data-mod-pagination-num="740">740</li>
    <li class="mod-ui-pagination__number" aria-selected="false" data-mod-pagination-num="741">741</li>
    <li class="mod-ui-pagination__arrows" aria-disabled="false"><i class="o-ft-icons-icon o-ft-icons-icon--arrow-right"></i></li>
</ul>
</code>```

PS: Is there a trick to quickly find how to access an element? Inspect > Copy Selector

Edit: Inspect > Copy Xpath returns this for the ul element: html/body/div[3]/div[2]/section/div[1]/div/div/div[3]/ul/li[2]

答:
Use evaluate() to access the real page environment (DOM)

Use querySelector() instead of querySelectorAll() because you just need one element

Use this CSS selector: ul.mod-ui-pagination > li[aria-selected="true"]

Here is the script:

```<code>var casper = require('casper').create({
  pageSettings: {
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20130404 Firefox/23.0'
  }
});

casper.start('https://markets.ft.com/data/director-dealings');

casper.waitForSelector('li.mod-ui-pagination__number', function () {
  this.echo(this.evaluate(function () {
    var el = document.querySelector('ul.mod-ui-pagination > li[aria-selected="true"]');
    return el.textContent;
  }));
});

casper.run();
</code>```

Body:
I'm just starting with CasperJs and I'd like to retrieve the current page number which is stored in a list. I assume this can be done by combining the class and the aria-selected which must be true to indicate the current page.

I would appreciate if someone can point out how to do this programmatically.
Here's what I've got so far:

var casper = require("casper").create({
    pageSettings: {
        userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20130404 Firefox/23.0"
    }
});

var url = 'https://markets.ft.com/data/director-dealings';
var currentPage = 1;
var jobs = [];

casper.start(url, function() {
    this.waitForSelector('li[class="mod-ui-pagination__number"]');
});

casper.then(function() {

    var el = document.querySelectorAll('body > div.o-grid-container.mod-container > div:nth-child(2) > section > div:nth-child(1) > div > div > div.mod-ui-pagination__results-count > ul');//div[3] div[2] section div[1] div div div[3] ul li[2]');

    this.echo(JSON.stringify(el));
});

casper.run();

HTML:

1

2

3

739

740

741

PS: Is there a trick to quickly find how to access an element? Inspect > Copy Selector

Edit: Inspect > Copy Xpath returns this for the ul element: html/body/div[3]/div[2]/section/div[1]/div/div/div[3]/ul/li[2]

Body:
Use evaluate() to access the real page environment (DOM)

Use querySelector() instead of querySelectorAll() because you just need one element

Use this CSS selector: ul.mod-ui-pagination > li[aria-selected="true"]

Here is the script:

var casper = require('casper').create({
  pageSettings: {
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20130404 Firefox/23.0'
  }
});

casper.start('https://markets.ft.com/data/director-dealings');

casper.waitForSelector('li.mod-ui-pagination__number', function () {
  this.echo(this.evaluate(function () {
    var el = document.querySelector('ul.mod-ui-pagination > li[aria-selected="true"]');
    return el.textContent;
  }));
});

casper.run();


问:
Unicode decode error in dynamodb put_item using boto3
I'm trying to store API passwords and the like in a dynamodb table, encrypted with AES, and I'm having trouble storing it. I have a dict with data that I'm writing.

```<code>for key in endpoint:
        if 'password' in key or 'security' in key or 'secret' in key:
            #encrypt the value
            obj = AES.new(
                landlord_registry['default_crypt_salt'],
                AES.MODE_CFB,
                landlord_registry['default_crypt_iv'])
            endpoint[key] = {'B' : obj.encrypt(endpoint[key])}
        else:
            endpoint[key] = {'S' : endpoint[key]}
</code>```

The resulting dict looks like this:

{'mvp_version': {'S': '0.3'}, 'endpoint_details': [{u'time_interval': {'S': u'30'}, u'username': {'S': u'blahblah@blahblah.org'}, u'primary_key': {'S': u'Id'}, u'security_token': {'B': '&\xd9\t\x7b\x9...'}, u'service_name': {'S': u'blahblah'}, u'enabled': {'S': u'1'}, u'endpoint_id': {'S': u'SFORG0'}, u'password': {'B': 'K9\x958,\x31....  '}}, {u'username': {'S': u'usernamelala'}, u'primary_key': {'S': u'ID__'}, u'database': {'S': u'z8_dev1'}, u'service_name': {'S': u'sdasda'}, u'enabled': {'S': u'1'}, u'host_name': {'S': u'lalala.rds.amazonaws.com'}, u'endpoint_id': {'S': u'MYSQL1'}, u'password': {'B': 'E##\xe2n....'}}]}

The error is: Dynamo Insert Error: (, UnicodeDecodeError('utf8', ... , 1, 2, 'invalid continuation byte')

But from what I can tell, since I've used {'B' : 'encoded text'} it should try to store this as bytes not unicode text.

答:
I needed to use the Binary(text) wrapper in Python 2 in order to store the binary text in dynamodb. So the line:

```<code>endpoint[key] = {'B' : obj.encrypt(endpoint[key])}
</code>```

should look like:

```<code>endpoint[key] = {'B' : Binary(obj.encrypt(endpoint[key]))}
</code>```

Body:
I'm trying to store API passwords and the like in a dynamodb table, encrypted with AES, and I'm having trouble storing it. I have a dict with data that I'm writing.

for key in endpoint:
        if 'password' in key or 'security' in key or 'secret' in key:
            #encrypt the value
            obj = AES.new(
                landlord_registry['default_crypt_salt'],
                AES.MODE_CFB,
                landlord_registry['default_crypt_iv'])
            endpoint[key] = {'B' : obj.encrypt(endpoint[key])}
        else:
            endpoint[key] = {'S' : endpoint[key]}

The resulting dict looks like this:

{'mvp_version': {'S': '0.3'}, 'endpoint_details': [{u'time_interval': {'S': u'30'}, u'username': {'S': u'blahblah@blahblah.org'}, u'primary_key': {'S': u'Id'}, u'security_token': {'B': '&\xd9\t\x7b\x9...'}, u'service_name': {'S': u'blahblah'}, u'enabled': {'S': u'1'}, u'endpoint_id': {'S': u'SFORG0'}, u'password': {'B': 'K9\x958,\x31....  '}}, {u'username': {'S': u'usernamelala'}, u'primary_key': {'S': u'ID__'}, u'database': {'S': u'z8_dev1'}, u'service_name': {'S': u'sdasda'}, u'enabled': {'S': u'1'}, u'host_name': {'S': u'lalala.rds.amazonaws.com'}, u'endpoint_id': {'S': u'MYSQL1'}, u'password': {'B': 'E##\xe2n....'}}]}

The error is: Dynamo Insert Error: (, UnicodeDecodeError('utf8', ... , 1, 2, 'invalid continuation byte')

But from what I can tell, since I've used {'B' : 'encoded text'} it should try to store this as bytes not unicode text.

Body:
I needed to use the Binary(text) wrapper in Python 2 in order to store the binary text in dynamodb. So the line:

endpoint[key] = {'B' : obj.encrypt(endpoint[key])}

should look like:

endpoint[key] = {'B' : Binary(obj.encrypt(endpoint[key]))}


问:
How to test file attachment on hidden input using capybara?
I have hidden input inside of label:

```<code><label for="upload">
  <input class="hidden" type="file" name="file[picture]">
</label>
</code>```

When I click on the label, I attach a file and then confirm.

After that modal window pops up and I need to find appropriate div class.

How can I test this with the help of capybara?

答:
Using Capybara '2.7.1':</p>

```<code>attach_file('file[picture]', 'path/to/file.png', visible: false)
</code>```

Body:
I have hidden input inside of label:

  <input class="hidden" type="file" name="file[picture]">

When I click on the label, I attach a file and then confirm.

After that modal window pops up and I need to find appropriate div class.

How can I test this with the help of capybara?

Body:
Using Capybara '2.7.1':

attach_file('file[picture]', 'path/to/file.png', visible: false)


问:
Return Unique Element with a Tolerance
In Matlab, there is this unique command that returns thew unique rows in an array. This is a very handy command.

But the problem is that I can't assign tolerance to it-- in double precision, we always have to compare two elements within a precision. Is there a built-in command that returns unique elements, within a certain tolerance?

答:
I was stuck the other day with a MatLab 2010, so, no round(X,n), no _mergesimpts (At least I couldn't get it to work) so, a simple solution that works (at least for my data):

Using rat default tolerance:

```<code>unique(cellstr(rat(x)))
</code>```

Other tolerance:

```<code>unique(cellstr(rat(x,tol)))
</code>```

Title: Return Unique Element with a Tolerance

Body:
I was stuck the other day with a MatLab 2010, so, no round(X,n), no _mergesimpts (At least I couldn't get it to work) so, a simple solution that works (at least for my data):

Using rat default tolerance:

unique(cellstr(rat(x)))

Other tolerance:

unique(cellstr(rat(x,tol)))


问:
Cannot use Swift array's first() method
So, I have this simple code

```<code>let arr = [8, 0, 2, 4]
let result = arr.first(where: { $0 == someparam })
print(result)
</code>```

and, I'm getting the error

cannot call value of non-function type 'Int?'

This is because the Array class has an instance property first

I have searched a lot on the swift documentation site, but I can't find anything that states how I should call this method correctly.

Even more, I can't understand how the Array class has a property and a method instance with the same name

Swift's official api on the 'first()' method

Swift's official api on the 'first' property

答:
Also note that if you have a syntax error in your where closure, you get the same unhelpful error:

cannot call value of non-function type 'Int?'

The original poster's code was fixed by the answer's declaration of someparam:

```<code>let someparam = 2
</code>```

I'm guessing that a syntax error in the closure leads swift to think you are using the property incorrectly, instead of the function incorrectly.

Title: Cannot use Swift array's first() method

Body:
So, I have this simple code

let arr = [8, 0, 2, 4]
let result = arr.first(where: { $0 == someparam })
print(result)

and, I'm getting the error

cannot call value of non-function type 'Int?'

This is because the Array class has an instance property first

I have searched a lot on the swift documentation site, but I can't find anything that states how I should call this method correctly.

Even more, I can't understand how the Array class has a property and a method instance with the same name

Swift's official api on the 'first()' method

Swift's official api on the 'first' property

Body:
Also note that if you have a syntax error in your where closure, you get the same unhelpful error:

cannot call value of non-function type 'Int?'

The original poster's code was fixed by the answer's declaration of someparam:

let someparam = 2

I'm guessing that a syntax error in the closure leads swift to think you are using the property incorrectly, instead of the function incorrectly.


问:
IIS/HttpHandler: Get relative absolute path?
I've got a site setup in IIS to run at http://localhost/WebApplication6. In my web application I have a handler (implements IHttpHandler). When I print context.Request.Url.AbsolutePath, I get /WebApplication6/whaetever. I want to trim off /WebApplication6 (the local site name). How can I do that? Is there a way to get the "WebApplication6" bit so I know what to trim off? (inside IHttpHandler.ProcessRequest).

ContentLicense: CC BY-SA 2.5

Body: VirtualPathUtility.GetDirectory(context.Request.Url.AbsolutePath)


问:
What all could be the reasons for a NavigationCancel event to get triggered?
I have a subscription for router events in angular2, When I console the events, I find a NavigationCancel event with reason: "". Curious to know what all could be the reasons for a NavigationCancel to get triggered. Not only with an empty reason but in general.

答:
NavigationCancel will be triggered when you are trying to naviggate to a route and navigated route children can not be loaded (CanLoad guard) or route itself cannot be activated (CanActivate guard)

you may use {enableTracing : true} while configuring RouterModule to see all events, and analyze further.

Hope this helps!!


问:
Android O Preview findViewById compile error
I tried to test the Android O Developer Preview second phase.
After the project was created, I just clicked build and run but I didn't have any success.

Android default generated code below:

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
</code>```

compile error occurred.

```<code>Error:(18, 37) error: reference to findViewById is ambiguous
both method findViewById(int) in Activity and method
<T>findViewById(int) in AppCompatActivity match
where T is a type-variable:
T extends View declared in method <T>findViewById(int)
</code>```

Help me! How do I fix this error?

Edit #1

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}
</code>```

=> compile Error

Error:(18, 27) error: reference to findViewById is ambiguous
both method findViewById(int) in Activity and method findViewById(int) in AppCompatActivity match
where T is a type-variable:
T extends View declared in method findViewById(int)

This is not casting issue.

My build.gradle is here.

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 'android-O'
    buildToolsVersion "26.0.0-rc2"
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 16
        targetSdkVersion 'O'
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.0-beta1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:26.0.0-beta1'
}
</code>```

I tried to Android Oreo Developer Preview 2.
And use Android Studio 3.0 Canary edition.

答:
Your build.gradle looks good, but the compiler seems still to compile with supportLib 26 against older compileSdkVersion (25 or lower).

Try to sync gradle and Build->Clean Project .
If that doesn't help, File->Invalidate Cache / Restart should do the thing...

Body:
I tried to test the Android O Developer Preview second phase.
After the project was created, I just clicked build and run but I didn't have any success.

Android default generated code below:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

compile error occurred.

Error:(18, 37) error: reference to findViewById is ambiguous
both method findViewById(int) in Activity and method
<T>findViewById(int) in AppCompatActivity match
where T is a type-variable:
T extends View declared in method <T>findViewById(int)

Help me! How do I fix this error?

Edit #1

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

=> compile Error

Error:(18, 27) error: reference to findViewById is ambiguous
both method findViewById(int) in Activity and method findViewById(int) in AppCompatActivity match
where T is a type-variable:
T extends View declared in method findViewById(int)

This is not casting issue.

My build.gradle is here.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 'android-O'
    buildToolsVersion "26.0.0-rc2"
    defaultConfig {
        applicationId "com.example.app"
        minSdkVersion 16
        targetSdkVersion 'O'
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.0-beta1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:26.0.0-beta1'
}

I tried to Android Oreo Developer Preview 2.
And use Android Studio 3.0 Canary edition.


问:
What id to use to generate promo codes for android app
I am thinking of having a way in my app to offer free unlock codes for valuable users, meaning that they won't have to purchase the app to have full access to it.

Looking into it there are a few ways:

Google Play Promo Codes: initially this sounded good but their terms are a bit constraining, for instance:

You agree to distribute Promotional Codes only to users located in
  countries where your Products, in-app item in your Products, or
  content related thereto, are permitted.

What if I want to reward a user from a country where I don't sell my apps to?

I could generate an unlock code for the user's email... but this rises a bit of privacy issues

I could have the user tell me some code from the app, and then for that code, generate an unlock code... I was thinking of maybe ANDROID_ID. Not sure what security issues may bring the read of ANDROID_ID as for instance the Advertiser id has. Another way could be generating a unique code on app install and use that.

Use something like Firebase Database and then store a bunch of codes there and check if the code entered in the app is available in the server.

I am waiting for your thoughts on how to implement this for android.

答:
what I can think of is to make a unique id (MD5 hash) for a particular user on your server side and thus having a flag for if the promo code can be applied or not.

If it (flag) changes from false to true, SMS or email the user that he can avail use of some code(sent along, generated by some algorithm on ID and credentials with a validity too) to unlock PAID content in free.

OO-> Else if you want to promote or distribute some of the promo codes like these, create a table with all the sorts of you wanted to distribute, then if any user enters that promo code, simply remove it from the promo code tables and assign that code to that respective user, if not already been used promo code ofcourse.


问:
Margin: 0 auto; not centering div with float:left
JSFiddle: https://jsfiddle.net/feyv4o4u/

```<code><div style="border:1px solid black;position:relative;float:left;margin:0 auto" >
</div>
</code>```

I have a division as presented in the fiddle above that cant be aligned in the center.

I have used float:left for the division so that the division width will fit the content as opposed to having 100% width.

How can I align a division as such to the center?
Note: Division width must fit content.

答:
float: left is designed to move an element to the left and let the content that follows it move up beside it.

If you don't want that. Don't use float: left.

You can get a shrink-wrapping effect with display: table.

Body:
JSFiddle: https://jsfiddle.net/feyv4o4u/

I have a division as presented in the fiddle above that cant be aligned in the center.

I have used float:left for the division so that the division width will fit the content as opposed to having 100% width.

How can I align a division as such to the center?
Note: Division width must fit content.


问:
Android Studio not detected my usb device - ubuntu
Android device is not detected in android studio after updating it from 2.1.4 to 2.2.3 on Ubuntu, previously it was working fine. Even I tried with previous version still its not detecting.
I have already enabled usb debugging. I tried MTP and PTP too nothing works for me.

android device is connected to computer

```<code>bhanuchand@bhanuchand-X550CC:~$ lsusb
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 004: ID 04f2:b40a Chicony Electronics Co., Ltd
Bus 001 Device 006: ID 13d3:3362 IMC Networks Atheros AR3012 Bluetooth 4.0 Adapter
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 011: ID 2717:1218
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
</code>```

Bus 003 is my device redmi 1s which doesn't have any description

adb device

```<code>bhanuchand@bhanuchand-X550CC:~$ adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
976fc0d9    device
</code>```

it showing nothing
 enter image description here

PS: sorry for my english

答: It is because, I'm running studio on ubuntu 32-bit version. Android studio Developers stopped supporting 32-bit versions. To get it worked downgrade your build version to 21 or below in gradle and rebuild the project (download if it needed).

Body:
Android device is not detected in android studio after updating it from 2.1.4 to 2.2.3 on Ubuntu, previously it was working fine. Even I tried with previous version still its not detecting.
I have already enabled usb debugging. I tried MTP and PTP too nothing works for me.

android device is connected to computer

bhanuchand@bhanuchand-X550CC:~$ lsusb
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 004: ID 04f2:b40a Chicony Electronics Co., Ltd
Bus 001 Device 006: ID 13d3:3362 IMC Networks Atheros AR3012 Bluetooth 4.0 Adapter
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 011: ID 2717:1218
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 003 is my device redmi 1s which doesn't have any description

adb device

bhanuchand@bhanuchand-X550CC:~$ adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
976fc0d9    device

it showing nothing
 enter image description here

PS: sorry for my english


问:
Android switching switch buttons on iteration
In a custom arrayadapter I have a list of string values being either "true" or "false".

```<code>public class CustomFriendList  extends ArrayAdapter<String> {

private final Activity context;
private List<String> friendName = new ArrayList<String>();
private List<String> backchatable = new ArrayList<String>();

public CustomFriendList(Activity context, List<String> friendName, List<String> backchatable){
    super(context, R.layout.fragment_friend_list_item, friendName);
    this.context = context;
    this.friendName = friendName;
    this.backchatable = backchatable;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView= inflater.inflate(R.layout.fragment_friend_list_item, null, true);
    TextView friend = (TextView) rowView.findViewById(R.id.friendName);
    Switch switchBackChat = (Switch) rowView.findViewById(R.id.on_off_backchatable);

    friend.setText(friendName.get(position));

    for (String ele : backchatable) {
        //System.out.println(ele.toString());
        if(ele.equals("false")){
            switchBackChat.setChecked(false);
        }else if(ele.equals("true")){
            switchBackChat.setChecked(true);
        }
    }

    return rowView;
}

}
</code>```

I am looking to set the state of the switches according to the values "true" or "false".

However the code above switches all the switches in the custom listView and not the respective ones at some position in the listView.

答:
Use ele.equals("false") and ele.equals("true") in the if statements or just use booleans instead of string values.

And why are you setting the checked status while iterating through the backchatable array? By this only the last string of the array matters and if the last string is "false" the switch will not be checked and if the last string is "true" the switch will be checked.

Body:
In a custom arrayadapter I have a list of string values being either "true" or "false".

public class CustomFriendList  extends ArrayAdapter<String> {

private final Activity context;
private List<String> friendName = new ArrayList<String>();
private List<String> backchatable = new ArrayList<String>();

public CustomFriendList(Activity context, List<String> friendName, List<String> backchatable){
    super(context, R.layout.fragment_friend_list_item, friendName);
    this.context = context;
    this.friendName = friendName;
    this.backchatable = backchatable;
}

@Override
public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    View rowView= inflater.inflate(R.layout.fragment_friend_list_item, null, true);
    TextView friend = (TextView) rowView.findViewById(R.id.friendName);
    Switch switchBackChat = (Switch) rowView.findViewById(R.id.on_off_backchatable);

    friend.setText(friendName.get(position));

    for (String ele : backchatable) {
        //System.out.println(ele.toString());
        if(ele.equals("false")){
            switchBackChat.setChecked(false);
        }else if(ele.equals("true")){
            switchBackChat.setChecked(true);
        }
    }

    return rowView;
}

}

I am looking to set the state of the switches according to the values "true" or "false".

However the code above switches all the switches in the custom listView and not the respective ones at some position in the listView.


问:
Maximum time allowed to complete authentication has been exceeded
I am using DotNetOpenAuth  to authenticate an app on Windows Azure. From time to time, the system is slow, and I end up with the following error message

Login failed: The maximum time allowed to complete authentication has been exceeded. Please try again.

Any suggestion how to increase this timeout?

答:
Note for other folks: IF this keeps happening, it can also be to do with the ASP.NET cache flushing, on development machines this is quite possible.

Can verify this with

```<code><caching>
  <cache disableMemoryCollection = "true"
    disableExpiration = "false"
    privateBytesLimit = "0"
    percentagePhysicalMemoryUsedLimit = "90"
    privateBytesPollTime = "00:02:00"/>
</caching>
</code>```

In System.Web in Web.Config

Body:
Note for other folks: IF this keeps happening, it can also be to do with the ASP.NET cache flushing, on development machines this is quite possible.

Can verify this with

<caching>
  <cache disableMemoryCollection = "true"
    disableExpiration = "false"
    privateBytesLimit = "0"
    percentagePhysicalMemoryUsedLimit = "90"
    privateBytesPollTime = "00:02:00"/>
</caching>

In System.Web in Web.Config


问:
preventDefault() stops form validation
having a problem with browser form validation using .preventDefault()

Is there a way to let browser check validation of required inputs, but stops submit?

Is there any flags I can use to get if form is valid?

Thanks

update:
using both backbone and jquery

```<code>events: {
    "click #commentFormSubmit": "commentFormSubmit",
},
commentFormSubmit: function(el){
    el.preventDefault();
    var $el = $(el.target).parent();

    // this.$el.find('button').prop('disabled', true).addClass('disabled');
    var commentData = {};
    commentData.name = this.$el.find('input[name=comment_name]').val();
    commentData.country = this.$el.find('input[name=comment_country]').val();
    commentData.email = this.$el.find('input[name=comment_email]').val();
    commentData.comment = this.$el.find('textarea[name=comment_text]').val();
    commentData.grade = this.$el.find('.commnt_grade:checked').val();
    console.log('dd')
    this.model.onSubmitComment(commentData);
},
</code>```

and the form:

```<code>    <form action="" class="" method="post">
        <span>
            <input type="text" name="comment_name" class="comment_input" placeholder="{{ 'your name'|_ }}" required>
            <input type="text" name="comment_country" class="comment_input" placeholder="{{ 'country'|_ }}">
            <input type="text" name="comment_email" class="comment_input" placeholder="{{ 'your email'|_ }}" required>
        </span>

        <textarea name="comment_text" id="comment_text" cols="30" rows="10" placeholder="{{ 'your comment'|_ }}" required></textarea>
        <span class="grades">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_1" value="1">
            <label for="grade_1" class="selectGrades" data-eq="1"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_2" value="2">
            <label for="grade_2" class="selectGrades" data-eq="2"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_3" value="3">
            <label for="grade_3" class="selectGrades" data-eq="3"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_4" value="4">
            <label for="grade_4" class="selectGrades" data-eq="4"></label>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_5" value="5">
            <label for="grade_5" class="selectGrades" data-eq="5"></label>
        </span>
        <button type="submit" id="commentFormSubmit">{{ 'submit'|_ }}</button>

    </form>
</code>```

答:
You can always rely to HTML5 form validation attributes that prevents you to submit your request while you have invalid form data:

disabled

max

min

pattern

required

So you do not need to prevent default behavior - use can't submit form until you have invalid data.

```<code><form action="/action_page_post.php" method="post">
  <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>
</code>```

https://www.w3schools.com/js/js_validation.asp

Title: preventDefault() stops form validation

Body:
having a problem with browser form validation using .preventDefault()

Is there a way to let browser check validation of required inputs, but stops submit?

Is there any flags I can use to get if form is valid?

Thanks

update:
using both backbone and jquery

events: {
    "click #commentFormSubmit": "commentFormSubmit",
},
commentFormSubmit: function(el){
    el.preventDefault();
    var $el = $(el.target).parent();

    // this.$el.find('button').prop('disabled', true).addClass('disabled');
    var commentData = {};
    commentData.name = this.$el.find('input[name=comment_name]').val();
    commentData.country = this.$el.find('input[name=comment_country]').val();
    commentData.email = this.$el.find('input[name=comment_email]').val();
    commentData.comment = this.$el.find('textarea[name=comment_text]').val();
    commentData.grade = this.$el.find('.commnt_grade:checked').val();
    console.log('dd')
    this.model.onSubmitComment(commentData);
},

and the form:

    <form action="" class="" method="post">

            <input type="text" name="comment_name" class="comment_input" placeholder="{{ 'your name'|_ }}" required>
            <input type="text" name="comment_country" class="comment_input" placeholder="{{ 'country'|_ }}">
            <input type="text" name="comment_email" class="comment_input" placeholder="{{ 'your email'|_ }}" required>

        <textarea name="comment_text" id="comment_text" cols="30" rows="10" placeholder="{{ 'your comment'|_ }}" required></textarea>

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_1" value="1">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_2" value="2">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_3" value="3">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_4" value="4">

            <input type="radio" name="commnt_grade" class="commnt_grade" id="grade_5" value="5">

        <button type="submit" id="commentFormSubmit">{{ 'submit'|_ }}</button>

    </form>

Body:
You can always rely to HTML5 form validation attributes that prevents you to submit your request while you have invalid form data:

disabled

max

min

pattern

required

So you do not need to prevent default behavior - use can't submit form until you have invalid data.

<form action="/action_page_post.php" method="post">
  <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>

https://www.w3schools.com/js/js_validation.asp


问:
z-index'ed parent div background not showing
I have a bootstrap jumbotron with a video background. The video background is position absolute and z-index: -1 and the jumbotron div is position relative and z-index: 1. The desired result here is to have a white transparent overlay on top of the video. However the background property is not visible, even when i switch it to say a solid color. here is a pen: https://codepen.io/anon/pen/LLEOoO?editors=1100

html

```<code><div class="container">
  <div id="block-1" class="block row jumbotron">
    <div class="col col-md-12">
      <respond-html id="html-5" description="HTML">
        <video class="video-background" autoplay="" loop="" poster="/static/template/themes/video-theme/video/video.jpg">
          <source src="https://host.ohiocashflow.com/sites/home-giveaway/videos/Productive-Morning.webm" type="video/webm">
          <source src="https://host.ohiocashflow.com/sites/home-giveaway/videos/Productive-Morning.mp4" type="video/mp4">
        </video>
      </respond-html>
      <div id="image-1" class="respond-image">
        <img src="https://host.ohiocashflow.com:443/sites/home-giveaway/files/logo.png">
      </div>
      <p>Your purpose in life has to be bigger and better than yourself... <a href="#">DONATE</a></p>
    </div>
  </div>
</div>
</code>```

css

```<code>.container .jumbotron{
  position: relative;
  box-sizing: border-box;
  background: rgba(255,255,255,.5);
  border-radius: 0 !important;
  color: #fff;
  max-width: 100%;
  margin: 0 0 0 0;
  padding: 150px 0 0 0;
  text-align: center;
  height: 350px;
  z-index: 1;
}

.video-background {
  position: absolute;
  top: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: 100%;
  height: auto;
  z-index: -1;
  -webkit-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
}
</code>```

答:
When you add a z-index to the parent, that creates a new stacking order starting at the parent. If you want a child element to be below it's parent, remove the parent z-index and use a negative z-index on the child.

.container .jumbotron{
  position: relative;
  box-sizing: border-box;
  background: rgba(255,255,255,.5);
  border-radius: 0 !important;
  color: #fff;
  max-width: 100%;
  margin: 0 0 0 0;
  padding: 150px 0 0 0;
  text-align: center;
  height: 350px;
}

.video-background {
  position: absolute;
  top: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: 100%;
  height: auto;
  z-index: -1;
  -webkit-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div id="block-1" class="block row jumbotron">
    <div class="col col-md-12">
      <respond-html id="html-5" description="HTML">
        <video class="video-background" autoplay="" loop="" poster="/static/template/themes/video-theme/video/video.jpg">
          <source src="https://host.ohiocashflow.com/sites/home-giveaway/videos/Productive-Morning.webm" type="video/webm">
          <source src="https://host.ohiocashflow.com/sites/home-giveaway/videos/Productive-Morning.mp4" type="video/mp4">
        </video>
      </respond-html>
      <div id="image-1" class="respond-image">
        <img src="https://host.ohiocashflow.com:443/sites/home-giveaway/files/logo.png">
      </div>
      <p>Your purpose in life has to be bigger and better than yourself... DONATE</p>
    </div>
  </div>
</div></code>```

Body:
I have a bootstrap jumbotron with a video background. The video background is position absolute and z-index: -1 and the jumbotron div is position relative and z-index: 1. The desired result here is to have a white transparent overlay on top of the video. However the background property is not visible, even when i switch it to say a solid color. here is a pen: https://codepen.io/anon/pen/LLEOoO?editors=1100

html

      <respond-html id="html-5" description="HTML">
        <video class="video-background" autoplay="" loop="" poster="/static/template/themes/video-theme/video/video.jpg">
          <source src="https://host.ohiocashflow.com/sites/home-giveaway/videos/Productive-Morning.webm" type="video/webm">
          <source src="https://host.ohiocashflow.com/sites/home-giveaway/videos/Productive-Morning.mp4" type="video/mp4">
        </video>
      </respond-html>

Your purpose in life has to be bigger and better than yourself... DONATE

css

.container .jumbotron{
  position: relative;
  box-sizing: border-box;
  background: rgba(255,255,255,.5);
  border-radius: 0 !important;
  color: #fff;
  max-width: 100%;
  margin: 0 0 0 0;
  padding: 150px 0 0 0;
  text-align: center;
  height: 350px;
  z-index: 1;
}

.video-background {
  position: absolute;
  top: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: 100%;
  height: auto;
  z-index: -1;
  -webkit-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
}

Body:
When you add a z-index to the parent, that creates a new stacking order starting at the parent. If you want a child element to be below it's parent, remove the parent z-index and use a negative z-index on the child.

.container .jumbotron{
  position: relative;
  box-sizing: border-box;
  background: rgba(255,255,255,.5);
  border-radius: 0 !important;
  color: #fff;
  max-width: 100%;
  margin: 0 0 0 0;
  padding: 150px 0 0 0;
  text-align: center;
  height: 350px;
}

.video-background {
  position: absolute;
  top: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: 100%;
  height: auto;
  z-index: -1;
  -webkit-transform: translateX(-50%) translateY(-50%);
  transform: translateX(-50%) translateY(-50%);
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div id="block-1" class="block row jumbotron">
    <div class="col col-md-12">
      <respond-html id="html-5" description="HTML">
        <video class="video-background" autoplay="" loop="" poster="/static/template/themes/video-theme/video/video.jpg">
          <source src="https://host.ohiocashflow.com/sites/home-giveaway/videos/Productive-Morning.webm" type="video/webm">
          <source src="https://host.ohiocashflow.com/sites/home-giveaway/videos/Productive-Morning.mp4" type="video/mp4">
        </video>
      </respond-html>
      <div id="image-1" class="respond-image">
        <img src="https://host.ohiocashflow.com:443/sites/home-giveaway/files/logo.png">
      </div>
      <p>Your purpose in life has to be bigger and better than yourself...&nbsp;<a href="#">DONATE</a></p>
    </div>
  </div>
</div>


问:
How to get File Type of a file
Is there a way to get the file type displayed in windows explorer in VB.net

i.e in windows explorer in details view one can see for example

```
Name          Date Modified           Type                           Size
A.PDF         05/06/2017 5:54PM       Adobe Acrobat reader           150kb
B.DOCX        05/06/2017 5:00PM       Microsoft Word Document        100kb
etc.
```

I want to get the type.  I cant seem to find a way to get there.  It feels like this should be very easy.

```<code>Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(txtFileName.Text)
</code>```

FileInfo gets me modified data and size of the file.. but not the type.

Appreciate forums help!

. I.e. for .pdf file the display with would "adobe acrobat document" .xls file would be "Microsoft excel worksheet"

答:
You can use below VB.net code for getting the file type description. Basically you have to use SHGetFileInfo API to get that information.

```<code>Imports System.Runtime.InteropServices

Module Get_File_Type

Sub Main()
    Dim info As New NativeMethods.SHFILEINFO()

    Dim fileName As String = "C:\TEST\TEST.xlsx"
    Dim dwFileAttributes As UInteger = NativeMethods.FILE_ATTRIBUTE.FILE_ATTRIBUTE_NORMAL
    Dim uFlags As UInteger = CUInt(NativeMethods.SHGFI.SHGFI_TYPENAME Or NativeMethods.SHGFI.SHGFI_USEFILEATTRIBUTES)

    NativeMethods.SHGetFileInfo(fileName, dwFileAttributes, info, CUInt(Marshal.SizeOf(info)), uFlags)

    Console.WriteLine(info.szTypeName)
    Console.ReadLine()
End Sub

End Module

NotInheritable Class NativeMethods
    Private Sub New()
    End Sub
    <StructLayout(LayoutKind.Sequential)> _
    Public Structure SHFILEINFO
        Public hIcon As IntPtr
        Public iIcon As Integer
        Public dwAttributes As UInteger
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
        Public szDisplayName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
        Public szTypeName As String
    End Structure

    Public NotInheritable Class FILE_ATTRIBUTE
        Private Sub New()
        End Sub
        Public Const FILE_ATTRIBUTE_NORMAL As UInteger = &H80
    End Class

    Public NotInheritable Class SHGFI
        Private Sub New()
        End Sub
        Public Const SHGFI_TYPENAME As UInteger = &H400
        Public Const SHGFI_USEFILEATTRIBUTES As UInteger = &H10
    End Class

    <DllImport("shell32.dll")> _
    Public Shared Function SHGetFileInfo(pszPath As String, dwFileAttributes As UInteger, ByRef psfi As SHFILEINFO, cbSizeFileInfo As UInteger, uFlags As UInteger) As IntPtr
    End Function
End Class
</code>```

Title: How to get File Type of a file

Body:
Is there a way to get the file type displayed in windows explorer in VB.net

i.e in windows explorer in details view one can see for example

Name          Date Modified           Type                           Size
A.PDF         05/06/2017 5:54PM       Adobe Acrobat reader           150kb
B.DOCX        05/06/2017 5:00PM       Microsoft Word Document        100kb
etc.

I want to get the type.  I cant seem to find a way to get there.  It feels like this should be very easy.

Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(txtFileName.Text)

FileInfo gets me modified data and size of the file.. but not the type.

Appreciate forums help!

. I.e. for .pdf file the display with would "adobe acrobat document" .xls file would be "Microsoft excel worksheet"

Body:
You can use below VB.net code for getting the file type description. Basically you have to use SHGetFileInfo API to get that information.

Imports System.Runtime.InteropServices

Module Get_File_Type

Sub Main()
    Dim info As New NativeMethods.SHFILEINFO()

    Dim fileName As String = "C:\TEST\TEST.xlsx"
    Dim dwFileAttributes As UInteger = NativeMethods.FILE_ATTRIBUTE.FILE_ATTRIBUTE_NORMAL
    Dim uFlags As UInteger = CUInt(NativeMethods.SHGFI.SHGFI_TYPENAME Or NativeMethods.SHGFI.SHGFI_USEFILEATTRIBUTES)

    NativeMethods.SHGetFileInfo(fileName, dwFileAttributes, info, CUInt(Marshal.SizeOf(info)), uFlags)

    Console.WriteLine(info.szTypeName)
    Console.ReadLine()
End Sub

End Module

NotInheritable Class NativeMethods
    Private Sub New()
    End Sub
    <StructLayout(LayoutKind.Sequential)> _
    Public Structure SHFILEINFO
        Public hIcon As IntPtr
        Public iIcon As Integer
        Public dwAttributes As UInteger
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
        Public szDisplayName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
        Public szTypeName As String
    End Structure

    Public NotInheritable Class FILE_ATTRIBUTE
        Private Sub New()
        End Sub
        Public Const FILE_ATTRIBUTE_NORMAL As UInteger = &H80
    End Class

    Public NotInheritable Class SHGFI
        Private Sub New()
        End Sub
        Public Const SHGFI_TYPENAME As UInteger = &H400
        Public Const SHGFI_USEFILEATTRIBUTES As UInteger = &H10
    End Class

    <DllImport("shell32.dll")> _
    Public Shared Function SHGetFileInfo(pszPath As String, dwFileAttributes As UInteger, ByRef psfi As SHFILEINFO, cbSizeFileInfo As UInteger, uFlags As UInteger) As IntPtr
    End Function
End Class


问:
Is this PHP opendir() very taxing on the server?
```<code>if (is_dir($dir)) {
  if($handle = opendir($dir)) {
        while($file = readdir($handle)) {
        // Break the filename by period; if there's more than one piece, grab the last piece.
        $parts = explode(".", $file);
        if (is_array($parts) && count($parts) > 1) {
            $ext = end($parts);
            // If it's an image that we want, echo the code.
          if ($ext == "png" OR $ext == "PNG" OR $ext == "jpg" OR $ext == "JPG" OR $ext == "jpeg" OR $ext == "JPEG" OR $ext == "gif" OR $ext == "GIF")
            echo "<img src=\"$path/$file\" />";
      }
    }
    closedir($handle);
  }
...
</code>```

I'm using it in Wordpress, and the page loads pretty slowly, but it could also be from having a lot of images on it. I just wanted to make sure I wasn't doing something that was frowned upon for performance reasons.

答:
Get the firefox "quickjava" plugin.

This way you can disable images (by clicking the blue I in the right corner so it turns red) and test the performance of your webpage without any images.

Body:
if (is_dir($dir)) {
  if($handle = opendir($dir)) {
        while($file = readdir($handle)) {
        // Break the filename by period; if there's more than one piece, grab the last piece.
        $parts = explode(".", $file);
        if (is_array($parts) && count($parts) > 1) {
            $ext = end($parts);
            // If it's an image that we want, echo the code.
          if ($ext == "png" OR $ext == "PNG" OR $ext == "jpg" OR $ext == "JPG" OR $ext == "jpeg" OR $ext == "JPEG" OR $ext == "gif" OR $ext == "GIF")
            echo "";
      }
    }
    closedir($handle);
  }
...

I'm using it in Wordpress, and the page loads pretty slowly, but it could also be from having a lot of images on it. I just wanted to make sure I wasn't doing something that was frowned upon for performance reasons.


问:
Non-deterministic* data in header/beginning of PNG files
I noticed that PNG files created by Gimp from the same RPG data are identical except for the very beginning. This image shows a diff of otherwise identical PNG files created with Gimp:

What is this data which changes each time and how is it encoded? Are there tools to decode it? Can you learn something from this information, e.g. can you find out when a PNG file was (probably) created by this information?

I was under the impression that PNG files are created deterministically* and don't store meta data which isn't necessary to decode the image. (Obviously, the last part is not true, either, as Gimp writes its own name into the files but doesn't ask the user (which is does if you export something as a JPEG file).)

 * I use the word "deterministic" here to refer to things and only such which are the same on each execution/export/whatever given the same input. I'd usually use the word "functional" (i.e. like a mathematical function) but I fear this could be misunderstood by people who don't know what "functional" means in mathematics. Obviously, this is different from the usage of this word in information theory.

答:
See the PNG header definition.

tIME stores the time that the image was last changed, so for me it's the same as the timestamp of the file you create.

bKGD gives the default background color. Possibly the bakcgournd color you are using in Gimp, or the color of the transparent pixels.

tEXT with key Comment and value Created with Gimp is just the default comment. You can change the comment for the image in Image>Properties and you can set a default comment in Edit>Preferences>Default Image

When I export the same PNG twice, I only see a change in tIME. In fact I can't get a bKGD item, even when exporting a PNG with transparent pixels. Are you using any specific options when exporting?


问:
"<type> is pointer to interface, not interface" confusion
I have this problem which seems a bit weird to me. Take a look at this snippet of code:

```<code>package coreinterfaces

type FilterInterface interface {
    Filter(s *string) bool
}

type FieldFilter struct {
    Key string
    Val string
}

func (ff *FieldFilter) Filter(s *string) bool {
    // Some code
}

type FilterMapInterface interface {
    AddFilter(f *FilterInterface) uuid.UUID
    RemoveFilter(i uuid.UUID)
    GetFilterByID(i uuid.UUID) *FilterInterface
}

type FilterMap struct {
    mutex   sync.Mutex
    Filters map[uuid.UUID]FilterInterface
}

func (fp *FilterMap) AddFilter(f *FilterInterface) uuid.UUID {
    // Some code
}

func (fp *FilterMap) RemoveFilter(i uuid.UUID) {
    // Some code
}

func (fp *FilterMap) GetFilterByID(i uuid.UUID) *FilterInterface {
    // Some code
}
</code>```

On some other package, I have the following code:

```<code>func DoFilter() {
    fieldfilter := &coreinterfaces.FieldFilter{Key: "app", Val: "152511"}
    filtermap := &coreinterfaces.FilterMap{}
    _ = filtermap.AddFilter(fieldfilter) // <--- Exception is raised here
}
</code>```

The run-time won't accept the line mentioned because

"cannot use fieldfilter (type *coreinterfaces.FieldFilter) as type
*coreinterfaces.FilterInterface in argument to fieldint.AddFilter:
*coreinterfaces.FilterInterface is pointer to interface, not interface"

However, when changing the code to:

```<code>func DoBid() error {
    bs := string(b)
    var ifilterfield coreinterfaces.FilterInterface
    fieldfilter := &coreinterfaces.FieldFilter{Key: "app", Val: "152511"}
    ifilterfield = fieldfilter
    filtermap := &coreinterfaces.FilterMap{}
    _ = filtermap.AddFilter(&ifilterfield)
}
</code>```

Everything is alright and when debugging the application it really seems to include

I'm a bit confused on this topic. When looking at other blog posts and stack overflow threads discussing this exact same issue (for example - This, or
This) the first snippet which raises this exception should work, because both fieldfilter and fieldmap are initialized as pointers to interfaces, rather than value of interfaces. I haven't been able to wrap my head around what actually happens here that I need to change in order for me not to declare a FieldInterface and assign the implementation for that interface. There must be an elegant way to do this.

答:
So you're confusing two concepts here.  A pointer to a struct and a pointer to an interface are not the same.  An interface can store either a struct directly or a pointer to a struct.  In the latter case, you still just use the interface directly, not a pointer to the interface.  For example:

```<code>type Fooer interface {
    Dummy()
}

type Foo struct{}

func (f Foo) Dummy() {}

func main() {
    var f1 Foo
    var f2 *Foo = &Foo{}

    DoFoo(f1)
    DoFoo(f2)
}

func DoFoo(f Fooer) {
    fmt.Printf("[%T] %+v\n", f, f)
}
</code>```

Output:

```<code>[main.Foo] {}
[*main.Foo] &{}
</code>```

https://play.golang.org/p/I7H_pv5H3Xl

In both cases, the f variable in DoFoo is just an interface, not a pointer to an interface.  However, when storing f2, the interface holds a pointer to a Foo structure.

Pointers to interfaces are almost never useful.  In fact, the Go runtime was specifically changed a few versions back to no longer automatically dereference interface pointers (like it does for structure pointers), to discourage their use.  In the overwhelming majority of cases, a pointer to an interface reflects a misunderstanding of how interfaces are supposed to work.

However, there is a limitation on interfaces.  If you pass a structure directly into an interface, only value methods of that type (ie. func (f Foo) Dummy(), not func (f *Foo) Dummy()) can be used to fulfill the interface.  This is because you're storing a copy of the original structure in the interface, so pointer methods would have unexpected effects (ie. unable to alter the original structure).  Thus the default rule of thumb is to store pointers to structures in interfaces, unless there's a compelling reason not to.

Specifically with your code, if you change the AddFilter function signature to:

```<code>func (fp *FilterMap) AddFilter(f FilterInterface) uuid.UUID
</code>```

And the GetFilterByID signature to:

```<code>func (fp *FilterMap) GetFilterByID(i uuid.UUID) FilterInterface
</code>```

Your code will work as expected.  fieldfilter is of type *FieldFilter, which fullfills the FilterInterface interface type, and thus AddFilter will accept it.

Here's a couple of good references for understanding how methods, types, and interfaces work and integrate with each other in Go:

https://medium.com/@agileseeker/go-interfaces-pointers-4d1d98d5c9c6

https://www.goinggo.net/2014/05/methods-interfaces-and-embedded-types.html

https://blog.golang.org/laws-of-reflection

ContentLicense: CC BY-SA 4.0

Body:
I have this problem which seems a bit weird to me. Take a look at this snippet of code:

package coreinterfaces

type FilterInterface interface {
    Filter(s *string) bool
}

type FieldFilter struct {
    Key string
    Val string
}

func (ff *FieldFilter) Filter(s *string) bool {
    // Some code
}

type FilterMapInterface interface {
    AddFilter(f *FilterInterface) uuid.UUID
    RemoveFilter(i uuid.UUID)
    GetFilterByID(i uuid.UUID) *FilterInterface
}

type FilterMap struct {
    mutex   sync.Mutex
    Filters map[uuid.UUID]FilterInterface
}

func (fp *FilterMap) AddFilter(f *FilterInterface) uuid.UUID {
    // Some code
}

func (fp *FilterMap) RemoveFilter(i uuid.UUID) {
    // Some code
}

func (fp *FilterMap) GetFilterByID(i uuid.UUID) *FilterInterface {
    // Some code
}

On some other package, I have the following code:

func DoFilter() {
    fieldfilter := &coreinterfaces.FieldFilter{Key: "app", Val: "152511"}
    filtermap := &coreinterfaces.FilterMap{}
    _ = filtermap.AddFilter(fieldfilter) // <--- Exception is raised here
}

The run-time won't accept the line mentioned because

"cannot use fieldfilter (type *coreinterfaces.FieldFilter) as type
*coreinterfaces.FilterInterface in argument to fieldint.AddFilter:
*coreinterfaces.FilterInterface is pointer to interface, not interface"

However, when changing the code to:

func DoBid() error {
    bs := string(b)
    var ifilterfield coreinterfaces.FilterInterface
    fieldfilter := &coreinterfaces.FieldFilter{Key: "app", Val: "152511"}
    ifilterfield = fieldfilter
    filtermap := &coreinterfaces.FilterMap{}
    _ = filtermap.AddFilter(&ifilterfield)
}

Everything is alright and when debugging the application it really seems to include

I'm a bit confused on this topic. When looking at other blog posts and stack overflow threads discussing this exact same issue (for example - This, or
This) the first snippet which raises this exception should work, because both fieldfilter and fieldmap are initialized as pointers to interfaces, rather than value of interfaces. I haven't been able to wrap my head around what actually happens here that I need to change in order for me not to declare a FieldInterface and assign the implementation for that interface. There must be an elegant way to do this.

Body:
So you're confusing two concepts here.  A pointer to a struct and a pointer to an interface are not the same.  An interface can store either a struct directly or a pointer to a struct.  In the latter case, you still just use the interface directly, not a pointer to the interface.  For example:

type Fooer interface {
    Dummy()
}

type Foo struct{}

func (f Foo) Dummy() {}

func main() {
    var f1 Foo
    var f2 *Foo = &Foo{}

    DoFoo(f1)
    DoFoo(f2)
}

func DoFoo(f Fooer) {
    fmt.Printf("[%T] %+v\n", f, f)
}

Output:

[main.Foo] {}
[*main.Foo] &{}

https://play.golang.org/p/I7H_pv5H3Xl

In both cases, the f variable in DoFoo is just an interface, not a pointer to an interface.  However, when storing f2, the interface holds a pointer to a Foo structure.

Pointers to interfaces are almost never useful.  In fact, the Go runtime was specifically changed a few versions back to no longer automatically dereference interface pointers (like it does for structure pointers), to discourage their use.  In the overwhelming majority of cases, a pointer to an interface reflects a misunderstanding of how interfaces are supposed to work.

However, there is a limitation on interfaces.  If you pass a structure directly into an interface, only value methods of that type (ie. func (f Foo) Dummy(), not func (f *Foo) Dummy()) can be used to fulfill the interface.  This is because you're storing a copy of the original structure in the interface, so pointer methods would have unexpected effects (ie. unable to alter the original structure).  Thus the default rule of thumb is to store pointers to structures in interfaces, unless there's a compelling reason not to.

Specifically with your code, if you change the AddFilter function signature to:

func (fp *FilterMap) AddFilter(f FilterInterface) uuid.UUID

And the GetFilterByID signature to:

func (fp *FilterMap) GetFilterByID(i uuid.UUID) FilterInterface

Your code will work as expected.  fieldfilter is of type *FieldFilter, which fullfills the FilterInterface interface type, and thus AddFilter will accept it.

Here's a couple of good references for understanding how methods, types, and interfaces work and integrate with each other in Go:

https://medium.com/@agileseeker/go-interfaces-pointers-4d1d98d5c9c6

https://www.goinggo.net/2014/05/methods-interfaces-and-embedded-types.html

https://blog.golang.org/laws-of-reflection