问:
"this" inside prototype takes window instead of object
I created an Object called Survey and added a prototype function to it, and when I console log this inside the prototype function the log shows window object instead of parent Survey Object.

```<code>function Survey(questions = []) {
  this.__questions__ = questions;
};
Survey.prototype.testFunction = () => {
  console.log(this);
  return this.__questions__;
}
// Create your object here
const SUR = new Survey(['1','2']);

SUR.testFunction(); // this prints [[Window]] Object instead of Survey
</code>```

Expected result would be Survey object

答:
It is because you used an Arrow function.
In arrow function, this will be reference to outside. Just use a normal function instead.

```<code>Survey.prototype.testFunction = function() {
  console.log(this);
  return this.__questions__;
}
</code>```

Body:
I created an Object called Survey and added a prototype function to it, and when I console log this inside the prototype function the log shows window object instead of parent Survey Object.

function Survey(questions = []) {
  this.__questions__ = questions;
};
Survey.prototype.testFunction = () => {
  console.log(this);
  return this.__questions__;
}
// Create your object here
const SUR = new Survey(['1','2']);

SUR.testFunction(); // this prints [[Window]] Object instead of Survey

Expected result would be Survey object

Body:
It is because you used an Arrow function.
In arrow function, this will be reference to outside. Just use a normal function instead.

Survey.prototype.testFunction = function() {
  console.log(this);
  return this.__questions__;
}


来源: stackexchange

问:
How do I stop Magento merging the basket on login?
If you were to login to Magento and add some products to your basket and then leave the site, these are saved for the next time you return to the site.

This, however, causes an issue when you do return. If, on your return, you added a product to your basket without logging in and then logged in at the start of the checkout process, your guest and saved basket will be merged. This is undesirable.

Is there any way to make Magento clear the saved basket on login if your current basket has items in it?

答:
It looks like the code that governs this is in Mage_Checkout_Model_Session, specifically where it calls Mage_Sales_Model_Quote::merge. This means that you have a few options.

Override the session class and force it not to cause the merge.

Override the quote class and cause it never to merge carts. There may be secondary bugs to this approach if other parts of the system also attempt to merge carts.

Hook into the event that quote calls (sales_quote_merge_before) and use that opportunity to empty one of the carts. You would have to detect around when this should be done, but it is by far cleaner than the other two.

ContentLicense: CC BY-SA 4.0


问:
How to apply background image for a specific view in asp.net MVC 5
For my login view, i'am willing to set a specific background for it's view.</p>

```<code><body style="background-image: url('../../Content/AdminLTE/img/LogIn-BackGround.jpg');"> ...</body>
</code>```

答:
If you are using a Layout for your views so you can add a section in your _Layout like this :

```<code><Html>
...
<head>
    @RenderSection( "Head",required: false )
    ....
</code>```

Now you can add every thing you like in your html header. For example :

```<code>@section Head
{
   <style>
      body
      {
          background-image:url('/Images/img.jpg');
      }
    </style>
}
</code>```

good luck

ContentLicense: CC BY-SA 3.0

Body:
For my login view, i'am willing to set a specific background for it's view.

 ...

Body:
If you are using a Layout for your views so you can add a section in your _Layout like this :

<Html>
...
<head>
    @RenderSection( "Head",required: false )
    ....

Now you can add every thing you like in your html header. For example :

@section Head
{
   <style>
      body
      {
          background-image:url('/Images/img.jpg');
      }
    </style>
}

good luck


问:
Having trouble accessing element in object returned from get request in Express
I've got a get request returning an array of objects taken from a database using Knex, I want to return them using .map giving them accessible elements. But the final element as such is a sum(), so I just don't get how I can access it. Probably a very simple problem but I'm just not getting it.

My current function added below returns everything i'm after except the total. i.e. referencing area as res.area works. But request returns the sum as 'sum(areas)': 20. So I guess i'm wondering how to reference a sum that has no variable name

```<code>router.get("/search/:param",function(req,res,next)
{
  req.database.from('animals')
  .select('animals.name', 'areas.lat', 'areas.lng', req.params.area)
  .sum(req.params.area).groupBy('animals.name')
  .leftJoin('areas','req.params.area', 'areas.area')
  .then((rows) => {
    const x = mapFunction(rows)
    res.send({query: req.params.area, result: x})
  })
})

function mapFunction(results) {
  return results.map((res) =>
  ({area: res.area, lat: res.lat, lng: res.lng, total: res.????}))
}
</code>```

答:
The trick is to provide usable names for your results. This makes it much easier to reference them later. For example:

```<code>knex
  .from('animals')
  .select('animals.name', 'areas.lat', 'areas.lng', req.params.area)
  .sum(`${req.params.area} as areaSum`)
</code>```

This way, the sum is available as areaSum in your result.

Body:
I've got a get request returning an array of objects taken from a database using Knex, I want to return them using .map giving them accessible elements. But the final element as such is a sum(), so I just don't get how I can access it. Probably a very simple problem but I'm just not getting it.

My current function added below returns everything i'm after except the total. i.e. referencing area as res.area works. But request returns the sum as 'sum(areas)': 20. So I guess i'm wondering how to reference a sum that has no variable name

router.get("/search/:param",function(req,res,next)
{
  req.database.from('animals')
  .select('animals.name', 'areas.lat', 'areas.lng', req.params.area)
  .sum(req.params.area).groupBy('animals.name')
  .leftJoin('areas','req.params.area', 'areas.area')
  .then((rows) => {
    const x = mapFunction(rows)
    res.send({query: req.params.area, result: x})
  })
})

function mapFunction(results) {
  return results.map((res) =>
  ({area: res.area, lat: res.lat, lng: res.lng, total: res.????}))
}

Body:
The trick is to provide usable names for your results. This makes it much easier to reference them later. For example:

knex
  .from('animals')
  .select('animals.name', 'areas.lat', 'areas.lng', req.params.area)
  .sum(`${req.params.area} as areaSum`)

This way, the sum is available as areaSum in your result.


问:
How to generate 4 different random numbers in C++
I am making Bulls and Cows assignment from Bjarne Stroustrup's "Programming Principles and Practice Using C++" book (p. 130, exercise 13) and I want program to generate four different integers in the range 0 to 9 (e.g., 1234 but not 1122)

I made a vector to store numbers and a function which generates 4 numbers and adds them to vector, but numbers might be the same and I can't return numbers to main function

```<code>#include "../..//..//std_lib_facilities.h"

vector<int> gen4Nums(vector<int> secNum)
{
    random_device rd; // obtain a random number from hardware
    mt19937 eng(rd()); // seed the generator
    uniform_int_distribution<> distr(0, 9); // define the range

    secNum.clear();
    for (int i = 0; i < 4; i++)
    {
        secNum.push_back(distr(eng));
        cout << secNum[i];
    }
    return secNum;
}

int main()
{
        vector<int> secNum;
        gen4Nums(secNum);
}
</code>```

I expect to return 4 different random numbers to the main function

答:
You can ensure to get different random numbers in the result if you change your code like this:</p>

```<code>#include <vector>
#include <random>
#include <algorithm>

using namespace std;

vector<int> gen4Nums()
{
    vector<int> result;
    random_device rd; // obtain a random number from hardware
    mt19937 eng(rd()); // seed the generator
    uniform_int_distribution<> distr(0, 9); // define the range

    int i = 0;
    while(i < 4) { // loop until you have collected the sufficient number of results
        int randVal = distr(eng);
        if(std::find(std::begin(result),std::end(result),randVal) == std::end(result)) {
        // ^^^^^^^^^^^^ The above part is essential, only add random numbers to the result
        // which aren't yet contained.
            result.push_back(randVal);
            cout << result[i];
            ++i;
        }
    }
    return result;
}

int main() {
    vector<int> secNum = gen4Nums();
}
</code>```

Body:
I am making Bulls and Cows assignment from Bjarne Stroustrup's "Programming Principles and Practice Using C++" book (p. 130, exercise 13) and I want program to generate four different integers in the range 0 to 9 (e.g., 1234 but not 1122)

I made a vector to store numbers and a function which generates 4 numbers and adds them to vector, but numbers might be the same and I can't return numbers to main function

#include "../..//..//std_lib_facilities.h"

vector<int> gen4Nums(vector<int> secNum)
{
    random_device rd; // obtain a random number from hardware
    mt19937 eng(rd()); // seed the generator
    uniform_int_distribution<> distr(0, 9); // define the range

    secNum.clear();
    for (int i = 0; i < 4; i++)
    {
        secNum.push_back(distr(eng));
        cout << secNum[i];
    }
    return secNum;
}

int main()
{
        vector<int> secNum;
        gen4Nums(secNum);
}

I expect to return 4 different random numbers to the main function

Body:
You can ensure to get different random numbers in the result if you change your code like this:

#include <vector>
#include <random>
#include <algorithm>

using namespace std;

vector<int> gen4Nums()
{
    vector<int> result;
    random_device rd; // obtain a random number from hardware
    mt19937 eng(rd()); // seed the generator
    uniform_int_distribution<> distr(0, 9); // define the range

    int i = 0;
    while(i < 4) { // loop until you have collected the sufficient number of results
        int randVal = distr(eng);
        if(std::find(std::begin(result),std::end(result),randVal) == std::end(result)) {
        // ^^^^^^^^^^^^ The above part is essential, only add random numbers to the result
        // which aren't yet contained.
            result.push_back(randVal);
            cout << result[i];
            ++i;
        }
    }
    return result;
}

int main() {
    vector<int> secNum = gen4Nums();
}


问:
Class has no instance setter 'id='
In dart, I am getting this error while trying to override a property like this

```<code>var newId = state.myMatches[0][0].id = 90;
</code>```

I am getting this error

```<code>flutter: The following NoSuchMethodError was thrown while handling a gesture:
flutter: Class 'DivMatches' has no instance setter 'id='.
flutter: Receiver: Instance of 'DivMatches'
flutter: Tried calling: id=90
</code>```

There is no properties that private. All are public. Any help what's happening?

Thank you.

答: You are looking up state.myMatches[0][0], which is apparently an instance of DivMatches. Then you try to assign 90 to the id property of that object, but DivMatches does not have any id setter, so the assignment fails with a NoSuchMethodError.

Title: Class has no instance setter 'id='

Body:
In dart, I am getting this error while trying to override a property like this

var newId = state.myMatches[0][0].id = 90;

I am getting this error

flutter: The following NoSuchMethodError was thrown while handling a gesture:
flutter: Class 'DivMatches' has no instance setter 'id='.
flutter: Receiver: Instance of 'DivMatches'
flutter: Tried calling: id=90

There is no properties that private. All are public. Any help what's happening?

Thank you.


答:
Seems like you're trying to generate 4 unique random integers in the range 0...9.

You can do this by generating a vector of integers containing the values 0...9. Then shuffle the vector, as you want it to be a random selection of the integers. Lastly trimming the vector to the desired size, as you only want 4 unique random integers:

```<code>#include <vector>
#include <random>
#include <algorithm>
#include <numeric>

void gen4Nums(std::vector<int>& v) {
    //Generate initial vector with values 0...9:
    v.resize(10, 0);
    std::iota(v.begin(), v.end(), 0);

    //Shuffle the vector:
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(v.begin(), v.end(), g);

    //Trim the vector to contain only 4 integers:
    v.resize(4);
}
</code>```

Title: How to generate 4 different random numbers in C++

Body:
Seems like you're trying to generate 4 unique random integers in the range 0...9.

You can do this by generating a vector of integers containing the values 0...9. Then shuffle the vector, as you want it to be a random selection of the integers. Lastly trimming the vector to the desired size, as you only want 4 unique random integers:

#include <vector>
#include <random>
#include <algorithm>
#include <numeric>

void gen4Nums(std::vector<int>& v) {
    //Generate initial vector with values 0...9:
    v.resize(10, 0);
    std::iota(v.begin(), v.end(), 0);

    //Shuffle the vector:
    std::random_device rd;
    std::mt19937 g(rd());
    std::shuffle(v.begin(), v.end(), g);

    //Trim the vector to contain only 4 integers:
    v.resize(4);
}


答:
The problem is over here:

```<code>Survey.prototype.testFunction = () => {}
</code>```

Arrow functions don't have a this-context and it will use the this-context from outside of the method. Since no other this-context is defined, it will be the window object.

The fix is very easy: use a regular function:

```<code>Survey.prototype.testFunction = function () {}
</code>```

Title: "this" inside prototype takes window instead of object

Body:
The problem is over here:

Survey.prototype.testFunction = () => {}

Arrow functions don't have a this-context and it will use the this-context from outside of the method. Since no other this-context is defined, it will be the window object.

The fix is very easy: use a regular function:

Survey.prototype.testFunction = function () {}


问:
R parallel abort all mclapply operations
Is it possible to request that parallel::mclapply() abandons all further processing asap if it encounters an error (e.g., a stop()) in any one of its processes?

答:
The following is ugly, but workable.  It uses the filesystem as a global shared variable.

```<code>options( mc.cores=2 )

if (!exists("touchFile"))
    touchFile <- function(filename) { system(paste0("touch ", filename)); }

tfnm <- paste0("mytemporary",as.numeric(Sys.time()))

mfun <- function( i ) {
    if (file.exists( tfnm )) stop("done due to process ", i)
    message("Mfun(", i,")")
    if ( i == 3 ) { message("creating ", tfnm); touchFile(tfnm); stop("goodbye"); }
    Sys.sleep( i%%3 )
}

v <- mclapply( 1:10, mfun )
if (file.exists(tfnm)) file.remove(tfnm)
</code>```

This would be nicer to implement by mclapply itself.

Body:
The following is ugly, but workable.  It uses the filesystem as a global shared variable.

options( mc.cores=2 )

if (!exists("touchFile"))
    touchFile <- function(filename) { system(paste0("touch ", filename)); }

tfnm <- paste0("mytemporary",as.numeric(Sys.time()))

mfun <- function( i ) {
    if (file.exists( tfnm )) stop("done due to process ", i)
    message("Mfun(", i,")")
    if ( i == 3 ) { message("creating ", tfnm); touchFile(tfnm); stop("goodbye"); }
    Sys.sleep( i%%3 )
}

v <- mclapply( 1:10, mfun )
if (file.exists(tfnm)) file.remove(tfnm)

This would be nicer to implement by mclapply itself.


问:
return numbers from the middle of a string with irregular format
I have a field in a MySQL database that contains item descriptions of purchased products. Some of these are descriptions in plain English, others are part numbers, and others still are part numbers followed by a description. I have removed all spaces and dashes from the strings with a replace().

data looks like this:

```<code>1938420985390asdfih
1234812934810dflkasd
asdfasldkjfaasdfjasd
asd;flkjaklsdf
adfsdf1234073927357sdapjfas
1/4sdikhsd
</code>```

and I would like to return:

```<code>1938420985390
1234812934810
(null)
(null)
1234073927357
(null)
</code>```

What I really need is to write a SQL that will return the 13 digit part numbers, but not the extra letters/characters. I would prefer that it return the actual number, too, rather than a 1 or 0 for match/ no match.

I tried using a REGEXP function (someone suggested regexp ('\d{13}') or regexp ('\p{13}') but these didn't work. [These returned a 0 or 1, and not the part of the string that matched.] Any suggestions?

Thanks!

答:
The function you are looking for is REGEXP_SUBSTR():

```<code>SELECT REGEXP_SUBSTR(`dirty_value`,'[0-9]+') AS `clean_value` FROM `the_table`;
</code>```

Note: I test it and works; I'm using MySQL Server v8.0 (not sure it worked in previous versions).

Good luck!

Body:
I have a field in a MySQL database that contains item descriptions of purchased products. Some of these are descriptions in plain English, others are part numbers, and others still are part numbers followed by a description. I have removed all spaces and dashes from the strings with a replace().

data looks like this:

1938420985390asdfih
1234812934810dflkasd
asdfasldkjfaasdfjasd
asd;flkjaklsdf
adfsdf1234073927357sdapjfas
1/4sdikhsd

and I would like to return:

1938420985390
1234812934810
(null)
(null)
1234073927357
(null)

What I really need is to write a SQL that will return the 13 digit part numbers, but not the extra letters/characters. I would prefer that it return the actual number, too, rather than a 1 or 0 for match/ no match.

I tried using a REGEXP function (someone suggested regexp ('\d{13}') or regexp ('\p{13}') but these didn't work. [These returned a 0 or 1, and not the part of the string that matched.] Any suggestions?

Thanks!

Body:
The function you are looking for is REGEXP_SUBSTR():

SELECT REGEXP_SUBSTR(`dirty_value`,'[0-9]+') AS `clean_value` FROM `the_table`;

Note: I test it and works; I'm using MySQL Server v8.0 (not sure it worked in previous versions).

Good luck!


问:
Kotlin replacement for javah
javah has been deprecated since JDK 8 and will be/has been removed in JDK 10, and according to JEP 313 and the deprecation text, javac with the -h flag should be used instead:

Warning: The javah tool is planned to be removed in the next major JDK release. The tool has been superseded by the '-h' option added to javac in JDK 8. Users are recommended to migrate to using the javac '-h' option; see the javac man page for more information.

The problem is, javah operates on compiled .class files, while javac operates on source files (i.e. .java files.)

javah works fine with Kotlin and external functions, since everything ends up compiled as Java bytecode, but since there aren't any Java source files when using Kotlin, I don't see any way javac -h could work.

Is there a javah replacement, or a workaround, for Kotlin?

答:
You can also make it using javap and creating facade classes based on class files.

Take a look here for a sample: http://www.owsiak.org/how-to-solve-missing-javah-ugly-way/

Title: Kotlin replacement for javah


问:
Moodle web services refresh token
I understand that i can fetch web services client token through the url

https://www.yourmoodle.com/login/token.php?username=USERNAME&password=PASSWORD&service=SERVICESHORTNAME

and it works. I am getting a token and private token.

but i do not see a refreshtoken url. I can see the expiry date through moodle admin account.

Does anyone how to refresh moodle token?
what is the use of private token?

Thanks

答:
It looks like there's no inbuilt functionality to refresh a token like the OAuth 2 spec. You would need to call the login/token.php again if your API call fails.

Unfortunately the login/token.php file only returns the token and may return the private token (Private token, only transmitted to https sites and non-admin users.). From the client's perspective there's no way to know when the token will expire.

References:

https://github.com/moodle/moodle/blob/master/login/token.php

https://github.com/moodle/moodle/blob/master/lib/externallib.php#L1034

Title: Moodle web services refresh token


问:
How do I interpolate a variable as a key in a JavaScript object?
How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b["whatever"] and have this return 20:

```<code>var a = "whatever";
var b = {a : 20};     // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`
</code>```

I am asking if it's possible during the creation of b, to have it contain "whatever":20 instead of a:20 where "whatever" is itself in a variable. Maybe an eval could be used?

答:
```<code>var a = "whatever";
var b = {a : 20};
b[a] = 37;
alert(b["whatever"]); // 37
</code>```

'a' is a string with the value 'a'. a is a variable with the value 'whatever'.

Body:
How can I use the value of the variable a as a key to lookup a property? I want to be able to say: b["whatever"] and have this return 20:

var a = "whatever";
var b = {a : 20};     // Want this to assign b.whatever
alert(b["whatever"]); // so that this shows 20, not `undefined`

I am asking if it's possible during the creation of b, to have it contain "whatever":20 instead of a:20 where "whatever" is itself in a variable. Maybe an eval could be used?

Body:
var a = "whatever";
var b = {a : 20};
b[a] = 37;
alert(b["whatever"]); // 37

'a' is a string with the value 'a'. a is a variable with the value 'whatever'.


问:
How do I integrate Flutter web with Firebase?
I need to integrate my Flutter web app with Firebase. I found information, but it is all about Flutter for mobile apps and I need it for Flutter for web.</p>

答:
Integrate Flutter project with Firebase:

Step 1: Firebase Setup. Visit Firebase official site Here. Click on GO TO CONSOLE.

Step 2: Add App to Project.

Step 2.1: Integrate Firebase into iOS. Open your Flutter project. ...

Step 2.2: Integrate Firebase into Android. The easiest way to get the Android App Id is navigate to the build.gradle file.


问:
Is it possible to develop a new UI on top of Windows Workflow Foundation?
There this application called UiPath and it's been said that UiPath is built on top of Workflow Foundation. I was wondering if it is possible to use Workflow Foundation as a Framework and create custom EXE file with a custom UI. This will allow us to run Workflow Foundation tools within a custom application rather than Visual Studio. It this possible?

Thanks in advance,

答:
The answer was just a click away of searching "windows workflow foundation designer rehosting"

For a more straight forward answer click here


问:
Scrollview not working inside linearlayout
I want to use scrollview inside linearlayout and want to scroll particular this layout but it is not working.this is my code

```<code>  <?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:scrollbars="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/activity_custom_action_bar" />

    <LinearLayout
        android:id="@+id/ll_client_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dp15"
        android:background="@drawable/rounded_layout_white"
        android:orientation="horizontal"
        android:padding="@dimen/dp5"
        android:weightSum="1">

        <ImageView
            android:layout_width="@dimen/dp0"
            android:layout_height="match_parent"
            android:layout_weight="0.1"
            android:src="@drawable/img_user_icon" />

        <TextView
            android:id="@+id/tv_client_name"
            android:layout_width="@dimen/dp0"
            android:layout_height="match_parent"
            android:layout_weight="0.9"
            android:gravity="left|center"
            android:padding="@dimen/dp10"
            android:text=""
            android:textColor="@color/colorLightBlue"
            android:textSize="@dimen/dp12"
            android:textStyle="bold"

            />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp50"
        android:theme="@style/AppTheme.WhiteAccent"
        android:visibility="visible" />

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ListView
                android:id="@+id/lst_client_scheme"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/dp10"
                android:layout_marginTop="@dimen/dp20"
                android:layout_marginRight="@dimen/dp10"
                android:background="@color/colorGray"
                android:dividerHeight="0sp"
                android:scrollbars="vertical"
                android:visibility="visible"></ListView>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp300"
                android:layout_marginLeft="@dimen/dp10"
                android:layout_marginTop="@dimen/dp10"
                android:layout_marginRight="@dimen/dp10"
                android:background="@android:color/darker_gray"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_summary_date"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp25"
                    android:layout_marginTop="@dimen/dp20"
                    android:background="@android:color/darker_gray"
                    android:gravity="center"
                    android:text=""
                    android:textColor="@color/colorWhite"
                    android:textSize="@dimen/dp12" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp2"
                    android:background="@color/colorWhite" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal"
                    android:weightSum="1">

                    <LinearLayout
                        android:layout_width="@dimen/dp0"
                        android:layout_height="match_parent"
                        android:layout_weight="0.5"
                        android:gravity="center"
                        android:orientation="vertical"
                        android:weightSum="1">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="right"
                            android:orientation="vertical">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp30"
                                android:gravity="right"
                                android:text="Total Amount Invested"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_invst_amt"
                                android:layout_width="wrap_content"
                                android:layout_height="@dimen/dp40"
                                android:layout_marginTop="@dimen/dp5"

                              android:background="@drawable/corner_border"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text="9,857.51"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="@dimen/dp5"
                            android:gravity="right"
                            android:orientation="vertical">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp30"
                                android:gravity="right"
                                android:text="Total Current Amount"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_Curr_val"
                                android:layout_width="wrap_content"
                                android:layout_height="@dimen/dp40"
                                android:layout_marginTop="@dimen/dp5"

                              android:background="@drawable/corner_border"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text="9,857.51"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />
                        </LinearLayout>

                    </LinearLayout>

                    <View
                        android:layout_width="@dimen/dp2"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="@dimen/dp3"
                        android:background="@color/colorWhite" />

                    <LinearLayout
                        android:layout_width="@dimen/dp0"
                        android:layout_height="match_parent"
                        android:layout_weight="0.5"
                        android:gravity="top"
                        android:orientation="vertical"
                        android:weightSum="5">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Gain/Loss ST"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_gl_St"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Gain/Loss LT"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_gl_lt"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Dividend Reinvest"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_div_amt"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Ret ABS"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_ret_abs"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Weg. CAGR"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_weg_cagr"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                        </LinearLayout>
                    </LinearLayout>

                </LinearLayout>
            </LinearLayout>

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
  </LinearLayout>
 </ScrollView>
</code>```

How I modify this code to scroll layout? I want to scroll particular layout inside the main linear layout.is it fine? guide me over this.is this code is ok?
How I use scroll view inside the linear layout.

答: Surround the layout which you want to make scrollable with ScrollView and set orientation to vertical or vertical.In  your code,remove nested scroll view and try once</p>

Body:
I want to use scrollview inside linearlayout and want to scroll particular this layout but it is not working.this is my code

  <?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:scrollbars="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/activity_custom_action_bar" />

    <LinearLayout
        android:id="@+id/ll_client_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dp15"
        android:background="@drawable/rounded_layout_white"
        android:orientation="horizontal"
        android:padding="@dimen/dp5"
        android:weightSum="1">

        <ImageView
            android:layout_width="@dimen/dp0"
            android:layout_height="match_parent"
            android:layout_weight="0.1"
            android:src="@drawable/img_user_icon" />

        <TextView
            android:id="@+id/tv_client_name"
            android:layout_width="@dimen/dp0"
            android:layout_height="match_parent"
            android:layout_weight="0.9"
            android:gravity="left|center"
            android:padding="@dimen/dp10"
            android:text=""
            android:textColor="@color/colorLightBlue"
            android:textSize="@dimen/dp12"
            android:textStyle="bold"

            />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp50"
        android:theme="@style/AppTheme.WhiteAccent"
        android:visibility="visible" />

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ListView
                android:id="@+id/lst_client_scheme"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/dp10"
                android:layout_marginTop="@dimen/dp20"
                android:layout_marginRight="@dimen/dp10"
                android:background="@color/colorGray"
                android:dividerHeight="0sp"
                android:scrollbars="vertical"
                android:visibility="visible"></ListView>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="@dimen/dp300"
                android:layout_marginLeft="@dimen/dp10"
                android:layout_marginTop="@dimen/dp10"
                android:layout_marginRight="@dimen/dp10"
                android:background="@android:color/darker_gray"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/tv_summary_date"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp25"
                    android:layout_marginTop="@dimen/dp20"
                    android:background="@android:color/darker_gray"
                    android:gravity="center"
                    android:text=""
                    android:textColor="@color/colorWhite"
                    android:textSize="@dimen/dp12" />

                <View
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp2"
                    android:background="@color/colorWhite" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal"
                    android:weightSum="1">

                    <LinearLayout
                        android:layout_width="@dimen/dp0"
                        android:layout_height="match_parent"
                        android:layout_weight="0.5"
                        android:gravity="center"
                        android:orientation="vertical"
                        android:weightSum="1">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="right"
                            android:orientation="vertical">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp30"
                                android:gravity="right"
                                android:text="Total Amount Invested"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_invst_amt"
                                android:layout_width="wrap_content"
                                android:layout_height="@dimen/dp40"
                                android:layout_marginTop="@dimen/dp5"

                              android:background="@drawable/corner_border"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text="9,857.51"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="@dimen/dp5"
                            android:gravity="right"
                            android:orientation="vertical">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp30"
                                android:gravity="right"
                                android:text="Total Current Amount"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_Curr_val"
                                android:layout_width="wrap_content"
                                android:layout_height="@dimen/dp40"
                                android:layout_marginTop="@dimen/dp5"

                              android:background="@drawable/corner_border"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text="9,857.51"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />
                        </LinearLayout>

                    </LinearLayout>

                    <View
                        android:layout_width="@dimen/dp2"
                        android:layout_height="match_parent"
                        android:layout_marginLeft="@dimen/dp3"
                        android:background="@color/colorWhite" />

                    <LinearLayout
                        android:layout_width="@dimen/dp0"
                        android:layout_height="match_parent"
                        android:layout_weight="0.5"
                        android:gravity="top"
                        android:orientation="vertical"
                        android:weightSum="5">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Gain/Loss ST"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_gl_St"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Gain/Loss LT"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_gl_lt"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Dividend Reinvest"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_total_div_amt"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Ret ABS"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_ret_abs"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <View
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp2"
                                android:background="@color/colorWhite" />
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/dp0"
                            android:layout_weight="1"
                            android:orientation="vertical"
                            android:weightSum="1">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="right|center"
                                android:padding="@dimen/dp5"
                                android:text="Total Weg. CAGR"
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                            <TextView
                                android:id="@+id/tv_weg_cagr"
                                android:layout_width="match_parent"
                                android:layout_height="@dimen/dp0"
                                android:layout_weight="0.5"
                                android:gravity="center|right"
                                android:padding="@dimen/dp5"
                                android:text=""
                                android:textColor="@color/colorWhite"
                                android:textSize="@dimen/dp12"
                                android:textStyle="bold" />

                        </LinearLayout>
                    </LinearLayout>

                </LinearLayout>
            </LinearLayout>

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
  </LinearLayout>
 </ScrollView>

How I modify this code to scroll layout? I want to scroll particular layout inside the main linear layout.is it fine? guide me over this.is this code is ok?
How I use scroll view inside the linear layout.


问:
Hiding button if swift Coredata function is blank
I have a problem with some code. I have a function called attachments. It calls on a DatabaseManager to a specific function getttachmentdata. This calls on coredata to see if a user has uploaded an image and call on it. If it has it I have another part of the code where the user clicks on a button and it shows that image.

The problem is that when the data is blank or there is nothing uploaded I wanted the button to be disabled. This might be a simple fix but I am not quite sure actually.

```<code>    let attachments = DataBaseManager().getAttachmentData()
    if attachments.isEmpty  {
        btnProofOfDelivery.isHidden = true
        btnProofOfDelivery.isEnabled = false
    }
</code>```

I wrote the code above, however, when I tried running my program it still displayed the button that I wanted to disappear. Running without the if statement makes the button disappear.

code for getattachments

```<code>func getAttachmentData()-> Array<Data>{
    var data1 = [Data]()
    let context = CoreData.sharedCoreData.managedObjectContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Attachments")

    do {
        let result = try context.fetch(request)
        print(result)
        for data in result as! [NSManagedObject] {
            print(data.value(forKey: "attachment") as! Data)
            data1.append(data.value(forKey: "attachment") as! Data)
        }
        if data1.count == 0 {
            return [Data()]
        }else{
            return data1
        }
    } catch {
        return [Data()]
    }
}
</code>```

答:
Below is your bug, if the fetch doesn't return anything you return a new Data object

```<code>if data1.count == 0 {
   return [Data()]
}
</code>```

You of course meant to write

```<code>if data1.count == 0 {
   return [Data]()
}
</code>```

and some issue in catch

or you can just remove all of that since data1 is properly initialised so you can just return it either way so the code after the for {} loop can then be reduced to

```<code>        return data1
    } catch {
        print(error)
    }
}
</code>```

Body:
I have a problem with some code. I have a function called attachments. It calls on a DatabaseManager to a specific function getttachmentdata. This calls on coredata to see if a user has uploaded an image and call on it. If it has it I have another part of the code where the user clicks on a button and it shows that image.

The problem is that when the data is blank or there is nothing uploaded I wanted the button to be disabled. This might be a simple fix but I am not quite sure actually.

    let attachments = DataBaseManager().getAttachmentData()
    if attachments.isEmpty  {
        btnProofOfDelivery.isHidden = true
        btnProofOfDelivery.isEnabled = false
    }

I wrote the code above, however, when I tried running my program it still displayed the button that I wanted to disappear. Running without the if statement makes the button disappear.

code for getattachments

func getAttachmentData()-> Array<Data>{
    var data1 = [Data]()
    let context = CoreData.sharedCoreData.managedObjectContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Attachments")

    do {
        let result = try context.fetch(request)
        print(result)
        for data in result as! [NSManagedObject] {
            print(data.value(forKey: "attachment") as! Data)
            data1.append(data.value(forKey: "attachment") as! Data)
        }
        if data1.count == 0 {
            return [Data()]
        }else{
            return data1
        }
    } catch {
        return [Data()]
    }
}

Body:
Below is your bug, if the fetch doesn't return anything you return a new Data object

if data1.count == 0 {
   return [Data()]
}

You of course meant to write

if data1.count == 0 {
   return [Data]()
}

and some issue in catch

or you can just remove all of that since data1 is properly initialised so you can just return it either way so the code after the for {} loop can then be reduced to

        return data1
    } catch {
        print(error)
    }
}


问:
How to specify float precision in knex schema ?
I'm having trouble defining float precision in a knex schema, i want it to be a float(10,6) in order to store lat/long location. Here's how im trying to declare it :

```<code>lat: {type: 'float(10,6)', nullable: false},
</code>```

It fails at migrate because of the (10,6), so how is the right way to do this ?

答:
To store geolocation I used a double precision data type, and for that my migration stays like that:</p>
```<code>exports.up = function(knex, Promise) {
    return knex.schema.createTable('route', table => {
        table.increments('id').primary()
        table.specificType('latitude', 'double precision').notNull()
        table.specificType('longitude', 'double precision').notNull()
    })
};

exports.down = function(knex, Promise) {
    return knex.schema.dropTable('route')
};
</code>```

Body:
I'm having trouble defining float precision in a knex schema, i want it to be a float(10,6) in order to store lat/long location. Here's how im trying to declare it :

lat: {type: 'float(10,6)', nullable: false},

It fails at migrate because of the (10,6), so how is the right way to do this ?

Body:
To store geolocation I used a double precision data type, and for that my migration stays like that:

exports.up = function(knex, Promise) {
    return knex.schema.createTable('route', table => {
        table.increments('id').primary()
        table.specificType('latitude', 'double precision').notNull()
        table.specificType('longitude', 'double precision').notNull()
    })
};

exports.down = function(knex, Promise) {
    return knex.schema.dropTable('route')
};


问:
Bitbucket API - payload for "push" event - how to most reliably get latest hash
It looks like to get the latest hash of a change it's something like:

```<code>const hash = body.push.changes[0].new.target.hash;
</code>```

That seems a little awkward though, given the array access - will it always be the first element?

Here are the docs I am looking at:
https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html

And the sample payload for a push is:
https://gist.github.com/ORESoftware/1ef3abe66dba23039ddd90fef1093318

I really am confused about how to access the latest hash when there's a change/push to a repository.

答:
From the doc you linked, the push property contains:

The details of the push, which includes the changes property. This property contains an array with all the references that the push updated and the following properties:

So no, you can't just look at the first value. If the user pushes multiple branches at once (git push origin --all, for example), you may have multiple objects in the changes array. For instance, one branch could have been deleted, another one created (old would be null), and a third could have been updated. So in processing these push events, you should make sure to handle multiple possible reference updates at once.

How to most reliably get latest hash

What exactly are you trying to accomplish by getting the latest hash? If you just need to record all the hashes, it should suffice to just map over the changes array, e.g.

```<code>const hashes = body.push.changes.map(change => change.new.target.hash);
</code>```

But it seems like you're making the assumption that you can handle repository changes one at a time. This is most likely false -- someone can clone a repository, change a ton of branches in diverging ways, and push (or force push!) those changes up.

Body:
It looks like to get the latest hash of a change it's something like:

const hash = body.push.changes[0].new.target.hash;

That seems a little awkward though, given the array access - will it always be the first element?

Here are the docs I am looking at:
https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html

And the sample payload for a push is:
https://gist.github.com/ORESoftware/1ef3abe66dba23039ddd90fef1093318

I really am confused about how to access the latest hash when there's a change/push to a repository.

Body:
From the doc you linked, the push property contains:

The details of the push, which includes the changes property. This property contains an array with all the references that the push updated and the following properties:

So no, you can't just look at the first value. If the user pushes multiple branches at once (git push origin --all, for example), you may have multiple objects in the changes array. For instance, one branch could have been deleted, another one created (old would be null), and a third could have been updated. So in processing these push events, you should make sure to handle multiple possible reference updates at once.

How to most reliably get latest hash

What exactly are you trying to accomplish by getting the latest hash? If you just need to record all the hashes, it should suffice to just map over the changes array, e.g.

const hashes = body.push.changes.map(change => change.new.target.hash);

But it seems like you're making the assumption that you can handle repository changes one at a time. This is most likely false -- someone can clone a repository, change a ton of branches in diverging ways, and push (or force push!) those changes up.


问:
edit regedit value using bat file
I am trying to change the value of a reg_dword entry: start in location: Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv
to value 2.

I tried already exacting code from several sites, nothing works and I am launching it as admin:

```<code>REG.exe ADD "Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv" /t REG_DWORD /v Start /d 2 /f
REG ADD "Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv" /t REG_DWORD /v Start /d 2 /f
REG.exe ADD "Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv" /v "Start" /t REG_DWORD /d 2 /f
</code>```

On every site there was information with slight difference, but i don't think order matter, maybe "".

What is the correct syntax for adding a registry value as described above?

答:
Your problem is the Computer.
Indeed, the order of the options does not matter. Also it doesn't matter if you call REG or REG.exe.

Usually, the inbuilt help is also your friend:

reg add /?

Which tells you that Computer is the (network) name of the remote computer and can be omitted to use the current (local) computer as default.

This line works fine (as any other of yours without the Computer\:

```<code>REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv" /t REG_DWORD /v Start /d 3 /f
</code>```

Offtopic: Check out the other networks of stackexchange. I'd think this question would be more suitable for https://superuser.com/.

Title: edit regedit value using bat file

Body:
I am trying to change the value of a reg_dword entry: start in location: Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv
to value 2.

I tried already exacting code from several sites, nothing works and I am launching it as admin:

REG.exe ADD "Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv" /t REG_DWORD /v Start /d 2 /f
REG ADD "Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv" /t REG_DWORD /v Start /d 2 /f
REG.exe ADD "Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv" /v "Start" /t REG_DWORD /d 2 /f

On every site there was information with slight difference, but i don't think order matter, maybe "".

What is the correct syntax for adding a registry value as described above?

Body:
Your problem is the Computer.
Indeed, the order of the options does not matter. Also it doesn't matter if you call REG or REG.exe.

Usually, the inbuilt help is also your friend:

reg add /?

Which tells you that Computer is the (network) name of the remote computer and can be omitted to use the current (local) computer as default.

This line works fine (as any other of yours without the Computer\:

REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\hidserv" /t REG_DWORD /v Start /d 3 /f

Offtopic: Check out the other networks of stackexchange. I'd think this question would be more suitable for https://superuser.com/.


问:
How to group by similar rows in pandas
I applied groupby on a dataframe

df.groupby('Category').sum()

after which the result dataframe looks like this

```<code>               height      weight
General  42.849980  157.500553
GENERAL  49.607315  177.340407
Genera  56.293531  171.524640
CategoryA  48.421077  144.251986
CategoryB  48.421077  144.251986
CategoryC  48.421077  144.251986
</code>```

I need to group General, GENERAL and Genera in a single row and the result to look like

```<code>General    123.849980  300.500553
CategoryA  48.421077  144.251986
CategoryB  48.421077  144.251986
CategoryC  48.421077  144.251986
</code>```

How can I accomplish this ?

Edit: Got the solution with the regex.
Is there any way if I need to categorize General, GENERAL, Genera and CategoryA into a single group ?

答:
Assuming that the category you are grouping by is in the index, you can do:

```<code>import re

result = (
    df
    .groupby(df.index.str.replace("genera.*", "General", flags=re.IGNORECASE))
    .sum()
)
</code>```

Edit: If you don't want to use regex, you can use a different approach with .map. In the example below I assume that your categories are in a column named Category:

```<code>mapping = {
    "General": "CategoryA",
    "GENERAL": "CategoryA",
    "Genera": "CategoryA",
}
result = (
    df
    .groupby(df.Category.map(mapping).fillna(df.Category))
    .sum()
)
</code>```

Title: How to group by similar rows in pandas

Body:
I applied groupby on a dataframe

df.groupby('Category').sum()

after which the result dataframe looks like this

               height      weight
General  42.849980  157.500553
GENERAL  49.607315  177.340407
Genera  56.293531  171.524640
CategoryA  48.421077  144.251986
CategoryB  48.421077  144.251986
CategoryC  48.421077  144.251986

I need to group General, GENERAL and Genera in a single row and the result to look like

General    123.849980  300.500553
CategoryA  48.421077  144.251986
CategoryB  48.421077  144.251986
CategoryC  48.421077  144.251986

How can I accomplish this ?

Edit: Got the solution with the regex.
Is there any way if I need to categorize General, GENERAL, Genera and CategoryA into a single group ?

Body:
Assuming that the category you are grouping by is in the index, you can do:

import re

result = (
    df
    .groupby(df.index.str.replace("genera.*", "General", flags=re.IGNORECASE))
    .sum()
)

Edit: If you don't want to use regex, you can use a different approach with .map. In the example below I assume that your categories are in a column named Category:

mapping = {
    "General": "CategoryA",
    "GENERAL": "CategoryA",
    "Genera": "CategoryA",
}
result = (
    df
    .groupby(df.Category.map(mapping).fillna(df.Category))
    .sum()
)


问:
Convert pivot table generated from pivottabler package to dataframe
I'm trying to make a pivot table with pivottabler package. I want to convert the pivot table object to dataframe, so that I can convert it to data table (with DT) and render it in Shiny app, so that it's downloadable.

```<code>library(pivottabler)
pt = qpvt(mtcars, 'cyl', 'vs', 'n()')
</code>```

I tried to convert it to matrix

```<code>as.data.frame(pt)
</code>```

I got error message like below:

```<code>Error in as.data.frame.default(pt) : cannot coerce class ‘c("PivotTable", "R6")’ to a data.frame
</code>```

Does anyone know how to convert the pivot table object to dataframe?

答:
It is an R6 class.  One option would be to extract with asDataFrame which can be revealed if we check the str

```<code>str(pt)
#...
#...
#asDataFrame: function (separator = " ", stringsAsFactors = default.stringsAsFactors())
#asJSON: function ()
#asList: function ()
#asMatrix: function (includeHeaders = TRUE, repeatHeaders = FALSE, rawValue = FALSE)
#asTidyDataFrame: function (includeGroupCaptions = TRUE, includeGroupValues = TRUE,
...
</code>```

Therefore, applying asDataFrame() on the R6 object

```<code>out <- pt$asDataFrame()
out
#     0  1 Total
#4      1 10    11
#6      3  4     7
#8     14 NA    14
#Total 18 14    32

str(out)
#'data.frame':  4 obs. of  3 variables:
#$ 0    : int  1 3 14 18
#$ 1    : int  10 4 NA 14
#$ Total: int  11 7 14 32
</code>```

or to get a matrix, asMatrix

```<code>pt$asMatrix()
#      [,1]    [,2] [,3] [,4]
#[1,] ""      "0"  "1"  "Total"
#[2,] "4"     "1"  "10" "11"
#[3,] "6"     "3"  "4"  "7"
#[4,] "8"     "14" ""   "14"
#[5,] "Total" "18" "14" "32"
</code>```

Body:
I'm trying to make a pivot table with pivottabler package. I want to convert the pivot table object to dataframe, so that I can convert it to data table (with DT) and render it in Shiny app, so that it's downloadable.

library(pivottabler)
pt = qpvt(mtcars, 'cyl', 'vs', 'n()')

I tried to convert it to matrix

as.data.frame(pt)

I got error message like below:

Error in as.data.frame.default(pt) : cannot coerce class ‘c("PivotTable", "R6")’ to a data.frame

Does anyone know how to convert the pivot table object to dataframe?

Body:
It is an R6 class.  One option would be to extract with asDataFrame which can be revealed if we check the str

str(pt)
#...
#...
#asDataFrame: function (separator = " ", stringsAsFactors = default.stringsAsFactors())
#asJSON: function ()
#asList: function ()
#asMatrix: function (includeHeaders = TRUE, repeatHeaders = FALSE, rawValue = FALSE)
#asTidyDataFrame: function (includeGroupCaptions = TRUE, includeGroupValues = TRUE,
...

Therefore, applying asDataFrame() on the R6 object

out <- pt$asDataFrame()
out
#     0  1 Total
#4      1 10    11
#6      3  4     7
#8     14 NA    14
#Total 18 14    32

str(out)
#'data.frame':  4 obs. of  3 variables:
#$ 0    : int  1 3 14 18
#$ 1    : int  10 4 NA 14
#$ Total: int  11 7 14 32

or to get a matrix, asMatrix

pt$asMatrix()
#      [,1]    [,2] [,3] [,4]
#[1,] ""      "0"  "1"  "Total"
#[2,] "4"     "1"  "10" "11"
#[3,] "6"     "3"  "4"  "7"
#[4,] "8"     "14" ""   "14"
#[5,] "Total" "18" "14" "32"


问:
Are there any pitfalls in displaying a "No JavaScript" warning in the following fashion?
I have a webpage that has a comment box that can be toggled by clicking a link (the opening and closing of the box is controlled using JavaScript, specifically JQuery). This box is hidden by default, so naturally, it's impossible to display without the use of JavaScript. I'm not concerned by this fact: the comment box is not a "necessary" feature and this is a small personal site, so I don't mind that a tiny percentage of visitors may not experience full functionality. However, I would like to display a warning if the user does not have JavaScript enabled.

I've considered the idea of doing this by presenting a small message (with the use of a simple HTML
 tag) near the link that toggles the comment box, using the following bit of code:

```<code><p class="alert" id="nojs-warning">You must have JavaScript enabled to leave a comment.</p>
</code>```

Of course, I don't want to display this if JavaScript is enabled, so I have the following JQuery trigger set up to immediately hide the box when the page is loaded:

```<code>$(function() {
    $('#nojs-warning').hide();
});
</code>```

Thus, if the user has JavaScript enabled, the event will fire and the warning will be hidden; if the user doesn't have JavaScript enabled, the event won't fire, and thus the warning will still be displayed.

For such a small, personal site, this seems like an elegant solution. Are there any pitfalls to this approach?

答:
The only obvious concern is that the function doesn't run even if javascript is enabled. Is there a particular reason you aren't using the  tag built into HTML. It's likely doing the same thing but without the need for javascript.
link text</p>

OwnerDisplayName: mipadi

ContentLicense: CC BY-SA 2.5

Body:
I have a webpage that has a comment box that can be toggled by clicking a link (the opening and closing of the box is controlled using JavaScript, specifically JQuery). This box is hidden by default, so naturally, it's impossible to display without the use of JavaScript. I'm not concerned by this fact: the comment box is not a "necessary" feature and this is a small personal site, so I don't mind that a tiny percentage of visitors may not experience full functionality. However, I would like to display a warning if the user does not have JavaScript enabled.

I've considered the idea of doing this by presenting a small message (with the use of a simple HTML
 tag) near the link that toggles the comment box, using the following bit of code:

You must have JavaScript enabled to leave a comment.

Of course, I don't want to display this if JavaScript is enabled, so I have the following JQuery trigger set up to immediately hide the box when the page is loaded:

$(function() {
    $('#nojs-warning').hide();
});

Thus, if the user has JavaScript enabled, the event will fire and the warning will be hidden; if the user doesn't have JavaScript enabled, the event won't fire, and thus the warning will still be displayed.

For such a small, personal site, this seems like an elegant solution. Are there any pitfalls to this approach?

OwnerDisplayName: Paulo


问:
Cutting a database down to size
Say you have a database that has served a company for 10 years. It is 500GB in size, it has myriad tables, stored procedures and triggers.

Now say you wish to create a cut down version of the database to use as a test bed for use in integration testing and for individual testers and developers to spin up instances of to play around with.

In broad terms how would you set about this task?

In case it matters, the database I have in mind is SQL Server 2008.

Edit: removed "unit testing" because of course unit tests should not test db integration

答: Check http://jailer.sourceforge.net/ out. It is a tool that can extract a subset of the data from a DB while keeping it consistent referentially. I haven't used it myself, but I've been meaning to.</p>

Title: Cutting a database down to size