问:
Hide FloatingActionButton on scroll of RecyclerView
I want to hide/show FloatingActionButton on scroll of RecyclerView.

My XML layout :

<android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerview_eventlist"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab_createevent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/fab_margin"
                app:layout_anchor="@id/recyclerview_eventlist"
                app:layout_anchorGravity="bottom|right|end"
                app:layout_behavior="com.eventizon.behavior.ScrollAwareFABBehavior"
                android:src="@drawable/ic_edit"
                app:backgroundTint="@color/custom_color_1"
                app:borderWidth="0dp" />
        </android.support.design.widget.CoordinatorLayout>
```

<p>DrawerLayout is the parent layout of this layout.</p>

```    public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {

    private static final String TAG = "ScrollAwareFABBehavior";

    public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
        super();
        Log.e(TAG,"ScrollAwareFABBehavior");
    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout,
            FloatingActionButton child, View target, int dxConsumed,
            int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
        // TODO Auto-generated method stub
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed,
                dxUnconsumed, dyUnconsumed);
        Log.e(TAG,"onNestedScroll called");
        if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
            Log.e(TAG,"child.hide()");
            child.hide();
        } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
            Log.e(TAG,"child.show()");
            child.show();
        }
    }
}
```

Used this layout behaviour for FloatingActionButton.

When I see logcat only constructor is getting called. onNestedScroll() doesn't get called when I scroll the list.

答:
I used this in a RecyclerView.Adapter's onBindViewHolder method to set the bottom margin of the last item in the list to 72dp so that it will scroll up above the floating action button.

This does not require a dummy entry in the list.

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // other binding code goes here.

    if (position + 1 == getItemCount()) {
        // set bottom margin to 72dp.
        setBottomMargin(holder.itemView, (int) (72 * Resources.getSystem().getDisplayMetrics().density));
    } else {
        // reset bottom margin back to zero. (your value may be different)
        setBottomMargin(holder.itemView, 0);
    }
}

public static void setBottomMargin(View view, int bottomMargin) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        params.setMargins(params.leftMargin, params.topMargin, params.rightMargin, bottomMargin);
        view.requestLayout();
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to hide/show FloatingActionButton on scroll of RecyclerView.

My XML layout :

<android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerview_eventlist"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab_createevent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/fab_margin"
                app:layout_anchor="@id/recyclerview_eventlist"
                app:layout_anchorGravity="bottom|right|end"
                app:layout_behavior="com.eventizon.behavior.ScrollAwareFABBehavior"
                android:src="@drawable/ic_edit"
                app:backgroundTint="@color/custom_color_1"
                app:borderWidth="0dp" />
        </android.support.design.widget.CoordinatorLayout>

DrawerLayout is the parent layout of this layout.

    public class ScrollAwareFABBehavior extends FloatingActionButton.Behavior {

    private static final String TAG = "ScrollAwareFABBehavior";

    public ScrollAwareFABBehavior(Context context, AttributeSet attrs) {
        super();
        Log.e(TAG,"ScrollAwareFABBehavior");
    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout,
            FloatingActionButton child, View target, int dxConsumed,
            int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
        // TODO Auto-generated method stub
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed,
                dxUnconsumed, dyUnconsumed);
        Log.e(TAG,"onNestedScroll called");
        if (dyConsumed > 0 && child.getVisibility() == View.VISIBLE) {
            Log.e(TAG,"child.hide()");
            child.hide();
        } else if (dyConsumed < 0 && child.getVisibility() != View.VISIBLE) {
            Log.e(TAG,"child.show()");
            child.show();
        }
    }
}

Used this layout behaviour for FloatingActionButton.

When I see logcat only constructor is getting called. onNestedScroll() doesn't get called when I scroll the list.

Body:
I used this in a RecyclerView.Adapter's onBindViewHolder method to set the bottom margin of the last item in the list to 72dp so that it will scroll up above the floating action button.

This does not require a dummy entry in the list.

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // other binding code goes here.

    if (position + 1 == getItemCount()) {
        // set bottom margin to 72dp.
        setBottomMargin(holder.itemView, (int) (72 * Resources.getSystem().getDisplayMetrics().density));
    } else {
        // reset bottom margin back to zero. (your value may be different)
        setBottomMargin(holder.itemView, 0);
    }
}

public static void setBottomMargin(View view, int bottomMargin) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        params.setMargins(params.leftMargin, params.topMargin, params.rightMargin, bottomMargin);
        view.requestLayout();
    }
}


来源: stackexchange

问:
MySQL Workbench left navigator panel missing on MAC?
I connected to the server in mysql workbench but I see that something has changed? There used to be a navigator panel on the left hand side with all the schemas and the database options like this:

But now on mine it only shows:

I have tried going to the preferences and clicking on all the options but nothing works???

答:
There's a splitter between the Object/Session info and the schema tree/management part. In your case it's moved up all the way, so you only see the lower part. Drag the marked line down to make the upper part visible:

Update

Starting with MySQL Workbench 8.0.14 the splitter has been changed to show in a different style which makes it much more easy to recognize it:

ContentLicense: CC BY-SA 3.0


问:
trigger build for git repo B for a commit/pull request done on Git repo A using jenkins pipeline
My objective is to trigger a build on Git repo A whenever there is commit/Pull request done on Git Repo B. Git repo has all the pipeline code as separate groovy code and Git Repo b has the application Code done by dev team. I would like to test the case where a commit done in pipeline code is triggering the build in application code. How can I acheive this using Jenkins 2 with pipeline? Any thoughts or approach how it is done is greatly appreciated.

Here is my jenkinsfile in Git repo A.

```<code>branches {
    masterBranch = 'master'

}

integration {

pullRequest {
    version = gradle {
        goals = 'clean build'
        gradlePath = '/gradle-4.1/bin/gradle'
    }

}

master {
    version = gradle {
        goals = 'clean build'
        gradlePath = '/gradle-4.1/bin/gradle'
    }

}
</code>```

}

答:
So you need to create 2 jobs

git repo a : with development code

git repo b : with option "Build when a change is pushed to GitHub" in
build triggers job config.

then  use "Parameterized Trigger Plugin" to build required job( repo A ) based on the previous build status.

ref :
https://wiki.jenkins.io/display/JENKINS/Parameterized+Trigger+Plugin

Body:
My objective is to trigger a build on Git repo A whenever there is commit/Pull request done on Git Repo B. Git repo has all the pipeline code as separate groovy code and Git Repo b has the application Code done by dev team. I would like to test the case where a commit done in pipeline code is triggering the build in application code. How can I acheive this using Jenkins 2 with pipeline? Any thoughts or approach how it is done is greatly appreciated.

Here is my jenkinsfile in Git repo A.

branches {
    masterBranch = 'master'

}

integration {

pullRequest {
    version = gradle {
        goals = 'clean build'
        gradlePath = '/gradle-4.1/bin/gradle'
    }

}

master {
    version = gradle {
        goals = 'clean build'
        gradlePath = '/gradle-4.1/bin/gradle'
    }

}

}


问:
MYSQL select same column name as alias as Number not working
I have create query something like bellow :

```<code>SELECT col_1 as "0", Col_2 as "1" FROM table
</code>```

It is working when run in phpmyadmin but not work when run through php.
But when change as "zero" as "one" its working fine.

Any solution or suggestion.

I am using wordpress

```<code>$results = $wpdb->get_results(
                'SELECT t.id,qrnumber ,
                tu.display_name,if(t.status=0,"---","Used") as "3"
                FROM '.$table.' t
                LEFT JOIN '.$table_wp.' tu ON tu.ID=t.user_id', ARRAY_A
            );
</code>```

Thanks

答:
You are missing a comma</p>

```<code>SELECT col_1 as "0", Col_2 as "1" FROM table
</code>```

Body:
I have create query something like bellow :

SELECT col_1 as "0", Col_2 as "1" FROM table

It is working when run in phpmyadmin but not work when run through php.
But when change as "zero" as "one" its working fine.

Any solution or suggestion.

I am using wordpress

$results = $wpdb->get_results(
                'SELECT t.id,qrnumber ,
                tu.display_name,if(t.status=0,"---","Used") as "3"
                FROM '.$table.' t
                LEFT JOIN '.$table_wp.' tu ON tu.ID=t.user_id', ARRAY_A
            );

Thanks

Body:
You are missing a comma

SELECT col_1 as "0", Col_2 as "1" FROM table


问:
Switch statement doesn't work with some variables
I want to make the Angular2 Pipe which returns different values according to passed variable. The variable device.display can be of different type (object or string) and takes only two values null and "dataTime".

Component part:

```<code><div class="col col-2">{{values[variable.id] | display: device.display}}</div>
</code>```

Pipe:

```<code>Pipe
import { Pipe } from '@angular/core';
@Pipe({
    name: 'display'
})
export class DisplayPipe {
    transform(value: any, display: string): string {
        display = String(display);
        switch (display) {
            case 'dateTime': {
                value = value * 60;
            }
            case 'null': {
                value = value;
           }
        default: value = 'abc';
        }
    return value;
    }
}
</code>```

I'm sure that after parsing variable to String it is equal to "null" or "dateTime". I checked it with console.log.

The problem is the switch statement always returns default value:"abc".

答: If you miss the break statement in Javascript fall-through condition will happen so default statement got executed and value is always "abc"</p>

Body:
I want to make the Angular2 Pipe which returns different values according to passed variable. The variable device.display can be of different type (object or string) and takes only two values null and "dataTime".

Component part:

{{values[variable.id] | display: device.display}}

Pipe:

Pipe
import { Pipe } from '@angular/core';
@Pipe({
    name: 'display'
})
export class DisplayPipe {
    transform(value: any, display: string): string {
        display = String(display);
        switch (display) {
            case 'dateTime': {
                value = value * 60;
            }
            case 'null': {
                value = value;
           }
        default: value = 'abc';
        }
    return value;
    }
}

I'm sure that after parsing variable to String it is equal to "null" or "dateTime". I checked it with console.log.

The problem is the switch statement always returns default value:"abc".


问:
Failed to execute goal on project spark-core_2.11
,
Spark code compile operation fails on few machines whereas the same source code passes on few other machines.
Please check the error on Centos (4.10.12-1.el7.elrepo.x86_64)
./build/mvn -X -DskipTests -Dscala.lib.directory=/usr/share/scala -pl core compile

```<code>INFO] Building Spark Project Core 2.2.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] The POM for org.apache.spark:spark-launcher_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-network-common_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-network-shuffle_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-unsafe_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-tags_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-tags_2.11:jar:tests:2.2.2-SNAPSHOT is missing, no dependency information available
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.804 s
[INFO] Finished at: 2017-12-04T23:18:58-08:00
[INFO] Final Memory: 43M/1963M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project spark-core_2.11: Could not resolve dependencies for project org.apache.spark:spark-core_2.11:jar:2.2.2-SNAPSHOT: The following artifacts could not be resolved: org.apache.spark:spark-launcher_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-network-common_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-network-shuffle_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-unsafe_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-tags_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-tags_2.11:jar:tests:2.2.2-SNAPSHOT: Failure to find org.apache.spark:spark-launcher_2.11:jar:2.2.2-SNAPSHOT in http://artifact.eng.stellus.in:8081/artifactory/libs-snapshot was cached in the local repository, resolution will not be reattempted until the update interval of snapshots has elapsed or updates are forced -> [Help 1]
</code>```

Note: The same source code passes on another CentOS machine(3.10.0-514.el7.x86_64)
./build/mvn -DskipTests -Dscala.lib.directory=/usr/share/scala -pl core compile

```<code>[INFO] — maven-compiler-plugin:3.7.0:compile (default-compile) @ spark-core_2.11 —
[INFO] Not compiling main sources
[INFO]
[INFO] — scala-maven-plugin:3.2.2:compile (scala-compile-first) @ spark-core_2.11 —
[INFO] Using zinc server for incremental compilation
[info] Compile success at Dec 4, 2017 11:17:34 PM [0.331s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.663 s
[INFO] Finished at: 2017-12-04T23:17:34-08:00
[INFO] Final Memory: 52M/1297M
[INFO] ------------------------------------------------------------------------
</code>```

答:
If the build works only in specific machine it means that you already have the missing dependency on your .m2 local repository.
If you will remove all your directories under .m2 (on the centos machine) the build will fail.

You should add all your missing dependencies.

```<code>[WARNING] The POM for org.apache.spark:spark-launcher_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-network-common_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-network-shuffle_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-unsafe_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-tags_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-tags_2.11:jar:tests:2.2.2-SNAPSHOT is missing, no dependency information available
</code>```

Body:
,
Spark code compile operation fails on few machines whereas the same source code passes on few other machines.
Please check the error on Centos (4.10.12-1.el7.elrepo.x86_64)
./build/mvn -X -DskipTests -Dscala.lib.directory=/usr/share/scala -pl core compile

INFO] Building Spark Project Core 2.2.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] The POM for org.apache.spark:spark-launcher_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-network-common_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-network-shuffle_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-unsafe_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-tags_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-tags_2.11:jar:tests:2.2.2-SNAPSHOT is missing, no dependency information available
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.804 s
[INFO] Finished at: 2017-12-04T23:18:58-08:00
[INFO] Final Memory: 43M/1963M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal on project spark-core_2.11: Could not resolve dependencies for project org.apache.spark:spark-core_2.11:jar:2.2.2-SNAPSHOT: The following artifacts could not be resolved: org.apache.spark:spark-launcher_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-network-common_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-network-shuffle_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-unsafe_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-tags_2.11:jar:2.2.2-SNAPSHOT, org.apache.spark:spark-tags_2.11:jar:tests:2.2.2-SNAPSHOT: Failure to find org.apache.spark:spark-launcher_2.11:jar:2.2.2-SNAPSHOT in http://artifact.eng.stellus.in:8081/artifactory/libs-snapshot was cached in the local repository, resolution will not be reattempted until the update interval of snapshots has elapsed or updates are forced -> [Help 1]

Note: The same source code passes on another CentOS machine(3.10.0-514.el7.x86_64)
./build/mvn -DskipTests -Dscala.lib.directory=/usr/share/scala -pl core compile

[INFO] — maven-compiler-plugin:3.7.0:compile (default-compile) @ spark-core_2.11 —
[INFO] Not compiling main sources
[INFO]
[INFO] — scala-maven-plugin:3.2.2:compile (scala-compile-first) @ spark-core_2.11 —
[INFO] Using zinc server for incremental compilation
[info] Compile success at Dec 4, 2017 11:17:34 PM [0.331s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.663 s
[INFO] Finished at: 2017-12-04T23:17:34-08:00
[INFO] Final Memory: 52M/1297M
[INFO] ------------------------------------------------------------------------

Body:
If the build works only in specific machine it means that you already have the missing dependency on your .m2 local repository.
If you will remove all your directories under .m2 (on the centos machine) the build will fail.

You should add all your missing dependencies.

[WARNING] The POM for org.apache.spark:spark-launcher_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-network-common_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-network-shuffle_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-unsafe_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-tags_2.11:jar:2.2.2-SNAPSHOT is missing, no dependency information available
[WARNING] The POM for org.apache.spark:spark-tags_2.11:jar:tests:2.2.2-SNAPSHOT is missing, no dependency information available


问:
java h2 in-memory database error: Table not found
I tried googling around, but the solution to almost all this kind of questions was to add ;DB_CLOSE_DELAY=-1, however it does not solve anything for me.

Here is my test class

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Main.class})
public class Testas {

    @Autowired
    @Qualifier("managerImplementation")
    private ClassifierManager manager;

    @Test
    public void testManager(){
        ClassifierGroupEntity cge = new ClassifierGroupEntity();
        manager.saveClassifierGroup(cge);
    }
}
</code>```

Manager class

```<code>@Service("managerImplementation")
public class ClassifierManagerImpl implements ClassifierManager{

    @Autowired
    private ClassifierGroupEntityRepository groupEntityRepository;

    @Autowired
    private ClassifierEntityRepository entityRepository;

    @Autowired
    private ClassifierValueEntityRepository valueEntityRepository;

    @Override
    public ClassifierGroupEntity getClassifierGroup(long id) {
        return groupEntityRepository.findOne(id);
    }

    @Override
    public ClassifierGroupEntity getClassifierGroup(String code) {
        return groupEntityRepository.findByCode(code);
    }

    @Override
    public ClassifierGroupEntity saveClassifierGroup(ClassifierGroupEntity entity) {
        return groupEntityRepository.save(entity);
    }

    @Override
    public void deleteClassifierGroup(long id) {
        groupEntityRepository.delete(id);
    }

    @Override
    public ClassifierEntity getClassifier(long id) {
        return entityRepository.findOne(id);
    }

    @Override
    public ClassifierEntity getClassifier(String code) {
        return entityRepository.findByCode(code);
    }

    @Override
    public ClassifierEntity saveClassifier(ClassifierEntity entity) {
        return entityRepository.save(entity);
    }

    @Override
    public void deleteClassifier(long id) {
        entityRepository.delete(id);
    }

    @Override
    public ClassifierValueEntity getClassifierValue(long id) {
        return valueEntityRepository.findOne(id);
    }

    @Override
    public ClassifierValue getClassifierValue(String classifiedCode, String valueCode) {
        return null;
    }

    @Override
    public ClassifierValueEntity saveClassifierValue(ClassifierValueEntity entity) {
        return valueEntityRepository.save(entity);
    }

    @Override
    public void deleteClassifierValue(long id) {
        valueEntityRepository.delete(id);
    }

}
</code>```

And finally properties file

```<code>spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.user=sa
spring.datasource.password=
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
</code>```

Launching the test throws me

```<code>org.h2.jdbc.JdbcSQLException: Table "CLASSIFIER_GROUP_ENTITY" not found; SQL statement:
insert into classifier_group_entity (id, code, modified_details, modified_time, modified_user_id, order, revision, valid_details, valid_from, valid_till, parent_id) values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [42102-191]
</code>```

I don't know if I should provide anything else, please tell me if I do. I appreciate your help in advance.

答: I encountered the same problem while I was writing unit tests for my own application. After many tries, I was not able to get my application test cases running. I was running on version 1.4.191 and then I upgraded to 1.4.196 and it started working. </p>

Body:
I tried googling around, but the solution to almost all this kind of questions was to add ;DB_CLOSE_DELAY=-1, however it does not solve anything for me.

Here is my test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Main.class})
public class Testas {

    @Autowired
    @Qualifier("managerImplementation")
    private ClassifierManager manager;

    @Test
    public void testManager(){
        ClassifierGroupEntity cge = new ClassifierGroupEntity();
        manager.saveClassifierGroup(cge);
    }
}

Manager class

@Service("managerImplementation")
public class ClassifierManagerImpl implements ClassifierManager{

    @Autowired
    private ClassifierGroupEntityRepository groupEntityRepository;

    @Autowired
    private ClassifierEntityRepository entityRepository;

    @Autowired
    private ClassifierValueEntityRepository valueEntityRepository;

    @Override
    public ClassifierGroupEntity getClassifierGroup(long id) {
        return groupEntityRepository.findOne(id);
    }

    @Override
    public ClassifierGroupEntity getClassifierGroup(String code) {
        return groupEntityRepository.findByCode(code);
    }

    @Override
    public ClassifierGroupEntity saveClassifierGroup(ClassifierGroupEntity entity) {
        return groupEntityRepository.save(entity);
    }

    @Override
    public void deleteClassifierGroup(long id) {
        groupEntityRepository.delete(id);
    }

    @Override
    public ClassifierEntity getClassifier(long id) {
        return entityRepository.findOne(id);
    }

    @Override
    public ClassifierEntity getClassifier(String code) {
        return entityRepository.findByCode(code);
    }

    @Override
    public ClassifierEntity saveClassifier(ClassifierEntity entity) {
        return entityRepository.save(entity);
    }

    @Override
    public void deleteClassifier(long id) {
        entityRepository.delete(id);
    }

    @Override
    public ClassifierValueEntity getClassifierValue(long id) {
        return valueEntityRepository.findOne(id);
    }

    @Override
    public ClassifierValue getClassifierValue(String classifiedCode, String valueCode) {
        return null;
    }

    @Override
    public ClassifierValueEntity saveClassifierValue(ClassifierValueEntity entity) {
        return valueEntityRepository.save(entity);
    }

    @Override
    public void deleteClassifierValue(long id) {
        valueEntityRepository.delete(id);
    }

}

And finally properties file

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.user=sa
spring.datasource.password=
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1

Launching the test throws me

org.h2.jdbc.JdbcSQLException: Table "CLASSIFIER_GROUP_ENTITY" not found; SQL statement:
insert into classifier_group_entity (id, code, modified_details, modified_time, modified_user_id, order, revision, valid_details, valid_from, valid_till, parent_id) values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [42102-191]

I don't know if I should provide anything else, please tell me if I do. I appreciate your help in advance.


问:
Sql 2008 r2 - Datename
This is copied ditto from example given in Sql2008 R2 doc - Syntax: DATENAME (datepart ,date )

```<code>SELECT DATENAME(datepart,'2007-10-30 12:15:32.1234567 +05:10')
</code>```

And it throws

```<code>Msg 155, Level 15, State 1, Line 4
'datepart' is not a recognized datename option.
</code>```

What is wrong here ? Where is Bill...

答:
What is wrong here?

This is not supposed to be copied and run.

You should substitute datepart with any of the valid options given under the example your copied (year, quarter, month etc).

Where is Bill...

http://en.wikipedia.org/wiki/Bill_Gates%27_house

ContentLicense: CC BY-SA 2.5

Title: Sql 2008 r2 - Datename

Body:
This is copied ditto from example given in Sql2008 R2 doc - Syntax: DATENAME (datepart ,date )

SELECT DATENAME(datepart,'2007-10-30 12:15:32.1234567 +05:10')

And it throws

Msg 155, Level 15, State 1, Line 4
'datepart' is not a recognized datename option.

What is wrong here ? Where is Bill...


问:
MY_Model jamierumbelow
Guys

I have been using this model in my project.But ,nowadays i m facing with performance noises due to repeated query by with method and of course the need to make and Inner Join with Where clause on related objects  and how could i ever does that?

I have Profile ,Media,Product table related.
When i want to get all products with profile , media and details i use below code.And , its working except the with createsrepeated select statements.

```<code>$all_products = $this->with('medias')->with('profile')->get_all();
</code>```

Now , i want all products their profile is verified.

```<code>select * from products
inner join profile as p on p.id = product.profile_id
inner join media as m on m.product_id=p.product_id
where profile.is_verfied='true';
</code>```

How can i ever do this using my MY_MODEL way or with little modifications.

答:
I too use @Jamie Rumbelow's Base Model, with few modifications (one or two). When It comes to joining, it has a wonderful triggering method that you can use:  before_get observer. In your case, simply add an observer where you can join from needed tables like so:

In your model constructor:

```<code>public function __constrcutor()
{
    array_unshift(
        $this->before_get,
        'join_from_profile_and_media'
    );
    // Then
    parent::__construct();
}
</code>```

And the observer would be:

```<code>protected function join_from_profile_and_media()
{
    $this->db->join('profile', 'profile.id = product.profile_id');
    $this->db->join('media', 'media.product_id = profile.product_id');
}
</code>```

And now whenever you call get(), get_many(), get_by() or get_many_by() all tables are joint.

Title: MY_Model jamierumbelow

Body:
Guys

I have been using this model in my project.But ,nowadays i m facing with performance noises due to repeated query by with method and of course the need to make and Inner Join with Where clause on related objects  and how could i ever does that?

I have Profile ,Media,Product table related.
When i want to get all products with profile , media and details i use below code.And , its working except the with createsrepeated select statements.

$all_products = $this->with('medias')->with('profile')->get_all();

Now , i want all products their profile is verified.

select * from products
inner join profile as p on p.id = product.profile_id
inner join media as m on m.product_id=p.product_id
where profile.is_verfied='true';

How can i ever do this using my MY_MODEL way or with little modifications.

Body:
I too use @Jamie Rumbelow's Base Model, with few modifications (one or two). When It comes to joining, it has a wonderful triggering method that you can use:  before_get observer. In your case, simply add an observer where you can join from needed tables like so:

In your model constructor:

public function __constrcutor()
{
    array_unshift(
        $this->before_get,
        'join_from_profile_and_media'
    );
    // Then
    parent::__construct();
}

And the observer would be:

protected function join_from_profile_and_media()
{
    $this->db->join('profile', 'profile.id = product.profile_id');
    $this->db->join('media', 'media.product_id = profile.product_id');
}

And now whenever you call get(), get_many(), get_by() or get_many_by() all tables are joint.


问:
how to change json structure in javascript?
I have a json Object like following.

```<code>{987: "sqa", 988: "Squad"}
</code>```

I need to change the structure like following

```<code>[{id:987, value:'sqa'}, {id:988, value:'Squad'}]
</code>```

How to do this with Javascript?

答:
You have written invalid JSON in your question, but I assume you want it as a JavaScript object.

Something like this perhaps.

var oldObj = {
    987: "sqa",
    988: "Squad"
}

var newArray = [];

for (let k in oldObj) {
    newArray.push({'id': k, 'value': oldObj[k]});
}

console.log(newArray);```

Body:
I have a json Object like following.

{987: "sqa", 988: "Squad"}

I need to change the structure like following

[{id:987, value:'sqa'}, {id:988, value:'Squad'}]

How to do this with Javascript?


问:
Orion Context Broker and CKAN professional hosting service?
Is there any Orion Context Broker and CKAN professional hosting service? How can I get them on cloud and access with a good scalability as I'm going to use these applications in my real project?</p>

答:
You have two options:

Host those components in a mainstream cloud platform, AWS, Azure, etc.

Use a FIWARE Cloud platform. You can find existing providers at

http://marketplace.fiware.org/pages/platforms


问:
How can I get Month Name from Calendar?
Is there a oneliner to get the name of the month when we know:

int monthNumber  = calendar.get(Calendar.MONTH)
```

Or what is the easiest way?

答:
This code has language support.
I had used them in Android App.</p>

```<code>String[] mons = new DateFormatSymbols().getShortMonths();//Jan,Feb,Mar,...

String[] months = new DateFormatSymbols().getMonths();//January,Februaty,March,...
</code>```

Title: How can I get Month Name from Calendar?

Body:
Is there a oneliner to get the name of the month when we know:

int monthNumber  = calendar.get(Calendar.MONTH)

Or what is the easiest way?

Body:
This code has language support.
I had used them in Android App.

String[] mons = new DateFormatSymbols().getShortMonths();//Jan,Feb,Mar,...

String[] months = new DateFormatSymbols().getMonths();//January,Februaty,March,...


问:
Have Excel Row Saved in SQL Server Column (XML data type). How Do I update a particular Cell value?
I have a row of excel data (i.e. several cells from an excel sheet) saved into a SQL Server table, in a column that is of datatype XML.

I need to update the value, in a particular cell, in this data saved in the XML column, with a new value that is stored in another column in the same table.
How do I do that?

I am not able to even select the cell propery using the XMLColumnName.Query() method in T-SQL of SQL Server 2005.

Pasting a sample table, with sample rows here, so you can experiment and let me know if you were able to figure this out! Thank you!!

-Shiva

```<code>    -- reference article for XML data manipulation
-- http://msdn.microsoft.com/en-us/library/ms345117(v=sql.90).aspx#sql2k5xml_topic3

  -- create test table for xml data
CREATE TABLE testdocs (pk INT PRIMARY KEY, xCol XML not null)

  -- insert 1 row of test data
insert into testdocs values(1,'<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://www.w3.org/TR/REC-html40">
  <Worksheet ss:Name="TestSheet">
    <Table ss:ExpandedColumnCount="509" ss:ExpandedRowCount="1" ss:StyleID="s191">
      <Column ss:StyleID="s1" ss:AutoFitWidth="0" ss:Width="55" />
      <Column ss:StyleID="s2" ss:AutoFitWidth="0" ss:Width="55" />
      <Row>
        <Cell>
          <Data ss:Type="String">TestValue1</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">TestValue2</Data>
        </Cell>
      </Row>
    </Table>
  </Worksheet>
</Workbook>')

  -- select records, and inspect the XML in SSMS
select * from testdocs

-- want to replace / update "TestValue2" in the XML for the 1s rows, to "New TestValue2"
-- location in XML hierarchy is as follows

    /Workbook/Worksheet/Table/Row/Cell/Data

-- how do i do that ?
</code>```

答:
You need to get the XML namespaces properly:

```<code>with xmlnamespaces (
    DEFAULT 'urn:schemas-microsoft-com:office:spreadsheet'
    , 'urn:schemas-microsoft-com:office:office' as o
    , 'urn:schemas-microsoft-com:office:excel' as x
    , 'urn:schemas-microsoft-com:office:spreadsheet' as ss
    , 'http://www.w3.org/TR/REC-html40' as html)
select xCol.value ('(/Workbook/Worksheet/Table/Row/Cell/Data)[1]','varchar(100)') as Data
from testdocs
</code>```

Update:

```<code>with xmlnamespaces (
    DEFAULT 'urn:schemas-microsoft-com:office:spreadsheet'
    , 'urn:schemas-microsoft-com:office:office' as o
    , 'urn:schemas-microsoft-com:office:excel' as x
    , 'urn:schemas-microsoft-com:office:spreadsheet' as ss
    , 'http://www.w3.org/TR/REC-html40' as html)
update testdocs
set xCol.modify (' replace value of (/Workbook/Worksheet/Table/Row/Cell/Data/text())[1]
    with "ReplacedValue1"');

select  * from testdocs
</code>```

Body:
I have a row of excel data (i.e. several cells from an excel sheet) saved into a SQL Server table, in a column that is of datatype XML.

I need to update the value, in a particular cell, in this data saved in the XML column, with a new value that is stored in another column in the same table.
How do I do that?

I am not able to even select the cell propery using the XMLColumnName.Query() method in T-SQL of SQL Server 2005.

Pasting a sample table, with sample rows here, so you can experiment and let me know if you were able to figure this out! Thank you!!

-Shiva

    -- reference article for XML data manipulation
-- http://msdn.microsoft.com/en-us/library/ms345117(v=sql.90).aspx#sql2k5xml_topic3

  -- create test table for xml data
CREATE TABLE testdocs (pk INT PRIMARY KEY, xCol XML not null)

  -- insert 1 row of test data
insert into testdocs values(1,'<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  xmlns:html="http://www.w3.org/TR/REC-html40">
  <Worksheet ss:Name="TestSheet">

      <Column ss:StyleID="s1" ss:AutoFitWidth="0" ss:Width="55" />
      <Column ss:StyleID="s2" ss:AutoFitWidth="0" ss:Width="55" />
      <Row>
        <Cell>
          <Data ss:Type="String">TestValue1</Data>
        </Cell>
        <Cell>
          <Data ss:Type="String">TestValue2</Data>
        </Cell>
      </Row>

  </Worksheet>
</Workbook>')

  -- select records, and inspect the XML in SSMS
select * from testdocs

-- want to replace / update "TestValue2" in the XML for the 1s rows, to "New TestValue2"
-- location in XML hierarchy is as follows

    /Workbook/Worksheet/Table/Row/Cell/Data

-- how do i do that ?

Body:
You need to get the XML namespaces properly:

with xmlnamespaces (
    DEFAULT 'urn:schemas-microsoft-com:office:spreadsheet'
    , 'urn:schemas-microsoft-com:office:office' as o
    , 'urn:schemas-microsoft-com:office:excel' as x
    , 'urn:schemas-microsoft-com:office:spreadsheet' as ss
    , 'http://www.w3.org/TR/REC-html40' as html)
select xCol.value ('(/Workbook/Worksheet/Table/Row/Cell/Data)[1]','varchar(100)') as Data
from testdocs

Update:

with xmlnamespaces (
    DEFAULT 'urn:schemas-microsoft-com:office:spreadsheet'
    , 'urn:schemas-microsoft-com:office:office' as o
    , 'urn:schemas-microsoft-com:office:excel' as x
    , 'urn:schemas-microsoft-com:office:spreadsheet' as ss
    , 'http://www.w3.org/TR/REC-html40' as html)
update testdocs
set xCol.modify (' replace value of (/Workbook/Worksheet/Table/Row/Cell/Data/text())[1]
    with "ReplacedValue1"');

select  * from testdocs


问:
Confused about the depth-first-search result when using Golang
I tried to solve the 'Combination Sum' on leetcode, and the result is wrong when using test case:

[7,3,2] 18

I used C++ with the same logic and passed, but when using Golang, my result is:

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,7,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

and the correct one should be

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

the code is shown below:

```<code>import "sort"
func combinationSum(candidates []int, target int) [][]int {
    result := make([][]int, 0, 0)
    resultp := &result
    sort.Ints(candidates)
    helper(candidates, 0, target, make([]int, 0, 0), resultp, len(candidates))
    return *resultp
}

func helper(nums []int, index int, target int, list []int, resultp *[][]int, length int) {
    if target == 0 {
        *resultp = append(*resultp, list)
        return
    }
    for i := index; i < length; i++ {
        if i != index && nums[i] == nums[i - 1] {
            continue
        }
        if (nums[i] > target) {
            break
        }
        helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)
    }
}
</code>```

Can anyone tell me why the result is incorrect, I am just confused about the [2,2,2,2,2,7,3,3] in my answer, why the 7 is before the 3 since the array has been sorted? Or anyone can tell me what mistake I have made in my code

答:
append function may or may not modify the underlying array that your slice refers to. So you are not creating a completely new list when using append. I changed helper to match your desired behavior.

```<code>for i := index; i < length; i++ {
    if i != index && nums[i] == nums[i - 1] {
        continue
    }
    if nums[i] > target {
        break
    }
    var newList []int
    newList = append(newList, list...)
    newList = append(newList, nums[i])
    helper(nums, i, target - nums[i], newList, resultp, length)
}
</code>```

Body:
I tried to solve the 'Combination Sum' on leetcode, and the result is wrong when using test case:

[7,3,2] 18

I used C++ with the same logic and passed, but when using Golang, my result is:

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,7,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

and the correct one should be

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

the code is shown below:

import "sort"
func combinationSum(candidates []int, target int) [][]int {
    result := make([][]int, 0, 0)
    resultp := &result
    sort.Ints(candidates)
    helper(candidates, 0, target, make([]int, 0, 0), resultp, len(candidates))
    return *resultp
}

func helper(nums []int, index int, target int, list []int, resultp *[][]int, length int) {
    if target == 0 {
        *resultp = append(*resultp, list)
        return
    }
    for i := index; i < length; i++ {
        if i != index && nums[i] == nums[i - 1] {
            continue
        }
        if (nums[i] > target) {
            break
        }
        helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)
    }
}

Can anyone tell me why the result is incorrect, I am just confused about the [2,2,2,2,2,7,3,3] in my answer, why the 7 is before the 3 since the array has been sorted? Or anyone can tell me what mistake I have made in my code

Body:
append function may or may not modify the underlying array that your slice refers to. So you are not creating a completely new list when using append. I changed helper to match your desired behavior.

for i := index; i < length; i++ {
    if i != index && nums[i] == nums[i - 1] {
        continue
    }
    if nums[i] > target {
        break
    }
    var newList []int
    newList = append(newList, list...)
    newList = append(newList, nums[i])
    helper(nums, i, target - nums[i], newList, resultp, length)
}


问:
Image is not visible in android project with XAML forms - Xamarin even though provided solutions applied
I tried solutions from the following links but none worked.

where-to-put-images-for-xamarin-froms-application

developer.xamarin.com/guides/xamarin-forms/user-interface/images/#Local_Images

image-not-showing-in-xamarin-forms-app.html

I used below syntax

```<code><Image Source="lock.png" HeightRequest="20" WidthRequest="20" HorizontalOptions="Center" VerticalOptions="Center"  Grid.Row="0" Grid.Column="0"></Image>
</code>```

Here is the image for where i've kept image

No image displays

Edit

These are the only things in my XAML page.

答:
In my case the issue was of assembly.
when trying all the possible solutions like

1.) Changing Build Action

2.) Adding Image to all the folders within Resources

3.) Naming Convention should not include - in File/Image Name.

4.) Changing Background Color

I also got one solution while searching for embedded Images that assembly was missing here.

This change worked for me in using Local Images.
Got that solution from this link

Body:
I tried solutions from the following links but none worked.

where-to-put-images-for-xamarin-froms-application

developer.xamarin.com/guides/xamarin-forms/user-interface/images/#Local_Images

image-not-showing-in-xamarin-forms-app.html

I used below syntax

<Image Source="lock.png" HeightRequest="20" WidthRequest="20" HorizontalOptions="Center" VerticalOptions="Center"  Grid.Row="0" Grid.Column="0"></Image>

Here is the image for where i've kept image

No image displays

Edit

These are the only things in my XAML page.


问:
Getting data from three tables using join mysql
I have three tables in my database

1.Users (id,username)

2.Stories (id,user_id,content) here user_id is forigen key refers Users table id

3.Comments (id,user_id,story_id,comment)   here user_id is forigen key refers Users table id and story_id is forigen key refers Stories table id

I need to get list of stories from  Stories table with total number of comments on that post and username of the storie author

Here is my query for that

```<code>SELECT stories.id,stories.content,COUNT(stories.id) as totalcomment
FROM stories
 JOIN comments
ON stories.id=comments.story_id GROUP BY stories.id
</code>```

I will get the total comment of the each post ,but can't fetch the username of the storie author (ie username from Users table)

答:
```<code>SELECT s.id,s.content,COUNT(c.story_id) as totalcomment, u.username
FROM stories s LEFT JOIN comments c ON (s.id=c.story_id)
LEFT JOIN users u ON (s.user_id = u.id)
GROUP BY s.id
</code>```

Body:
I have three tables in my database

1.Users (id,username)

2.Stories (id,user_id,content) here user_id is forigen key refers Users table id

3.Comments (id,user_id,story_id,comment)   here user_id is forigen key refers Users table id and story_id is forigen key refers Stories table id

I need to get list of stories from  Stories table with total number of comments on that post and username of the storie author

Here is my query for that

SELECT stories.id,stories.content,COUNT(stories.id) as totalcomment
FROM stories
 JOIN comments
ON stories.id=comments.story_id GROUP BY stories.id

I will get the total comment of the each post ,but can't fetch the username of the storie author (ie username from Users table)


问:
How to put out apk file uses gradle v4.1 in Android Studio 3.0+?
I want to set APK filePath in gradle that version is v4.1,but I can set its name and not set file path. What do I do?</p>

```<code>applicationVariants.all {
    variant->
        variant.outputs.all {
            output->
                def outputFile = output.outputFile
                if (outputFile != null && outputFile.name.endsWith('.apk')) {
                    outputFileName = "${defaultConfig.applicationId}_${variant.productFlavors[0].name}_${defaultConfig.versionName}_${releaseTime()}.apk"
                }
        }
}
</code>```

答:
From this migration guide,

Using the Variant API to manipulate variant outputs is broken with the
  new plugin. It still works for simple tasks, such as changing the APK
  name during build time.

However, more complicated tasks that involve accessing outputFile
  objects no longer work. That's because variant-specific tasks are no
  longer created during the configuration stage.

What you already achieved is the ONLY thing that we can do with APK at build time.

You can workaround by moving the files to another location after build completion using Gradle copy task:

```<code>task copySupportFiles(type: Copy){
    from 'src/main/support'
    into 'build/outputs/apk'
    include '**/*.dat'
    include '**/.txt'
}

assembleDebug {}.doLast{
    tasks.copySupportFiles.execute()
}
</code>```

Body:
I want to set APK filePath in gradle that version is v4.1,but I can set its name and not set file path. What do I do?

applicationVariants.all {
    variant->
        variant.outputs.all {
            output->
                def outputFile = output.outputFile
                if (outputFile != null && outputFile.name.endsWith('.apk')) {
                    outputFileName = "${defaultConfig.applicationId}_${variant.productFlavors[0].name}_${defaultConfig.versionName}_${releaseTime()}.apk"
                }
        }
}

Body:
From this migration guide,

Using the Variant API to manipulate variant outputs is broken with the
  new plugin. It still works for simple tasks, such as changing the APK
  name during build time.

However, more complicated tasks that involve accessing outputFile
  objects no longer work. That's because variant-specific tasks are no
  longer created during the configuration stage.

What you already achieved is the ONLY thing that we can do with APK at build time.

You can workaround by moving the files to another location after build completion using Gradle copy task:

task copySupportFiles(type: Copy){
    from 'src/main/support'
    into 'build/outputs/apk'
    include '**/*.dat'
    include '**/.txt'
}

assembleDebug {}.doLast{
    tasks.copySupportFiles.execute()
}


问:
How to replace an entire table with pictures?
This is my table, of course with some text in it, and I want on a button click to hide it, and show some images. I also want to reverse the action on the same button click. How can I do that?

```

答:
Please have a look at this code sample. I have used jQuery 2.1.1

$(function() {
  $('#toggler').click(function() {
    $('#Table').toggle();
    $('#imageblock').toggle();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="aspect">
<div style="display:none;" id="imageblock">
<img src="http://lorempixel.com/400/200/" />
</div>
<table id="Table">
<tr>
    <th id="textul" > </th>
    <th id="textul4"> </th>
    </tr>
    <tr>
  <td id="testul2and3" style="vertical-align:top"> </td>
    <td style="vertical-align:top" id="textul6">
            <p> <iframe></iframe> </p> </td>
  </tr>
     </table>
</div>
<button id="toggler">Toggle Image/Table</button></code>```

Body:
Please have a look at this code sample. I have used jQuery 2.1.1

$(function() {
  $('#toggler').click(function() {
    $('#Table').toggle();
    $('#imageblock').toggle();
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="aspect">
<div style="display:none;" id="imageblock">
<img src="http://lorempixel.com/400/200/" />
</div>
<table id="Table">
<tr>
    <th id="textul" > </th>
    <th id="textul4"> </th>
    </tr>
    <tr>
  <td id="testul2and3" style="vertical-align:top"> </td>
    <td style="vertical-align:top" id="textul6">
            <p> <iframe></iframe> </p> </td>
  </tr>
     </table>
</div>
<button id="toggler">Toggle Image/Table</button>


问:
Why does "auto" declare strings as const char* instead of std::string?
I made a template which adds the data it is given. If I use it like this, the compiler declares in_1 and in_2 as const char *, and the code doesn't compile.

```<code>#include <iostream>
using namespace std;
template <class T>
T addstuff(T part_1, T part_2){
    return(part_1+part_2);
}

int main(int argc, char const *argv[])
{
    auto in_1="Shut ";
    auto in_2="up.";
    cout<<addstuff(in_1, in_2)<<endl;
    return 0;
}
</code>```

If I declare in_1 and in_2 std::string, it works like a charm.

Why can't (or doesn't) the compiler declare those strings automatically std::string?

答:
If you use string literals, auto will work as expected.

In C++14, C++17 or C++20, you can place an s after the quotes, and it will create a std::string instead of a const char* string.

This can be used together with auto to create a std::string:

```<code>auto hello = "hello"s;
</code>```

String literals are not enabled by default. One way of enabling string literals is to place the following at the top of the source file:

```<code>#include <string>
using namespace std::string_literals;
</code>```

As an example, this loop works for std::string (with s added to the string literal), but not for const char* type string literals:

```<code>for (auto &x : hello) {
    std::cout << "letter: " << x << std::endl;
}
</code>```

Here is the cppreference page for the ""s operator.

Body:
I made a template which adds the data it is given. If I use it like this, the compiler declares in_1 and in_2 as const char *, and the code doesn't compile.

#include <iostream>
using namespace std;
template <class T>
T addstuff(T part_1, T part_2){
    return(part_1+part_2);
}

int main(int argc, char const *argv[])
{
    auto in_1="Shut ";
    auto in_2="up.";
    cout<<addstuff(in_1, in_2)<<endl;
    return 0;
}

If I declare in_1 and in_2 std::string, it works like a charm.

Why can't (or doesn't) the compiler declare those strings automatically std::string?

Body:
If you use string literals, auto will work as expected.

In C++14, C++17 or C++20, you can place an s after the quotes, and it will create a std::string instead of a const char* string.

This can be used together with auto to create a std::string:

auto hello = "hello"s;

String literals are not enabled by default. One way of enabling string literals is to place the following at the top of the source file:

#include <string>
using namespace std::string_literals;

As an example, this loop works for std::string (with s added to the string literal), but not for const char* type string literals:

for (auto &x : hello) {
    std::cout << "letter: " << x << std::endl;
}

Here is the cppreference page for the ""s operator.


问:
Disable browser's back button
How to disable browser's BACK Button (across browsers)?</p>

答:
```<code><script>
    $(document).ready(function() {
        function disableBack() { window.history.forward() }

        window.onload = disableBack();
        window.onpageshow = function(evt) { if (evt.persisted) disableBack() }
    });
</script>
</code>```

Title: Disable browser's back button


问:
Device independent pixel in UWP-XAML
I want to fix the position of button to a particular point in uwp app. I have used margin to positioning it. But when running in another windows device it seems misplaced. How can I use DIP values in it? Is it possible to use dip instead of px for each control as in android?</p>

```<code> <Button x:Name="btnIcon" Height="200px" Width="300px" Click="btnIcon_Click"  Margin="0,578,280,0" HorizontalAlignment="Right" >
</code>```

答:
In the vast majority of cases (and your case), px values in XAML ARE device-independent units.

Also, most double length units will default to px so you don't usually have to specify the px suffix in markup.

Perhaps however, you need to consider using different logic to place your item. You're currently anchoring it to be 280 dip's from the right side of the screen and 578 from the top, is that what you're really intending on doing? Were you aiming to centre it or something?

Title: Device independent pixel in UWP-XAML

Body:
I want to fix the position of button to a particular point in uwp app. I have used margin to positioning it. But when running in another windows device it seems misplaced. How can I use DIP values in it? Is it possible to use dip instead of px for each control as in android?

 <Button x:Name="btnIcon" Height="200px" Width="300px" Click="btnIcon_Click"  Margin="0,578,280,0" HorizontalAlignment="Right" >


答:
You could get the entries of the object and map new objects in an array.

Techniques:

Object.entries for getting all key/value pairs from an object in an array,

Array#map, for mapping a new item for each item of the array,

destructuring assignment for the key/value pair and

short hand properties for taking the name as key and the value as value for an object.

var object = { 987: "sqa", 988: "Squad" },
    result = Object.entries(object).map(([id, value]) => ({ id, value }));

console.log(result);```

Title: how to change json structure in javascript?


问:
How to return a 2D vector in C++?
```<code>vector <vector<int> > pasTriangleUsingVector(int A)
{
    vector <vector<int> > arr;
    for(int line=0;line<A;line++)
    {
        for(int i=0;i<=line;i++)
        {
            if(i==0 || line==i)
                arr[line][i]=1;
            else
                arr[line][i] = arr[line-1][i-1] + arr[line-1][i];

            //cout<<arr[line][i]<<" ";
        }
     }

     return arr;
}
</code>```

I'm trying to return a vector containing the Pascal Triangle

It's showing segmentation error

答:
The problem isn't that you're returning a vector. The problem is that you're trying to access arr[line][i] without allocating memory for it.
That is the difference between an array (constant pointer) int a[100]; and a vector std::vector<int> a; that defining the array this way is enough to allocate memory in compile time for it meanwhile defining a vector with default constructor will allocate no memory for it.
So here comes the solution:
There are many ways of allocating and reallocating memory for a vector.
One standard way is in the constructor:

```<code>vector<int> a(A, 0);
</code>```

which defines an integer vector with 10 indices with a default value of 0 (you don't have to give a default value though).
in your case you can use the following

```<code>vector<int> temp(A);
vector<vector<int>> a(10, temp);
</code>```

which defines a vector of 10 lines with 10 columns in every line.
That's what you don't need, since the width of the vector is constant in all lines so let's find some other way.
The first thing you should do is to allocate A lines which is:

```<code>vector<vector<int>> arr(A);
</code>```

then you can use std::vector::push_back() member function instead of calling operator [].
that means

```<code>arr[line][i]=1;
</code>```

should become

```<code>arr[line].push_back(1);
</code>```

and

```<code>arr[line][i] = arr[line-1][i-1] + arr[line-1][i];
</code>```

should become

```<code>arr[line].push_back(arr[line-1][i-1] + arr[line-1][i]).
</code>```

Note that for every index you're adding, appending an element at the end, you will use this function only once then you can reach the added element from it's index using operator [], you can always use std::vector::size to get the number of elements in the vector as well.

Title: How to return a 2D vector in C++?

Body:
vector <vector<int> > pasTriangleUsingVector(int A)
{
    vector <vector<int> > arr;
    for(int line=0;line<A;line++)
    {
        for(int i=0;i<=line;i++)
        {
            if(i==0 || line==i)
                arr[line][i]=1;
            else
                arr[line][i] = arr[line-1][i-1] + arr[line-1][i];

            //cout<<arr[line][i]<<" ";
        }
     }

     return arr;
}

I'm trying to return a vector containing the Pascal Triangle

It's showing segmentation error

Body:
The problem isn't that you're returning a vector. The problem is that you're trying to access arr[line][i] without allocating memory for it.
That is the difference between an array (constant pointer) int a[100]; and a vector std::vector<int> a; that defining the array this way is enough to allocate memory in compile time for it meanwhile defining a vector with default constructor will allocate no memory for it.
So here comes the solution:
There are many ways of allocating and reallocating memory for a vector.
One standard way is in the constructor:

vector<int> a(A, 0);

which defines an integer vector with 10 indices with a default value of 0 (you don't have to give a default value though).
in your case you can use the following

vector<int> temp(A);
vector<vector<int>> a(10, temp);

which defines a vector of 10 lines with 10 columns in every line.
That's what you don't need, since the width of the vector is constant in all lines so let's find some other way.
The first thing you should do is to allocate A lines which is:

vector<vector<int>> arr(A);

then you can use std::vector::push_back() member function instead of calling operator [].
that means

arr[line][i]=1;

should become

arr[line].push_back(1);

and

arr[line][i] = arr[line-1][i-1] + arr[line-1][i];

should become

arr[line].push_back(arr[line-1][i-1] + arr[line-1][i]).

Note that for every index you're adding, appending an element at the end, you will use this function only once then you can reach the added element from it's index using operator [], you can always use std::vector::size to get the number of elements in the vector as well.


答:
```<code>const intial = {987: "sqa", 988: "Squad"}
const final = [];
for(let idNum in intial){
  const data = {
    id: idNum,
    value: intial[idNum]
   }
  final.push(data);
}
console.log(final);  //[ { id: '987', value: 'sqa' }, { id: '988', value: 'Squad' } ]
</code>```

<p>This will achieve what you're trying to do </p>

Body:
I have a json Object like following.

{987: "sqa", 988: "Squad"}

I need to change the structure like following

[{id:987, value:'sqa'}, {id:988, value:'Squad'}]

How to do this with Javascript?

Body:
const intial = {987: "sqa", 988: "Squad"}
const final = [];
for(let idNum in intial){
  const data = {
    id: idNum,
    value: intial[idNum]
   }
  final.push(data);
}
console.log(final);  //[ { id: '987', value: 'sqa' }, { id: '988', value: 'Squad' } ]

This will achieve what you're trying to do


问:
converting numbers to currency format when text changes
I am using RxTextView.textChanges for EditText that when the user is typing change value of EditText to convert numbers to currency format like below:

```<code>1,000
</code>```

But I can't see any convert numbers to currency format.

I am using from:  NumberFormat.getNumberInstance(Locale.US).format(productPrice);

My code is like bellow:

```<code>Observable<CharSequence> observableDiscountPrice = RxTextView.textChanges(discountPriceEdittext);
        observableDiscountPrice.map(new Function<CharSequence, Boolean>() {
            @Override
            public Boolean apply(@io.reactivex.annotations.NonNull CharSequence charSequence) throws Exception {
                try {
                    if (charSequence.length() > 0) {
                        String pPrice = NumberFormat.getNumberInstance(Locale.US).format(charSequence.toString());
                        originalPriceEdittext.setText(String.valueOf(pPrice));
                        return true;
                    } else {
                        return false;
                    }
                } catch (Exception e) {
                    return true;
                }
            }
        }).subscribe(new Subject<Boolean>() {
            @Override
            public boolean hasObservers() {
                return false;
            }

            @Override
            public boolean hasThrowable() {
                return false;
            }

            @Override
            public boolean hasComplete() {
                return false;
            }

            @Override
            public Throwable getThrowable() {
                return null;
            }

            @Override
            protected void subscribeActual(Observer<? super Boolean> observer) {

            }

            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Boolean aBoolean) {
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
</code>```

答:
Use this TextWatcher class:

```<code>public class NumberTextWatcherWithSeperator implements TextWatcher {

private EditText editText;

public NumberTextWatcherWithSeperator(EditText editText) {
    this.editText = editText;

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable s) {
    try {
        editText.removeTextChangedListener(this);
        String value = editText.getText().toString();

        if (!value.equals("")) {

            if (value.startsWith(".")) {
                editText.setText("0.");
            }
            if (value.startsWith("0") && !value.startsWith("0.")) {
                editText.setText("");

            }

            String str = editText.getText().toString().replaceAll(",", "");
            if (!value.equals(""))
                editText.setText(getDecimalFormattedString(str));
            editText.setSelection(editText.getText().toString().length());
        }
        editText.addTextChangedListener(this);
    } catch (Exception ex) {
        ex.printStackTrace();
        editText.addTextChangedListener(this);
    }
}

private static String getDecimalFormattedString(String value) {
    StringTokenizer lst = new StringTokenizer(value, ".");
    String str1 = value;
    String str2 = "";
    if (lst.countTokens() > 1) {
        str1 = lst.nextToken();
        str2 = lst.nextToken();
    }
    String str3 = "";
    int i = 0;
    int j = -1 + str1.length();
    if (str1.charAt(-1 + str1.length()) == '.') {
        j--;
        str3 = ".";
    }
    for (int k = j; ; k--) {
        if (k < 0) {
            if (str2.length() > 0)
                str3 = str3 + "." + str2;
            return str3;
        }
        if (i == 3) {
            str3 = "," + str3;
            i = 0;
        }
        str3 = str1.charAt(k) + str3;
        i++;
    }

}

}
</code>```

and

```<code>yourEditText.addTextChangedListener(new NumberTextWatcherWithSeperator(yourEditText));
</code>```

Body:
I am using RxTextView.textChanges for EditText that when the user is typing change value of EditText to convert numbers to currency format like below:

1,000

But I can't see any convert numbers to currency format.

I am using from:  NumberFormat.getNumberInstance(Locale.US).format(productPrice);

My code is like bellow:

Observable<CharSequence> observableDiscountPrice = RxTextView.textChanges(discountPriceEdittext);
        observableDiscountPrice.map(new Function<CharSequence, Boolean>() {
            @Override
            public Boolean apply(@io.reactivex.annotations.NonNull CharSequence charSequence) throws Exception {
                try {
                    if (charSequence.length() > 0) {
                        String pPrice = NumberFormat.getNumberInstance(Locale.US).format(charSequence.toString());
                        originalPriceEdittext.setText(String.valueOf(pPrice));
                        return true;
                    } else {
                        return false;
                    }
                } catch (Exception e) {
                    return true;
                }
            }
        }).subscribe(new Subject<Boolean>() {
            @Override
            public boolean hasObservers() {
                return false;
            }

            @Override
            public boolean hasThrowable() {
                return false;
            }

            @Override
            public boolean hasComplete() {
                return false;
            }

            @Override
            public Throwable getThrowable() {
                return null;
            }

            @Override
            protected void subscribeActual(Observer<? super Boolean> observer) {

            }

            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Boolean aBoolean) {
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

Body:
Use this TextWatcher class:

public class NumberTextWatcherWithSeperator implements TextWatcher {

private EditText editText;

public NumberTextWatcherWithSeperator(EditText editText) {
    this.editText = editText;

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable s) {
    try {
        editText.removeTextChangedListener(this);
        String value = editText.getText().toString();

        if (!value.equals("")) {

            if (value.startsWith(".")) {
                editText.setText("0.");
            }
            if (value.startsWith("0") && !value.startsWith("0.")) {
                editText.setText("");

            }

            String str = editText.getText().toString().replaceAll(",", "");
            if (!value.equals(""))
                editText.setText(getDecimalFormattedString(str));
            editText.setSelection(editText.getText().toString().length());
        }
        editText.addTextChangedListener(this);
    } catch (Exception ex) {
        ex.printStackTrace();
        editText.addTextChangedListener(this);
    }
}

private static String getDecimalFormattedString(String value) {
    StringTokenizer lst = new StringTokenizer(value, ".");
    String str1 = value;
    String str2 = "";
    if (lst.countTokens() > 1) {
        str1 = lst.nextToken();
        str2 = lst.nextToken();
    }
    String str3 = "";
    int i = 0;
    int j = -1 + str1.length();
    if (str1.charAt(-1 + str1.length()) == '.') {
        j--;
        str3 = ".";
    }
    for (int k = j; ; k--) {
        if (k < 0) {
            if (str2.length() > 0)
                str3 = str3 + "." + str2;
            return str3;
        }
        if (i == 3) {
            str3 = "," + str3;
            i = 0;
        }
        str3 = str1.charAt(k) + str3;
        i++;
    }

}

}

and

yourEditText.addTextChangedListener(new NumberTextWatcherWithSeperator(yourEditText));


问:
Alignment of dynamic views
I want the alignment of the editext and the imageviewin the same horizontal line but I am getting the imageview below the edittext.

main fragment code

```<code> final LinearLayout lnrView = (LinearLayout)
 child.findViewById(R.id.lnrView);
                Button btnad = (Button) child.findViewById(R.id.btnad);
                btnad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        lnrView.addView(newedittext());
                        lnrView.addView(newImageview(getActivity()));
                    }
                });
</code>```

neweditext method

```<code>  private View newedittext() {
    final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final EditText editText = new EditText(getActivity());
    int id = 0;
    editText.setId(id);
    editText.setTextSize(14);
    editText.setTextColor(Color.rgb(0, 0, 0));
    editText.setMaxEms(2);
    editText.setInputType(InputType.TYPE_CLASS_TEXT);
    return editText;
}
</code>```

newImageview method

```<code> public ImageView newImageview(Context context) {
    final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final ImageView imgView = new ImageView(context);
    int id = 0;
    imgView.setId(id);
    imgView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_close_red));
    return imgView;
}
</code>```

main fragment xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
    android:id="@+id/btnad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="add" />

<LinearLayout
    android:id="@+id/lnrView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

</LinearLayout>

</LinearLayout>
</code>```

when i click the Add button an edittext and  Imageview is created dynamically and my output screen look like below

i want the imageview and the edittext in the same line. can anyone help me.

when i add "Horizontal" this is the output

this my expected result

答:
Or simpler use

ListView

with

ArrayAdapter

where you define you own layout (EditText and button)

There is better way to manage add and remove lines.

Also you have all EditTexts in one array and you can do your logic simpler.

Title: Alignment of dynamic views

Body:
I want the alignment of the editext and the imageviewin the same horizontal line but I am getting the imageview below the edittext.

main fragment code

 final LinearLayout lnrView = (LinearLayout)
 child.findViewById(R.id.lnrView);
                Button btnad = (Button) child.findViewById(R.id.btnad);
                btnad.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        lnrView.addView(newedittext());
                        lnrView.addView(newImageview(getActivity()));
                    }
                });

neweditext method

  private View newedittext() {
    final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final EditText editText = new EditText(getActivity());
    int id = 0;
    editText.setId(id);
    editText.setTextSize(14);
    editText.setTextColor(Color.rgb(0, 0, 0));
    editText.setMaxEms(2);
    editText.setInputType(InputType.TYPE_CLASS_TEXT);
    return editText;
}

newImageview method

 public ImageView newImageview(Context context) {
    final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final ImageView imgView = new ImageView(context);
    int id = 0;
    imgView.setId(id);
    imgView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_close_red));
    return imgView;
}

main fragment xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
    android:id="@+id/btnad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="add" />

<LinearLayout
    android:id="@+id/lnrView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

</LinearLayout>

</LinearLayout>

when i click the Add button an edittext and  Imageview is created dynamically and my output screen look like below

i want the imageview and the edittext in the same line. can anyone help me.

when i add "Horizontal" this is the output

this my expected result


问:
WPF DataVisualization Chart Format Labels
I'm using the DataVisualization charting within WPF and creating a BarSeries in code, but I can't get the numbers formatted on the X axis.

I don't want to do this in XAML because the type of chart can vary according to user selection and it seemed more flexible to do all of this in code rather than having different chart types. The number of data series also fluctuates.

The XAML is just

```<code>xmlns:chttk="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"

<chttk:Chart Name="DataChart1" Margin="0" Title="{Binding AxisXTitle}" DataContext="{Binding GraphData1}" Style="{StaticResource ChartStyle1}" BorderBrush="Transparent"/>
</code>```

The code behind is

```<code>Dim dataChart As System.Windows.Controls.DataVisualization.Charting.Chart = DataChart1
Dim s As New System.Windows.Controls.DataVisualization.Charting.BarSeries
s.Title = "My Chart"
s.DependentValuePath = "Value"
s.IndependentValuePath = "Key"
s.DataContext = New Binding("[0]")
s.ItemsSource = CType(itm, IEnumerable)
dataChart.Series.Add(s)
</code>```

The DataContext is a DataSeries.Collection with the data in KeyValuePairs. The values are all Double values.

The graph is displaying, but the values on the axis are un-formatted, e.g. 120000. I have found a few examples pointing at different Axis types and LabelFormat and LabelStyle.Format but I can't find anything that works in the WPF environment in the code behind.

答:
Thanks for the input - I finally managed to get it working with the following code:

```<code>Dim n As Integer
dataChart.Series.Clear()
Dim x As New System.Windows.Controls.DataVisualization.Charting.LinearAxis
x.Orientation = DataVisualization.Charting.AxisOrientation.X
Dim y As New System.Windows.Controls.DataVisualization.Charting.CategoryAxis
y.Orientation = DataVisualization.Charting.AxisOrientation.Y
Dim stl As New Style(GetType(System.Windows.Controls.DataVisualization.Charting.AxisLabel))
stl.Setters.Add(New Setter(System.Windows.Controls.DataVisualization.Charting.AxisLabel.StringFormatProperty, "{0:#,0}"))
x.AxisLabelStyle = stl
For Each itm As Object In o
    Dim srs As New System.Windows.Controls.DataVisualization.Charting.BarSeries
    pi = itm.GetType.GetProperty("SeriesTitle")
    srs.Title = pi.GetValue(itm, Nothing)
    srs.DependentValuePath = "Value"
    srs.IndependentValuePath = "Key"
    srs.DataContext = New Binding("[" & n & "]")
    srs.ItemsSource = CType(itm, IEnumerable)
    srs.DependentRangeAxis = x
    srs.IndependentAxis = y
    dataChart.Series.Add(srs)
    n += 1
Next
</code>```

Some of the gotchas that tripped me up were adding the axis. You need to add the right type of axis to the DependentRangeAxis or IndependentAxis. With a BarSeries the DependentRangeAxis is the X axis and can be a LinearAxis and the IndependentAxis is the Y axis and for me was a CategoryAxis. Also if you have multiple series then you need to apply the same axis to all series.

Hope this helps someone else.

Body:
I'm using the DataVisualization charting within WPF and creating a BarSeries in code, but I can't get the numbers formatted on the X axis.

I don't want to do this in XAML because the type of chart can vary according to user selection and it seemed more flexible to do all of this in code rather than having different chart types. The number of data series also fluctuates.

The XAML is just

xmlns:chttk="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"

<chttk:Chart Name="DataChart1" Margin="0" Title="{Binding AxisXTitle}" DataContext="{Binding GraphData1}" Style="{StaticResource ChartStyle1}" BorderBrush="Transparent"/>

The code behind is

Dim dataChart As System.Windows.Controls.DataVisualization.Charting.Chart = DataChart1
Dim s As New System.Windows.Controls.DataVisualization.Charting.BarSeries
s.Title = "My Chart"
s.DependentValuePath = "Value"
s.IndependentValuePath = "Key"
s.DataContext = New Binding("[0]")
s.ItemsSource = CType(itm, IEnumerable)
dataChart.Series.Add(s)

The DataContext is a DataSeries.Collection with the data in KeyValuePairs. The values are all Double values.

The graph is displaying, but the values on the axis are un-formatted, e.g. 120000. I have found a few examples pointing at different Axis types and LabelFormat and LabelStyle.Format but I can't find anything that works in the WPF environment in the code behind.

Body:
Thanks for the input - I finally managed to get it working with the following code:

Dim n As Integer
dataChart.Series.Clear()
Dim x As New System.Windows.Controls.DataVisualization.Charting.LinearAxis
x.Orientation = DataVisualization.Charting.AxisOrientation.X
Dim y As New System.Windows.Controls.DataVisualization.Charting.CategoryAxis
y.Orientation = DataVisualization.Charting.AxisOrientation.Y
Dim stl As New Style(GetType(System.Windows.Controls.DataVisualization.Charting.AxisLabel))
stl.Setters.Add(New Setter(System.Windows.Controls.DataVisualization.Charting.AxisLabel.StringFormatProperty, "{0:#,0}"))
x.AxisLabelStyle = stl
For Each itm As Object In o
    Dim srs As New System.Windows.Controls.DataVisualization.Charting.BarSeries
    pi = itm.GetType.GetProperty("SeriesTitle")
    srs.Title = pi.GetValue(itm, Nothing)
    srs.DependentValuePath = "Value"
    srs.IndependentValuePath = "Key"
    srs.DataContext = New Binding("[" & n & "]")
    srs.ItemsSource = CType(itm, IEnumerable)
    srs.DependentRangeAxis = x
    srs.IndependentAxis = y
    dataChart.Series.Add(srs)
    n += 1
Next

Some of the gotchas that tripped me up were adding the axis. You need to add the right type of axis to the DependentRangeAxis or IndependentAxis. With a BarSeries the DependentRangeAxis is the X axis and can be a LinearAxis and the IndependentAxis is the Y axis and for me was a CategoryAxis. Also if you have multiple series then you need to apply the same axis to all series.

Hope this helps someone else.


问:
Django Deep Linking render with #tag
I am trying to Deep Link tabs with Dango by adding the #panel1 at the end.

This would be the template needed:

```<code>template = "charts/chart1.html#panel1"
return render ( request, template, context )
</code>```

But obviously Django can not find that template once I add the hashtag.

Is there a way to overcome this issue?

Thank You.

https://foundation.zurb.com/sites/docs/tabs.html

答:
Anything after the # ( hashbang ) is not even sent to Django webserver. You have to do the logic in your Javascript. Please consider add all your chart code to charts/chart.html and I think adding tabs class enought for the toggle.

views

```<code>template = "charts/chart.html"
return render ( request, template, context )
</code>```

html

```<code><ul class="tabs" data-tabs id="example-tabs">
  <li class="tabs-title is-active"><a href="#panel1" aria-selected="true">Tab 1</a></li>
  <li class="tabs-title"><a data-tabs-target="panel2" href="#panel2">Tab 2</a></li>
</ul>
</code>```

But also if you're looking for the JS reference here

Title: Django Deep Linking render with #tag

Body:
I am trying to Deep Link tabs with Dango by adding the #panel1 at the end.

This would be the template needed:

template = "charts/chart1.html#panel1"
return render ( request, template, context )

But obviously Django can not find that template once I add the hashtag.

Is there a way to overcome this issue?

Thank You.

https://foundation.zurb.com/sites/docs/tabs.html

Body:
Anything after the # ( hashbang ) is not even sent to Django webserver. You have to do the logic in your Javascript. Please consider add all your chart code to charts/chart.html and I think adding tabs class enought for the toggle.

views

template = "charts/chart.html"
return render ( request, template, context )

html

<ul class="tabs" data-tabs id="example-tabs">
  <li class="tabs-title is-active"><a href="#panel1" aria-selected="true">Tab 1</a></li>
  <li class="tabs-title"><a data-tabs-target="panel2" href="#panel2">Tab 2</a></li>
</ul>

But also if you're looking for the JS reference here


问:
RSS feed link broken , only loading after wordpress admin login
I am trying to open my rss feed link but it is not loading. Only loading when I logged in WordPress admin panel.

I don't know why it is happening. Please help me out with this problem.

Rss Fedd Url  : http://odishatv.in/feed

答:
I got the proper solution through the given link below.

https://wordpress.org/support/topic/rss-feed-broken-for-the-rest-of-the-world-only-loading-for-blog-admin/


问:
How can I use postgres roles and passwords for website authentication
I want a future web application's users to be able to log into a postgres database using their website usernames and passwords.

The website will connect to postgres with a special username (e.g. "web") which will be unavailable as a website username.  (As would "postgres", etc.)

No users or passwords exist yet, so there are no migration issues.  All website users will be postgres users.  The website can hash passwords however postgres does.

What is the most sensible way to achieve this with the least duplication of data?

Can I use/extend postgres's internal roles tables as a general source of username/password authentication?  i.e. I would need to be able to run a query which will tell me if a given username/password combination is valid.

Or is it better to a have a separate store of website usernames and passwords and somehow get postgres to use this?

答:
I've found https://www.postgresql.org/docs/9.6/static/catalog-pg-authid.html which writes about a pg_authid table, which contains usernames and md5 hashes of password || username.

When I've created a user which can update this table, I hope to be able to use it for website logins.  It constrains me to using md5, which is not not ideal.


问:
How to use logic checking for derived types in RavenDB indexes?
I need to store different values in the index based on the type of PriceSetup.

I've tries the code below.

I've alos tried specyfing the fully qualifies class name.

In both cases RavenDB tell me that is could not find the type FixedPriceSetup when I try to create the index.

How can I store different values in the index based on type of PriceSetup?

```<code>public class Trade
{
    public PriceSetup PriceSetup;
}

public abstract class PriceSetup
{
    public int TotalPrice;
}

public class FixedPriceSetup : PriceSetup
{
    public int DailyPrice;
}

public class FlexiblePriceSetup : PriceSetup
{
    //...some other stuff
}

public class TradeSearchIndex : AbstractIndexCreationTask<Trade>
{
    public TradeSearchIndex()
    {
        Map = trades =>
            from trade in trades
            select new
            {
                TotalPrice = trade.PriceSetup is FixedPriceSetup
                    ? Math.Abs(trade.PriceSetup.TotalPrice) * Math.Sign((trade.PriceSetup as FixedPriceSetup).DailyPrice)
                    : trade.PriceSetup.TotalPrice
            }
    }
}
</code>```

I would like to keep the index definition in code since the Trade class is very complicated and intellisense is a blessing in this case.

Edit:
The code beloew seems to work:

```<code>public class TradeSearchIndex : AbstractIndexCreationTask<Trade>
{
    public TradeSearchIndex()
    {
        Map = trades =>
            from trade in trades
            select new
            {
                TotalPrice =
                    AsDocument(trade.PriceSetup)["$type"].ToString() == "RavenTest.FixedPriceSetup, RavenTest"
                        ? Math.Abs(trade.PriceSetup.TotalPrice) * Math.Sign(AsDocument(trade.PriceSetup)["DailyPrice"].Value<int>)
                        : trade.PriceSetup.TotalPrice
            }
    }
}
</code>```

答:
The type doesn't exist on the server, which is why you get this error.
However, this is a really good place to use multi map.
https://ravendb.net/docs/article-page/3.5/Csharp/indexes/multi-map-indexes</p>

Body:
I need to store different values in the index based on the type of PriceSetup.

I've tries the code below.

I've alos tried specyfing the fully qualifies class name.

In both cases RavenDB tell me that is could not find the type FixedPriceSetup when I try to create the index.

How can I store different values in the index based on type of PriceSetup?

public class Trade
{
    public PriceSetup PriceSetup;
}

public abstract class PriceSetup
{
    public int TotalPrice;
}

public class FixedPriceSetup : PriceSetup
{
    public int DailyPrice;
}

public class FlexiblePriceSetup : PriceSetup
{
    //...some other stuff
}

public class TradeSearchIndex : AbstractIndexCreationTask<Trade>
{
    public TradeSearchIndex()
    {
        Map = trades =>
            from trade in trades
            select new
            {
                TotalPrice = trade.PriceSetup is FixedPriceSetup
                    ? Math.Abs(trade.PriceSetup.TotalPrice) * Math.Sign((trade.PriceSetup as FixedPriceSetup).DailyPrice)
                    : trade.PriceSetup.TotalPrice
            }
    }
}

I would like to keep the index definition in code since the Trade class is very complicated and intellisense is a blessing in this case.

Edit:
The code beloew seems to work:

public class TradeSearchIndex : AbstractIndexCreationTask<Trade>
{
    public TradeSearchIndex()
    {
        Map = trades =>
            from trade in trades
            select new
            {
                TotalPrice =
                    AsDocument(trade.PriceSetup)["$type"].ToString() == "RavenTest.FixedPriceSetup, RavenTest"
                        ? Math.Abs(trade.PriceSetup.TotalPrice) * Math.Sign(AsDocument(trade.PriceSetup)["DailyPrice"].Value<int>)
                        : trade.PriceSetup.TotalPrice
            }
    }
}


问:
Reading value from Excel sheet

```<code>$filepath = "C:\Users\Desktop\New folder\Tangent.xlsx"
$sheetname = "sheet"
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
$WorkBook = $objExcel.Workbooks.Open($filepath)
$WorkBook.sheets | Select-Object -Property Name
$WorkSheet = $WorkBook.Sheets.Item($sheetname)
$myObj = [PSCustomObject][ordered]@{
    john  = $WorkSheet.Range("B1").Text
    Rebel = $WorkSheet.Range("B2").Text
    MArk  = $WorkSheet.Range("B3").Text
    Susan = $WorkSheet.Range("B4").Text
    Patty = $WorkSheet.Range("B5").Text
}
</code>```

I have hardcoded all the names into the code which is a weird way of doing it. I want it to read from the Excel directing using command. Can anyone help me please?

答:
Create an empty hashtable and fill it as you iterate over the rows in your Excel sheet, then create the object.

```<code>$ht = @{}
$i = 1
while ($WorkSheet.Cells.Item($i, 1).Text) {
    $ht[$WorkSheet.Cells.Item($i, 1).Text] = $WorkSheet.Cells.Item($i, 2).Text
    $i++
}
$obj = [PSCustomObject]$ht
</code>```

Untested, as I don't have Excel at hand here.

Title: Reading value from Excel sheet

Body:
$filepath = "C:\Users\Desktop\New folder\Tangent.xlsx"
$sheetname = "sheet"
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
$WorkBook = $objExcel.Workbooks.Open($filepath)
$WorkBook.sheets | Select-Object -Property Name
$WorkSheet = $WorkBook.Sheets.Item($sheetname)
$myObj = [PSCustomObject][ordered]@{
    john  = $WorkSheet.Range("B1").Text
    Rebel = $WorkSheet.Range("B2").Text
    MArk  = $WorkSheet.Range("B3").Text
    Susan = $WorkSheet.Range("B4").Text
    Patty = $WorkSheet.Range("B5").Text
}

I have hardcoded all the names into the code which is a weird way of doing it. I want it to read from the Excel directing using command. Can anyone help me please?

Body:
Create an empty hashtable and fill it as you iterate over the rows in your Excel sheet, then create the object.

$ht = @{}
$i = 1
while ($WorkSheet.Cells.Item($i, 1).Text) {
    $ht[$WorkSheet.Cells.Item($i, 1).Text] = $WorkSheet.Cells.Item($i, 2).Text
    $i++
}
$obj = [PSCustomObject]$ht

Untested, as I don't have Excel at hand here.


问:
why button in view inactive with parent view's controller?
I am using swipView to make a page scrolling app

according to  its SwipeViewDataSource protocol, I make a method

```<code> - (UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{

        ContentViewController *contentVC = [[ContentViewController alloc]init];
        view = contentVC.view;
        return view;
}
</code>```

to provide the swipping content

and the ContentViewController is simple enough:

It only has this two custom methods:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 100, 200)];
    [btn setTitle:@"click me" forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor redColor]];
    [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

}
-(void) onClick:(id) sender {
    NSLog(@"click detected in contentView controller");
}
</code>```

only added a  button in viewDidLoad and the click listen method

when running the app, the button showed, but click on don't fire the OnClick: method.

After figuring around, I notice that if I put this method

```<code>-(void) onClick:(id)sender {
    NSLog(@"on click detected  main view controller");
}
</code>```

To the view which implements the SwipeViewDataSource ie in the "parent" which init the ContentViewController that line of debug info will be printed.

It's very weird, to me. I mean why that happens?

答: Your contentviewcontroller will be released after returning its view in viewForItemAtIndex delegate method since you are retaining its view only. But you are adding button target to self(contentviewcontroller) which was released already.</p>

Body:
I am using swipView to make a page scrolling app

according to  its SwipeViewDataSource protocol, I make a method

 - (UIView *)swipeView:(SwipeView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{

        ContentViewController *contentVC = [[ContentViewController alloc]init];
        view = contentVC.view;
        return view;
}

to provide the swipping content

and the ContentViewController is simple enough:

It only has this two custom methods:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 100, 200)];
    [btn setTitle:@"click me" forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor redColor]];
    [btn addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

}
-(void) onClick:(id) sender {
    NSLog(@"click detected in contentView controller");
}

only added a  button in viewDidLoad and the click listen method

when running the app, the button showed, but click on don't fire the OnClick: method.

After figuring around, I notice that if I put this method

-(void) onClick:(id)sender {
    NSLog(@"on click detected  main view controller");
}

To the view which implements the SwipeViewDataSource ie in the "parent" which init the ContentViewController that line of debug info will be printed.

It's very weird, to me. I mean why that happens?