问:
Can anyone point me to a reference for the Drupal $account->content array?
I've been digging around all morning and I can't find any reference that defines the account object.

In particular, I want to modify another drupal admin's user hook() function to change the way it works. Currently, it comes out as dt/dd pairs without any css classes or custom styles, and I need to be able to theme the content.

```<code>  function acidfree_user($op, &$edit, &$account, $category = NULL) {
    if ($op == 'view') {
    //Pachkov.Sergey.START - MODIFIED BY MHEINZ
      $result = db_query("SELECT nid, title FROM node WHERE nid IN (SELECT nid FROM node WHERE uid=%d
                         AND type='acidfree') ORDER BY nid desc", $account->uid);

      $i=0;
      $account->content['acidfree-albums'] = array(
        '#type' => 'user_profile_category',
        '#title' => t('Photo albums'),
      );
      while ($item = db_fetch_array($result)) {
        $title_node = $item['title'];
        $nid = $item['nid'];
        $account->content['acidfree-albums'][$i] = array(
                '#title' => t(' '),
                '#value' => l($title_node, "node/{$nid}"),
                '#class' => 'acidfree-albums',
                '#type' => 'user_profile_item',
        );
        $i++;
      }
    }
    //Pachkov.Sergey.END - MODIFIED BY MHEINZ
  }
</code>```

答:
The best reference you can get is

```<code>print_r($account->content);
</code>```

and to see the trace to your current location (to see where the object is set) you could use

```<code>debug_print_backtrace();
</code>```

Body:
I've been digging around all morning and I can't find any reference that defines the account object.

In particular, I want to modify another drupal admin's user hook() function to change the way it works. Currently, it comes out as dt/dd pairs without any css classes or custom styles, and I need to be able to theme the content.

  function acidfree_user($op, &$edit, &$account, $category = NULL) {
    if ($op == 'view') {
    //Pachkov.Sergey.START - MODIFIED BY MHEINZ
      $result = db_query("SELECT nid, title FROM node WHERE nid IN (SELECT nid FROM node WHERE uid=%d
                         AND type='acidfree') ORDER BY nid desc", $account->uid);

      $i=0;
      $account->content['acidfree-albums'] = array(
        '#type' => 'user_profile_category',
        '#title' => t('Photo albums'),
      );
      while ($item = db_fetch_array($result)) {
        $title_node = $item['title'];
        $nid = $item['nid'];
        $account->content['acidfree-albums'][$i] = array(
                '#title' => t(' '),
                '#value' => l($title_node, "node/{$nid}"),
                '#class' => 'acidfree-albums',
                '#type' => 'user_profile_item',
        );
        $i++;
      }
    }
    //Pachkov.Sergey.END - MODIFIED BY MHEINZ
  }

Body:
The best reference you can get is

print_r($account->content);

and to see the trace to your current location (to see where the object is set) you could use

debug_print_backtrace();


来源: stackexchange

问:
how to reformat a json in python
I am trying to make a json file as I am new in python
the json file
i have is as followed and i want to reformat it

```<code>{
   "A1":"a1",
   "aback":"\u0259b\u00e6k",
   "abaft":"abaft",
   "abandon":"\u0259b\u00e6nd\u0259n",
   "abandoned":"\u0259b\u00e6nd\u0259nd",
   "abandonment":"\u0259b\u00e6nd\u0259nm\u0259nt",
   "abase":"abase",
   "abash":"\u0259b\u00e6\u0283",
   "abashment":"abashment",
   "abate":"\u0259bet",
   "abatement":"\u0259betm\u0259nt",
   "abbey":"\u00e6bi",
   "abbreviate":"\u0259briviet",
   "abbreviation":"\u0259brivie\u0283\u0259n"
}
</code>```

the format that i want to achieve is

```<code>{
   word: "A1",
   transcription:"a1"
}
{
   word: "aback",
   transcription :"\u0259b\u00e6k"
}
{
  word:"abaft"
  transcrition:"abaft"
}
{
  word:"abbreviation",
  transcription:"\u0259brivie\u0283\u0259n"
}
</code>```

答:
Read the JSON from the file and convert it to a dictionary. Use a list comprehension to generate a list of dictionaries and write that out as a JSON list:

```<code>import json

with open('file.json') as infile, open('out.json', 'w') as outfile:
    d = json.load(infile)
    json.dump([{'word': k, 'transcription': d[k]} for k in d], outfile)
</code>```

For your input file this will produce an output file containing:

```
[{"transcription": "\u0259b\u00e6\u0283", "word": "abash"}, {"transcription": "\u0259briviet", "word": "abbreviate"}, {"transcription": "abaft", "word": "abaft"}, {"transcription": "a1", "word": "A1"}, {"transcription": "\u0259b\u00e6nd\u0259nd", "word": "abandoned"}, {"transcription": "\u0259b\u00e6nd\u0259nm\u0259nt", "word": "abandonment"}, {"transcription": "\u0259betm\u0259nt", "word": "abatement"}, {"transcription": "\u0259bet", "word": "abate"}, {"transcription": "\u0259b\u00e6nd\u0259n", "word": "abandon"}, {"transcription": "\u00e6bi", "word": "abbey"}, {"transcription": "\u0259brivie\u0283\u0259n", "word": "abbreviation"}, {"transcription": "\u0259b\u00e6k", "word": "aback"}, {"transcription": "abase", "word": "abase"}, {"transcription": "abashment", "word": "abashment"}]
```

You can format the output a bit, use indent:

```<code>json.dump([{'word': k, 'transcription': d[k]} for k in d], outfile, indent='')
</code>```

will output:

```
[
    {
        "word": "aback",
        "transcription": "\u0259b\u00e6k"
    },
    {
        "word": "abandonment",
        "transcription": "\u0259b\u00e6nd\u0259nm\u0259nt"
    },
    {
        "word": "abatement",
        "transcription": "\u0259betm\u0259nt"
    },
    {
        "word": "abbey",
        "transcription": "\u00e6bi"
    },
    {
        "word": "abbreviation",
        "transcription": "\u0259brivie\u0283\u0259n"
    },
    {
        "word": "abandoned",
        "transcription": "\u0259b\u00e6nd\u0259nd"
    },
    {
        "word": "abash",
        "transcription": "\u0259b\u00e6\u0283"
    },
    {
        "word": "abaft",
        "transcription": "abaft"
    },
    {
        "word": "abashment",
        "transcription": "abashment"
    },
    {
        "word": "abate",
        "transcription": "\u0259bet"
    },
    {
        "word": "abbreviate",
        "transcription": "\u0259briviet"
    },
    {
        "word": "A1",
        "transcription": "a1"
    },
    {
        "word": "abandon",
        "transcription": "\u0259b\u00e6nd\u0259n"
    },
    {
        "word": "abase",
        "transcription": "abase"
    }
]
```

Note that your requested format is not actually valid JSON. If you do not want the commas and list brackets you can write the file out like this:

```<code>with open('file.json') as infile, open('out.json', 'w') as outfile:
    d = json.load(infile)
    print(*[json.dumps({'word': k, 'transcription': d[k]}, indent='    ') for k in d], file=outfile, sep='\n')
</code>```

```
{
    "word": "aback",
    "transcription": "\u0259b\u00e6k"
}
{
    "word": "abandonment",
    "transcription": "\u0259b\u00e6nd\u0259nm\u0259nt"
}
{
    "word": "abatement",
    "transcription": "\u0259betm\u0259nt"
}
{
    "word": "abbey",
    "transcription": "\u00e6bi"
}
{
    "word": "abbreviation",
    "transcription": "\u0259brivie\u0283\u0259n"
}
{
    "word": "abandoned",
    "transcription": "\u0259b\u00e6nd\u0259nd"
}
{
    "word": "abash",
    "transcription": "\u0259b\u00e6\u0283"
}
{
    "word": "abaft",
    "transcription": "abaft"
}
{
    "word": "abashment",
    "transcription": "abashment"
}
{
    "word": "abate",
    "transcription": "\u0259bet"
}
{
    "word": "abbreviate",
    "transcription": "\u0259briviet"
}
{
    "word": "A1",
    "transcription": "a1"
}
{
    "word": "abandon",
    "transcription": "\u0259b\u00e6nd\u0259n"
}
{
    "word": "abase",
    "transcription": "abase"
}
```

Finally, if the order is important you can iterate over the sorted keys, just use:

for k in sorted(d)

where appropriate.

ContentLicense: CC BY-SA 3.0

Title: how to reformat a json in python

Body:
I am trying to make a json file as I am new in python
the json file
i have is as followed and i want to reformat it

{
   "A1":"a1",
   "aback":"\u0259b\u00e6k",
   "abaft":"abaft",
   "abandon":"\u0259b\u00e6nd\u0259n",
   "abandoned":"\u0259b\u00e6nd\u0259nd",
   "abandonment":"\u0259b\u00e6nd\u0259nm\u0259nt",
   "abase":"abase",
   "abash":"\u0259b\u00e6\u0283",
   "abashment":"abashment",
   "abate":"\u0259bet",
   "abatement":"\u0259betm\u0259nt",
   "abbey":"\u00e6bi",
   "abbreviate":"\u0259briviet",
   "abbreviation":"\u0259brivie\u0283\u0259n"
}

the format that i want to achieve is

{
   word: "A1",
   transcription:"a1"
}
{
   word: "aback",
   transcription :"\u0259b\u00e6k"
}
{
  word:"abaft"
  transcrition:"abaft"
}
{
  word:"abbreviation",
  transcription:"\u0259brivie\u0283\u0259n"
}

Body:
Read the JSON from the file and convert it to a dictionary. Use a list comprehension to generate a list of dictionaries and write that out as a JSON list:

import json

with open('file.json') as infile, open('out.json', 'w') as outfile:
    d = json.load(infile)
    json.dump([{'word': k, 'transcription': d[k]} for k in d], outfile)

For your input file this will produce an output file containing:

[{"transcription": "\u0259b\u00e6\u0283", "word": "abash"}, {"transcription": "\u0259briviet", "word": "abbreviate"}, {"transcription": "abaft", "word": "abaft"}, {"transcription": "a1", "word": "A1"}, {"transcription": "\u0259b\u00e6nd\u0259nd", "word": "abandoned"}, {"transcription": "\u0259b\u00e6nd\u0259nm\u0259nt", "word": "abandonment"}, {"transcription": "\u0259betm\u0259nt", "word": "abatement"}, {"transcription": "\u0259bet", "word": "abate"}, {"transcription": "\u0259b\u00e6nd\u0259n", "word": "abandon"}, {"transcription": "\u00e6bi", "word": "abbey"}, {"transcription": "\u0259brivie\u0283\u0259n", "word": "abbreviation"}, {"transcription": "\u0259b\u00e6k", "word": "aback"}, {"transcription": "abase", "word": "abase"}, {"transcription": "abashment", "word": "abashment"}]

You can format the output a bit, use indent:

json.dump([{'word': k, 'transcription': d[k]} for k in d], outfile, indent='')

will output:

[
    {
        "word": "aback",
        "transcription": "\u0259b\u00e6k"
    },
    {
        "word": "abandonment",
        "transcription": "\u0259b\u00e6nd\u0259nm\u0259nt"
    },
    {
        "word": "abatement",
        "transcription": "\u0259betm\u0259nt"
    },
    {
        "word": "abbey",
        "transcription": "\u00e6bi"
    },
    {
        "word": "abbreviation",
        "transcription": "\u0259brivie\u0283\u0259n"
    },
    {
        "word": "abandoned",
        "transcription": "\u0259b\u00e6nd\u0259nd"
    },
    {
        "word": "abash",
        "transcription": "\u0259b\u00e6\u0283"
    },
    {
        "word": "abaft",
        "transcription": "abaft"
    },
    {
        "word": "abashment",
        "transcription": "abashment"
    },
    {
        "word": "abate",
        "transcription": "\u0259bet"
    },
    {
        "word": "abbreviate",
        "transcription": "\u0259briviet"
    },
    {
        "word": "A1",
        "transcription": "a1"
    },
    {
        "word": "abandon",
        "transcription": "\u0259b\u00e6nd\u0259n"
    },
    {
        "word": "abase",
        "transcription": "abase"
    }
]

Note that your requested format is not actually valid JSON. If you do not want the commas and list brackets you can write the file out like this:

with open('file.json') as infile, open('out.json', 'w') as outfile:
    d = json.load(infile)
    print(*[json.dumps({'word': k, 'transcription': d[k]}, indent='    ') for k in d], file=outfile, sep='\n')

{
    "word": "aback",
    "transcription": "\u0259b\u00e6k"
}
{
    "word": "abandonment",
    "transcription": "\u0259b\u00e6nd\u0259nm\u0259nt"
}
{
    "word": "abatement",
    "transcription": "\u0259betm\u0259nt"
}
{
    "word": "abbey",
    "transcription": "\u00e6bi"
}
{
    "word": "abbreviation",
    "transcription": "\u0259brivie\u0283\u0259n"
}
{
    "word": "abandoned",
    "transcription": "\u0259b\u00e6nd\u0259nd"
}
{
    "word": "abash",
    "transcription": "\u0259b\u00e6\u0283"
}
{
    "word": "abaft",
    "transcription": "abaft"
}
{
    "word": "abashment",
    "transcription": "abashment"
}
{
    "word": "abate",
    "transcription": "\u0259bet"
}
{
    "word": "abbreviate",
    "transcription": "\u0259briviet"
}
{
    "word": "A1",
    "transcription": "a1"
}
{
    "word": "abandon",
    "transcription": "\u0259b\u00e6nd\u0259n"
}
{
    "word": "abase",
    "transcription": "abase"
}

Finally, if the order is important you can iterate over the sorted keys, just use:

for k in sorted(d)

where appropriate.


问:
Adding Facebook Dependency
I'm trying to add Facebook dependency to my project.

I tried adding the following to my pom.xml:

```<code>    <dependency>
        <groupId>com.facebook.android</groupId>
        <artifactId>facebook-android-sdk</artifactId>
        <version>4.1.0</version>
        <type>aar</type>
    </dependency>
</code>```

And suddenly none of the previously accepted dependencies is found:

When I exclude support-v4 library

```<code>    <dependency>
        <groupId>com.facebook.android</groupId>
        <artifactId>facebook-android-sdk</artifactId>
        <version>4.1.0</version>
        <type>aar</type>
        <exclusions>
            <exclusion>
                <artifactId>support-v4</artifactId>
                <groupId>com.android.support</groupId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

I don't have as many errors,

but it does not seem to include my dependency:

Is there anything I'm missing there?

Here's my build :

```<code><build>
    <plugins>
        <plugin>
            <groupId>com.jayway.maven.plugins.android.generation2</groupId>
            <artifactId>android-maven-plugin</artifactId>
            <version>${android.maven.version}</version> <!-- 4.0.0-rc.2 -->
            <goals>
                <goal>consume-aar</goal>
            </goals>
            <extensions>true</extensions>
            <configuration>
                <sdk>
                    <platform>${platform.version}</platform> <!-- 4.3 -->
                </sdk>
                <deleteConflictingFiles>true</deleteConflictingFiles>
                <undeployBeforeDeploy>true</undeployBeforeDeploy>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

--- EDIT ----

The dependency tree seems fine:

```<code>[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ konnect-android ---
[INFO] com.company:project-android:apk:1.0.0
[INFO] +- com.company:project-shared:jar:1.0.0:compile
[INFO] +- com.google.android:android:jar:4.1.1.4:provided
[INFO] |  +- commons-logging:commons-logging:jar:1.1.1:provided
[INFO] |  +- org.apache.httpcomponents:httpclient:jar:4.0.1:provided
[INFO] |  |  +- org.apache.httpcomponents:httpcore:jar:4.0.1:provided
[INFO] |  |  \- commons-codec:commons-codec:jar:1.3:provided
[INFO] |  +- org.khronos:opengl-api:jar:gl1.1-android-2.1_r1:provided
[INFO] |  +- xerces:xmlParserAPIs:jar:2.6.2:provided
[INFO] |  \- xpp3:xpp3:jar:1.1.4c:provided
[INFO] +- com.marvinlabs:android-slideshow-widget:jar:0.5.0:compile
[INFO] +- com.marvinlabs:android-slideshow-widget-picasso-    plugin:jar:0.5.0:compile
[INFO] +- com.squareup.okhttp:okhttp:jar:2.3.0:compile
[INFO] |  \- com.squareup.okio:okio:jar:1.3.0:compile
[INFO] +- com.squareup.okhttp:okhttp-urlconnection:jar:2.3.0:compile
[INFO] +- com.squareup.picasso:picasso:jar:2.5.2:compile
[INFO] +- com.parse.bolts:bolts-android:jar:1.2.0:compile
[INFO] +- com.facebook.android:facebook-android-sdk:aar:4.1.0:compile
[INFO] +- junit:junit:jar:4.11:test
[INFO] |  \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] \- com.facebook.android:facebook-android-sdk:jar:4.1.0:system
</code>```

答:
```<code>compile 'com.facebook.android:facebook-android-sdk:[4,5)'

1. Go to Android Studio | New Project | Minimum SDK
2. Select "API 15: Android 4.0.3" or higher and create your new project.
3. In your project, open
your_app | Gradle Scripts | build.gradle
4. Add the Maven Central Repository to build.gradle before dependencies:
repositories {
        mavenCentral()
    }
5. Add compile 'com.facebook.android:facebook-android-sdk:[4,5)' to your build.gradle dependencies.
6. Build your project.
7. Import Facebook SDK into your app:
import com.facebook.FacebookSdk;
</code>```

Title: Adding Facebook Dependency

Body:
I'm trying to add Facebook dependency to my project.

I tried adding the following to my pom.xml:

    <dependency>
        <groupId>com.facebook.android</groupId>
        <artifactId>facebook-android-sdk</artifactId>
        <version>4.1.0</version>
        <type>aar</type>
    </dependency>

And suddenly none of the previously accepted dependencies is found:

When I exclude support-v4 library

    <dependency>
        <groupId>com.facebook.android</groupId>
        <artifactId>facebook-android-sdk</artifactId>
        <version>4.1.0</version>
        <type>aar</type>
        <exclusions>
            <exclusion>
                <artifactId>support-v4</artifactId>
                <groupId>com.android.support</groupId>
            </exclusion>
        </exclusions>
    </dependency>

I don't have as many errors,

but it does not seem to include my dependency:

Is there anything I'm missing there?

Here's my build :

<build>
    <plugins>
        <plugin>
            <groupId>com.jayway.maven.plugins.android.generation2</groupId>
            <artifactId>android-maven-plugin</artifactId>
            <version>${android.maven.version}</version>
            <goals>
                <goal>consume-aar</goal>
            </goals>
            <extensions>true</extensions>
            <configuration>
                <sdk>
                    <platform>${platform.version}</platform>
                </sdk>
                <deleteConflictingFiles>true</deleteConflictingFiles>
                <undeployBeforeDeploy>true</undeployBeforeDeploy>
            </configuration>
        </plugin>
    </plugins>
</build>

--- EDIT ----

The dependency tree seems fine:

[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ konnect-android ---
[INFO] com.company:project-android:apk:1.0.0
[INFO] +- com.company:project-shared:jar:1.0.0:compile
[INFO] +- com.google.android:android:jar:4.1.1.4:provided
[INFO] |  +- commons-logging:commons-logging:jar:1.1.1:provided
[INFO] |  +- org.apache.httpcomponents:httpclient:jar:4.0.1:provided
[INFO] |  |  +- org.apache.httpcomponents:httpcore:jar:4.0.1:provided
[INFO] |  |  \- commons-codec:commons-codec:jar:1.3:provided
[INFO] |  +- org.khronos:opengl-api:jar:gl1.1-android-2.1_r1:provided
[INFO] |  +- xerces:xmlParserAPIs:jar:2.6.2:provided
[INFO] |  \- xpp3:xpp3:jar:1.1.4c:provided
[INFO] +- com.marvinlabs:android-slideshow-widget:jar:0.5.0:compile
[INFO] +- com.marvinlabs:android-slideshow-widget-picasso-    plugin:jar:0.5.0:compile
[INFO] +- com.squareup.okhttp:okhttp:jar:2.3.0:compile
[INFO] |  \- com.squareup.okio:okio:jar:1.3.0:compile
[INFO] +- com.squareup.okhttp:okhttp-urlconnection:jar:2.3.0:compile
[INFO] +- com.squareup.picasso:picasso:jar:2.5.2:compile
[INFO] +- com.parse.bolts:bolts-android:jar:1.2.0:compile
[INFO] +- com.facebook.android:facebook-android-sdk:aar:4.1.0:compile
[INFO] +- junit:junit:jar:4.11:test
[INFO] |  \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] \- com.facebook.android:facebook-android-sdk:jar:4.1.0:system


问:
Java Apache JEXL boolean expressions issue
I'm developing in Java a system to check the occurrence of a combination of keywords in a text.
For example, I have the following expression to check: ( yellow || red ) && sofa .
 I divided the job into two steps. The first one is to detect individual words in the text.
 The second one is to use the result for checking the boolean expression.
 After a short web search I choose Apache JEXL.

```<code>// My web app contains a set of preconfigured keywords inserted by administrator:
List<String> system_occurence =new ArrayList<String>() {{
    add("yellow");
    add("brown");
    add("red");
    add("kitchen");
    add("sofa");
}};

// The method below check if some of system keywords are in the text
List<String> occurence = getOccurenceKeywordsInTheText();
for ( String word :occurrence){
    jexlContext.set(word,true);
}

// Set to false system keywords not in the text
system_occurence.removeAll(occurence);
for ( String word :system_occurence){
    jexlContext.set(word,false);
}

// Value the boolean expression
String jexlExp ="( yellow || red ) && sofa";
JexlExpression e = jexl.createExpression( jexlExp_ws_keyword_matching );

Boolean o = (Boolean) e.evaluate(jexlContext);
</code>```

In the above example, I use simple words in the boolean expression. With ASCII and non-composite words I've no problems.
I've problems with non-ASCII and composite keywords inside the boolean expression because I can't use those as variables names.

```<code>// The below example fails, JEXL launch Exception
String jexlExp ="( Lebron James || red ) && sofa";

// The below example fails, JEXL launch Exception
String jexlExp ="( òsdà || red ) && sofa";
</code>```

How can I solve? Is it right my way?

Sorry for my bad English :)

答:
Try to replace space with some other character like underscore (_).</p>

```<code>package jexl;

   import org.apache.commons.jexl3.*;

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

    public class Test2 {

    private static final JexlEngine JEXL_ENGINE = new JexlBuilder().cache(512).strict(false).silent(false).create();
    public static void main(String[] args) {
        // My web app contains a set of preconfigured keywords inserted by administrator:
        List<String> system_occurence =new ArrayList<String>() {{
            add("yellow");
            add("brown");
            add("red");
            add("kitchen");
            add("sofa");
        }};

        JexlContext jexlContext = new MapContext();

// The method below check if some of system keywords are in the text
        List<String> occurence = Arrays.asList("kitchen");
        for ( String word :occurence){
            jexlContext.set(word,true);
        }

// Set to false system keywords not in the text
        system_occurence.removeAll(occurence);
        for ( String word :system_occurence){
            jexlContext.set(word,false);
        }

// Value the boolean expression
        String jexlExp ="( Lebron_James || red ) && sofa";
        JexlExpression e = JEXL_ENGINE.createExpression( jexlExp );

        Boolean o = (Boolean) e.evaluate(jexlContext);

        System.out.println(o);
    }

}
</code>```

Body:
I'm developing in Java a system to check the occurrence of a combination of keywords in a text.
For example, I have the following expression to check: ( yellow || red ) && sofa .
 I divided the job into two steps. The first one is to detect individual words in the text.
 The second one is to use the result for checking the boolean expression.
 After a short web search I choose Apache JEXL.

// My web app contains a set of preconfigured keywords inserted by administrator:
List<String> system_occurence =new ArrayList<String>() {{
    add("yellow");
    add("brown");
    add("red");
    add("kitchen");
    add("sofa");
}};

// The method below check if some of system keywords are in the text
List<String> occurence = getOccurenceKeywordsInTheText();
for ( String word :occurrence){
    jexlContext.set(word,true);
}

// Set to false system keywords not in the text
system_occurence.removeAll(occurence);
for ( String word :system_occurence){
    jexlContext.set(word,false);
}

// Value the boolean expression
String jexlExp ="( yellow || red ) && sofa";
JexlExpression e = jexl.createExpression( jexlExp_ws_keyword_matching );

Boolean o = (Boolean) e.evaluate(jexlContext);

In the above example, I use simple words in the boolean expression. With ASCII and non-composite words I've no problems.
I've problems with non-ASCII and composite keywords inside the boolean expression because I can't use those as variables names.

// The below example fails, JEXL launch Exception
String jexlExp ="( Lebron James || red ) && sofa";

// The below example fails, JEXL launch Exception
String jexlExp ="( òsdà || red ) && sofa";

How can I solve? Is it right my way?

Sorry for my bad English :)

Body:
Try to replace space with some other character like underscore (_).

package jexl;

   import org.apache.commons.jexl3.*;

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

    public class Test2 {

    private static final JexlEngine JEXL_ENGINE = new JexlBuilder().cache(512).strict(false).silent(false).create();
    public static void main(String[] args) {
        // My web app contains a set of preconfigured keywords inserted by administrator:
        List<String> system_occurence =new ArrayList<String>() {{
            add("yellow");
            add("brown");
            add("red");
            add("kitchen");
            add("sofa");
        }};

        JexlContext jexlContext = new MapContext();

// The method below check if some of system keywords are in the text
        List<String> occurence = Arrays.asList("kitchen");
        for ( String word :occurence){
            jexlContext.set(word,true);
        }

// Set to false system keywords not in the text
        system_occurence.removeAll(occurence);
        for ( String word :system_occurence){
            jexlContext.set(word,false);
        }

// Value the boolean expression
        String jexlExp ="( Lebron_James || red ) && sofa";
        JexlExpression e = JEXL_ENGINE.createExpression( jexlExp );

        Boolean o = (Boolean) e.evaluate(jexlContext);

        System.out.println(o);
    }

}


问:
How do I insert a space after a character in a textbox, depending on the total characters entered, JQuery?
Is it possible to add a space in a textbox depending on the total characters entered by the user.

For example if the user entered 'LU33RT' on blur I'd like it to display 'LU3 3RT'. The rule that I'm looking to incorporate is by counting 3 characters in from the right then add a space.

$('#postcode').blur(...

Any help would be greatly appreciated, Thanks

My Solution, Although it's basic:

```<code>$(document).ready(function(){

    $('#postcode').blur(function(){
        if(($(this).val().length == 6) && (/\S/)){
           var myString = $(this).val().slice(0, 3);
           var myString2 = $(this).val().slice(-3);
           $(this).val(myString + ' ' + myString2);
        }else{
            document.write('OOPS!');}
    });
});
</code>```

答:
```<code>$('#postcode').blur(function()
{
    $(this).val( $(this).val().substring( 0, -3 ) + ' ' + $(this).val().substring( -3 ));
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to add a space in a textbox depending on the total characters entered by the user.

For example if the user entered 'LU33RT' on blur I'd like it to display 'LU3 3RT'. The rule that I'm looking to incorporate is by counting 3 characters in from the right then add a space.

$('#postcode').blur(...

Any help would be greatly appreciated, Thanks

My Solution, Although it's basic:

$(document).ready(function(){

    $('#postcode').blur(function(){
        if(($(this).val().length == 6) && (/\S/)){
           var myString = $(this).val().slice(0, 3);
           var myString2 = $(this).val().slice(-3);
           $(this).val(myString + ' ' + myString2);
        }else{
            document.write('OOPS!');}
    });
});


Title: how to reformat a json in python

Body:
In [16]: d
Out[16]: {'a': 'A', 'b': 'B', 'c': 'C'}

In [17]: lis = []

In [18]: lis
Out[18]: []

In [19]: for key in d:
    ...:     dd ={}
    ...:     dd["word"] = key
    ...:     dd["transcrition"] = d[key]
    ...:     lis.append(dd)
    ...:

In [20]: lis
Out[20]:
[{'transcrition': 'A', 'word': 'a'},
 {'transcrition': 'C', 'word': 'c'},
 {'transcrition': 'B', 'word': 'b'}]


问:
How can i convert linux "date +%s" output to a more readable format in bash script
Here is the script:

```<code>
#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

</code>
```

so i want to convert $startTime into a UTC format

答:
Try:

```<code>date -d @$(($startTime-$1-5))
</code>```

if you want to decode the first state of $startTime variable, or this:

```<code>date -d @$startTime
</code>```

and, you can add -u argument to get the UTC time... %)

read the man date

Body:
Here is the script:

#!/bin/bash

i="0"
startTime=`date -u +%s`
startTime=$[$startTime+$1+5]
echo ""
echo "##################"
echo "LAUNCHING REQUESTS"
echo "  COUNT:  $1 "
echo "  DELAY:  1 "
echo "  EXECUTION:  $startTime "
echo "##################"
echo ""

while [ $1 -gt "$i" ]
do
  i=$[$i+1]
  php avtestTimed.php $1 $2 $startTime &
  echo "QUEUEING REQUEST $i"
  sleep 1
done

so i want to convert $startTime into a UTC format

Body:
Try:

date -d @$(($startTime-$1-5))

if you want to decode the first state of $startTime variable, or this:

date -d @$startTime

and, you can add -u argument to get the UTC time... %)

read the man date


问:
How to use LogEntries on Angular 2 applications (TypeScript)
I have this tsconfig.json:

```<code>{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false,
        "outDir": "dist"
    },
    "exclude": [
        "node_modules"
    ]
}
</code>```

With dashboard.component.ts:

```<code>import { Component, OnInit } from '@angular/core';

import Logger = require('le_node');
var log = new Logger({
  token:'abcdef-1234-ghijklm-5678-nopqrstuvwxyz'
});

@Component({
    selector: 'dashboard',
    templateUrl: 'app/dashboard.component.html'
})

export class DashboardComponent implements OnInit {

    constructor() { }

    ngOnInit(): void {
        log.log('Test LogEntries...');
    }

}
</code>```

And run npm install le_node --save to install LogEntries. When tried to run the application with npm start, I am getting this error:

```<code>> sample-app@2.0.0 start /Users/user/Workspace/sample-app
> tsc && concurrently "tsc -w" "lite-server"

app/dashboard.component.ts(10,25): error TS2307: Cannot find module 'le_node'.
</code>```

答:
A solution that worked for me is just to not use the le_node module which is not browser friendly.
And use the logentries REST API

```<code>@Injectable()
export class LoggerService {
    constructor(private http: Http) {
    }

    public log(level: string, name: string) {
        // https://docs.logentries.com/docs/http-post
        const LOGENTRIES_URL = "https://webhook.logentries.com/noformat/logs/";
        let headers = new Headers();
        headers.append("Content-Type", 'application/json');
        let requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            headers: headers,
            body: JSON.stringify({ "level": level, "message": message })
        });
        this.http.request(LOGENTRIES_URL + YOUR_LE_TOKEN, requestoptions).toPromise().catch((error) => {
            console.log("faield to send log to the logentries server");
        });
    }
}
</code>```

Body:
I have this tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false,
        "outDir": "dist"
    },
    "exclude": [
        "node_modules"
    ]
}

With dashboard.component.ts:

import { Component, OnInit } from '@angular/core';

import Logger = require('le_node');
var log = new Logger({
  token:'abcdef-1234-ghijklm-5678-nopqrstuvwxyz'
});

@Component({
    selector: 'dashboard',
    templateUrl: 'app/dashboard.component.html'
})

export class DashboardComponent implements OnInit {

    constructor() { }

    ngOnInit(): void {
        log.log('Test LogEntries...');
    }

}

And run npm install le_node --save to install LogEntries. When tried to run the application with npm start, I am getting this error:

> sample-app@2.0.0 start /Users/user/Workspace/sample-app
> tsc && concurrently "tsc -w" "lite-server"

app/dashboard.component.ts(10,25): error TS2307: Cannot find module 'le_node'.

Body:
A solution that worked for me is just to not use the le_node module which is not browser friendly.
And use the logentries REST API

@Injectable()
export class LoggerService {
    constructor(private http: Http) {
    }

    public log(level: string, name: string) {
        // https://docs.logentries.com/docs/http-post
        const LOGENTRIES_URL = "https://webhook.logentries.com/noformat/logs/";
        let headers = new Headers();
        headers.append("Content-Type", 'application/json');
        let requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            headers: headers,
            body: JSON.stringify({ "level": level, "message": message })
        });
        this.http.request(LOGENTRIES_URL + YOUR_LE_TOKEN, requestoptions).toPromise().catch((error) => {
            console.log("faield to send log to the logentries server");
        });
    }
}


问:
Angular localStorage array keeps getting reset on page refresh
Objective:

I want the  localStorage cached  answers array to be prepopulated only by the contents of the 4 object  var questions array  the first time it is loaded
on subsequent page refreshes I want the modified localStorage answers array to be loaded  e.g. there may be many more objects or spliced objects in array

At the moment every time I page refresh it reverts back to the original  4 object array .

```<code> var questions = [{"id":9,"Index":9,"Answered":"No","Correct":"?"},{"id":10,"Index":10,"Answered":"No","Correct":"?"},{"id":11,"Index":11,"Answered":"No","Correct":"?"},{"id":12,"Index":12,"Answered":"No","Correct":"?"}];

// storing our array as a string
localStorage.setItem("answers", JSON.stringify(questions));

// retrieving our data and converting it back into an array

var retrievedData = localStorage.getItem("answers");

// Possible Solution  this intial array  gets created every time the page refreshes and needs some logic to determine
// if it's intial length if not choose existing localstorage answers array in cache

   $scope.answers = JSON.parse(localStorage.getItem('answers'))

   $scope.addAnswer = function (){
    $scope.answers.push({"id":10,"Index":10,"Answered":"Yes","Correct":"Correct"})
        $scope.newAnswer = ''
    }

   $scope.spliceAnswer = function (){
    $scope.answers.splice(1, 1, {"id":10,"Index":10,"Answered":"Yes","Correct":"InCorrect"})
    $scope.replaceAnswer = ''
  }

   $scope.$watch('answers',function(newValue, oldValue){
    if(newValue!=oldValue){
        localStorage.setItem('answers',JSON.stringify(newValue))
    }
}, true)
</code>```

HTML

```<code><form name="frm" ng-submit="addAnswer()">
    <input type="text" name="newAnswer" ng-model="newAnswer" required />
    <button >Add </button>
</form>
<form name="frm" ng-submit="spliceAnswer()">
<input type="text" name="replaceAnswer" ng-model="replaceAnswer" required />
<button >Replace </button>
</form>
<h6>Answers : {answers}</h6>
</code>```

答:
I think problem lies here :

```<code>if(newValue!=oldValue){
    localStorage.setItem('answers',JSON.stringify(newValue))
}
</code>```

validate your new and old values also, change it to:

```<code>if(newValue && oldValue && newValue!=oldValue){
    localStorage.setItem('answers',JSON.stringify(newValue))
}
</code>```

Body:
Objective:

I want the  localStorage cached  answers array to be prepopulated only by the contents of the 4 object  var questions array  the first time it is loaded
on subsequent page refreshes I want the modified localStorage answers array to be loaded  e.g. there may be many more objects or spliced objects in array

At the moment every time I page refresh it reverts back to the original  4 object array .

 var questions = [{"id":9,"Index":9,"Answered":"No","Correct":"?"},{"id":10,"Index":10,"Answered":"No","Correct":"?"},{"id":11,"Index":11,"Answered":"No","Correct":"?"},{"id":12,"Index":12,"Answered":"No","Correct":"?"}];

// storing our array as a string
localStorage.setItem("answers", JSON.stringify(questions));

// retrieving our data and converting it back into an array

var retrievedData = localStorage.getItem("answers");

// Possible Solution  this intial array  gets created every time the page refreshes and needs some logic to determine
// if it's intial length if not choose existing localstorage answers array in cache

   $scope.answers = JSON.parse(localStorage.getItem('answers'))

   $scope.addAnswer = function (){
    $scope.answers.push({"id":10,"Index":10,"Answered":"Yes","Correct":"Correct"})
        $scope.newAnswer = ''
    }

   $scope.spliceAnswer = function (){
    $scope.answers.splice(1, 1, {"id":10,"Index":10,"Answered":"Yes","Correct":"InCorrect"})
    $scope.replaceAnswer = ''
  }

   $scope.$watch('answers',function(newValue, oldValue){
    if(newValue!=oldValue){
        localStorage.setItem('answers',JSON.stringify(newValue))
    }
}, true)

HTML

<form name="frm" ng-submit="addAnswer()">
    <input type="text" name="newAnswer" ng-model="newAnswer" required />
    <button >Add </button>
</form>
<form name="frm" ng-submit="spliceAnswer()">
<input type="text" name="replaceAnswer" ng-model="replaceAnswer" required />
<button >Replace </button>
</form>

Answers : {answers}

Body:
I think problem lies here :

if(newValue!=oldValue){
    localStorage.setItem('answers',JSON.stringify(newValue))
}

validate your new and old values also, change it to:

if(newValue && oldValue && newValue!=oldValue){
    localStorage.setItem('answers',JSON.stringify(newValue))
}


问:
In Java, what is the order of initialization for those statements after main method
I learned that the principle for order of initialization is:

Superclass first (not discussed here in this case)

Static variable declarations and static initialization blocks in the order of appearance

Instance variable declarations and static initialization blocks in the order of appearance

The constructor

But I'm still confused by the output of this code:

```<code>public class Test1 {

    static {
        add(2);
    }

    static void add (int num) {
        System.out.println(num + " ");
    }

    public Test1() {
        add(5);
        System.out.println("Constructor!");
    }

    static {
        add(4);
    }

    {
        add(6);
    }

    static {
        new Test1();
    }

    {
        add(8);
    }

    public static void main(String[] args) {
        System.out.println("Main method!");
        add(10);
    }

    {
        add(11);
    }
    static {
        add(12);
    }
}
</code>```

The result is:

```<code>2
4
6
8
11
5
Constructor!
12
Main method!
10
</code>```

If without the statements of add(10); add(11); add(12); I can totally understand. Can you please explain the order of initialization for those 3 statements?

答:
I think you confused because (12) before (main method - 10)

That happens because main method called at the last but other initialization order are clear

Body:
I learned that the principle for order of initialization is:

Superclass first (not discussed here in this case)

Static variable declarations and static initialization blocks in the order of appearance

Instance variable declarations and static initialization blocks in the order of appearance

The constructor

But I'm still confused by the output of this code:

public class Test1 {

    static {
        add(2);
    }

    static void add (int num) {
        System.out.println(num + " ");
    }

    public Test1() {
        add(5);
        System.out.println("Constructor!");
    }

    static {
        add(4);
    }

    {
        add(6);
    }

    static {
        new Test1();
    }

    {
        add(8);
    }

    public static void main(String[] args) {
        System.out.println("Main method!");
        add(10);
    }

    {
        add(11);
    }
    static {
        add(12);
    }
}

The result is:

2
4
6
8
11
5
Constructor!
12
Main method!
10

If without the statements of add(10); add(11); add(12); I can totally understand. Can you please explain the order of initialization for those 3 statements?


问:
BluetoothLeScanner could not find callback wrapper
Because of I had problems with Bluetooth on Android Lollipop, I have tried to change the scanner method.

So I have tried to use the new package.
In the previous version, I called startScan(mLeScanCallback) and everything works but now, when I call startScan(mScanCallback) I have the error: "D/BluetoothLeScanner: could not find callback wrapper".

No devices are found and the ListAdapter, I use to show the devices, is empty.

The comment lines are the previous code (and it worked!).
This my code:

```<code>public class Selection extends ListActivity implements ServiceConnection {

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHandler = new Handler();

        // Initializes a Bluetooth adapter through BluetoothManager.
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        getApplicationContext().bindService(new Intent(this, MetaWearBleService.class), this, Context.BIND_AUTO_CREATE);

}

private void scanLeDevice(final boolean enable) {
    final BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

    if (enable) {

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                //mBluetoothAdapter.stopLeScan(mLeScanCallback);
                bluetoothLeScanner.stopScan(mScanCallback);
                setListAdapter(listAdapter);

            }
        }, SCAN_PERIOD);

        //mBluetoothAdapter.startLeScan(mLeScanCallback);
        bluetoothLeScanner.startScan(mScanCallback);

   } else {

        //mBluetoothAdapter.stopLeScan(mLeScanCallback);
        bluetoothLeScanner.stopScan(mScanCallback);
        setListAdapter(listAdapter);

    }

}

private ScanCallback mScanCallback =
        new ScanCallback() {

            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        listAdapter.addDevice(device);

                    }
                });
            }
        };
</code>```

Instead  the ListAdapter extends BaseAdapter and use a ViewHolder. If it necessary, I post it.

So what does it mean "D/BluetoothLeScanner: could not find callback wrapper"? What is it wrong?

Otherwise how I can't resolve the problem of scanning with the Android Lollipop?
In Lollipop I have often errors about BluetoothGatt. I don't know to minized it (or solve it).

Thanks

答: I had the same problem with android m.It was due to lack of permissions.Make sure you go to settings and grant location permission to your app</p>

Body:
Because of I had problems with Bluetooth on Android Lollipop, I have tried to change the scanner method.

So I have tried to use the new package.
In the previous version, I called startScan(mLeScanCallback) and everything works but now, when I call startScan(mScanCallback) I have the error: "D/BluetoothLeScanner: could not find callback wrapper".

No devices are found and the ListAdapter, I use to show the devices, is empty.

The comment lines are the previous code (and it worked!).
This my code:

public class Selection extends ListActivity implements ServiceConnection {

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHandler = new Handler();

        // Initializes a Bluetooth adapter through BluetoothManager.
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        getApplicationContext().bindService(new Intent(this, MetaWearBleService.class), this, Context.BIND_AUTO_CREATE);

}

private void scanLeDevice(final boolean enable) {
    final BluetoothLeScanner bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

    if (enable) {

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                //mBluetoothAdapter.stopLeScan(mLeScanCallback);
                bluetoothLeScanner.stopScan(mScanCallback);
                setListAdapter(listAdapter);

            }
        }, SCAN_PERIOD);

        //mBluetoothAdapter.startLeScan(mLeScanCallback);
        bluetoothLeScanner.startScan(mScanCallback);

   } else {

        //mBluetoothAdapter.stopLeScan(mLeScanCallback);
        bluetoothLeScanner.stopScan(mScanCallback);
        setListAdapter(listAdapter);

    }

}

private ScanCallback mScanCallback =
        new ScanCallback() {

            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        listAdapter.addDevice(device);

                    }
                });
            }
        };

Instead  the ListAdapter extends BaseAdapter and use a ViewHolder. If it necessary, I post it.

So what does it mean "D/BluetoothLeScanner: could not find callback wrapper"? What is it wrong?

Otherwise how I can't resolve the problem of scanning with the Android Lollipop?
In Lollipop I have often errors about BluetoothGatt. I don't know to minized it (or solve it).

Thanks


问:
What is wrong in this Query why i am getting this Error?
```<code> with cte as(
            Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
            Sum(Price) AS Amount
            FROM [sTMS 3].dbo.Orders
            INNER JOIN [sTMS 3].dbo.MenuItems ON [sTMS 3].dbo.Orders.MenuItemId = [sTMS 3].dbo.MenuItems.Id
            INNER JOIN [sTMS 3].dbo.Tickets TCK ON TCK.Id = [sTMS 3].dbo.Orders.TicketId
            INNER JOIN [sTMS 3].dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
            WHERE
            (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
            AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
            Group by MenuItemName
            Order by Amount Desc  UNION ALL
            Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
            Sum(Price) AS Amount
            FROM sTMS10.dbo.Orders
            INNER JOIN sTMS10.dbo.MenuItems ON sTMS10.dbo.Orders.MenuItemId = sTMS10.dbo.MenuItems.Id
            INNER JOIN sTMS10.dbo.Tickets TCK ON TCK.Id = sTMS10.dbo.Orders.TicketId
            INNER JOIN sTMS10.dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
            WHERE
            (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
            AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
            Group by MenuItemName
            Order by Amount Desc)
            Select top 5 Name,Sum(Quantity) AS Quantity,Sum(Amount)/``
            (Select SUM(Amount) FROM (Select top 5 Sum(e.Amount) Amount From cte e Group by e.Name order by e.Amount desc)a) * 100 AS Percentage,Sum(Amount) AS Amount
            ,CONVERT(DATETIME,'Jan  1 2017 12:00AM',101) FromDate
            ,CONVERT(DATETIME,'Mar  3 2017 12:00AM',101) ToDate
            From cte Group by Name order by Amount desc
</code>```

Column "cte.Amount" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

答:
You cannot UNION ALL the TOP statements like that, you can put them in separate Common Table Expressions and then UNION ALL those.

So something like this, though you may need to wrap the UNION ALL in another CTE to be able to do another further TOP 5

```<code>WITH FirstTop5 AS
(
SELECT TOP 5
        MenuItemName AS Name
    ,   SUM(Quantity) AS Quantity
    ,   SUM(Price) AS Amount
    FROM [sTMS 3].dbo.Orders
    INNER JOIN [sTMS 3].dbo.MenuItems
        ON [sTMS 3].dbo.Orders.MenuItemId = [sTMS 3].dbo.MenuItems.id
    INNER JOIN [sTMS 3].dbo.Tickets TCK
        ON TCK.id = [sTMS 3].dbo.Orders.TicketId
    INNER JOIN [sTMS 3].dbo.TicketEntities TEN
        ON TEN.Ticket_Id = TCK.id
    WHERE (MenuItems.GroupCode = 'Rides'
    OR MenuItems.GroupCode = 'Ticket Rides')
    AND Orders.CreatedDateTime BETWEEN CONVERT(DATETIME, 'Jan  1 2017 12:00AM', 101) AND CONVERT(DATETIME, 'Mar  3 2017 12:00AM', 101)
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
    GROUP BY MenuItemName
    ORDER BY Amount DESC
)
, SecondTop5 AS
(
    SELECT TOP 5
        MenuItemName AS Name
    ,   SUM(Quantity) AS Quantity
    ,   SUM(Price) AS Amount
    FROM sTMS10.dbo.Orders
    INNER JOIN sTMS10.dbo.MenuItems
        ON sTMS10.dbo.Orders.MenuItemId = sTMS10.dbo.MenuItems.id
    INNER JOIN sTMS10.dbo.Tickets TCK
        ON TCK.id = sTMS10.dbo.Orders.TicketId
    INNER JOIN sTMS10.dbo.TicketEntities TEN
        ON TEN.Ticket_Id = TCK.id
    WHERE (MenuItems.GroupCode = 'Rides'
    OR MenuItems.GroupCode = 'Ticket Rides')
    AND Orders.CreatedDateTime BETWEEN CONVERT(DATETIME, 'Jan  1 2017 12:00AM', 101) AND CONVERT(DATETIME, 'Mar  3 2017 12:00AM', 101)
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
    GROUP BY MenuItemName
    ORDER BY Amount DESC
)

SELECT * FROM FirstTop5
UNION ALL
SELECT * FROM SecondTop5
</code>```

However it could be better to remove the TOP 5 restriction from your CTE and just do a UNION ALL and then do the TOP 5 in your outer query.

Body:
 with cte as(
            Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
            Sum(Price) AS Amount
            FROM [sTMS 3].dbo.Orders
            INNER JOIN [sTMS 3].dbo.MenuItems ON [sTMS 3].dbo.Orders.MenuItemId = [sTMS 3].dbo.MenuItems.Id
            INNER JOIN [sTMS 3].dbo.Tickets TCK ON TCK.Id = [sTMS 3].dbo.Orders.TicketId
            INNER JOIN [sTMS 3].dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
            WHERE
            (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
            AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
            Group by MenuItemName
            Order by Amount Desc  UNION ALL
            Select Top 5 MenuItemName AS Name, Sum(Quantity) AS Quantity ,
            Sum(Price) AS Amount
            FROM sTMS10.dbo.Orders
            INNER JOIN sTMS10.dbo.MenuItems ON sTMS10.dbo.Orders.MenuItemId = sTMS10.dbo.MenuItems.Id
            INNER JOIN sTMS10.dbo.Tickets TCK ON TCK.Id = sTMS10.dbo.Orders.TicketId
            INNER JOIN sTMS10.dbo.TicketEntities TEN ON TEN.Ticket_Id = TCK.Id
            WHERE
            (MenuItems.GroupCode = 'Rides' OR MenuItems.GroupCode = 'Ticket Rides')
            AND Orders.CreatedDateTime BETWEEN Convert(DATETIME,'Jan  1 2017 12:00AM',101) and Convert(DATETIME,'Mar  3 2017 12:00AM',101)
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
            AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
            Group by MenuItemName
            Order by Amount Desc)
            Select top 5 Name,Sum(Quantity) AS Quantity,Sum(Amount)/``
            (Select SUM(Amount) FROM (Select top 5 Sum(e.Amount) Amount From cte e Group by e.Name order by e.Amount desc)a) * 100 AS Percentage,Sum(Amount) AS Amount
            ,CONVERT(DATETIME,'Jan  1 2017 12:00AM',101) FromDate
            ,CONVERT(DATETIME,'Mar  3 2017 12:00AM',101) ToDate
            From cte Group by Name order by Amount desc

Column "cte.Amount" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

Body:
You cannot UNION ALL the TOP statements like that, you can put them in separate Common Table Expressions and then UNION ALL those.

So something like this, though you may need to wrap the UNION ALL in another CTE to be able to do another further TOP 5

WITH FirstTop5 AS
(
SELECT TOP 5
        MenuItemName AS Name
    ,   SUM(Quantity) AS Quantity
    ,   SUM(Price) AS Amount
    FROM [sTMS 3].dbo.Orders
    INNER JOIN [sTMS 3].dbo.MenuItems
        ON [sTMS 3].dbo.Orders.MenuItemId = [sTMS 3].dbo.MenuItems.id
    INNER JOIN [sTMS 3].dbo.Tickets TCK
        ON TCK.id = [sTMS 3].dbo.Orders.TicketId
    INNER JOIN [sTMS 3].dbo.TicketEntities TEN
        ON TEN.Ticket_Id = TCK.id
    WHERE (MenuItems.GroupCode = 'Rides'
    OR MenuItems.GroupCode = 'Ticket Rides')
    AND Orders.CreatedDateTime BETWEEN CONVERT(DATETIME, 'Jan  1 2017 12:00AM', 101) AND CONVERT(DATETIME, 'Mar  3 2017 12:00AM', 101)
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
    GROUP BY MenuItemName
    ORDER BY Amount DESC
)
, SecondTop5 AS
(
    SELECT TOP 5
        MenuItemName AS Name
    ,   SUM(Quantity) AS Quantity
    ,   SUM(Price) AS Amount
    FROM sTMS10.dbo.Orders
    INNER JOIN sTMS10.dbo.MenuItems
        ON sTMS10.dbo.Orders.MenuItemId = sTMS10.dbo.MenuItems.id
    INNER JOIN sTMS10.dbo.Tickets TCK
        ON TCK.id = sTMS10.dbo.Orders.TicketId
    INNER JOIN sTMS10.dbo.TicketEntities TEN
        ON TEN.Ticket_Id = TCK.id
    WHERE (MenuItems.GroupCode = 'Rides'
    OR MenuItems.GroupCode = 'Ticket Rides')
    AND Orders.CreatedDateTime BETWEEN CONVERT(DATETIME, 'Jan  1 2017 12:00AM', 101) AND CONVERT(DATETIME, 'Mar  3 2017 12:00AM', 101)
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Master Card"}%'
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Technical Card"}%'
    AND TEN.EntityCustomData NOT LIKE '%{"Name":"Card Type","Value":"Guest Card"}%'
    GROUP BY MenuItemName
    ORDER BY Amount DESC
)

SELECT * FROM FirstTop5
UNION ALL
SELECT * FROM SecondTop5

However it could be better to remove the TOP 5 restriction from your CTE and just do a UNION ALL and then do the TOP 5 in your outer query.