问:
c++ bitmask: explanation of a code block
I am new in c++ and i have some difficulties to understand bitmask. If someone could describe in the simplest way how the following code work (http://rosettacode.org/wiki/Combinations#C.2B.2B):

```<code>#include <algorithm>
#include <iostream>
#include <string>

void comb(int N, int K)
{
    std::string bitmask(K, 1); // K leading 1's
    bitmask.resize(N, 0); // N-K trailing 0's

    // print integers and permute bitmask
    do {
        for (int i = 0; i < N; ++i) // [0..N-1] integers
        {
            if (bitmask[i]) std::cout << " " << i;
        }
        std::cout << std::endl;
    } while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}

int main()
{
    comb(5, 3);
}
</code>```

I understand the purpose of this code and what is the output but i don't undertstand the initialization of the string bitmask std::string bitmask(K, 1), and what the resize(N, 0) do.

答:
std::string bitmask(K, 1) creates a string called bitmask, and initialises it with K instances of the char 1 (note, not the char '1').

The bitmask.resize(N, 0) then resizes the string to be of size N, and fills any gaps with the char 0 (again, note not the char '1')

So if 'K' were 2 and N were 5, you'd end up with a string containing the non-printable characters 1 1 0 0 0

There are a few issues with the code as it appears to me - first of all, the constructor and resize should be passed '0' and '1', not 0 and 1. Secondly, it doesn't cater for when N is less than K

Body:
I am new in c++ and i have some difficulties to understand bitmask. If someone could describe in the simplest way how the following code work (http://rosettacode.org/wiki/Combinations#C.2B.2B):

#include <algorithm>
#include <iostream>
#include <string>

void comb(int N, int K)
{
    std::string bitmask(K, 1); // K leading 1's
    bitmask.resize(N, 0); // N-K trailing 0's

    // print integers and permute bitmask
    do {
        for (int i = 0; i < N; ++i) // [0..N-1] integers
        {
            if (bitmask[i]) std::cout << " " << i;
        }
        std::cout << std::endl;
    } while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}

int main()
{
    comb(5, 3);
}

I understand the purpose of this code and what is the output but i don't undertstand the initialization of the string bitmask std::string bitmask(K, 1), and what the resize(N, 0) do.


来源: stackexchange

问:
Yii2 - Getting unknown property: yii\console\Application::user
I am trying to run a console controller from the terminal, but i am getting this errors every time

```<code>Error: Getting unknown property: yii\console\Application::user
</code>```

here is the controller

```<code>class TestController extends \yii\console\Controller {

public function actionIndex() {
    echo 'this is console action';
} }
</code>```

and this is the concole config

```<code>return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
    'log' => [
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
            ],
        ],
    ],
],
'params' => $params];
</code>```

I tried running it using these commands with no luck

```<code>php yii test/index
php yii test
php ./yii test
</code>```

can anyone help please?

答:
As @GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:</p>

```<code>$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run a console controller from the terminal, but i am getting this errors every time

Error: Getting unknown property: yii\console\Application::user

here is the controller

class TestController extends \yii\console\Controller {

public function actionIndex() {
    echo 'this is console action';
} }

and this is the concole config

return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
    'log' => [
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
            ],
        ],
    ],
],
'params' => $params];

I tried running it using these commands with no luck

php yii test/index
php yii test
php ./yii test

can anyone help please?

Body:
As @GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:

$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;


问:
search for exact string value in different json files with exact name
I have a directory structure like the one given below.

```<code>       main folder
      /     |     \
folder1  folder2 folder3 ...
</code>```

and in all of these folders have the same file data21.json

My goal is to search for specific string value (like '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615') in all these .json file and if found in one of them just stop searching, else print false.
I could do this only for one file with this

```<code>    pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
    found = False
    if pipeline_id in open('dir1/data21.json').read():
       found = True
    pprint(found)
</code>```

Just cannot find how to search in all /directory/anydirectory/data21.json

答:
I will elaborate my comment. This code will go through all the items inside your main folder and check what you want.

```<code>pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
#list all the dirs inside the main folder
found = False
main_folder_path = "main_folder" #this will change depending from where you call your script
for dir_name in os.listdir(main_folder_path):
    dir_path = main_folder_path+"/"+dir_name+"/data21.json"
    if pipeline_id in open(dir_path).read():
       found = True
       break
pprint(found)
</code>```

You may also need to check if the dir_name is a directory as you want or a file if you have them mixed inside main_folder.

Body:
I have a directory structure like the one given below.

       main folder
      /     |     \
folder1  folder2 folder3 ...

and in all of these folders have the same file data21.json

My goal is to search for specific string value (like '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615') in all these .json file and if found in one of them just stop searching, else print false.
I could do this only for one file with this

    pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
    found = False
    if pipeline_id in open('dir1/data21.json').read():
       found = True
    pprint(found)

Just cannot find how to search in all /directory/anydirectory/data21.json

Body:
I will elaborate my comment. This code will go through all the items inside your main folder and check what you want.

pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
#list all the dirs inside the main folder
found = False
main_folder_path = "main_folder" #this will change depending from where you call your script
for dir_name in os.listdir(main_folder_path):
    dir_path = main_folder_path+"/"+dir_name+"/data21.json"
    if pipeline_id in open(dir_path).read():
       found = True
       break
pprint(found)

You may also need to check if the dir_name is a directory as you want or a file if you have them mixed inside main_folder.


问:
Get data from a file and convert it to dictionary in unity using c#
i am trying to read from a file and convert it into dictionary in unity using c#.The file contains data like

```<code>1 1 1 acsbd
1 2 1 123ws
</code>```

here i want to make the first 6 characters to the key and rest characters as values.

here is the code i tried(it is mostly from stackoverflow)

```<code>System.IO.StreamReader file = new System.IO.StreamReader (
  @"D:\Programming\Projects\Launch pad\itnol\KeySound");

     while ((line = file.ReadLine()) != null)
     {
         char[] line1 = line.ToCharArray();
         if (line1.Length >= 11)
         {
             line1[5] = ':';
             line = line1.ToString();
             //Console.WriteLine(line);
         }
         var items = line.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
             .Select(s => s.Split(new[] { ':' }));

         Dictionary<string, string> dict = new Dictionary<string, string>();
         foreach (var item in items)
         {
             Debug.Log(item[0]);
             dict.Add(item[0], item[1]);
         }
</code>```

It complies but gives IndexOutOfRangeException exception thrown on run time

Thank you.

答:
Try using Linq:

```<code>using System.IO;
using System.Linq;

...

string fileName = @"D:\Programming\Projects\Launch pad\itnol\KeySound";

...

Dictionary<string, string> dict = File
  .ReadLines(fileName)
  .Where(line => line.Length >= 11)           // If you want to filter out lines
  .ToDictionary(line => line.Substring(0, 6), // Key:   first 6 characters
                line => line.Substring(6));   // Value: rest characters
</code>```

Edit: No Linq, no File version:

```<code>string fileName = @"D:\Programming\Projects\Launch pad\itnol\KeySound";

...

Dictionary<string, string> dict = new Dictionary<string, string>();

// Do not forget to wrap IDisposable into using
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName)) {
  while (true) {
    string line = reader.ReadLine();

    if (null == line)
      break;
    else if (line.Length >= 11)
      dict.Add(line.Substring(0, 6), line.Substring(6));
  }
}
</code>```

Body:
i am trying to read from a file and convert it into dictionary in unity using c#.The file contains data like

1 1 1 acsbd
1 2 1 123ws

here i want to make the first 6 characters to the key and rest characters as values.

here is the code i tried(it is mostly from stackoverflow)

System.IO.StreamReader file = new System.IO.StreamReader (
  @"D:\Programming\Projects\Launch pad\itnol\KeySound");

     while ((line = file.ReadLine()) != null)
     {
         char[] line1 = line.ToCharArray();
         if (line1.Length >= 11)
         {
             line1[5] = ':';
             line = line1.ToString();
             //Console.WriteLine(line);
         }
         var items = line.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
             .Select(s => s.Split(new[] { ':' }));

         Dictionary<string, string> dict = new Dictionary<string, string>();
         foreach (var item in items)
         {
             Debug.Log(item[0]);
             dict.Add(item[0], item[1]);
         }

It complies but gives IndexOutOfRangeException exception thrown on run time

Thank you.

Body:
Try using Linq:

using System.IO;
using System.Linq;

...

string fileName = @"D:\Programming\Projects\Launch pad\itnol\KeySound";

...

Dictionary<string, string> dict = File
  .ReadLines(fileName)
  .Where(line => line.Length >= 11)           // If you want to filter out lines
  .ToDictionary(line => line.Substring(0, 6), // Key:   first 6 characters
                line => line.Substring(6));   // Value: rest characters

Edit: No Linq, no File version:

string fileName = @"D:\Programming\Projects\Launch pad\itnol\KeySound";

...

Dictionary<string, string> dict = new Dictionary<string, string>();

// Do not forget to wrap IDisposable into using
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName)) {
  while (true) {
    string line = reader.ReadLine();

    if (null == line)
      break;
    else if (line.Length >= 11)
      dict.Add(line.Substring(0, 6), line.Substring(6));
  }
}


问:
ASP.NET 4.0 Object Caching
There are two kind of caches that need to be implemented: Global and Session Level.

The session level cache will store certain user specific data like Cart Items, user priviliges etc.

The global cache will store some data common to all the users in a subdomain.

So each subdomain will have a seperate global cache and each user(logged or not) might have a session/user specific cache.

I am thinking of using object caching features provided in 4.0 version of framework using System.Runtime.Caching. Wrapping the basic functionality inside a custom entity.

Another thing that comes to my mind is that the singleton pattern might do the trick, not sure though.

Also to keep in mind that the Website is hosted on a web farm.

Anyone can suggest how to go about this or point me in the right direction on how to implement this?

答: If your site is on a web farm, then you might consider using Memcached. It's a in-memopy key=>value caching. All you have to do is prefix your session-level cached objects with the sessionID.</p>

ContentLicense: CC BY-SA 2.5

Title: ASP.NET 4.0 Object Caching


问:
Pandas calculate average number of words in groupby
Lets say I have a dataframe that looks like this:

```<code>df = pd.DataFrame({'id': [1,1,1,1,2,2,2,3,4,4,4,4,4],
                   'feedback': ['one word', np.nan, np.nan, 'test',
                                'second', np.nan, 'test 2',
                                np.nan,
                                'fourth', 'multiple words', 'test 1 2 3', 'things', np.nan]})

print(df)

    id        feedback
0    1        one word
1    1             NaN
2    1             NaN
3    1            test
4    2          second
5    2             NaN
6    2          test 2
7    3             NaN
8    4          fourth
9    4  multiple words
10   4      test 1 2 3
11   4          things
12   4             NaN
</code>```

I want to calculate some aggregated values:

row count for each id

number of rows where feedback was provided for each id

average number of words of provided feedback for each
id

My desired output is:

```<code>   id  count  complete  avg_words
0   1      4         2        1.5
1   2      3         2        1.5
2   3      1         0        NaN
3   4      5         4        2.0
</code>```

I have the following code which accomplishes all but the final point:

```<code>df.groupby(['id']).agg({'id': 'count',
                        'feedback': ['count', lambda x: len(x)]}).reset_index()
</code>```

Which gives me:

```<code>  id       feedback
     count    count <lambda>
0  1     4        2        4
1  2     3        2        3
2  3     1        0        1
3  4     5        4        5
</code>```

Everything is correct apart from the final column (the indexing is also a bit strange, but thats a minor issue)

The lambda function is a placeholder. How do I calculate the average number of words of only the provided feedback for each id?

答:
Try this:</p>

```<code>In [96]: df.assign(avg_words=df['feedback'].str.split().str.len()) \
    ...:   .groupby('id') \
    ...:   .agg({'id': 'count','feedback': 'count', 'avg_words': 'mean'}) \
    ...:   .rename(columns={'id':'count', 'feedback':'complete'}) \
    ...:   .reset_index()
Out[96]:
   id  count  complete  avg_words
0   1      4         2        1.5
1   2      3         2        1.5
2   3      1         0        NaN
3   4      5         4        2.0
</code>```

Body:
Lets say I have a dataframe that looks like this:

df = pd.DataFrame({'id': [1,1,1,1,2,2,2,3,4,4,4,4,4],
                   'feedback': ['one word', np.nan, np.nan, 'test',
                                'second', np.nan, 'test 2',
                                np.nan,
                                'fourth', 'multiple words', 'test 1 2 3', 'things', np.nan]})

print(df)

    id        feedback
0    1        one word
1    1             NaN
2    1             NaN
3    1            test
4    2          second
5    2             NaN
6    2          test 2
7    3             NaN
8    4          fourth
9    4  multiple words
10   4      test 1 2 3
11   4          things
12   4             NaN

I want to calculate some aggregated values:

row count for each id

number of rows where feedback was provided for each id

average number of words of provided feedback for each
id

My desired output is:

   id  count  complete  avg_words
0   1      4         2        1.5
1   2      3         2        1.5
2   3      1         0        NaN
3   4      5         4        2.0

I have the following code which accomplishes all but the final point:

df.groupby(['id']).agg({'id': 'count',
                        'feedback': ['count', lambda x: len(x)]}).reset_index()

Which gives me:

  id       feedback
     count    count <lambda>
0  1     4        2        4
1  2     3        2        3
2  3     1        0        1
3  4     5        4        5

Everything is correct apart from the final column (the indexing is also a bit strange, but thats a minor issue)

The lambda function is a placeholder. How do I calculate the average number of words of only the provided feedback for each id?

Body:
Try this:

In [96]: df.assign(avg_words=df['feedback'].str.split().str.len()) \
    ...:   .groupby('id') \
    ...:   .agg({'id': 'count','feedback': 'count', 'avg_words': 'mean'}) \
    ...:   .rename(columns={'id':'count', 'feedback':'complete'}) \
    ...:   .reset_index()
Out[96]:
   id  count  complete  avg_words
0   1      4         2        1.5
1   2      3         2        1.5
2   3      1         0        NaN
3   4      5         4        2.0


问:
Badge icon resource/view
Is there a built in badge icon like the info icon so that I can show status updates on other views in my app? It's easy enough to duplicate manually but I'd like to use a built in resource if it's available.</p>

答: I'm sure it's not available for developers since Apple doesn't like to reuse assets for different purposes. Those badges have one definitive and simple purpose -- show the number of updates on the app icon. That's the only purpose they serve.</p>

Title: Badge icon resource/view


问:
<activity> vs. <activity/>. What is the difference?
When looking at most sites (including SO), most of them use:

```<code><activity android:name=".MainActivity" />
</code>```

insted of

```<code> <activity android:name=".Complaints"> </activity>
</code>```

What are the main differences between the two, if any?

Are there valid reasons to use one instead of the other?

Are there valid reasons to use combine them?
Does using  come with compatibility issues, seeing it is not very widely used?

答: First type is short way, else no difference at all but you can this as of if you have additional tags inside activity you will be using second type as you mentioned else it's up to you in which you feel comfortable go for that</p>

Body:
When looking at most sites (including SO), most of them use:

<activity android:name=".MainActivity" />

insted of

 <activity android:name=".Complaints"> </activity>

What are the main differences between the two, if any?

Are there valid reasons to use one instead of the other?

Are there valid reasons to use combine them?
Does using  come with compatibility issues, seeing it is not very widely used?


问:
Visual Studio Community 2017 not showing option for EF Code First on Publish
I'm trying to use publish asp.net Mvc project with EF and Code First but not able to find any option to use the Code First . Link
Am I missing something here in the Publish Profile or any settings missing?
Thanks in advance.

答:
Run Your visual studio as administrator

2.Go to Publish setting

3 Select Published Method "Web Deploy"

Then Flow this link.


问:
Check for newer Docker build for image
I'm running Jenkins from Docker with tag lts. behind this tag was version 2.73.2. Now there is a newer lts version available: 2.73.3. Docker doesn't automatically check for it. I had to do docker pull jenkins/jenkins:lts to get the new version.

But how can check if there is a newer build for a tag?

EDIT:
I want to make clear: This is not a duplicate! I asked how to check for a newer Docker image available. I know how to upgrade (as I said above).

答:
Docker does not check for newer version of remote image. When building, Docker first check to see if the base image is in the local cache. If it find it is uses it, otherwise it tries to pull it from the remote repository.

I order to get latest image, you have to do it manually by running:

```<code>docker pull jenkins/jenkins:lts
</code>```

Alternatively, you can disable the cache when building and always download the latest image by specifying the --no-cache option:

```<code>docker build --no-cache ...
</code>```

ContentLicense: CC BY-SA 4.0

Title: Check for newer Docker build for image

Body:
Docker does not check for newer version of remote image. When building, Docker first check to see if the base image is in the local cache. If it find it is uses it, otherwise it tries to pull it from the remote repository.

I order to get latest image, you have to do it manually by running:

docker pull jenkins/jenkins:lts

Alternatively, you can disable the cache when building and always download the latest image by specifying the --no-cache option:

docker build --no-cache ...


问:
cpputest on STM8 failed due multiple 'main'
I want to use cpputest on STM8 and installed all the required tools for it.
I am able to run cpputest on my simplified code.
on my main file which belongs to the hardware I have of course the main function. But in the Test environment I have a main function under AllTests.cpp as well. When I compile it i get the error:

```<code>multiple definition of `main'
</code>```

A further issue I run into is: I compile the code for a 8bit processor and i use the library <stdint.h>, so my main file has the line uint8_t main(){ . The compiler of cpputest does not like that at all...

Does anyone has an idea how to fix this?

Files:

blinky.h:

```<code>#ifndef BLINKY_H
#define BLINKY_H

#include "stm8l.h"
#include <stdint.h>

uint16_t blink(void);

#endif
</code>```

blinky.c

```<code>#include "blinky.h"

uint16_t blink(){
    PD_DDR = 0x1;
    PD_CR1 = 0x1;
    return 1;
}
uint8_t main() {
    // Configure pins
    while(1){
    // Loop
    blink();
    }
}
</code>```

test.cpp:

```<code>#include "CppUTest/TestHarness.h"

extern "C"
{
#include "blinky.h"
}

TEST_GROUP(FirstTestGroup)
{
    void setup()
    {
    }

    void teardown()
    {
    }
};

TEST(FirstTestGroup, test1)
{
    LONGS_EQUAL(1, blink());
}
</code>```

AllTest.cpp:

```<code>#include "CppUTest/CommandLineTestRunner.h"

int main(int ac, char** av)
{
    return CommandLineTestRunner::RunAllTests(ac, av);
}
</code>```

Makefile:

```<code>#Set this to @ to keep the makefile quiet
SILENCE = @

#---- Outputs ----#
COMPONENT_NAME = blinky

#--- Inputs ----#
PROJECT_HOME_DIR = .
ifeq "$(CPPUTEST_HOME)" ""
    CPPUTEST_HOME = ~/tools/cpputest
endif

# --- SRC_FILES ---
# Use SRC_FILES to specifiy individual production
# code files.
# These files are compiled and put into the
# ProductionCode library and links with the test runner
SRC_FILES = src/blinky.c

# --- SRC_DIRS ---
# Use SRC_DIRS to specifiy production directories
# code files.
# These files are compiled and put into a the
# ProductionCode library and links with the test runner
SRC_DIRS = \
    platform

# --- TEST_SRC_FILES ---
# TEST_SRC_FILES specifies individual test files to build.  Test
# files are always included in the build and they
# pull in production code from the library
TEST_SRC_FILES = \

# --- TEST_SRC_DIRS ---
# Like TEST_SRC_FILES, but biulds everyting in the directory
TEST_SRC_DIRS = \
    tests \
    #tests/blinky \
    #tests/io-cppumock \
    #tests/exploding-fakes \
    #tests \
    #tests/example-fff \
    #tests/fff \
# --- MOCKS_SRC_DIRS ---
# MOCKS_SRC_DIRS specifies a directories where you can put your
# mocks, stubs and fakes.  You can also just put them
# in TEST_SRC_DIRS
MOCKS_SRC_DIRS = \

# Turn on CppUMock
CPPUTEST_USE_EXTENSIONS = Y

INCLUDE_DIRS =\
  .\
  $(CPPUTEST_HOME)/include/ \
  $(CPPUTEST_HOME)/include/Platforms/Gcc \
  platform \
  src \
  include \
  #example-fff \
  #test/exploding-fakes \
  #tests/fff

#STM8DIR

#SDCC_DIR :=$(CPPUTEST_HOME)/../sdcc/
#CC       :=@$(SDCC_DIR)/bin/sdcc
# --- CPPUTEST_OBJS_DIR ---
# if you have to use "../" to get to your source path
# the makefile will put the .o and .d files in surprising
# places.
# To make up for each level of "../", add place holder
# sub directories in CPPUTEST_OBJS_DIR
# each "../".  It is kind of a kludge, but it causes the
# .o and .d files to be put under objs.
# e.g. if you have "../../src", set to "test-objs/1/2"
# This is set no "../" in the source path.
CPPUTEST_OBJS_DIR = test-obj

CPPUTEST_LIB_DIR = test-lib
CPPUTEST_WARNINGFLAGS += -Wall
CPPUTEST_WARNINGFLAGS += -Werror
CPPUTEST_WARNINGFLAGS += -Wswitch-default
CPPUTEST_WARNINGFLAGS += -Wfatal-errors
CPPUTEST_CXXFLAGS = -Wno-c++14-compat
CPPUTEST_CFLAGS = -std=c99
CPPUTEST_CXXFLAGS += $(CPPUTEST_PLATFORM_CXXFLAGS)
CPPUTEST_CFLAGS += -Wno-missing-prototypes
CPPUTEST_CXXFLAGS += -Wno-missing-variable-declarations
# --- LD_LIBRARIES -- Additional needed libraries can be added here.
# commented out example specifies math library
#LD_LIBRARIES += -lm

# Look at $(CPPUTEST_HOME)/build/MakefileWorker.mk for more controls

include $(CPPUTEST_HOME)/build/MakefileWorker.mk
</code>```

答:
As suggested in the commends, there was no other way to create a file with the main loop for only the Controller and separate it from the unit tests.

My structure looks like:
main.c:
- contains the includes from the firmware (app.h) and the main() with the  run_app()
app.c:
contains all the firmware and is tested with cpputest

Body:
I want to use cpputest on STM8 and installed all the required tools for it.
I am able to run cpputest on my simplified code.
on my main file which belongs to the hardware I have of course the main function. But in the Test environment I have a main function under AllTests.cpp as well. When I compile it i get the error:

multiple definition of `main'

A further issue I run into is: I compile the code for a 8bit processor and i use the library <stdint.h>, so my main file has the line uint8_t main(){ . The compiler of cpputest does not like that at all...

Does anyone has an idea how to fix this?

Files:

blinky.h:

#ifndef BLINKY_H
#define BLINKY_H

#include "stm8l.h"
#include <stdint.h>

uint16_t blink(void);

#endif

blinky.c

#include "blinky.h"

uint16_t blink(){
    PD_DDR = 0x1;
    PD_CR1 = 0x1;
    return 1;
}
uint8_t main() {
    // Configure pins
    while(1){
    // Loop
    blink();
    }
}

test.cpp:

#include "CppUTest/TestHarness.h"

extern "C"
{
#include "blinky.h"
}

TEST_GROUP(FirstTestGroup)
{
    void setup()
    {
    }

    void teardown()
    {
    }
};

TEST(FirstTestGroup, test1)
{
    LONGS_EQUAL(1, blink());
}

AllTest.cpp:

#include "CppUTest/CommandLineTestRunner.h"

int main(int ac, char** av)
{
    return CommandLineTestRunner::RunAllTests(ac, av);
}

Makefile:

#Set this to @ to keep the makefile quiet
SILENCE = @

#---- Outputs ----#
COMPONENT_NAME = blinky

#--- Inputs ----#
PROJECT_HOME_DIR = .
ifeq "$(CPPUTEST_HOME)" ""
    CPPUTEST_HOME = ~/tools/cpputest
endif

# --- SRC_FILES ---
# Use SRC_FILES to specifiy individual production
# code files.
# These files are compiled and put into the
# ProductionCode library and links with the test runner
SRC_FILES = src/blinky.c

# --- SRC_DIRS ---
# Use SRC_DIRS to specifiy production directories
# code files.
# These files are compiled and put into a the
# ProductionCode library and links with the test runner
SRC_DIRS = \
    platform

# --- TEST_SRC_FILES ---
# TEST_SRC_FILES specifies individual test files to build.  Test
# files are always included in the build and they
# pull in production code from the library
TEST_SRC_FILES = \

# --- TEST_SRC_DIRS ---
# Like TEST_SRC_FILES, but biulds everyting in the directory
TEST_SRC_DIRS = \
    tests \
    #tests/blinky \
    #tests/io-cppumock \
    #tests/exploding-fakes \
    #tests \
    #tests/example-fff \
    #tests/fff \
# --- MOCKS_SRC_DIRS ---
# MOCKS_SRC_DIRS specifies a directories where you can put your
# mocks, stubs and fakes.  You can also just put them
# in TEST_SRC_DIRS
MOCKS_SRC_DIRS = \

# Turn on CppUMock
CPPUTEST_USE_EXTENSIONS = Y

INCLUDE_DIRS =\
  .\
  $(CPPUTEST_HOME)/include/ \
  $(CPPUTEST_HOME)/include/Platforms/Gcc \
  platform \
  src \
  include \
  #example-fff \
  #test/exploding-fakes \
  #tests/fff

#STM8DIR

#SDCC_DIR :=$(CPPUTEST_HOME)/../sdcc/
#CC       :=@$(SDCC_DIR)/bin/sdcc
# --- CPPUTEST_OBJS_DIR ---
# if you have to use "../" to get to your source path
# the makefile will put the .o and .d files in surprising
# places.
# To make up for each level of "../", add place holder
# sub directories in CPPUTEST_OBJS_DIR
# each "../".  It is kind of a kludge, but it causes the
# .o and .d files to be put under objs.
# e.g. if you have "../../src", set to "test-objs/1/2"
# This is set no "../" in the source path.
CPPUTEST_OBJS_DIR = test-obj

CPPUTEST_LIB_DIR = test-lib
CPPUTEST_WARNINGFLAGS += -Wall
CPPUTEST_WARNINGFLAGS += -Werror
CPPUTEST_WARNINGFLAGS += -Wswitch-default
CPPUTEST_WARNINGFLAGS += -Wfatal-errors
CPPUTEST_CXXFLAGS = -Wno-c++14-compat
CPPUTEST_CFLAGS = -std=c99
CPPUTEST_CXXFLAGS += $(CPPUTEST_PLATFORM_CXXFLAGS)
CPPUTEST_CFLAGS += -Wno-missing-prototypes
CPPUTEST_CXXFLAGS += -Wno-missing-variable-declarations
# --- LD_LIBRARIES -- Additional needed libraries can be added here.
# commented out example specifies math library
#LD_LIBRARIES += -lm

# Look at $(CPPUTEST_HOME)/build/MakefileWorker.mk for more controls

include $(CPPUTEST_HOME)/build/MakefileWorker.mk


问:
C# int does not contain a definition for Clone
I have a Dictionary that I need to copy, since it is not possible to change a Dictionary in a foreach loop. (Will lead to the error "Collection was modified; enumeration operation may not execute")
After I learned

```<code>dictTemp.Add(dict);
</code>```

will just reference one Dictionary to another. I tried to copy it

```<code>foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dict.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value);
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}
</code>```

But I sill got the error and so I think the Add of the Key and the Value is just a reference. I looked about the problem and found a solution by deep copy with Clone (.Net 2.0). https://stackoverflow.com/a/139841/3772108

```<code>foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dict.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value.Clone());
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}
</code>```

But it is not possible in .Net 4.5 because of the message "'int' does not contain a definition for Clone and no extension method Clone accepting a first argument of type 'int' could be found"

Now is my question in the year 2017, how is it possible to COPY a dictionary completely. (Not referencing it) Or is there a smarter/better way?

答:
First, you try to clone an int not the dictionary. You don't need to clone value types, just assign them to the variable and you get a "clone".

Your foreach-loop has also a bug, you check if !dict.ContainsKey instead of !dictTemp.ContainsKey:

```<code>foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dictTemp.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value);
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}
</code>```

Finally, you can use the constructor to get a "clone":

```<code>var dictTemp = new Dictionary<string, int>(dict);
</code>```

Body:
I have a Dictionary that I need to copy, since it is not possible to change a Dictionary in a foreach loop. (Will lead to the error "Collection was modified; enumeration operation may not execute")
After I learned

dictTemp.Add(dict);

will just reference one Dictionary to another. I tried to copy it

foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dict.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value);
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}

But I sill got the error and so I think the Add of the Key and the Value is just a reference. I looked about the problem and found a solution by deep copy with Clone (.Net 2.0). https://stackoverflow.com/a/139841/3772108

foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dict.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value.Clone());
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}

But it is not possible in .Net 4.5 because of the message "'int' does not contain a definition for Clone and no extension method Clone accepting a first argument of type 'int' could be found"

Now is my question in the year 2017, how is it possible to COPY a dictionary completely. (Not referencing it) Or is there a smarter/better way?

Body:
First, you try to clone an int not the dictionary. You don't need to clone value types, just assign them to the variable and you get a "clone".

Your foreach-loop has also a bug, you check if !dict.ContainsKey instead of !dictTemp.ContainsKey:

foreach (KeyValuePair<string, int> entry in dict)
{
    if (!dictTemp.ContainsKey(entry.Key))
    {
        dictTemp.Add(entry.Key, entry.Value);
    }
    else
    {
        dictTemp[entry.Key] = entry.Value;
    }
}

Finally, you can use the constructor to get a "clone":

var dictTemp = new Dictionary<string, int>(dict);


问:
Template inheritance with Node.js, Handlebars and Express
I'm just getting started with Node.js, so I'm building very simple applications in order to practice the basics. I was trying to get some Django-like template inheritance working, but I'm at a bit of a loss on how to do it.

I understand that the library "express-handlebars" includes the concept of layouts, and I thought that might be the best way to go about it, but at first glance I don't know if it allows more than one step of inheritance, or using it for replacing different blocks (I saw one general layout where the other templates are inserted in place of the {{{body}}} tag, although there may very well be more tricks to it).

So, my question: how would one implement a multi-layered template inheritance (also, with children inserting content into different separate blocks, instead of a single one)? I'm using Node.js, Express and handlebars, but if it's not possible with the latter two I don't mind trying out other frameworks or templating languages.

Thanks!

Edit:

A pseudo-coded example of what I mean:

First, we could have a common outer template:

```<code><html>
    <head></head>
    <body>
        <h1> Main Title </h1>
        <h2> {{section name block}} </h2>
        <h3> {{subsection name block}} </h3>
        {{content block}}
    </body>
</html>
</code>```

then another one under it (middle template), substituting some of the outer one's blocks (and potentially adding other ones):

```<code>{{inheriting from outer template}}
{{section name block}} Section Three {{/block}}
</code>```

and finally an inner one, which would be the one to call from the javascript code:

```<code>{{inheriting from middle template}}
{{subsection name block}} Subsection Two {{/block}}
{{content block}}
    <p>This is the content of Section Three, Subsection Two.</p>
{{/block}}
</code>```

The result when processing the inner template would be:

```<code><html>
    <head></head>
    <body>
        <h1> Main Title </h1>
        <h2> Section Three </h2>
        <h3> Subsection Two </h3>
        <p>This is the content of Section Three, Subsection Two.</p>
    </body>
</html>
</code>```

答:
Anyone landing on this question may want to know about this : Swig is no longer supported as their github says

That said, Nunjucks looks like the only alternative out there for extensible templating in Javascript. The syntax is very similar to the one of Twig (PHP)

I hope this helps

Body:
I'm just getting started with Node.js, so I'm building very simple applications in order to practice the basics. I was trying to get some Django-like template inheritance working, but I'm at a bit of a loss on how to do it.

I understand that the library "express-handlebars" includes the concept of layouts, and I thought that might be the best way to go about it, but at first glance I don't know if it allows more than one step of inheritance, or using it for replacing different blocks (I saw one general layout where the other templates are inserted in place of the {{{body}}} tag, although there may very well be more tricks to it).

So, my question: how would one implement a multi-layered template inheritance (also, with children inserting content into different separate blocks, instead of a single one)? I'm using Node.js, Express and handlebars, but if it's not possible with the latter two I don't mind trying out other frameworks or templating languages.

Thanks!

Edit:

A pseudo-coded example of what I mean:

First, we could have a common outer template:

 Main Title

 {{section name block}}

 {{subsection name block}}

        {{content block}}

then another one under it (middle template), substituting some of the outer one's blocks (and potentially adding other ones):

{{inheriting from outer template}}
{{section name block}} Section Three {{/block}}

and finally an inner one, which would be the one to call from the javascript code:

{{inheriting from middle template}}
{{subsection name block}} Subsection Two {{/block}}
{{content block}}

This is the content of Section Three, Subsection Two.

{{/block}}

The result when processing the inner template would be:

 Main Title

 Section Three

 Subsection Two

This is the content of Section Three, Subsection Two.


问:
email validation using regular expression
i am using this regular expression for email validation but it is not allowing hyphen (-):

```<code>/^\w+([\.-_]?\w+)*@\w+([\.-_]?\w+)*(\.\w{2,4})+$/
</code>```

please any one tell me how can i do this?

答:
There is a function in PHP for this filter_var, would try to avoid using RegEx as much as posible. They are powerful but can get pretty hairy.</p>

```<code>filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)
</code>```

Body:
i am using this regular expression for email validation but it is not allowing hyphen (-):

/^\w+([\.-_]?\w+)*@\w+([\.-_]?\w+)*(\.\w{2,4})+$/

please any one tell me how can i do this?

Body:
There is a function in PHP for this filter_var, would try to avoid using RegEx as much as posible. They are powerful but can get pretty hairy.

filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)


问:
Center UIView vertically without relating it to its superview centerY
I have a UIView in a portrait-only app. The view is centered vertically and horizontally with AutoLayout ("manually" using storyboards).

From the XCode IDE, is there any way to express the SAME vertical relation using the Top instead of the Superview.centerY? Can I perfectly center my view vertically another way?

This is the current situation:

答: If you want to express the SAME vertical relation using the Top instead of the Superview.centerY, change multiplier to 0.5


问:
Olingo: EntityContainer and EntitySets differences
I'm reading this documentation in order to figure out how to create an odata service.

I don't quite figure out what are EntityContainer and EntitySet for...

[EDIT]

I'd like to ask for a misunderstanding I don't quite figure out yet. If a EntitySet straightforwardly is a set of entities:

Why do I need to implement a EntitySet CsdlAbstractEdmProvider.getEntitySet() method on my OData provider? As you can see on here I need to implement this method that returns an EntitySet. This is the implementation on Olingo documentation:

```<code>public CsdlEntitySet getEntitySet(FullQualifiedName entityContainer, String entitySetName) {

  if(entityContainer.equals(CONTAINER)){
    if(entitySetName.equals(ES_PRODUCTS_NAME)){
      CsdlEntitySet entitySet = new CsdlEntitySet();
      entitySet.setName(ES_PRODUCTS_NAME);
      entitySet.setType(ET_PRODUCT_FQN);

      return entitySet;
    }
  }

  return null;
}
</code>```

I don't quite figure out what's this implementation for.

By other hand, on EntityCollectionProcessor documentation implementation you can see they are using EntitySet as well.

I don't understand which are the differences between both EntitySet inside a Provider and inside Processor.

I don't know if I've explained so well

答:
Based on the OData documentation, section 4.1:

The central concepts in the EDM are entities and associations. Entities are instances of Entity Types (for example, Customer, Employee, and so on) which are structured records consisting of named and typed properties and with a key. Complex Types are structured types also consisting of a list of properties but with no key, and thus can only exist as a property of a containing entity or as a temporary value. An Entity Key is formed from a subset of properties of the Entity Type. The Entity Key (for example, CustomerId or OrderId) is a fundamental concept for uniquely identifying instances of Entity Types and allowing Entity Type instances to participate in relationships. Entities are grouped in Entity Sets (for example, Customers is a set of Customer Entity Type instances).

Associations define the relationship between two or more Entity Types (for example, Employee WorksFor Department). Instances of associations are grouped in Association Sets. Navigation Properties are special properties on Entity Types which are bound to a specific association and can be used to refer to associations of an entity.

Finally, all instance containers (Entity Sets and Association Sets) are grouped in an Entity Container.

Summary:

An EntitySet is a set of Entity. Typically, an EntitySet is a business object; to use a relational database comparison, think of an EntitySet as a table and an Entity as a row in that table.

An EntityContainer is exactly that, a container for EntitySets and Associations. Roughly, you can think of it as a database which contains your tables, views, etc.

Hope this helps.

EDIT, following your question change:

The difference between the Provider.getEntitySet() method and the Processor.getEntitySet() comes down to differences in the purpose of the Provider and the Processor classes.

The Provider class defines the structure and metadata of your OData service. The getEntitySet method defines the structure (name and type) of each entity set.

The Processor class is the servlet for your OData service, essentially. Here, HTTP requests are parsed, processed and redirected (to your service or DAO layer). The getEntitySet method, in the processor, is used to process requests of this structure: (host and port)/(service root.svc)/(MyEntitySet), for example: http://services.odata.org/V3/Northwind/Northwind.svc/Customers. In this method, determine which entity set has been asked for, then call your DAO to fetch your data accordingly.

Body:
I'm reading this documentation in order to figure out how to create an odata service.

I don't quite figure out what are EntityContainer and EntitySet for...

[EDIT]

I'd like to ask for a misunderstanding I don't quite figure out yet. If a EntitySet straightforwardly is a set of entities:

Why do I need to implement a EntitySet CsdlAbstractEdmProvider.getEntitySet() method on my OData provider? As you can see on here I need to implement this method that returns an EntitySet. This is the implementation on Olingo documentation:

public CsdlEntitySet getEntitySet(FullQualifiedName entityContainer, String entitySetName) {

  if(entityContainer.equals(CONTAINER)){
    if(entitySetName.equals(ES_PRODUCTS_NAME)){
      CsdlEntitySet entitySet = new CsdlEntitySet();
      entitySet.setName(ES_PRODUCTS_NAME);
      entitySet.setType(ET_PRODUCT_FQN);

      return entitySet;
    }
  }

  return null;
}

I don't quite figure out what's this implementation for.

By other hand, on EntityCollectionProcessor documentation implementation you can see they are using EntitySet as well.

I don't understand which are the differences between both EntitySet inside a Provider and inside Processor.

I don't know if I've explained so well


问:
Bubble chart (relations between bubbles)
Please can you tell me, is it possible to create relations between bubbles (lines from one bubble to other(s))?

```<code>Example:
SE->FL->NL
FL->DE
SE->BE->DE
DE->NL
</code>```

Demo:
http://jsfiddle.net/2pLog7fw/

答:
Sure, it can be done. One way of creating lines is to set lineWidth to be higher than zero for bubble series.

Live demo: http://jsfiddle.net/kkulig/2d7u7orx/

But this only creates one relation within a series (from the first point to the last one).

The solution here is to create a new scatter series for every relation:

```<code>  {
    data: [
      [80.3, 86.1],
      [80.8, 91.5],
      [80.4, 102.5]
    ], // SE -> FI -> NL
    type: 'scatter'
  },  {
    data: [
      [86.5, 102.9],
      [80.4, 102.5]
    ], // DE -> NL
    type: 'scatter'
  }
</code>```

Configuration for all scatter series (plotOptions):

```<code>scatter: {
  lineWidth: 1, // show the line
  marker: {
    radius: 0
  }
}
</code>```

Live demo: http://jsfiddle.net/kkulig/x8r6uj5q/

If you want an arrow that shows the direction of the relation you can use the code from this demo: http://jsfiddle.net/kkulig/mLsbzgnp/

Body:
Please can you tell me, is it possible to create relations between bubbles (lines from one bubble to other(s))?

Example:
SE->FL->NL
FL->DE
SE->BE->DE
DE->NL

Demo:
http://jsfiddle.net/2pLog7fw/

Body:
Sure, it can be done. One way of creating lines is to set lineWidth to be higher than zero for bubble series.

Live demo: http://jsfiddle.net/kkulig/2d7u7orx/

But this only creates one relation within a series (from the first point to the last one).

The solution here is to create a new scatter series for every relation:

  {
    data: [
      [80.3, 86.1],
      [80.8, 91.5],
      [80.4, 102.5]
    ], // SE -> FI -> NL
    type: 'scatter'
  },  {
    data: [
      [86.5, 102.9],
      [80.4, 102.5]
    ], // DE -> NL
    type: 'scatter'
  }

Configuration for all scatter series (plotOptions):

scatter: {
  lineWidth: 1, // show the line
  marker: {
    radius: 0
  }
}

Live demo: http://jsfiddle.net/kkulig/x8r6uj5q/

If you want an arrow that shows the direction of the relation you can use the code from this demo: http://jsfiddle.net/kkulig/mLsbzgnp/


问:
Publish/Target npm package for different node versions
I have written a node module using ES7 features. I've also created a build script which transpiles to ES5.

Is there a way to publish the module, so that a node 8/9 user uses the original code and older node versions use the transpiled code?

The reason why I want this, is because I expect a better performance on the none transpiled code.

答:
As far as I understand, the perfomance differnce between the transpiled code and ES7 code is negligible. </p>

<p>So it suffices to just publish the transpiled code. </p>

Body:
As far as I understand, the perfomance differnce between the transpiled code and ES7 code is negligible.

So it suffices to just publish the transpiled code.


问:
Get all visible rows using Bootstrap Table
Bootstrap Table has a method to get all hidden rows:

getRowsHidden;    boolean;  Get all rows hidden and if you pass the show
parameter true the rows will be shown again, otherwise, the method
only will return the rows hidden.

It also has

getHiddenColumns  -   Get hidden columns.

getVisibleColumns -   Get visible columns

But how can I get all visible rows, using a combo of BT methods, or JQuery?

答:
Not sure if you still need this, but I managed to get all the data from both visible and hidden columns. The trick here is to set your hidden columns after the data has been loaded.

```<code>$("#TestTable").bootstrapTable({
    data: testData
}).bootstrapTable("hideColumn", "HiddenVals");
</code>```

Then you can call your $("#TestTable").bootstrapTable("getData");

Here's a sample of this: https://jsfiddle.net/Musikero31/ebqsyqsr/

Body:
Not sure if you still need this, but I managed to get all the data from both visible and hidden columns. The trick here is to set your hidden columns after the data has been loaded.

$("#TestTable").bootstrapTable({
    data: testData
}).bootstrapTable("hideColumn", "HiddenVals");

Then you can call your $("#TestTable").bootstrapTable("getData");

Here's a sample of this: https://jsfiddle.net/Musikero31/ebqsyqsr/


问:
jQuery click hide all modal
I have a few buttons that open modals by click and close them by the second click on the very same button. I need to achieve a behaviour when I can click on that button OR anywhere outside of the modal window and that windows will close.
Also, if I click another button, if any modal is open, it should close and new modal should appear instead.

This is what I have so far (I need to keep those functions separated due to there will be additional logic for each of them):

```<code><div class="container">
  <div class="box red"></div>
  <div class="box green"></div>
  <div class="box blue"></div>
  <div class="modal red"></div>
  <div class="modal green"></div>
  <div class="modal blue"></div>
</div>

<script>
// red
function redBoxShow() {
    $('.modal.red').animate({opacity: 1, top: '40'}, 400);
    $(this).one("click", redBoxHide);
}
function redBoxHide() {
    $('.modal.red').animate({opacity: 0, top: '-200px'}, 400);
    $(this).one("click", redBoxShow);
}
// green
function greenBoxShow() {
  $('.modal.green').animate({opacity: 1, top: '40'}, 400);
  $(this).one("click", greenBoxHide);
}
function greenBoxHide() {
  $('.modal.green').animate({opacity: 0, top: '-200px'}, 400);
  $(this).one("click", greenBoxShow);
}
// blue
function blueBoxShow() {
  $('.modal.blue').animate({opacity: 1, top: '40'}, 400);
  $(this).one("click", blueBoxHide);
}
function blueBoxHide() {
  $('.modal.blue').animate({opacity: 0, top: '-200px'}, 400);
  $(this).one("click", blueBoxShow);
}
$(".box.red").one("click", redBoxShow);
$(".box.green").one("click", greenBoxShow);
$(".box.blue").one("click", blueBoxShow);
</script>
</code>```

https://jsfiddle.net/8wfgbpau/9/

答:
All your requirements have been met.

$(window).click(function() {
hideAllActiveBoxes();
});

// red
function hideAllActiveBoxes() {
    $('.modal').each(function(e){
       if($('.modal').css('opacity',1)) $('.modal').css('opacity',0)
    })
}

function redBoxShow() {
  $('.modal.red').animate({opacity: 1, top: '40'}, 400);
}
function redBoxHide() {
  $('.modal.red').animate({opacity: 0, top: '-200px'}, 400);
}
// green
function greenBoxShow() {
  $('.modal.green').animate({opacity: 1, top: '40'}, 400);
}
function greenBoxHide() {
  $('.modal.green').animate({opacity: 0, top: '-200px'}, 400);
}
// blue
function blueBoxShow() {
  $('.modal.blue').animate({opacity: 1, top: '40'}, 400);
}
function blueBoxHide() {
  $('.modal.blue').animate({opacity: 0, top: '-200px'}, 400);
}
$(".box.red").on("click", function(){
   hideAllActiveBoxes();
   redBoxShow();
 });

 $(".box.green").on("click", function(){
   hideAllActiveBoxes();
   greenBoxShow();
 });

 $(".box.blue").on("click", function(){
   hideAllActiveBoxes();
   blueBoxShow();
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 300px;
  text-align: center;
  position: relative;
}
.red{background:red;}
.green{background:green;}
.blue{background:blue;}
.modal {
  position: absolute;
  opacity: 0;
  top: -200px;
}
.box {
  width: 30px;
  height: 30px;
  display: inline-block;
  margin-left: 10px;
}
.box:hover {
  cursor:pointer;
  opacity:0.8;
}
.modal {
  width: 150px;
  height: 150px;
}
.modal.red {
  left: 0;
}
.modal.green {
  left: calc(50% - 75px);
}
.modal.blue {
  right: 0;
}</code>```

```

Title: jQuery click hide all modal

Body:
I have a few buttons that open modals by click and close them by the second click on the very same button. I need to achieve a behaviour when I can click on that button OR anywhere outside of the modal window and that windows will close.
Also, if I click another button, if any modal is open, it should close and new modal should appear instead.

This is what I have so far (I need to keep those functions separated due to there will be additional logic for each of them):

https://jsfiddle.net/8wfgbpau/9/

Body:
All your requirements have been met.

$(window).click(function() {
hideAllActiveBoxes();
});

// red
function hideAllActiveBoxes() {
    $('.modal').each(function(e){
       if($('.modal').css('opacity',1)) $('.modal').css('opacity',0)
    })
}

function redBoxShow() {
  $('.modal.red').animate({opacity: 1, top: '40'}, 400);
}
function redBoxHide() {
  $('.modal.red').animate({opacity: 0, top: '-200px'}, 400);
}
// green
function greenBoxShow() {
  $('.modal.green').animate({opacity: 1, top: '40'}, 400);
}
function greenBoxHide() {
  $('.modal.green').animate({opacity: 0, top: '-200px'}, 400);
}
// blue
function blueBoxShow() {
  $('.modal.blue').animate({opacity: 1, top: '40'}, 400);
}
function blueBoxHide() {
  $('.modal.blue').animate({opacity: 0, top: '-200px'}, 400);
}
$(".box.red").on("click", function(){
   hideAllActiveBoxes();
   redBoxShow();
 });

 $(".box.green").on("click", function(){
   hideAllActiveBoxes();
   greenBoxShow();
 });

 $(".box.blue").on("click", function(){
   hideAllActiveBoxes();
   blueBoxShow();
 });

.container {
  width: 300px;
  text-align: center;
  position: relative;
}
.red{background:red;}
.green{background:green;}
.blue{background:blue;}
.modal {
  position: absolute;
  opacity: 0;
  top: -200px;
}
.box {
  width: 30px;
  height: 30px;
  display: inline-block;
  margin-left: 10px;
}
.box:hover {
  cursor:pointer;
  opacity:0.8;
}
.modal {
  width: 150px;
  height: 150px;
}
.modal.red {
  left: 0;
}
.modal.green {
  left: calc(50% - 75px);
}
.modal.blue {
  right: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="container">
  <div class="box red"></div>
  <div class="box green"></div>
  <div class="box blue"></div>
  <div class="modal red"></div>
  <div class="modal green"></div>
  <div class="modal blue"></div>
</div>


问:
SELECT QUERY LIKE containing only specific words in a string
I have one table like below ,table name is js_skills_achievements

```<code>id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery
</code>```

When admin search key is "java developer in nersupalli"

my query is below

```<code>SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java developer in nersupalli%'
   OR `skill2`  LIKE '%java developer in nersupalli%'
   OR `skill3`  LIKE '%java developer in nersupalli%'
   OR `skill4`  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10
</code>```

Its not working for me . My Requirement is i need to display all java records . here total 2 records in java . i.e id1,id2. But am getting empty rows.

Below ways only working

```<code>SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java%'
   OR `skill2`  LIKE '%java%'
   OR `skill3`  LIKE '%java%'
   OR `skill4`  LIKE '%java%'
ORDER BY id DESC
LIMIT 10
</code>```

I need based on string specified keyword search . can you any one please help on this . Am very appreciate. Thanks

答:
You can explode the search string on a space

```<code>$words = explode ( ' ' , $string);
</code>```

Than search all the words in skill1. All the words in skill2 etc.

Body:
I have one table like below ,table name is js_skills_achievements

id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery

When admin search key is "java developer in nersupalli"

my query is below

SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java developer in nersupalli%'
   OR `skill2`  LIKE '%java developer in nersupalli%'
   OR `skill3`  LIKE '%java developer in nersupalli%'
   OR `skill4`  LIKE '%java developer in nersupalli%'
ORDER BY id DESC
LIMIT 10

Its not working for me . My Requirement is i need to display all java records . here total 2 records in java . i.e id1,id2. But am getting empty rows.

Below ways only working

SELECT *
FROM `js_skills_achievements`
WHERE `skill1`  LIKE '%java%'
   OR `skill2`  LIKE '%java%'
   OR `skill3`  LIKE '%java%'
   OR `skill4`  LIKE '%java%'
ORDER BY id DESC
LIMIT 10

I need based on string specified keyword search . can you any one please help on this . Am very appreciate. Thanks

Body:
You can explode the search string on a space

$words = explode ( ' ' , $string);

Than search all the words in skill1. All the words in skill2 etc.


问:
MS ACCESS VBA, working days function incl. holiday when faling on weekend
When deploying MSDN function for calculating working days, beside a problem with date formatting I found an issue with Holiday count.

Calculation is correct, but only if Holiday is on working day. If it is on a saturday or sunday, it also substract it and produce a false result.
illustration of a false reading

A Function for Workdays:

```<code>Public Function Workdays(ByRef startDate As Date, ByRef endDate As Date, Optional ByRef strHolidays As String = "Holidays") As Integer
On Error GoTo Workdays_Error
Dim nWeekdays, nHolidays As Integer
Dim strWhere As String

startDate = DateValue(startDate)
endDate = DateValue(endDate)
nWeekdays = Weekdays(startDate, endDate)

If nWeekdays = -1 Then
    Workdays = -1
    GoTo Workdays_Exit
End If

strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays

Workdays_Exit:
    Exit Function
    Resume Workdays_Exit

End Function
</code>```

And here is a function for calculating weekdays:

```<code>Public Function Weekdays(ByRef startDate As Date, ByRef endDate As Date) As Integer
' Returns the number of weekdays in the period from startDate
' to endDate inclusive. Returns -1 if an error occurs.

On Error GoTo Weekdays_Error
Const ncNumberOfWeekendDays As Integer = 2 'The number of weekend days per week.
Dim varDays As Variant                  'The number of days inclusive.
Dim varWeekendDays As Variant     'The number of weekend days.
Dim dtmX As Date                          'Temporary storage for datetime.

' If the end date is earlier, swap the dates.
If endDate < startDate Then
    dtmX = startDate
    startDate = endDate
    endDate = dtmX
End If

' Calculate the number of days inclusive (+ 1 is to add back startDate).
varDays = DateDiff(Interval:="d", date1:=startDate, date2:=endDate) + 1

' Calculate the number of weekend days.
varWeekendDays = (DateDiff(Interval:="ww", date1:=startDate, date2:=endDate) _
    * ncNumberOfWeekendDays) + IIf(DatePart(Interval:="w", _
    Date:=startDate) = vbSunday, 1, 0) + IIf(DatePart(Interval:="w", Date:=endDate) = vbSaturday, 1, 0)

' Calculate the number of weekdays.
Weekdays = (varDays - varWeekendDays)

Weekdays_Exit:
    Exit Function

Weekdays_Error:
    Weekdays = -1
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Weekdays"
    Resume Weekdays_Exit
</code>```

Please advise how to ignore holiday if holiday = 1 or holiday = 7.
Plus, in extended period of time, there could be more than one holidays, falling or not on weekend.

答: without delving into your code, I'd suggest doing a count of holidays in your holiday table that fall on weekends and which also fall inside the range of days you are considering. Subtract that total from an (I presume) otherwise correctly calculated total and you should have the proper adjustment taking weekend holidays into account.</p>

Body:
When deploying MSDN function for calculating working days, beside a problem with date formatting I found an issue with Holiday count.

Calculation is correct, but only if Holiday is on working day. If it is on a saturday or sunday, it also substract it and produce a false result.
illustration of a false reading

A Function for Workdays:

Public Function Workdays(ByRef startDate As Date, ByRef endDate As Date, Optional ByRef strHolidays As String = "Holidays") As Integer
On Error GoTo Workdays_Error
Dim nWeekdays, nHolidays As Integer
Dim strWhere As String

startDate = DateValue(startDate)
endDate = DateValue(endDate)
nWeekdays = Weekdays(startDate, endDate)

If nWeekdays = -1 Then
    Workdays = -1
    GoTo Workdays_Exit
End If

strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays

Workdays_Exit:
    Exit Function
    Resume Workdays_Exit

End Function

And here is a function for calculating weekdays:

Public Function Weekdays(ByRef startDate As Date, ByRef endDate As Date) As Integer
' Returns the number of weekdays in the period from startDate
' to endDate inclusive. Returns -1 if an error occurs.

On Error GoTo Weekdays_Error
Const ncNumberOfWeekendDays As Integer = 2 'The number of weekend days per week.
Dim varDays As Variant                  'The number of days inclusive.
Dim varWeekendDays As Variant     'The number of weekend days.
Dim dtmX As Date                          'Temporary storage for datetime.

' If the end date is earlier, swap the dates.
If endDate < startDate Then
    dtmX = startDate
    startDate = endDate
    endDate = dtmX
End If

' Calculate the number of days inclusive (+ 1 is to add back startDate).
varDays = DateDiff(Interval:="d", date1:=startDate, date2:=endDate) + 1

' Calculate the number of weekend days.
varWeekendDays = (DateDiff(Interval:="ww", date1:=startDate, date2:=endDate) _
    * ncNumberOfWeekendDays) + IIf(DatePart(Interval:="w", _
    Date:=startDate) = vbSunday, 1, 0) + IIf(DatePart(Interval:="w", Date:=endDate) = vbSaturday, 1, 0)

' Calculate the number of weekdays.
Weekdays = (varDays - varWeekendDays)

Weekdays_Exit:
    Exit Function

Weekdays_Error:
    Weekdays = -1
    MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Weekdays"
    Resume Weekdays_Exit

Please advise how to ignore holiday if holiday = 1 or holiday = 7.
Plus, in extended period of time, there could be more than one holidays, falling or not on weekend.


问:
Symfony Automatism in URL reWrite
The name of my web site is "vg"
The dev url is : "http://localhost/vg/web/app_dev.php/"
The prefix definition set in the vg\app\config\routig.yml is : "/gallery"

So the question is : how to add automatically the prefix (gallery) to the url given by a user or process if the url is just "http://localhost/vg/web/app_dev.php/"

(.../gallery/ is the equivalent of traditional index page.)

Thanks

答:
In routing.yml you could add a simple redirect:

```<code># redirecting the root
root:
    path: /
    defaults:
        _controller: FrameworkBundle:Redirect:urlRedirect
        path: /gallery
        permanent: true
</code>```

Reference: https://symfony.com/doc/current/routing/redirect_in_config.html

If the prefix (here gallery) is a configured value, do the redirection with a controller method:

```<code>/**
 * @Route("/", name="index")
 */
public function indexAction(): Response
{
    $urlPrefix = 'gallery'; // get this value from wherever appropriate, e.g.
                            // a service, class constant, a value from parameters.yml

    return $this->redirectToRoute('some_route', [
        'prefix' => $urlPrefix
    ]);
}
</code>```

Suppose you want the prefix-value in code, then it shouldn't be a configured route prefix, but a proper router parameter:

```<code>/**
 * @Route("/{prefix}", name="some_route")
 *
 * @return Http\Response
 */
public function someAction($prefix): Response
{
    // do things with $prefix

    return $this->render('view.html.twig');
}
</code>```

both actions can be in the same controller.

Title: Symfony Automatism in URL reWrite

Body:
In routing.yml you could add a simple redirect:

# redirecting the root
root:
    path: /
    defaults:
        _controller: FrameworkBundle:Redirect:urlRedirect
        path: /gallery
        permanent: true

Reference: https://symfony.com/doc/current/routing/redirect_in_config.html

If the prefix (here gallery) is a configured value, do the redirection with a controller method:

/**
 * @Route("/", name="index")
 */
public function indexAction(): Response
{
    $urlPrefix = 'gallery'; // get this value from wherever appropriate, e.g.
                            // a service, class constant, a value from parameters.yml

    return $this->redirectToRoute('some_route', [
        'prefix' => $urlPrefix
    ]);
}

Suppose you want the prefix-value in code, then it shouldn't be a configured route prefix, but a proper router parameter:

/**
 * @Route("/{prefix}", name="some_route")
 *
 * @return Http\Response
 */
public function someAction($prefix): Response
{
    // do things with $prefix

    return $this->render('view.html.twig');
}

both actions can be in the same controller.


问:
Propagate constness to data pointed by member variables
It is often quite confusing to C++ newcomers that const member functions are allowed to call non-const methods on objects referenced by the class (either by pointer or reference). For example, the following is perfectly correct:

```<code>class SomeClass
{
    class SomeClassImpl;
    SomeClassImpl * impl_; // PImpl idiom

  public:

    void const_method() const;
};

struct SomeClass::SomeClassImpl
{
    void non_const_method() { /*modify data*/ }
};

void SomeClass::const_method() const
{
    impl_->non_const_method(); //ok because impl_ is const, not *impl_
};
</code>```

However, it would sometimes be rather handy if the constness would propagate to pointed objects (I voluntarily used the PImpl idiom because it is one of the case where I think "constness propagation" would be very useful).

When using pointers, this can easily be achieved by using some kind of smart pointer with operators overloaded on constness:

```<code>template < typename T >
class const_propagating_ptr
{
  public:

    const_propagating_ptr( T * ptr ) : ptr_( ptr ) {}

    T       & operator*()       { return *ptr_; }
    T const & operator*() const { return *ptr_; }

    T       * operator->()       { return ptr_; }
    T const * operator->() const { return ptr_; }

    // assignment operator (?), get() method (?), reset() method (?)
    // ...

  private:

    T * ptr_;
};
</code>```

Now, I just need to modify SomeClass::impl_ to be a const_propagating_ptr<SomeClassImpl> to obtain the wanted behavior.

So I have a few questions about this:

Are there some issues with constness propagation that I have overlooked?

If not, are there any libraries that provide classes to obtain constness propagation?

Wouldn't it be useful that the common smart pointers (unique_ptr, shared_ptr, etc.) provide some mean to obtain this behavior (for example through a template parameter)?

答:
As @Alf P. Steinbach noted, you oversaw the fact that copying your pointer would yield a non-const object pointing to the same underlying object. Pimpl (below) nicely circumvent the issue by performing a deep-copy, unique_ptr circumvents it by being non-copyable. It is much easier, of course, if the pointee is owned by a single entity.

Boost.Optional propagates const-ness, however it's not exactly a pointer (though it models the OptionalPointee concept). I know of no such other library.

I would favor that they provide it by default. Adding another template parameter (traits class I guess) does not seem worth the trouble. However that would radically change the syntax from a classic pointer, so I am not sure that people would be ready to embrace it.

Code of the Pimpl class

```<code>template <class T>
class Pimpl
{
public:
  /**
   * Types
   */
  typedef T value;
  typedef const T const_value;
  typedef T* pointer;
  typedef const T* const_pointer;
  typedef T& reference;
  typedef const T& const_reference;

  /**
   * Gang of Four
   */
  Pimpl() : _value(new T()) {}
  explicit Pimpl(const_reference v) : _value(new T(v)) {}

  Pimpl(const Pimpl& rhs) : _value(new T(*(rhs._value))) {}

  Pimpl& operator=(const Pimpl& rhs)
  {
    Pimpl tmp(rhs);
    swap(tmp);
    return *this;
  } // operator=

  ~Pimpl() { boost::checked_delete(_value); }

  void swap(Pimpl& rhs)
  {
    pointer temp(rhs._value);
    rhs._value = _value;
    _value = temp;
  } // swap

  /**
   * Data access
   */
  pointer get() { return _value; }
  const_pointer get() const { return _value; }

  reference operator*() { return *_value; }
  const_reference operator*() const { return *_value; }

  pointer operator->() { return _value; }
  const_pointer operator->() const { return _value; }

private:
  pointer _value;
}; // class Pimpl<T>

// Swap
template <class T>
void swap(Pimpl<T>& lhs, Pimpl<T>& rhs) { lhs.swap(rhs); }

// Not to be used with pointers or references
template <class T> class Pimpl<T*> {};
template <class T> class Pimpl<T&> {};
</code>```

Body:
It is often quite confusing to C++ newcomers that const member functions are allowed to call non-const methods on objects referenced by the class (either by pointer or reference). For example, the following is perfectly correct:

class SomeClass
{
    class SomeClassImpl;
    SomeClassImpl * impl_; // PImpl idiom

  public:

    void const_method() const;
};

struct SomeClass::SomeClassImpl
{
    void non_const_method() { /*modify data*/ }
};

void SomeClass::const_method() const
{
    impl_->non_const_method(); //ok because impl_ is const, not *impl_
};

However, it would sometimes be rather handy if the constness would propagate to pointed objects (I voluntarily used the PImpl idiom because it is one of the case where I think "constness propagation" would be very useful).

When using pointers, this can easily be achieved by using some kind of smart pointer with operators overloaded on constness:

template < typename T >
class const_propagating_ptr
{
  public:

    const_propagating_ptr( T * ptr ) : ptr_( ptr ) {}

    T       & operator*()       { return *ptr_; }
    T const & operator*() const { return *ptr_; }

    T       * operator->()       { return ptr_; }
    T const * operator->() const { return ptr_; }

    // assignment operator (?), get() method (?), reset() method (?)
    // ...

  private:

    T * ptr_;
};

Now, I just need to modify SomeClass::impl_ to be a const_propagating_ptr<SomeClassImpl> to obtain the wanted behavior.

So I have a few questions about this:

Are there some issues with constness propagation that I have overlooked?

If not, are there any libraries that provide classes to obtain constness propagation?

Wouldn't it be useful that the common smart pointers (unique_ptr, shared_ptr, etc.) provide some mean to obtain this behavior (for example through a template parameter)?

Body:
As @Alf P. Steinbach noted, you oversaw the fact that copying your pointer would yield a non-const object pointing to the same underlying object. Pimpl (below) nicely circumvent the issue by performing a deep-copy, unique_ptr circumvents it by being non-copyable. It is much easier, of course, if the pointee is owned by a single entity.

Boost.Optional propagates const-ness, however it's not exactly a pointer (though it models the OptionalPointee concept). I know of no such other library.

I would favor that they provide it by default. Adding another template parameter (traits class I guess) does not seem worth the trouble. However that would radically change the syntax from a classic pointer, so I am not sure that people would be ready to embrace it.

Code of the Pimpl class

template <class T>
class Pimpl
{
public:
  /**
   * Types
   */
  typedef T value;
  typedef const T const_value;
  typedef T* pointer;
  typedef const T* const_pointer;
  typedef T& reference;
  typedef const T& const_reference;

  /**
   * Gang of Four
   */
  Pimpl() : _value(new T()) {}
  explicit Pimpl(const_reference v) : _value(new T(v)) {}

  Pimpl(const Pimpl& rhs) : _value(new T(*(rhs._value))) {}

  Pimpl& operator=(const Pimpl& rhs)
  {
    Pimpl tmp(rhs);
    swap(tmp);
    return *this;
  } // operator=

  ~Pimpl() { boost::checked_delete(_value); }

  void swap(Pimpl& rhs)
  {
    pointer temp(rhs._value);
    rhs._value = _value;
    _value = temp;
  } // swap

  /**
   * Data access
   */
  pointer get() { return _value; }
  const_pointer get() const { return _value; }

  reference operator*() { return *_value; }
  const_reference operator*() const { return *_value; }

  pointer operator->() { return _value; }
  const_pointer operator->() const { return _value; }

private:
  pointer _value;
}; // class Pimpl<T>

// Swap
template <class T>
void swap(Pimpl<T>& lhs, Pimpl<T>& rhs) { lhs.swap(rhs); }

// Not to be used with pointers or references
template <class T> class Pimpl<T*> {};
template <class T> class Pimpl<T&> {};


问:
How to use multiple image tags with docker-compose
According to this and this GitHub issues, currently there is no native way how to supply multiple tags for a service's image when using docker-compose to build one or multiple images.

My use case for this would be to build images defined in a docker-compose.yml file and tag them once with some customized tag (e.g. some build no. or date or similar) and once as latest.

While this can be easily achieved with plain docker using docker tag, docker-compose only allows to set one single tag in the image key. Using docker tag together with docker-compose is not an option for me since I want to keep all my docker-related definitions in the docker-compose.yml file and not copy them over into my build script.

What would be a decent work-around to achieve setting of multiple tags with docker-compose and without having to hardcode/copy the image names first?

答:
I came up with a couple of work-arounds of different complexity. They all rely on the assumption that ${IMAGE_TAG} stores the customized tag that represents e.g. a build no. and we want to tag all services' images with this tag as well as with latest.

grep the image names from the docker-compose.yml file

```<code>images=$(cat docker-compose.yml | grep 'image: ' | cut -d':' -f 2 | tr -d '"')
for image in $images
do
  docker tag "${image}":"${IMAGE_TAG}" "${image}":latest
done
</code>```

However, this is error prone if somebody adds a comment in docker-compose.yml which would e.g. look like # Purpose of this image: do something useful....

Build twice

Use ${IMAGE_TAG} as an environment variable in your docker-compose.yml file as described here in the first example.

Then, simply run the build process twice, each time substituting ${IMAGE_TAG} with a different value:

```<code>IMAGE_TAG="${IMAGE_TAG}" docker-compose build
IMAGE_TAG=latest docker-compose build
</code>```

The second build process should be much faster than the first one since all image layers should still be cached from the first run.

Drawback of this approach is that it will flood your log output with two subsequent build processes for each single service which might make harder to search through it for something useful.

Besides, if you have any command in your Dockerfile which always flushes the build cache (e.g. an ADD command fetching from a remote location with auto-updating last-modified headers, adding files which are constantly updated by an external process etc.) then the extra build might slow things down significantly.

Parse image names from the docker-compose.yml file with some inline Python code

Using a real yaml parser in Python (or any other language such as Ruby or perl or whatever is installed on your system) is more robust than the first mentioned grep approach since it will not get confused by comments or strange but valid ways of writing the yml file.

In Python, this could look like this:

```<code>images=$(python3 <<-EOF # make sure below to indent with tabs, not spaces; or omit the "-" before "EOF" and use no indention at all
    import yaml
    content = yaml.load(open("docker-compose.build.yml"))
    services = content["services"].values()
    image_names = (service["image"].split(":")[0] for service in services)
    print("\n".join(image_names))
EOF
)

for image in ${images}
do
docker tag ${image}:${IMAGE_TAG} ${image}:latest
done
</code>```

Drawback of this approach is that the machine executing the build has to have Python3 installed, along with the PyYAML library. As already mentioned, this pattern could similarly be used with Python2 or any other programming language that is installed.

Get image names with combination of some docker commands

The following approach using some native docker and docker-compose commands (using go-templates) is a bit more complex to write but also works nicely.

```<code># this should be set to something unique in order to avoid conflicts with other running docker-compose projects
compose_project_name=myproject.tagging

# create containers for all services without starting them
docker-compose --project-name "${compose_project_name}" up --no-start

# get image names without tags for all started containers
images=$(docker-compose --project-name "${compose_project_name}" images -q | xargs docker inspect --format='{{ index .RepoTags 0}}' | cut -d':' -f1)

# iterate over images and re-tag
for image in ${images}
do
    docker tag "${image}":"${IMAGE_TAG}" "${image}":latest
done

# clean-up created containers again
docker-compose --project-name "${compose_project_name}" down
</code>```

While this approach does not have any external dependencies and is more safe than the grep method, it might take a few more seconds to execute on large setups for creating and removing the containers (typically not an issues though).

Body:
I came up with a couple of work-arounds of different complexity. They all rely on the assumption that ${IMAGE_TAG} stores the customized tag that represents e.g. a build no. and we want to tag all services' images with this tag as well as with latest.

grep the image names from the docker-compose.yml file

images=$(cat docker-compose.yml | grep 'image: ' | cut -d':' -f 2 | tr -d '"')
for image in $images
do
  docker tag "${image}":"${IMAGE_TAG}" "${image}":latest
done

However, this is error prone if somebody adds a comment in docker-compose.yml which would e.g. look like # Purpose of this image: do something useful....

Build twice

Use ${IMAGE_TAG} as an environment variable in your docker-compose.yml file as described here in the first example.

Then, simply run the build process twice, each time substituting ${IMAGE_TAG} with a different value:

IMAGE_TAG="${IMAGE_TAG}" docker-compose build
IMAGE_TAG=latest docker-compose build

The second build process should be much faster than the first one since all image layers should still be cached from the first run.

Drawback of this approach is that it will flood your log output with two subsequent build processes for each single service which might make harder to search through it for something useful.

Besides, if you have any command in your Dockerfile which always flushes the build cache (e.g. an ADD command fetching from a remote location with auto-updating last-modified headers, adding files which are constantly updated by an external process etc.) then the extra build might slow things down significantly.

Parse image names from the docker-compose.yml file with some inline Python code

Using a real yaml parser in Python (or any other language such as Ruby or perl or whatever is installed on your system) is more robust than the first mentioned grep approach since it will not get confused by comments or strange but valid ways of writing the yml file.

In Python, this could look like this:

images=$(python3 <<-EOF # make sure below to indent with tabs, not spaces; or omit the "-" before "EOF" and use no indention at all
    import yaml
    content = yaml.load(open("docker-compose.build.yml"))
    services = content["services"].values()
    image_names = (service["image"].split(":")[0] for service in services)
    print("\n".join(image_names))
EOF
)

for image in ${images}
do
docker tag ${image}:${IMAGE_TAG} ${image}:latest
done

Drawback of this approach is that the machine executing the build has to have Python3 installed, along with the PyYAML library. As already mentioned, this pattern could similarly be used with Python2 or any other programming language that is installed.

Get image names with combination of some docker commands

The following approach using some native docker and docker-compose commands (using go-templates) is a bit more complex to write but also works nicely.

# this should be set to something unique in order to avoid conflicts with other running docker-compose projects
compose_project_name=myproject.tagging

# create containers for all services without starting them
docker-compose --project-name "${compose_project_name}" up --no-start

# get image names without tags for all started containers
images=$(docker-compose --project-name "${compose_project_name}" images -q | xargs docker inspect --format='{{ index .RepoTags 0}}' | cut -d':' -f1)

# iterate over images and re-tag
for image in ${images}
do
    docker tag "${image}":"${IMAGE_TAG}" "${image}":latest
done

# clean-up created containers again
docker-compose --project-name "${compose_project_name}" down

While this approach does not have any external dependencies and is more safe than the grep method, it might take a few more seconds to execute on large setups for creating and removing the containers (typically not an issues though).


问:
hive, get the data location using an one-liner
I wonder if there is a way to get the data location from hive using a one-liner.  Something like </p>

```<code>select d.location from ( describe formatted table_name partition ( .. ) ) as d;
</code>```

<p>My current solution is to get the full output and then parse it. </p>

答:
Two methods if you do not have access to the metadata.

Parse DESCRIBE TABLE in the shell like in this answer: https://stackoverflow.com/a/43804621/2700344

Also Hive has a virtual column INPUT__FILE__NAME.

```<code>select INPUT__FILE__NAME from table
</code>```

will output locations URLs for each file.
You can split URL by '/', get element you need, aggregate, etc

Body:
I wonder if there is a way to get the data location from hive using a one-liner.  Something like

select d.location from ( describe formatted table_name partition ( .. ) ) as d;

My current solution is to get the full output and then parse it.

Body:
Two methods if you do not have access to the metadata.

Parse DESCRIBE TABLE in the shell like in this answer: https://stackoverflow.com/a/43804621/2700344

Also Hive has a virtual column INPUT__FILE__NAME.

select INPUT__FILE__NAME from table

will output locations URLs for each file.
You can split URL by '/', get element you need, aggregate, etc


问:
Get a specific value from a multidimensional array provided by AgileCRM
I'm trying to get the first deal ID from AgileCRM.

When using:

```<code>$test = json_decode($deal, true);
print_r($test);
</code>```

I get the following result:

```<code>Array (
[0] => Array (
    [colorName] => WHITE
    [id] => 5686812383117312
    [apply_discount] =>
    [discount_value] => 0
    [discount_amt] => 0
    [discount_type] => Value
    [name] => New Home Loan
    [contact_ids] => Array (
        [0] => 5645056174194688
    )
    [custom_data] => Array (
    )
    [products] => Array (
    )
    [description] => New Lead
    [expected_value] => 0
    [milestone] => New Loan
    [probability] => 10
    [close_date] => 1521192269
    [created_time] => 1510824270
    [milestone_changed_time] => 0
    [entity_type] => deal
    [notes] => Array (
    )
    [note_ids] => Array (
    )
    [note_created_time] => 0
    [pipeline_id] => 5719238044024832
    [archived] =>
    [lost_reason_id] => 0
    [deal_source_id] => 0
    [total_deal_value] => 0
    [updated_time] => 1510824270
    [isCurrencyUpdateRequired] => 1
    [currency_conversion_value] => 0
    [tags] => Array (
    )
    [tagsWithTime] => Array (
    )
    [contacts] => Array (
        [0] => Array (
            [id] => 5645056174194688
            [type] => PERSON
            [properties] => Array (
                [0] => Array (
                    [type] => SYSTEM
                    [name] => first_name
                    [value] => piet
                )
                [1] => Array (
                    [type] => SYSTEM
                    [name] => last_name
                    [value] => pompies
                )
                [2] => Array (
                    [type] => SYSTEM
                    [name] => name
                    [value] =>
                )
            )
        )
    )
    [owner] => Array (
        [id] => 5178546118721536
        [domain] => domainname
        [email] => myemail@email.com
        [phone] =>
        [name] => Piet Pompies
        [pic] => https://d1gwclp1pmzk26.cloudfront.net/img/gravatar/48.png
        [schedule_id] => Piet Pompies
        [calendar_url] => https://homeside.agilecrm.com/calendar/Piet_Pompies
        [calendarURL] => https://homeside.agilecrm.com/calendar/Piet_Pompies
    )
)
</code>```

)

I want to echo "5686812383117312" from "[id] => 5686812383117312" (4th line in the array above)

I've tried "foreach" statements but my expertise on it is limited and can't seem to get it right.

Any help will be appreciated.

答:
In order to access the ID field you should:

get the array's first key

Access the required field

Array:

```<code>Array ( //$test
  [0] => Array (  //first key [0]
      [colorName] => WHITE
      [id] => 5686812383117312  //the required field ['id']
      [apply_discount] =>
</code>```

PHP:

```<code>$test = json_decode($deal, true);
print_r($test);

echo $test[0]['id']; //Output: 5686812383117312
</code>```

Body:
I'm trying to get the first deal ID from AgileCRM.

When using:

$test = json_decode($deal, true);
print_r($test);

I get the following result:

Array (
[0] => Array (
    [colorName] => WHITE
    [id] => 5686812383117312
    [apply_discount] =>
    [discount_value] => 0
    [discount_amt] => 0
    [discount_type] => Value
    [name] => New Home Loan
    [contact_ids] => Array (
        [0] => 5645056174194688
    )
    [custom_data] => Array (
    )
    [products] => Array (
    )
    [description] => New Lead
    [expected_value] => 0
    [milestone] => New Loan
    [probability] => 10
    [close_date] => 1521192269
    [created_time] => 1510824270
    [milestone_changed_time] => 0
    [entity_type] => deal
    [notes] => Array (
    )
    [note_ids] => Array (
    )
    [note_created_time] => 0
    [pipeline_id] => 5719238044024832
    [archived] =>
    [lost_reason_id] => 0
    [deal_source_id] => 0
    [total_deal_value] => 0
    [updated_time] => 1510824270
    [isCurrencyUpdateRequired] => 1
    [currency_conversion_value] => 0
    [tags] => Array (
    )
    [tagsWithTime] => Array (
    )
    [contacts] => Array (
        [0] => Array (
            [id] => 5645056174194688
            [type] => PERSON
            [properties] => Array (
                [0] => Array (
                    [type] => SYSTEM
                    [name] => first_name
                    [value] => piet
                )
                [1] => Array (
                    [type] => SYSTEM
                    [name] => last_name
                    [value] => pompies
                )
                [2] => Array (
                    [type] => SYSTEM
                    [name] => name
                    [value] =>
                )
            )
        )
    )
    [owner] => Array (
        [id] => 5178546118721536
        [domain] => domainname
        [email] => myemail@email.com
        [phone] =>
        [name] => Piet Pompies
        [pic] => https://d1gwclp1pmzk26.cloudfront.net/img/gravatar/48.png
        [schedule_id] => Piet Pompies
        [calendar_url] => https://homeside.agilecrm.com/calendar/Piet_Pompies
        [calendarURL] => https://homeside.agilecrm.com/calendar/Piet_Pompies
    )
)

)

I want to echo "5686812383117312" from "[id] => 5686812383117312" (4th line in the array above)

I've tried "foreach" statements but my expertise on it is limited and can't seem to get it right.

Any help will be appreciated.

Body:
In order to access the ID field you should:

get the array's first key

Access the required field

Array:

Array ( //$test
  [0] => Array (  //first key [0]
      [colorName] => WHITE
      [id] => 5686812383117312  //the required field ['id']
      [apply_discount] =>

PHP:

$test = json_decode($deal, true);
print_r($test);

echo $test[0]['id']; //Output: 5686812383117312


问:
the application crashed when i used custom adapter with using json

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0  in
  spinner

```<code>   public void GetAllData() {
        JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    ArrayList<CityList>mylist=new ArrayList<CityList>();
                    JSONArray array=response.getJSONArray("data");
                    for(int index=0;index<array.length();index++)
                    {
                        JSONObject object=array.getJSONObject(index);
                        mylist.add(new CityList(object.getInt("id"),object.getString("name")));
                    }
                    CityAdapter cityAdapter=new CityAdapter(MainActivity.this,R.layout.custome_spinner,R.id.humanmed,mylist);
                    ServiceName.setAdapter(cityAdapter);
                } catch (JSONException e) {
                    Toast.makeText(MainActivity.this, "bad", Toast.LENGTH_SHORT).show();        }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "sad", Toast.LENGTH_SHORT).show();
            }
        });
</code>```

答:
only add this to your custom adapter spinner will work </p>

<p>@Override
    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        return getView(position, convertView, parent);
    }</p>

Body:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0  in
  spinner

   public void GetAllData() {
        JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    ArrayList<CityList>mylist=new ArrayList<CityList>();
                    JSONArray array=response.getJSONArray("data");
                    for(int index=0;index<array.length();index++)
                    {
                        JSONObject object=array.getJSONObject(index);
                        mylist.add(new CityList(object.getInt("id"),object.getString("name")));
                    }
                    CityAdapter cityAdapter=new CityAdapter(MainActivity.this,R.layout.custome_spinner,R.id.humanmed,mylist);
                    ServiceName.setAdapter(cityAdapter);
                } catch (JSONException e) {
                    Toast.makeText(MainActivity.this, "bad", Toast.LENGTH_SHORT).show();        }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "sad", Toast.LENGTH_SHORT).show();
            }
        });

Body:
only add this to your custom adapter spinner will work

@Override
    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        return getView(position, convertView, parent);
    }


问:
Change bookmark action Named destination to page number
I need to change bookmark actions Properties Named destination to Page number of an existing pdf file, using iText java code

```<code>   public void BookmarkZoomLevelChange(List<HashMap<String, Object>> list,
        PdfReader reader) {
    for (HashMap<String, Object> entry : list) {

        for (String key : entry.keySet()) {
            // System.out.println(key);
            if ("Kids".equals(key)) {
                Object o = entry.get(key);

                BookmarkZoomLevelChange((List<HashMap<String, Object>>) o,
                        reader);
            } else if ("Page".equals(key)) {
                String dest = (String) entry.get(key);
                // System.out.println(dest);
                if (dest.contains("FitR")) {

                    String cord[] = dest.substring(dest.indexOf("R"))
                            .split(" ");
                    entry.put("Page", dest.replaceAll("FitR", "XYZ "
                            + cord[1] + " " + cord[4] + " 0"));
                } else if (dest.contains("XYZ")) {
                    String cord[] = dest.substring(dest.indexOf("XYZ"))
                            .split(" ");
                    entry.put("Page", dest.replaceAll("XYZ", "XYZ "
                            + cord[1] + " " + cord[2] + " 0"));
                }
            }
        }
    }
}
</code>```

using above code i did not get  ("Page".equals(key)). So, how to convert Named destination to Page Number?

答:
Please take a look at the API documentation for the version you are using, more specifically at the methods available in the PdfReader class. You'll find the consolidateNamedDestinations() method that is described as follows:

Replaces all the local named links with the actual destinations.

You have named destinations. You don't like this. You want the named destinations to be replaced by explicit destinations that point to a specific location on a specific page. That's exactly what the consolidateNamedDestinations() method is about.

Try this:

```<code>PdfReader reader = new PdfReader(src);
reader.consolidateNamedDestinations();
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
</code>```

Normally, there should be no links to named destinations in the dest PDF anymore.

Body:
I need to change bookmark actions Properties Named destination to Page number of an existing pdf file, using iText java code

   public void BookmarkZoomLevelChange(List<HashMap<String, Object>> list,
        PdfReader reader) {
    for (HashMap<String, Object> entry : list) {

        for (String key : entry.keySet()) {
            // System.out.println(key);
            if ("Kids".equals(key)) {
                Object o = entry.get(key);

                BookmarkZoomLevelChange((List<HashMap<String, Object>>) o,
                        reader);
            } else if ("Page".equals(key)) {
                String dest = (String) entry.get(key);
                // System.out.println(dest);
                if (dest.contains("FitR")) {

                    String cord[] = dest.substring(dest.indexOf("R"))
                            .split(" ");
                    entry.put("Page", dest.replaceAll("FitR", "XYZ "
                            + cord[1] + " " + cord[4] + " 0"));
                } else if (dest.contains("XYZ")) {
                    String cord[] = dest.substring(dest.indexOf("XYZ"))
                            .split(" ");
                    entry.put("Page", dest.replaceAll("XYZ", "XYZ "
                            + cord[1] + " " + cord[2] + " 0"));
                }
            }
        }
    }
}

using above code i did not get  ("Page".equals(key)). So, how to convert Named destination to Page Number?

Body:
Please take a look at the API documentation for the version you are using, more specifically at the methods available in the PdfReader class. You'll find the consolidateNamedDestinations() method that is described as follows:

Replaces all the local named links with the actual destinations.

You have named destinations. You don't like this. You want the named destinations to be replaced by explicit destinations that point to a specific location on a specific page. That's exactly what the consolidateNamedDestinations() method is about.

Try this:

PdfReader reader = new PdfReader(src);
reader.consolidateNamedDestinations();
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();

Normally, there should be no links to named destinations in the dest PDF anymore.


问:
EC2 startup on schedule
I need to start up an EC2 instance at (say) 6am every day. The constraints are that I'd like to avoid having a computer running all day to do the startup or use a paid solution like ylastic's.

The solution at alestic, is the closest so far. The downside of this solution is that the startup time is high because of the time required to install custom software and to move around data.

Is there a way to just boot up an instance instead of creating a new instance each time as shown in this example?

答:
Amazon recently announced two new features to achieve this without custom implementations directly as configuration from AWS Web Console EC2 section.

Using Scheduled Scaling for Application Auto Scaling (After creating an autoscaling group, there is a tab where you can add additional time based autoscaling rules)

Reserving Scheduled EC2 instances (In the EC2 console, under Instances, there is the option to reserve Scheduled EC2 instances)

Title: EC2 startup on schedule