问:
CSV response from get request in elastic search
I am sending an http Get request to elastic search server and i want the response to be in csv format.Like in solr we can specify wt=csv is there any way In elastic Search too ?
My query is :</p>

```<code>enter code here
 http://elasticServer/_search?q=RCE:"some date" OR
 VENDOR_NAME:"Anuj"&from=0&size=5&sort=@timestamp

  -----After that i want to force the server to return me response in csv format
</code>```

答:
By default, ES supports only two data formats: JSON and YAML. However, if you're open to using Logstash, you can achieve what you want very easily like this:

```<code>input {
  elasticsearch {
    hosts => ["localhost:9200"]
    query => 'RCE:"some date" OR VENDOR_NAME:"Anuj"'
    size => 5
  }
}
filter {}
output {
  csv {
    fields => ["field1", "field2", "field3"]
    path => "/path/to/data.csv"
  }
}
</code>```

Since the elasticsearch input uses scrolling, you cannot specify any sorting. So if sorting is really important to you, you can use the http_poller input instead of the elasticsearch one, like this:

```<code>input {
  http_poller {
    urls => {
      es => {
        method => get
        url => 'http://elasticServer/_search?q=RCE:"some date" OR VENDOR_NAME:"Anuj"&from=0&size=5&sort=@timestamp'
        headers => {
          Accept => "application/json"
        }
      }
    }
    codec => "json"
  }
}
filter {}
output {
  csv {
    fields => ["field1", "field2", "field3"]
    path => "/path/to/data.csv"
  }
}
</code>```

Body:
I am sending an http Get request to elastic search server and i want the response to be in csv format.Like in solr we can specify wt=csv is there any way In elastic Search too ?
My query is :

enter code here
 http://elasticServer/_search?q=RCE:"some date" OR
 VENDOR_NAME:"Anuj"&from=0&size=5&sort=@timestamp

  -----After that i want to force the server to return me response in csv format

Body:
By default, ES supports only two data formats: JSON and YAML. However, if you're open to using Logstash, you can achieve what you want very easily like this:

input {
  elasticsearch {
    hosts => ["localhost:9200"]
    query => 'RCE:"some date" OR VENDOR_NAME:"Anuj"'
    size => 5
  }
}
filter {}
output {
  csv {
    fields => ["field1", "field2", "field3"]
    path => "/path/to/data.csv"
  }
}

Since the elasticsearch input uses scrolling, you cannot specify any sorting. So if sorting is really important to you, you can use the http_poller input instead of the elasticsearch one, like this:

input {
  http_poller {
    urls => {
      es => {
        method => get
        url => 'http://elasticServer/_search?q=RCE:"some date" OR VENDOR_NAME:"Anuj"&from=0&size=5&sort=@timestamp'
        headers => {
          Accept => "application/json"
        }
      }
    }
    codec => "json"
  }
}
filter {}
output {
  csv {
    fields => ["field1", "field2", "field3"]
    path => "/path/to/data.csv"
  }
}


来源: stackexchange

问:
Select query for filtering data from particular range of year and month
I want to display data from user selected year of March to next year of April(ex:if user selected 2017, then  need to select data from from 2017 march to april 2018 ). What is the best query for filtering it. It should be order by from selected year.</p>

```<code>SELECT DATEPART(mm,submitted_date),SUM(total_count),YEAR(submitted_date)
FROM store_details
WHERE YEAR(submitted_date) = '2017'
AND  MONTH(submitted_date) >=3
Group By YEAR(submitted_date),DATEPART(mm,submitted_date)
Order By YEAR(submitted_date),DATEPART(mm,submitted_date)
</code>```

答:
Well, later versions (2012+) of SQL Server have a nice built in function called datefromparts. However, since your question is tagged with sql-server-2005 this doesn't help so much unless you can upgrade your database (and you really should think about it, since 2005 is no longer supported by Microsoft).

However, since you know you want all the data between March and April of next year, you can simply do this:

```<code>SELECT DATEPART(MONTH,submitted_date),SUM(total_count),YEAR(submitted_date)
FROM store_details
WHERE submitted_date >= CAST(CAST(@Year as char(4)) + '-03-01 00:00:00' As datetime)
WHERE submitted_date < CAST(CAST(@Year + 1 as char(4)) + '-04-01 00:00:00' As datetime)

Group By YEAR(submitted_date),DATEPART(MONTH,submitted_date)
Order By YEAR(submitted_date),DATEPART(MONTH,submitted_date)
</code>```

(That is, assuming the user provides the year as an int value.)

ContentLicense: CC BY-SA 3.0

Body:
I want to display data from user selected year of March to next year of April(ex:if user selected 2017, then  need to select data from from 2017 march to april 2018 ). What is the best query for filtering it. It should be order by from selected year.

SELECT DATEPART(mm,submitted_date),SUM(total_count),YEAR(submitted_date)
FROM store_details
WHERE YEAR(submitted_date) = '2017'
AND  MONTH(submitted_date) >=3
Group By YEAR(submitted_date),DATEPART(mm,submitted_date)
Order By YEAR(submitted_date),DATEPART(mm,submitted_date)

Body:
Well, later versions (2012+) of SQL Server have a nice built in function called datefromparts. However, since your question is tagged with sql-server-2005 this doesn't help so much unless you can upgrade your database (and you really should think about it, since 2005 is no longer supported by Microsoft).

However, since you know you want all the data between March and April of next year, you can simply do this:

SELECT DATEPART(MONTH,submitted_date),SUM(total_count),YEAR(submitted_date)
FROM store_details
WHERE submitted_date >= CAST(CAST(@Year as char(4)) + '-03-01 00:00:00' As datetime)
WHERE submitted_date < CAST(CAST(@Year + 1 as char(4)) + '-04-01 00:00:00' As datetime)

Group By YEAR(submitted_date),DATEPART(MONTH,submitted_date)
Order By YEAR(submitted_date),DATEPART(MONTH,submitted_date)

(That is, assuming the user provides the year as an int value.)


问:
Scala type mismatch [scala]
I have the following function

```<code>def weight(Actors:RDD[(String,Int)],name:String,count:Int):Float={
    val count1=Actors.lookup(name)
    val i_count=if (!count1.isEmpty) count1(0) else 0
    val edge=if (i_count!=0) (count.toFloat/i_count.toFloat) else 0.0
}
</code>```

and I get the following error

```<code> <console>:229: error: type mismatch;
 found   : Unit
 required: Float
       }
</code>```

Is it caused by divide 0 error?
How to solve that problem?

答:
The weight function is not returning anything but Float is defined as a return type.

Replacing the final line

```<code>val edge=if (i_count!=0) (count.toFloat/i_count.toFloat) else 0.0
</code>```

by

```<code>if (i_count!=0) (count.toFloat/i_count.toFloat) else 0F
</code>```

should resolve your issue

Title: Scala type mismatch [scala]

Body:
I have the following function

def weight(Actors:RDD[(String,Int)],name:String,count:Int):Float={
    val count1=Actors.lookup(name)
    val i_count=if (!count1.isEmpty) count1(0) else 0
    val edge=if (i_count!=0) (count.toFloat/i_count.toFloat) else 0.0
}

and I get the following error

 <console>:229: error: type mismatch;
 found   : Unit
 required: Float
       }

Is it caused by divide 0 error?
How to solve that problem?

Body:
The weight function is not returning anything but Float is defined as a return type.

Replacing the final line

val edge=if (i_count!=0) (count.toFloat/i_count.toFloat) else 0.0

by

if (i_count!=0) (count.toFloat/i_count.toFloat) else 0F

should resolve your issue


问:
How to locate ng-model within a div element in Selenium C#
I need help with trying to locate an element with ng-model="error-message". This element is within a div element. I am using selenium with C#.

    Error while creating instance from import file: Error: End of data reached (data length = 0, asked index = 4). Corrupted zip ?
```

The value of the element changes based on button click and file upload window event. Below is the html code of the page.

答:
Hope the below locator solves your query:

driver.FindElement(By.CssSelector("label[ng-model='errorMessage']"));

Body:
I need help with trying to locate an element with ng-model="error-message". This element is within a div element. I am using selenium with C#.

    Error while creating instance from import file: Error: End of data reached (data length = 0, asked index = 4). Corrupted zip ?

The value of the element changes based on button click and file upload window event. Below is the html code of the page.


问:
Write shell script by taking table name as parameter and executing hive query
I'm trying to build a shell script that takes table_name as parameter and run the below hive query. </p>

```<code>INSERT OVERWRITE DIRECTORY '/data/table_name'
row format delimited
FIELDS TERMINATED BY ','
SELECT * FROM table_name
</code>```

答:
maybe you need it:</p>

```<code>#!/bin/bash
if [ -z "$1" ]; then exit 1; fi
printf -v TAB "%q" "$1"
/usr/bin/mysql -NBe "INSERT OVERWRITE DIRECTORY '/data/table_$TAB' row format delimited FIELDS TERMINATED BY ',' SELECT * FROM $TAB"
</code>```

Body:
I'm trying to build a shell script that takes table_name as parameter and run the below hive query.

INSERT OVERWRITE DIRECTORY '/data/table_name'
row format delimited
FIELDS TERMINATED BY ','
SELECT * FROM table_name

Body:
maybe you need it:

#!/bin/bash
if [ -z "$1" ]; then exit 1; fi
printf -v TAB "%q" "$1"
/usr/bin/mysql -NBe "INSERT OVERWRITE DIRECTORY '/data/table_$TAB' row format delimited FIELDS TERMINATED BY ',' SELECT * FROM $TAB"


问:
"ImportError: No module named" when trying to run Python script
I'm trying to run a script that launches, amongst other things, a python script.  I get a ImportError: No module named ..., however, if I launch ipython and import the same module in the same way through the interpreter, the module is accepted.

What's going on, and how can I fix it?  I've tried to understand how python uses PYTHONPATH but I'm thoroughly confused.  Any help would greatly appreciated.

答:
Remove pathlib and reinstall it. Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command:

```<code>pip install pathlib
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Remove pathlib and reinstall it. Delete the pathlib in sitepackages folder and reinstall the pathlib package by using pip command:

pip install pathlib


问:
D3 with custom element: TypeError: t is null
I'm trying to use D3 v.4 with a canvas element (following the pattern introduced here). I want to bind my data to a custom element, so that it is accessible in memory but isn't rendered to the page like an svg. However, the code below throws: TypeError: t is null. I can't get a good stack trace on the error.

```<code>const data = [{a:1,b:2},{a:2,b:4}];

const dataContainer = document.createElement('custom');
const container = d3.select(dataContainer)
      .data(data).enter()
      .append('custom')
      .attr('class','element')
      .attr('test-data-attribute', (d) => { return d; });

const nodes = container.selectAll('.element');
console.log(nodes.length);
</code>```

Codepen demo here: https://codepen.io/jaredsk/pen/OgPMpL?editors=0010 Thanks in advance!

答:
Whatever you're trying to do (which I'm not really following), for that enter selection to work you have to use selectAll:

```<code>const data = [{
    a: 1,
    b: 2
}, {
    a: 2,
    b: 4
}];

const dataContainer = document.createElement('custom');
const container = d3.select(dataContainer)
    .selectAll(null)// <---- selectAll here
    .data(data).enter()
    .append('custom')
    .attr('class', 'element')
    .attr('test-data-attribute', (d) => {
        return d;
    });

const nodes = container.selectAll('.element');
console.log(nodes);
</code>```

Here is the updated CodePen: https://codepen.io/anon/pen/gRbPjb?editors=0110

PS: I removed the length in console.log(nodes.length) because, in D3 v4.x, selections are objects, not arrays anymore.

Body:
I'm trying to use D3 v.4 with a canvas element (following the pattern introduced here). I want to bind my data to a custom element, so that it is accessible in memory but isn't rendered to the page like an svg. However, the code below throws: TypeError: t is null. I can't get a good stack trace on the error.

const data = [{a:1,b:2},{a:2,b:4}];

const dataContainer = document.createElement('custom');
const container = d3.select(dataContainer)
      .data(data).enter()
      .append('custom')
      .attr('class','element')
      .attr('test-data-attribute', (d) => { return d; });

const nodes = container.selectAll('.element');
console.log(nodes.length);

Codepen demo here: https://codepen.io/jaredsk/pen/OgPMpL?editors=0010 Thanks in advance!

Body:
Whatever you're trying to do (which I'm not really following), for that enter selection to work you have to use selectAll:

const data = [{
    a: 1,
    b: 2
}, {
    a: 2,
    b: 4
}];

const dataContainer = document.createElement('custom');
const container = d3.select(dataContainer)
    .selectAll(null)// <---- selectAll here
    .data(data).enter()
    .append('custom')
    .attr('class', 'element')
    .attr('test-data-attribute', (d) => {
        return d;
    });

const nodes = container.selectAll('.element');
console.log(nodes);

Here is the updated CodePen: https://codepen.io/anon/pen/gRbPjb?editors=0110

PS: I removed the length in console.log(nodes.length) because, in D3 v4.x, selections are objects, not arrays anymore.


问:
Pandas IOError: [Errno 13] Permission denied
I've been trying to run pandas using python 2.7 on a macbook pro and keep getting the following error:

File "/Users/Hofstadter/anaconda/lib/python2.7/site-packages/pandas/io/common.py", line 376, in _get_handle
    f = open(path_or_buf, mode)

IOError: [Errno 13] Permission denied: 'datasets/cats_0.8_0.6_0.4_0.2/target.csv'

It looks like for some reason the folder being created for the files below, including target.csv, has restricted permissions. Here's what that code looks like:

```<code>def get_tables(df):
    categorical_cols = [col for col in df.columns if col.endswith('_cat')]
    train_table = df[categorical_cols]
    for col in categorical_cols:
        train_table = pd.concat(
            [
                train_table, pd.get_dummies(
                    train_table[col],
                    prefix=col,
                    prefix_sep='_',
                    dummy_na=False).astype(int)
            ],
            axis=1,
            join='inner')
        train_table.drop(col, axis=1, inplace=True)

    print('Tables Created :)')
    return train_table
</code>```

The tables are created without issue but then I get a permission error when trying to save them as below.

```<code>def save_tables(data_path,
                df,
                top_quant,
                mh_quant,
                ml_quant,
                low_quant,
                train=True):

    df = categorize_features(df, top_quant, mh_quant, ml_quant, low_quant)
    X = get_tables(df)

    os.makedirs(data_path, True)

    x_path = '{}/tournament_table.csv'.format(data_path)

    if train:
        x_path = '{}/train_table.csv'.format(data_path)
        y = df['target'].to_frame()
        y.columns = ['target']
        y.to_csv('{}/target.csv'.format(data_path), index=False)
    else:
        ids = df['id'].to_frame()
        ids.columns = ['id']
        ids.to_csv('{}/ids.csv'.format(data_path), index=False)

    X.to_csv(x_path, index=False)
</code>```

答:
I suspect your issue is not the call to_csv() but where you are calling os.makedirs.

Calling os.makedirs(data_path, True) is interpreting the True as the parameter for mode. See:

```<code>makedirs(name [, mode=0o777][, exist_ok=False])
</code>```

If you want to use the default mode for the new directories but ignore existing, your call should be os.makedirs(data_path, exist_ok=True)

Body:
I've been trying to run pandas using python 2.7 on a macbook pro and keep getting the following error:

File "/Users/Hofstadter/anaconda/lib/python2.7/site-packages/pandas/io/common.py", line 376, in _get_handle
    f = open(path_or_buf, mode)

IOError: [Errno 13] Permission denied: 'datasets/cats_0.8_0.6_0.4_0.2/target.csv'

It looks like for some reason the folder being created for the files below, including target.csv, has restricted permissions. Here's what that code looks like:

def get_tables(df):
    categorical_cols = [col for col in df.columns if col.endswith('_cat')]
    train_table = df[categorical_cols]
    for col in categorical_cols:
        train_table = pd.concat(
            [
                train_table, pd.get_dummies(
                    train_table[col],
                    prefix=col,
                    prefix_sep='_',
                    dummy_na=False).astype(int)
            ],
            axis=1,
            join='inner')
        train_table.drop(col, axis=1, inplace=True)

    print('Tables Created :)')
    return train_table

The tables are created without issue but then I get a permission error when trying to save them as below.

def save_tables(data_path,
                df,
                top_quant,
                mh_quant,
                ml_quant,
                low_quant,
                train=True):

    df = categorize_features(df, top_quant, mh_quant, ml_quant, low_quant)
    X = get_tables(df)

    os.makedirs(data_path, True)

    x_path = '{}/tournament_table.csv'.format(data_path)

    if train:
        x_path = '{}/train_table.csv'.format(data_path)
        y = df['target'].to_frame()
        y.columns = ['target']
        y.to_csv('{}/target.csv'.format(data_path), index=False)
    else:
        ids = df['id'].to_frame()
        ids.columns = ['id']
        ids.to_csv('{}/ids.csv'.format(data_path), index=False)

    X.to_csv(x_path, index=False)

Body:
I suspect your issue is not the call to_csv() but where you are calling os.makedirs.

Calling os.makedirs(data_path, True) is interpreting the True as the parameter for mode. See:

makedirs(name [, mode=0o777][, exist_ok=False])

If you want to use the default mode for the new directories but ignore existing, your call should be os.makedirs(data_path, exist_ok=True)


问:
Perform the validation loss from .caffemodel?
AFAIK, we have two ways to obtain the validation loss.

(1) online during training process by setting the solver as follows:
train_net: 'train.prototxt'

```<code>test_net: "test.prototxt"
test_iter: 200
test_interval: 100
</code>```

(2) offline based on the weight in the .caffemodel file. In this question, I regard to the second way due to limited GPU. First, I saved the weight of network to .caffemodel after each 100 iterations by snapshot: 100. Based on these .caffemodel, I want to calculate the validation loss

```<code>../build/tools/caffe test -model ./test.prototxt -weights $snapshot -iterations 10 -gpu 0
</code>```

where snapshot is file name of .caffemodel. For example snap_network_100.caffemodel

And the data layer of my test prototxt is

```<code>layer {
  name: "data"
  type: "HDF5Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  hdf5_data_param {
    source: "./list.txt"
    batch_size: 8
    shuffle: true
  }
}
</code>```

The first and the second ways give different validation loss. I found that the first way the validation loss independent of batch size. It means the validation loss is same with different batch size. While, the second way, the validation loss changed with different batch size but the loss is very close together with different iterations.

My question is that which way is correct to compute validation loss?

答:
You compute the validation loss for different number of iterations:

```<code>test_iter: 200
</code>```

In your 'solver.prototxt', vs. -iterations 10 when running from command line. This means you are averaging the loss over different number of validation samples.

Since you are using far less samples when validating from command line, you are much more sensitive to batch_size.

Make sure you are using exactly the same settings and verify that the validation loss is indeed the same.

Body:
AFAIK, we have two ways to obtain the validation loss.

(1) online during training process by setting the solver as follows:
train_net: 'train.prototxt'

test_net: "test.prototxt"
test_iter: 200
test_interval: 100

(2) offline based on the weight in the .caffemodel file. In this question, I regard to the second way due to limited GPU. First, I saved the weight of network to .caffemodel after each 100 iterations by snapshot: 100. Based on these .caffemodel, I want to calculate the validation loss

../build/tools/caffe test -model ./test.prototxt -weights $snapshot -iterations 10 -gpu 0

where snapshot is file name of .caffemodel. For example snap_network_100.caffemodel

And the data layer of my test prototxt is

layer {
  name: "data"
  type: "HDF5Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  hdf5_data_param {
    source: "./list.txt"
    batch_size: 8
    shuffle: true
  }
}

The first and the second ways give different validation loss. I found that the first way the validation loss independent of batch size. It means the validation loss is same with different batch size. While, the second way, the validation loss changed with different batch size but the loss is very close together with different iterations.

My question is that which way is correct to compute validation loss?

Body:
You compute the validation loss for different number of iterations:

test_iter: 200

In your 'solver.prototxt', vs. -iterations 10 when running from command line. This means you are averaging the loss over different number of validation samples.

Since you are using far less samples when validating from command line, you are much more sensitive to batch_size.

Make sure you are using exactly the same settings and verify that the validation loss is indeed the same.


问:
How do you set text color of disabled form control button
I am trying to set the color of text in a control button to the same color of the control when it is disabled.
In other words... I don't want any text to show when button is disabled.

I don't know how else to phrase this question.

It is just important for the text not to appear when disabled.

Thank you for your help.

答:
Suppose you button is "button2". Then you can write this in button2's Enable_changed event.
You can select the event from the properties window.

```<code>private void button2_EnabledChanged(object sender, EventArgs e)
{
    if (((Button)sender).Enabled)
    {
       button2.Text = "Button";
    }
    else
    {
       button2.Text = "";
    }
}
</code>```

Then whenever you want you can call as

```<code>button2.Enabled = true
</code>```

Or you can set it to false. Tryout and respond. Bye

ContentLicense: CC BY-SA 2.5

Body:
Suppose you button is "button2". Then you can write this in button2's Enable_changed event.
You can select the event from the properties window.

private void button2_EnabledChanged(object sender, EventArgs e)
{
    if (((Button)sender).Enabled)
    {
       button2.Text = "Button";
    }
    else
    {
       button2.Text = "";
    }
}

Then whenever you want you can call as

button2.Enabled = true

Or you can set it to false. Tryout and respond. Bye


问:
Transform a string to Vector3
I have this string in a MySQL database:

"-1035.43, -2728.861, 13.75664"

How can i transform it to a Vector3 to use it in this function:

```<code>Vector3 newpos = new Vector3(getChar[15]);
API.setEntityPosition(player, newpos);
</code>```

getChar is the database list, and the 15 is the value.

答:
```<code>Vector3 ConvertFromString(string input)
{
    if (input != null)
    {
        var vals = input.Split(',').Select(s => s.Trim()).ToArray();
        if (vals.Length == 3)
        {
            Single v1, v2, v3;
            if (Single.TryParse(vals[0], out v1) &&
                Single.TryParse(vals[1], out v2) &&
                Single.TryParse(vals[2], out v3))
                return new Vector3(v1, v2, v3);
            else
                throw new ArgumentException();
        }
        else
            throw new ArgumentException();
    }
    else
        throw new ArgumentException();
}
</code>```

Here's results for the string you provided :

Title: Transform a string to Vector3

Body:
I have this string in a MySQL database:

"-1035.43, -2728.861, 13.75664"

How can i transform it to a Vector3 to use it in this function:

Vector3 newpos = new Vector3(getChar[15]);
API.setEntityPosition(player, newpos);

getChar is the database list, and the 15 is the value.

Body:
Vector3 ConvertFromString(string input)
{
    if (input != null)
    {
        var vals = input.Split(',').Select(s => s.Trim()).ToArray();
        if (vals.Length == 3)
        {
            Single v1, v2, v3;
            if (Single.TryParse(vals[0], out v1) &&
                Single.TryParse(vals[1], out v2) &&
                Single.TryParse(vals[2], out v3))
                return new Vector3(v1, v2, v3);
            else
                throw new ArgumentException();
        }
        else
            throw new ArgumentException();
    }
    else
        throw new ArgumentException();
}

Here's results for the string you provided :


问:
Can't get redux in react-native to work
I'm trying to run through a very minimal redux example:

http://www.reactnativeexpress.com/redux

It's the first box of code. All it does is store a number and with a reducer that just increments it. The code only imports redux (no redux-persist, react-redux, etc)

The problem I have is getting all of the dependencies down. I had no problems running react-native apps until redux. After a react-native init  and executing a run-ios a redbox error shows it can't find redux. This is the only part that makes sense to me. Here are the steps I tried taking:

```<code>$ npm install --save redux
</code>```

This proved to be problematic as it does a rollback and does the following:

added 5 packages, removed 617 packages and updated 17 packages in
  8.839s

run-ios or run-android no longer works as it gives:

Command run-ios unrecognized. Make sure that you have run npm
  install and that you are inside a react-native project.

Doing an npm install or npm install update does nothing as it still shows this message.

So then I tried creating a new project and pasting the code into index.ios.js again but using yarn instead (btw, I don't know what any of this means. npm or yarn.)

```<code>$ yarn add redux
</code>```

Then run-ios shows an red box error:

Can't find variable: React

The error is on

```<code><Text style={{fontSize: 100}}>
</code>```

so it must be something in react-native (ReactCompositeComponent.js to be exact). Okay.

```<code>$ yarn add react
</code>```

Now the red box error I'm getting is that it can't resolve react/lib/ReactDebugCurrentFrame and then it lists all of the default directories that it can't find it in.

npm install --save redux shouldn't be deleting all of those node_module files. Can anyone else make this work?

答: I had two problems. The first one was npm install --save redux (or even react-redux) was deleting a lot of node_modules. I never figured out why it was doing that, but after reinstalling node and watchman (brew uninstall --force then install) it stopped doing that. The second problem was that I needed to add import React, { Component } from 'react'; to the top of the file. </p>

Title: Can't get redux in react-native to work

Body:
I'm trying to run through a very minimal redux example:

http://www.reactnativeexpress.com/redux

It's the first box of code. All it does is store a number and with a reducer that just increments it. The code only imports redux (no redux-persist, react-redux, etc)

The problem I have is getting all of the dependencies down. I had no problems running react-native apps until redux. After a react-native init  and executing a run-ios a redbox error shows it can't find redux. This is the only part that makes sense to me. Here are the steps I tried taking:

$ npm install --save redux

This proved to be problematic as it does a rollback and does the following:

added 5 packages, removed 617 packages and updated 17 packages in
  8.839s

run-ios or run-android no longer works as it gives:

Command run-ios unrecognized. Make sure that you have run npm
  install and that you are inside a react-native project.

Doing an npm install or npm install update does nothing as it still shows this message.

So then I tried creating a new project and pasting the code into index.ios.js again but using yarn instead (btw, I don't know what any of this means. npm or yarn.)

$ yarn add redux

Then run-ios shows an red box error:

Can't find variable: React

The error is on

<Text style={{fontSize: 100}}>

so it must be something in react-native (ReactCompositeComponent.js to be exact). Okay.

$ yarn add react

Now the red box error I'm getting is that it can't resolve react/lib/ReactDebugCurrentFrame and then it lists all of the default directories that it can't find it in.

npm install --save redux shouldn't be deleting all of those node_module files. Can anyone else make this work?


问:
strstr() function in C programming
I am learning C from the book Head First C, and I tried one of the examples, and despite having the same code, my code won't run like the example in the book.
The code aims to use the strstr() function to find a string within another string, but after running my code, it only asks for my input, and displays "Program ended with exit code: 0"

Below is my code:

```<code>#include <stdio.h>
#include <string.h>

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "Newark, Newark - a wonderful town",
    "Dancing with a Dork",
    "From here to maternity",
    "The girl from Iwo Jima",
};

void find_track(char search_for[])
{
    int i;
    for (i=0; i<5; i++) {
        if(strstr(tracks[i],search_for))
            printf("Track %i: '%s'\n", i, tracks[i]);
    }
}

int main()
{
    char search_for[80];
    printf("Search for: ");
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0;
}
</code>```

The result after running the code is:

```<code>Search for: (my input)
Program ended with exit code: 0
</code>```

Help!

答:
If your input was entered with a newline, fgets() includes the newline in the resulting search_for string. On the other hand, if you terminate your input with EOF (usually ctrl+D) then it doesn't contain the newline, and your program works as intended.

You can find techniques for avoiding this issue in this question and its answers.

Title: strstr() function in C programming

Body:
I am learning C from the book Head First C, and I tried one of the examples, and despite having the same code, my code won't run like the example in the book.
The code aims to use the strstr() function to find a string within another string, but after running my code, it only asks for my input, and displays "Program ended with exit code: 0"

Below is my code:

#include <stdio.h>
#include <string.h>

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "Newark, Newark - a wonderful town",
    "Dancing with a Dork",
    "From here to maternity",
    "The girl from Iwo Jima",
};

void find_track(char search_for[])
{
    int i;
    for (i=0; i<5; i++) {
        if(strstr(tracks[i],search_for))
            printf("Track %i: '%s'\n", i, tracks[i]);
    }
}

int main()
{
    char search_for[80];
    printf("Search for: ");
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0;
}

The result after running the code is:

Search for: (my input)
Program ended with exit code: 0

Help!


问:
Can't load http authorisation website url in webview on IOS9 with swift 2
I'm now to IOS development and i encounter a problem that i can't load a http authorisation site in webview, it just show blank page and nothing comes out, here is my code to load the website:

```<code>@IBAction func testhttp(sender: AnyObject) {

    let url = NSURL(string: "http://www.obee.com.au/demo/admin/index.php");
    let request = NSURLRequest(URL: url!);
    //see2 is the webview....
    see2.loadRequest(request);
}
</code>```

Can anyone help me fix this problem ?

Cheers

答:
It seems like it needs an authentication to load the page. You might fix it with providing credential info in the header of NSURLRequest.

How to make an HTTP request + basic auth in Swift

Body:
I'm now to IOS development and i encounter a problem that i can't load a http authorisation site in webview, it just show blank page and nothing comes out, here is my code to load the website:

@IBAction func testhttp(sender: AnyObject) {

    let url = NSURL(string: "http://www.obee.com.au/demo/admin/index.php");
    let request = NSURLRequest(URL: url!);
    //see2 is the webview....
    see2.loadRequest(request);
}

Can anyone help me fix this problem ?

Cheers


问:
finishActivityAffinity NullPointerException
Am getting this Error in production. When calling finishAffinity in splashscreen.

答:
Try this code for splashscreen...

```<code>public class SplashScreen extends AppCompatActivity {

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

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            Intent i = new Intent(SplashScreen.this, LoginActivity.class);
            startActivity(i);
            finish();
        }
    }, 2*1000);
}
</code>```

}

Body:
Try this code for splashscreen...

public class SplashScreen extends AppCompatActivity {

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

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            Intent i = new Intent(SplashScreen.this, LoginActivity.class);
            startActivity(i);
            finish();
        }
    }, 2*1000);
}

}


问:
How to allow user to input a color (non hex or rbga) for list customization but make sure it's valid
Just wondering if anyone knows the best way to implement this into code. Is there a method for checking if a string is a valid color?

I want to allow the user to click a button to change color and then enter a color name, changing the background color of their list.

答:
Simply by assigning the color to a style attribute, and checking that the attribute has a length > 0 will do the job

e.g. you could do it like this

```<code>function testColor(color) {
    var head = document.head || document.getElementsByTagName('head')[0];
    head.style.backgroundColor = ''; // clear it first - which makes it valid
    head.style.backgroundColor = color;
    return head.style.backgroundColor.length > 0;
}
</code>```

Tested in firefox, chrome, IE and Edge

Body:
Simply by assigning the color to a style attribute, and checking that the attribute has a length > 0 will do the job

e.g. you could do it like this

function testColor(color) {
    var head = document.head || document.getElementsByTagName('head')[0];
    head.style.backgroundColor = ''; // clear it first - which makes it valid
    head.style.backgroundColor = color;
    return head.style.backgroundColor.length > 0;
}

Tested in firefox, chrome, IE and Edge


问:
mysql string contained within a search string
What I need seems simple, but I haven't been able to pull it off so far. Maybe it's just these late hours, or maybe it's not that simple after all, I don't know any more :)
So, here's the thing. I want to be able to check whether the search string from my site contains any of the fields from a particular column in my database. So, it would be the opposite of the usual one:

```<code>mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$search}%'
");
</code>```

which looks for the fields with values where the search string is contained.

What would be the easiest way, using some regular expressions or...?

Thanks a bunch!

答:
Just do it the other way around

```<code>SELECT *
FROM `table`
WHERE '{$search}' LIKE concat('%', `column`, '%')</code>```

bear with me for the proper syntax for variable escaping for SQL-injection.

Body:
What I need seems simple, but I haven't been able to pull it off so far. Maybe it's just these late hours, or maybe it's not that simple after all, I don't know any more :)
So, here's the thing. I want to be able to check whether the search string from my site contains any of the fields from a particular column in my database. So, it would be the opposite of the usual one:

mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$search}%'
");

which looks for the fields with values where the search string is contained.

What would be the easiest way, using some regular expressions or...?

Thanks a bunch!

Body:
Just do it the other way around

SELECT *
FROM `table`
WHERE '{$search}' LIKE concat('%', `column`, '%')

bear with me for the proper syntax for variable escaping for SQL-injection.


问:
Different onClick and onLongClick methods for two buttons
I'm trying to create buttons that will execute certain different instructions based on a simple click and a long click, but I'm struck with low understanding on how to put everything together. Performing a defined method for every button is ok, but I think it would be better to use onClickListeners for this, isn't it?

So my code is as follows. As you can see, I'm trying to catch both types of event for each button, but when I press the button 1A I get the toast of the 2A, and when I click the button 2A I get an error and the app crashes.
The second thing to fix is to bind together the onClick and the onLongClick.

activity_scout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.scout.ScoutActivity">

<LinearLayout
    android:id="@+id/activity_scout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="8dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingTop="8dp"
    android:orientation="vertical" >

    <Button
        android:id="@+id/but1A"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1a"
        android:onClick="click1a"
        />

    <Button
        android:id="@+id/but2A"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2a"
        android:onClick="click2a" />

   </LinearLayout>
</ScrollView>
</code>```

ScoutActivity.java

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import static com.example.android.basketscout.R.id.butPlayer1A;
import static com.example.android.basketscout.R.id.butPlayer2A;
import static com.example.android.basketscout.R.id.butPlayer3A;
import static com.example.android.basketscout.R.id.butPlayer4A;
import static com.example.android.basketscout.R.id.butPlayer5A;
import static com.example.android.basketscout.R.id.textView;

public class ScoutActivity extends AppCompatActivity {

    Button but1A;
    Button but2A;
    Button but3A;
    Button but4A;
    Button but5A;

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

        but1A = (Button) findViewById(R.id.but1A);
        but2A = (Button) findViewById(R.id.but1A);

        but1A.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                Toast.makeText(getApplicationContext(), "Button 1A clicked", Toast.LENGTH_SHORT).show();
            }
        });

        but2A.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                Toast.makeText(getApplicationContext(), "Button 2A clicked", Toast.LENGTH_SHORT).show();
            }
        });

        but1A.setOnLongClickListener(new View.OnLongClickListener(){
            public void onLongClick (View view) {
                Toast.makeText(getApplicationContext(),"Button 1A long clicked", Toast.LENGTH_SHORT).show();
            }
        });

    but2A.setOnLongClickListener(new View.OnLongClickListener(){
        public void onLongClick (View view) {
            Toast.makeText(getApplicationContext(),"Button 2A long clicked", Toast.LENGTH_SHORT).show();
        }
    });
    }

 }
</code>```

[If you see any error like unclosed parentheris or not completely correct variable names, it's because of some edit from the copy/paste I did]

答:
problem is you finding the same id twice:

```<code>    but1A = (Button) findViewById(R.id.but1A);
    but2A = (Button) findViewById(R.id.but1A);
</code>```

To

```<code>  but1A = (Button) findViewById(R.id.but1A);
    but2A = (Button) findViewById(R.id.but2A);
</code>```

Then,

For long click listener for views see this how to implement a long click listener on a listview

Body:
I'm trying to create buttons that will execute certain different instructions based on a simple click and a long click, but I'm struck with low understanding on how to put everything together. Performing a defined method for every button is ok, but I think it would be better to use onClickListeners for this, isn't it?

So my code is as follows. As you can see, I'm trying to catch both types of event for each button, but when I press the button 1A I get the toast of the 2A, and when I click the button 2A I get an error and the app crashes.
The second thing to fix is to bind together the onClick and the onLongClick.

activity_scout.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.scout.ScoutActivity">

<LinearLayout
    android:id="@+id/activity_scout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="8dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingTop="8dp"
    android:orientation="vertical" >

    <Button
        android:id="@+id/but1A"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1a"
        android:onClick="click1a"
        />

    <Button
        android:id="@+id/but2A"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2a"
        android:onClick="click2a" />

   </LinearLayout>
</ScrollView>

ScoutActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import static com.example.android.basketscout.R.id.butPlayer1A;
import static com.example.android.basketscout.R.id.butPlayer2A;
import static com.example.android.basketscout.R.id.butPlayer3A;
import static com.example.android.basketscout.R.id.butPlayer4A;
import static com.example.android.basketscout.R.id.butPlayer5A;
import static com.example.android.basketscout.R.id.textView;

public class ScoutActivity extends AppCompatActivity {

    Button but1A;
    Button but2A;
    Button but3A;
    Button but4A;
    Button but5A;

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

        but1A = (Button) findViewById(R.id.but1A);
        but2A = (Button) findViewById(R.id.but1A);

        but1A.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                Toast.makeText(getApplicationContext(), "Button 1A clicked", Toast.LENGTH_SHORT).show();
            }
        });

        but2A.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                Toast.makeText(getApplicationContext(), "Button 2A clicked", Toast.LENGTH_SHORT).show();
            }
        });

        but1A.setOnLongClickListener(new View.OnLongClickListener(){
            public void onLongClick (View view) {
                Toast.makeText(getApplicationContext(),"Button 1A long clicked", Toast.LENGTH_SHORT).show();
            }
        });

    but2A.setOnLongClickListener(new View.OnLongClickListener(){
        public void onLongClick (View view) {
            Toast.makeText(getApplicationContext(),"Button 2A long clicked", Toast.LENGTH_SHORT).show();
        }
    });
    }

 }

[If you see any error like unclosed parentheris or not completely correct variable names, it's because of some edit from the copy/paste I did]

Body:
problem is you finding the same id twice:

    but1A = (Button) findViewById(R.id.but1A);
    but2A = (Button) findViewById(R.id.but1A);

To

  but1A = (Button) findViewById(R.id.but1A);
    but2A = (Button) findViewById(R.id.but2A);

Then,

For long click listener for views see this how to implement a long click listener on a listview


问:
CSV response from get request in elastic search
I am sending an http Get request to elastic search server and i want the response to be in csv format.Like in solr we can specify wt=csv is there any way In elastic Search too ?
My query is :</p>

```<code>enter code here
 http://elasticServer/_search?q=RCE:"some date" OR
 VENDOR_NAME:"Anuj"&from=0&size=5&sort=@timestamp

  -----After that i want to force the server to return me response in csv format
</code>```

答: There is a ElasticSearch plugin on Github called Elasticsearch Data Format Plugin that should satisfy your requirements.</p>

Body:
I am sending an http Get request to elastic search server and i want the response to be in csv format.Like in solr we can specify wt=csv is there any way In elastic Search too ?
My query is :

enter code here
 http://elasticServer/_search?q=RCE:"some date" OR
 VENDOR_NAME:"Anuj"&from=0&size=5&sort=@timestamp

  -----After that i want to force the server to return me response in csv format


问:
Drawable ID's come zero
```<code><integer-array name="ar_ex_1">
    <item>@drawable/ar_001_main</item>
    <item>@drawable/ar_001_1</item>
    <item>@drawable/ar_001_2</item>
    <item>@drawable/ar_001_3</item>
    <item>@drawable/ar_001_4</item>
    <item>@drawable/ar_001_5</item>
</integer-array>
</code>```

I have this integer array, and I load it into Java using:

```<code>int[] arr = getResources().getIntArray(R.array.ar_ex_1);
for(int i: arr) {
   Log.e("anindya", ""+i);
}
</code>```

The output is:

```<code>06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
</code>```

I was expecting integers, (the values for the drawables in R.java, but instead I get only zeroes. Is this not the way to load an array of drawables?

答:
if this is your drawable array in array.xml try this kind of code.

```<code> <integer-array name="ar_ex_1">
        <item>@drawable/ar_001_main</item>
        <item>@drawable/ar_001_1</item>
        <item>@drawable/ar_001_2</item>
        <item>@drawable/ar_001_3</item>
        <item>@drawable/ar_001_4</item>
        <item>@drawable/ar_001_5</item>
    </integer-array>
</code>```

Then in your activity, access them like so:

```<code>TypedArray imgs = getResources().obtainTypedArray(R.array.ar_ex_1);

// get resource ID by index
imgs.getResourceId(i, -1)

// or set you ImageView's resource to the id
mImgView1.setImageResource(imgs.getResourceId(i, -1));

// recycle the array
imgs.recycle();
</code>```

Title: Drawable ID's come zero

Body:
<integer-array name="ar_ex_1">
    <item>@drawable/ar_001_main</item>
    <item>@drawable/ar_001_1</item>
    <item>@drawable/ar_001_2</item>
    <item>@drawable/ar_001_3</item>
    <item>@drawable/ar_001_4</item>
    <item>@drawable/ar_001_5</item>
</integer-array>

I have this integer array, and I load it into Java using:

int[] arr = getResources().getIntArray(R.array.ar_ex_1);
for(int i: arr) {
   Log.e("anindya", ""+i);
}

The output is:

06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0
06-04 20:31:57.045 9360-9360/edu.usc.projecttalent.cognitive E/anindya: 0

I was expecting integers, (the values for the drawables in R.java, but instead I get only zeroes. Is this not the way to load an array of drawables?

Body:
if this is your drawable array in array.xml try this kind of code.

 <integer-array name="ar_ex_1">
        <item>@drawable/ar_001_main</item>
        <item>@drawable/ar_001_1</item>
        <item>@drawable/ar_001_2</item>
        <item>@drawable/ar_001_3</item>
        <item>@drawable/ar_001_4</item>
        <item>@drawable/ar_001_5</item>
    </integer-array>

Then in your activity, access them like so:

TypedArray imgs = getResources().obtainTypedArray(R.array.ar_ex_1);

// get resource ID by index
imgs.getResourceId(i, -1)

// or set you ImageView's resource to the id
mImgView1.setImageResource(imgs.getResourceId(i, -1));

// recycle the array
imgs.recycle();


问:
Windows Phone 10 Universal, how to resize and move a rectangle?
I am pretty new to C# and XAML, and I am trying to create an application that allows the user to move a rectangle, resize the rectangle using pinch, and change the color when touched. I have successfully created the application for Windows Phone 8.1 Silverlight, but I am having a lot of trouble creating it for Windows Phone 10 Universal. There is very limited literature out there in regards to handling manipulation events in Windows Phone 10.

Can someone please direct me to the appropriate information for doing this, or if you could show me where I went wrong in my code?

I would greatly appreciate it!

Thank you,

Page

Here is my MainPage.xaml

```<code><Page
x:Class="Gesture_App_UWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Gesture_App_UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <TextBlock x:Name="textBlock" HorizontalAlignment="Left"
               Height="50" TextWrapping="Wrap"
               Text="Gesture Application" VerticalAlignment="Top"
               Width="360" FontSize="36" TextAlignment="Center"
               FontFamily="Bauhaus 93" Margin="0,25,0,0" >
        <TextBlock.Foreground>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF23AFE2" Offset="1"/>
            </LinearGradientBrush>
        </TextBlock.Foreground>
    </TextBlock>

    <Button x:Name="button_Info" Content="Info" HorizontalAlignment="Left"
            Height="34" Margin="35,91,0,0" VerticalAlignment="Top" Width="110"
            Click="button_Info_Click" BorderThickness="2" Foreground="#FFFA9F11"
            BorderBrush="#FF09B4F3">
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF3A3939" Offset="1"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
    <Button x:Name="button_Instructions" Content="Instructions"
            HorizontalAlignment="Left" Height="34" Margin="210,91,0,0"
            VerticalAlignment="Top" Width="110" BorderThickness="2"
            Foreground="#FFFA9F11" BorderBrush="#FF09B4F3" Click="button_Instructions_Click">
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF3A3939" Offset="1"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>

    <Border BorderBrush="Black" BorderThickness="2" HorizontalAlignment="Left"
            Height="5" Margin="10,160,0,0" VerticalAlignment="Top" Width="340"/>

    <Grid HorizontalAlignment="Left" Height="475" Margin="0,165,0,0"
          VerticalAlignment="Top" Width="360"/>

    <Canvas HorizontalAlignment="Left" Height="470" Margin="0,170,0,0"
            VerticalAlignment="Top" Width="360" >

        <Rectangle Name="touchRectangle" Fill="Green" Width="200" Height="40" Canvas.Left="80"
                   Stroke="Blue" Canvas.Top="190" RadiusX="5" RadiusY="5"
                   HorizontalAlignment="Center" VerticalAlignment="Center"
                   ManipulationMode="All"/>
    </Canvas>

</Grid>
</Page>
</code>```

Here is my MainPage.xaml.cs, I have updated it to reflect the changes mentioned below and still the rectangle does not move or resize.

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Input;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;
using System.Windows.Input;

namespace Gesture_App_UWP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
    // Global translation transform used for changing the position of
    // the Rectangle based on input data from the touch contact.
    private TranslateTransform dragTranslation;
    private CompositeTransform deltaTransform;
    private TransformGroup rectangleTransforms;

    //Various Brushes for changing rectangle's color
    private Brush stationaryBrush;
    private SolidColorBrush greenBrush = new SolidColorBrush(Colors.Green);
    private SolidColorBrush redBrush = new SolidColorBrush(Colors.Red);
    private SolidColorBrush orangeBrush = new SolidColorBrush(Colors.Orange);

    public MainPage()
    {
        this.InitializeComponent();

        // Pointer event listeners.
        touchRectangle.PointerPressed += touchRectangle_PointerPressed;
        touchRectangle.PointerReleased += touchRectangle_PointerReleased;

        // Listener for Manipulation events
        touchRectangle.ManipulationStarted += new ManipulationStartedEventHandler(touchRectangle_ManipulationStarted);
        touchRectangle.ManipulationDelta += new ManipulationDeltaEventHandler(touchRectangle_ManipulationDelta);
        touchRectangle.ManipulationInertiaStarting += new ManipulationInertiaStartingEventHandler(touchRectangle_ManipulationInertiaStarting);
        touchRectangle.ManipulationCompleted += new ManipulationCompletedEventHandler(touchRectangle_ManipulationCompleted);

        //Initiate new instance of various Transforms
        dragTranslation = new TranslateTransform();
        deltaTransform = new CompositeTransform();
        rectangleTransforms = new TransformGroup();

        // Combine moving & resizing tranforms into one TransformGroup.
        // Rectangle's RenderTransform can only contain a single transform or TransformGroup.
        rectangleTransforms.Children.Add(dragTranslation);
        rectangleTransforms.Children.Add(deltaTransform);

        //Assign manipulation data to rectangle
        touchRectangle.RenderTransform = rectangleTransforms;
    }
    private async void button_Info_Click(object sender, RoutedEventArgs e)
    {
        var dialog_Info = new MessageDialog("Page Lynn Potter");
        await dialog_Info.ShowAsync();
    }
    private async void button_Instructions_Click(object sender, RoutedEventArgs e)
    {
        var dialog_Instructions = new MessageDialog("PINCH - Zoom In & Out, LONG TOUCH - Toggle Color, FLICK - Move Rectangle");
        await dialog_Instructions.ShowAsync();
    }
    //Handler for pointer released event.
    private void touchRectangle_PointerReleased(object sender, PointerRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = greenBrush;
    }
    // Handler for pointer pressed event.
    private void touchRectangle_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = orangeBrush;
    }
    void touchRectangle_ManipulationInertiaStarting(object sender, ManipulationInertiaStartingRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = redBrush;
    }
    void touchRectangle_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
    {
        // Save rectangle's original color before changing color.
        stationaryBrush = touchRectangle.Fill;

        //Change rectangle's color
        touchRectangle.Fill = orangeBrush;
    }

    // Handler for ManipulationDelta event.
    // ManipulationDelta data loaded into translation transform & applied to Rectangle
    void touchRectangle_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY | ManipulationModes.Scale;

        // Move rectangle.
        dragTranslation.X += e.Delta.Translation.X;
        dragTranslation.Y += e.Delta.Translation.Y;

        // Resize rectangle.
        if (deltaTransform.ScaleX > 0 && deltaTransform.ScaleY > 0)
        {
            //Scale Rectangle
            deltaTransform.ScaleX *= e.Delta.Scale;
            deltaTransform.ScaleY *= e.Delta.Scale;
        }
    }
    //When manipulation ends, event handler restores original color to Rectangle
    void touchRectangle_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
    {
        // Restore rectangle's original color.
        touchRectangle.Fill = stationaryBrush;
    }
}
}
</code>```

答:
Here is a simplified working exmple of a Rectangle that can be moved and scaled by touch input.

Note that a ScaleTransform and a TranslateTransform are added to a TransformGroup in XAML. Instead of setting Canvas.Left and Canvas.Top, the TranslateTransform is initialized with their values.

The RenderTransformOrigin property is set such that the scaling takes place at the center of the Rectangle.

It may also be sufficient to set ManipulationMode="Scale,TranslateX,TranslateY" instead of All.

```<code><Rectangle ManipulationDelta="Rectangle_ManipulationDelta"
           ManipulationMode="All" Fill="Red"
           Width="200" Height="40" RadiusX="5" RadiusY="5"
           RenderTransformOrigin="0.5,0.5">
    <Rectangle.RenderTransform>
        <TransformGroup>
            <ScaleTransform x:Name="scaleTransform"/>
            <TranslateTransform x:Name="translateTransform" X="80" Y="190"/>
        </TransformGroup>
    </Rectangle.RenderTransform>
</Rectangle>
</code>```

The only code behind is the ManipulationDelta handler:

```<code>private void Rectangle_ManipulationDelta(
    object sender, ManipulationDeltaRoutedEventArgs e)
{
    scaleTransform.ScaleX *= e.Delta.Scale;
    scaleTransform.ScaleY *= e.Delta.Scale;
    translateTransform.X += e.Delta.Translation.X;
    translateTransform.Y += e.Delta.Translation.Y;
}
</code>```

Body:
I am pretty new to C# and XAML, and I am trying to create an application that allows the user to move a rectangle, resize the rectangle using pinch, and change the color when touched. I have successfully created the application for Windows Phone 8.1 Silverlight, but I am having a lot of trouble creating it for Windows Phone 10 Universal. There is very limited literature out there in regards to handling manipulation events in Windows Phone 10.

Can someone please direct me to the appropriate information for doing this, or if you could show me where I went wrong in my code?

I would greatly appreciate it!

Thank you,

Page

Here is my MainPage.xaml

<Page
x:Class="Gesture_App_UWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Gesture_App_UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <TextBlock x:Name="textBlock" HorizontalAlignment="Left"
               Height="50" TextWrapping="Wrap"
               Text="Gesture Application" VerticalAlignment="Top"
               Width="360" FontSize="36" TextAlignment="Center"
               FontFamily="Bauhaus 93" Margin="0,25,0,0" >
        <TextBlock.Foreground>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF23AFE2" Offset="1"/>
            </LinearGradientBrush>
        </TextBlock.Foreground>
    </TextBlock>

    <Button x:Name="button_Info" Content="Info" HorizontalAlignment="Left"
            Height="34" Margin="35,91,0,0" VerticalAlignment="Top" Width="110"
            Click="button_Info_Click" BorderThickness="2" Foreground="#FFFA9F11"
            BorderBrush="#FF09B4F3">
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF3A3939" Offset="1"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>
    <Button x:Name="button_Instructions" Content="Instructions"
            HorizontalAlignment="Left" Height="34" Margin="210,91,0,0"
            VerticalAlignment="Top" Width="110" BorderThickness="2"
            Foreground="#FFFA9F11" BorderBrush="#FF09B4F3" Click="button_Instructions_Click">
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF3A3939" Offset="1"/>
            </LinearGradientBrush>
        </Button.Background>
    </Button>

    <Border BorderBrush="Black" BorderThickness="2" HorizontalAlignment="Left"
            Height="5" Margin="10,160,0,0" VerticalAlignment="Top" Width="340"/>

    <Grid HorizontalAlignment="Left" Height="475" Margin="0,165,0,0"
          VerticalAlignment="Top" Width="360"/>

    <Canvas HorizontalAlignment="Left" Height="470" Margin="0,170,0,0"
            VerticalAlignment="Top" Width="360" >

        <Rectangle Name="touchRectangle" Fill="Green" Width="200" Height="40" Canvas.Left="80"
                   Stroke="Blue" Canvas.Top="190" RadiusX="5" RadiusY="5"
                   HorizontalAlignment="Center" VerticalAlignment="Center"
                   ManipulationMode="All"/>
    </Canvas>

</Grid>
</Page>

Here is my MainPage.xaml.cs, I have updated it to reflect the changes mentioned below and still the rectangle does not move or resize.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.Input;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;
using System.Windows.Input;

namespace Gesture_App_UWP
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class MainPage : Page
{
    // Global translation transform used for changing the position of
    // the Rectangle based on input data from the touch contact.
    private TranslateTransform dragTranslation;
    private CompositeTransform deltaTransform;
    private TransformGroup rectangleTransforms;

    //Various Brushes for changing rectangle's color
    private Brush stationaryBrush;
    private SolidColorBrush greenBrush = new SolidColorBrush(Colors.Green);
    private SolidColorBrush redBrush = new SolidColorBrush(Colors.Red);
    private SolidColorBrush orangeBrush = new SolidColorBrush(Colors.Orange);

    public MainPage()
    {
        this.InitializeComponent();

        // Pointer event listeners.
        touchRectangle.PointerPressed += touchRectangle_PointerPressed;
        touchRectangle.PointerReleased += touchRectangle_PointerReleased;

        // Listener for Manipulation events
        touchRectangle.ManipulationStarted += new ManipulationStartedEventHandler(touchRectangle_ManipulationStarted);
        touchRectangle.ManipulationDelta += new ManipulationDeltaEventHandler(touchRectangle_ManipulationDelta);
        touchRectangle.ManipulationInertiaStarting += new ManipulationInertiaStartingEventHandler(touchRectangle_ManipulationInertiaStarting);
        touchRectangle.ManipulationCompleted += new ManipulationCompletedEventHandler(touchRectangle_ManipulationCompleted);

        //Initiate new instance of various Transforms
        dragTranslation = new TranslateTransform();
        deltaTransform = new CompositeTransform();
        rectangleTransforms = new TransformGroup();

        // Combine moving & resizing tranforms into one TransformGroup.
        // Rectangle's RenderTransform can only contain a single transform or TransformGroup.
        rectangleTransforms.Children.Add(dragTranslation);
        rectangleTransforms.Children.Add(deltaTransform);

        //Assign manipulation data to rectangle
        touchRectangle.RenderTransform = rectangleTransforms;
    }
    private async void button_Info_Click(object sender, RoutedEventArgs e)
    {
        var dialog_Info = new MessageDialog("Page Lynn Potter");
        await dialog_Info.ShowAsync();
    }
    private async void button_Instructions_Click(object sender, RoutedEventArgs e)
    {
        var dialog_Instructions = new MessageDialog("PINCH - Zoom In & Out, LONG TOUCH - Toggle Color, FLICK - Move Rectangle");
        await dialog_Instructions.ShowAsync();
    }
    //Handler for pointer released event.
    private void touchRectangle_PointerReleased(object sender, PointerRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = greenBrush;
    }
    // Handler for pointer pressed event.
    private void touchRectangle_PointerPressed(object sender, PointerRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = orangeBrush;
    }
    void touchRectangle_ManipulationInertiaStarting(object sender, ManipulationInertiaStartingRoutedEventArgs e)
    {
        //Change rectangle's color
        touchRectangle.Fill = redBrush;
    }
    void touchRectangle_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e)
    {
        // Save rectangle's original color before changing color.
        stationaryBrush = touchRectangle.Fill;

        //Change rectangle's color
        touchRectangle.Fill = orangeBrush;
    }

    // Handler for ManipulationDelta event.
    // ManipulationDelta data loaded into translation transform & applied to Rectangle
    void touchRectangle_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY | ManipulationModes.Scale;

        // Move rectangle.
        dragTranslation.X += e.Delta.Translation.X;
        dragTranslation.Y += e.Delta.Translation.Y;

        // Resize rectangle.
        if (deltaTransform.ScaleX > 0 && deltaTransform.ScaleY > 0)
        {
            //Scale Rectangle
            deltaTransform.ScaleX *= e.Delta.Scale;
            deltaTransform.ScaleY *= e.Delta.Scale;
        }
    }
    //When manipulation ends, event handler restores original color to Rectangle
    void touchRectangle_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
    {
        // Restore rectangle's original color.
        touchRectangle.Fill = stationaryBrush;
    }
}
}

Body:
Here is a simplified working exmple of a Rectangle that can be moved and scaled by touch input.

Note that a ScaleTransform and a TranslateTransform are added to a TransformGroup in XAML. Instead of setting Canvas.Left and Canvas.Top, the TranslateTransform is initialized with their values.

The RenderTransformOrigin property is set such that the scaling takes place at the center of the Rectangle.

It may also be sufficient to set ManipulationMode="Scale,TranslateX,TranslateY" instead of All.

<Rectangle ManipulationDelta="Rectangle_ManipulationDelta"
           ManipulationMode="All" Fill="Red"
           Width="200" Height="40" RadiusX="5" RadiusY="5"
           RenderTransformOrigin="0.5,0.5">
    <Rectangle.RenderTransform>
        <TransformGroup>
            <ScaleTransform x:Name="scaleTransform"/>
            <TranslateTransform x:Name="translateTransform" X="80" Y="190"/>
        </TransformGroup>
    </Rectangle.RenderTransform>
</Rectangle>

The only code behind is the ManipulationDelta handler:

private void Rectangle_ManipulationDelta(
    object sender, ManipulationDeltaRoutedEventArgs e)
{
    scaleTransform.ScaleX *= e.Delta.Scale;
    scaleTransform.ScaleY *= e.Delta.Scale;
    translateTransform.X += e.Delta.Translation.X;
    translateTransform.Y += e.Delta.Translation.Y;
}


问:
Add class to unselected item in VueJS 2
I tried setting an active state whenever I select an item and add an active class to it. Now, I wonder how can we get the unselected item and add a specific class to it like not-active.

Sample:

```<code><img src="/images/icons/thumbup.png"
     @click="setActive('thumbUp')"
     class="thumb-active"
     :class="{ active: isActive('thumbUp') }">

<img src="/images/icons/thumbdown.png"
     @click="setActive('thumbDown')"
     class="thumb-active"
     :class="{ active: isActive('thumbDown') }">
</code>```

Vue script:

```<code>export default {
        data() {
            return {
                activeItem: '',
            }
        },
        methods: {
            isActive: function (button) {
                return this.activeItem === button
            },
            setActive: function (button) {
                this.activeItem = button
            }
        },
    }
</code>```

答:
Very, very simply

```<code>:class="{ active: isActive('state A'), 'not-active': isActive('state B') }"
</code>```

Here's a demo...

var app = new Vue({
  el: '#app',
  data: {
    activeItem: null
  },
  methods: {
    isActive: function (button) {
        return this.activeItem === button
    },
    setActive: function (button) {
        this.activeItem = button
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  background-color: green;
  color: white;
  font-weight: bold;
}

.not-active {
  background-color: red;
  color: white;
}

button {
  font-size: 2em;
}</code>```

<button src="/images/icons/thumbup.png"
     @click="setActive('thumbUp')"
     class="thumb-active"
     :class="{ active: isActive('thumbUp'), 'not-active': isActive('thumbDown') }">
     Thumbs Up!
</button>

<button src="/images/icons/thumbdown.png"
     @click="setActive('thumbDown')"
     class="thumb-active"
     :class="{ active: isActive('thumbDown'), 'not-active': isActive('thumbUp') }">
     Thumbs Down¡
</button>

```

Title: Add class to unselected item in VueJS 2

Body:
I tried setting an active state whenever I select an item and add an active class to it. Now, I wonder how can we get the unselected item and add a specific class to it like not-active.

Sample:

Vue script:

export default {
        data() {
            return {
                activeItem: '',
            }
        },
        methods: {
            isActive: function (button) {
                return this.activeItem === button
            },
            setActive: function (button) {
                this.activeItem = button
            }
        },
    }

Body:
Very, very simply

:class="{ active: isActive('state A'), 'not-active': isActive('state B') }"

Here's a demo...

var app = new Vue({
  el: '#app',
  data: {
    activeItem: null
  },
  methods: {
    isActive: function (button) {
        return this.activeItem === button
    },
    setActive: function (button) {
        this.activeItem = button
    }
  }
})

.active {
  background-color: green;
  color: white;
  font-weight: bold;
}

.not-active {
  background-color: red;
  color: white;
}

button {
  font-size: 2em;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>
<div id="app">
<button src="/images/icons/thumbup.png"
     @click="setActive('thumbUp')"
     class="thumb-active"
     :class="{ active: isActive('thumbUp'), 'not-active': isActive('thumbDown') }">
     Thumbs Up!
</button>

<button src="/images/icons/thumbdown.png"
     @click="setActive('thumbDown')"
     class="thumb-active"
     :class="{ active: isActive('thumbDown'), 'not-active': isActive('thumbUp') }">
     Thumbs Down¡
</button>
</div>


问:
creating a parcelable object in kotlin
Best way to create a parcelable object in kotlin?</p>

答:
TestActivity.kt

```<code>class TestActivity : Activity() {
    val DEVOTIONAL_RESPONSE: String = "DEVOTIONAL_RESPONSE"
    var holdr: Holdr_ActivityTest? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        holdr = Holdr_ActivityTest(findViewById(android.R.id.content))

        //create response
        var response: DevotionalResponse = DevotionalResponse()
        fillInResponse(response)

        //write it to a Bundle
        var newBundle: Bundle = Bundle()
        newBundle.putParcelable(DEVOTIONAL_RESPONSE, response)

        //read it from the new Bundle
        var newResponse: DevotionalResponse = newBundle.getParcelable(DEVOTIONAL_RESPONSE)

        //check that they're the same
        assert(newResponse.getDevotionals().get(0).getContent().equalsIgnoreCase(response.getDevotionals().get(0).getContent()))
    }
}
</code>```

DevotionalResponse.kt

```<code>class DevotionalResponse() : Parcelable {

    @Expose
    var devotionals = arrayListOf<Devotional>();

    constructor(in: Parcel) : this() {
        in.readTypedList(this.devotionals, Devotional.CREATOR)
    }

    override fun describeContents(): Int = 0

    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeTypedList(devotionals)
    }

    companion object {
        @JvmField val CREATOR = object : Parcelable.Creator<DevotionalResponse>() {
            override fun createFromParcel(in: Parcel): DevotionalResponse =
                    DevotionalResponse(in)

            override fun newArray(size: Int): Array<DevotionalResponse?> =
                    arrayOfNulls(size)
        }
    }
}
</code>```

Go on This Link For full Solution

Kotlin Object Example

Title: creating a parcelable object in kotlin

Body:
TestActivity.kt

class TestActivity : Activity() {
    val DEVOTIONAL_RESPONSE: String = "DEVOTIONAL_RESPONSE"
    var holdr: Holdr_ActivityTest? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        holdr = Holdr_ActivityTest(findViewById(android.R.id.content))

        //create response
        var response: DevotionalResponse = DevotionalResponse()
        fillInResponse(response)

        //write it to a Bundle
        var newBundle: Bundle = Bundle()
        newBundle.putParcelable(DEVOTIONAL_RESPONSE, response)

        //read it from the new Bundle
        var newResponse: DevotionalResponse = newBundle.getParcelable(DEVOTIONAL_RESPONSE)

        //check that they're the same
        assert(newResponse.getDevotionals().get(0).getContent().equalsIgnoreCase(response.getDevotionals().get(0).getContent()))
    }
}

DevotionalResponse.kt

class DevotionalResponse() : Parcelable {

    @Expose
    var devotionals = arrayListOf<Devotional>();

    constructor(in: Parcel) : this() {
        in.readTypedList(this.devotionals, Devotional.CREATOR)
    }

    override fun describeContents(): Int = 0

    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeTypedList(devotionals)
    }

    companion object {
        @JvmField val CREATOR = object : Parcelable.Creator<DevotionalResponse>() {
            override fun createFromParcel(in: Parcel): DevotionalResponse =
                    DevotionalResponse(in)

            override fun newArray(size: Int): Array<DevotionalResponse?> =
                    arrayOfNulls(size)
        }
    }
}

Go on This Link For full Solution

Kotlin Object Example


问:
can you create sites automatically (with a html page) with drupal on the same server?
I've read that you can host multiple drupal sites, while they use the same core files(so not needing to copy a few megabytes for each site). I wanted to ask if there is an automated tool that can create a new site, while let you choose a template and then connecting it to the drupal system?

Are there tools like that(with a web layout)?

I would really like to get a few pointers as to how, lets say a company for building websites, will be able to use an automated system to build sites easily. I also understand that with drupal you have alot of manuver to edit your own code, when lets say you want some future in one of the sites. Is it pure php/html or in order to do that you have to delve into core Drupal futures? Also what are the chances that somebody already did it before and you can use this module?

Last, if a company wants to move to a Drupal system (web development company), how much of a transformation is it? Should they be Drupal core experts in order to not lose themself? Or they can keep a drupal base while still using the regular html/php? I really appreciate any leads.

Thanks.

*the questions is also intended to Joomla.

答:
To answer your first question, the Aegir project is a system whereby you can use Drupal to create and manage Drupal sites. That includes installing from install profiles--which are sort of like site templates--or a distribution (Drupal installations pre-packaged with modules). The downside is that installation is fairly involved, more so than just Drupal itself. There's a lot of documentation on the Drupal groups site for Aegir. For a straight multi-site install, there's some documentation on the subject, but the install instructions with the software come with help that you should consult first.

As for your second question, the answer is (unfortunately) "it depends". Knowledge of PHP, especially "the Drupal way", plus integration with the community, are huge plusses. If you intend to join the community, immediately sign up both yourself and all developers an account on Drupal.org and, if you find solutions to bugs or other problems, providing back is a sign of goodwill, and it usually pays back dividends (one example: you submit a patch, it gets included in a module, and then the community maintains it for you). Developers need not be experts with Drupal core, but they need to be pretty comfortable with learning the API and knowing how to create sites for clients in general. First start with requirements gathering, then see how it fits into the Drupal way of doing things. If it doesn't fit, then use the right tool.

That's a tip of the iceberg view from the developer's point of view (as opposed to the businessman's point of view). There are plenty of companies that do only Drupal and there are plenty of companies where Drupal is one tool they use out of many.


问:
Rails activeadmin save data in associated table
I have one table for Products and the product can either be in the interior or exterior or both. So I created another table to save the Products location. Now when admin adds the product I have provided the option to select the location(s) the product can be in, but when it is posted the code says the field can't be blank because of the validation. I am not sure what I am missing or the approach is wrong.

The product model:

```<code>class Product < ApplicationRecord
  validates :name, presence: true

  has_many :product_locations

  accepts_nested_attributes_for :product_locations
end
</code>```

The product location model:

```<code>class ProductLocation < ApplicationRecord

  enum locations: [:exterior, :interior]

  validates :location, presence: true
  validates :product_id, presence: true

  belongs_to :product
end
</code>```

The ActiveAdmin file for Product:

```<code>ActiveAdmin.register Product do

  permit_params :name, product_locations_attributes: {}

  actions :all, except: [:show, :destroy]

  filter :name

  index do
    column 'Product Name',  :name
    actions
  end

  form do |f|
    f.semantic_errors *f.object.errors.keys

    f.inputs "Products" do
      f.input :name
    end

    f.has_many :product_locations do |location|
      location.inputs "Locations" do
        location.input :location, as: :select, multiple: true, collection: ProductLocation.locations.keys
      end
    end

    f.actions
  end

  controller do
    def scoped_collection
      Product.where(user_id: nil)
    end
  end

end
</code>```

I get a multi-select for the locations which has "Interior" and "Exterior" for selection, but it says the field can't be blank when I select the location and submit the form

The error on save click I get is:

Location can't be blank

The params that get posted are:

```<code>Parameters: {"utf8"=>"✓", "product"=>{"name"=>"Test Product", "product_locations_attributes"=>{"0"=>{"location"=>["0", "1"]}}}, "commit"=>"Create Product"}
</code>```

答:
First, the permit attributes should be,

product_locations_attributes: [:id, :location]

Then, in your form

```<code>location.input :location, as: :select, multiple: true, collection: ProductLocation.locations.keys
</code>```

Since ProductLocation.locations is an array, array.keys is an invalid method.

So, use directly

```<code>location.input :location, as: :select, multiple: true, collection: ProductLocation.locations.map { |n| [n,n] }
</code>```

To store an array of multiple values take serialize field as an array,

```<code>class ProductLocation < ApplicationRecord

  enum locations: [:exterior, :interior]

  serialize :location, Array

  validates :location, presence: true
  validates :product_id, presence: true

  belongs_to :product
end
</code>```

Note: Inorder to get the serialize work, you need to have the dataType of the location as a text. If it is not text run a migration to change to text data type

Reason for text field: Rails will convert all those object into plain text when storing in database

Body:
I have one table for Products and the product can either be in the interior or exterior or both. So I created another table to save the Products location. Now when admin adds the product I have provided the option to select the location(s) the product can be in, but when it is posted the code says the field can't be blank because of the validation. I am not sure what I am missing or the approach is wrong.

The product model:

class Product < ApplicationRecord
  validates :name, presence: true

  has_many :product_locations

  accepts_nested_attributes_for :product_locations
end

The product location model:

class ProductLocation < ApplicationRecord

  enum locations: [:exterior, :interior]

  validates :location, presence: true
  validates :product_id, presence: true

  belongs_to :product
end

The ActiveAdmin file for Product:

ActiveAdmin.register Product do

  permit_params :name, product_locations_attributes: {}

  actions :all, except: [:show, :destroy]

  filter :name

  index do
    column 'Product Name',  :name
    actions
  end

  form do |f|
    f.semantic_errors *f.object.errors.keys

    f.inputs "Products" do
      f.input :name
    end

    f.has_many :product_locations do |location|
      location.inputs "Locations" do
        location.input :location, as: :select, multiple: true, collection: ProductLocation.locations.keys
      end
    end

    f.actions
  end

  controller do
    def scoped_collection
      Product.where(user_id: nil)
    end
  end

end

I get a multi-select for the locations which has "Interior" and "Exterior" for selection, but it says the field can't be blank when I select the location and submit the form

The error on save click I get is:

Location can't be blank

The params that get posted are:

Parameters: {"utf8"=>"✓", "product"=>{"name"=>"Test Product", "product_locations_attributes"=>{"0"=>{"location"=>["0", "1"]}}}, "commit"=>"Create Product"}

Body:
First, the permit attributes should be,

product_locations_attributes: [:id, :location]

Then, in your form

location.input :location, as: :select, multiple: true, collection: ProductLocation.locations.keys

Since ProductLocation.locations is an array, array.keys is an invalid method.

So, use directly

location.input :location, as: :select, multiple: true, collection: ProductLocation.locations.map { |n| [n,n] }

To store an array of multiple values take serialize field as an array,

class ProductLocation < ApplicationRecord

  enum locations: [:exterior, :interior]

  serialize :location, Array

  validates :location, presence: true
  validates :product_id, presence: true

  belongs_to :product
end

Note: Inorder to get the serialize work, you need to have the dataType of the location as a text. If it is not text run a migration to change to text data type

Reason for text field: Rails will convert all those object into plain text when storing in database