问:
Handling hidden and shown fragments onbackpressed
I have an activity which hosts three Fragment's and I can switch between Fragment's using BottomNavigationView.The mechanism that I use to switch between Fragment's is using show and hide functions of FragmentTransaction instead of replace function of FragmentTransaction. I am doing so because I want some network operations to be done only once and also to inflate Layout only once.

The problem that I am facing using this mechanism is that when I start another Activity from any of the Fragment and then hit the back button the selectedItem of the BottomNavigationView and the Fragment shown are mismatching.

I was able to solve this problem though but I feel it has less efficiency. The procedure was that whenever I clicked a tab in BottomNavigation while switching Fragment's I gave it some predecided number and saved in a static variable(X) and whenever I clicked back button in the OnResume() method of the hosting activity I made a switch-case block using X to know which Fragment was visible before starting the new Activity and then finally making three FragmentTransaction's to show and hide required Fragment's.

```<code>protected void onResume() {
        super.onResume();

        if(selectedId!=63){
           switch(selectedId){
               case 0:if(bottomNavigationView.getSelectedItemId()==R.id.navigation_home){handleHomeFragmentVisibility();}
                   break;
               case 1:if(bottomNavigationView.getSelectedItemId()==R.id.navigation_dashboard)
               {handleDashboardFragmentVisibility();}
                   break;
               case 2:if(bottomNavigationView.getSelectedItemId()==R.id.navigation_notifications)
               {handleNotificationFragmentVisibility();}
                   break;
           }

        }
</code>```

I feel using three FragmentTransaction's is costly and I was looking for some efficient way. Can you tell me one if you know ?

```<code>public void handleHomeFragmentVisibility(){
        FragmentManager fragmentManager=  getSupportFragmentManager();
        if (fragmentManager.findFragmentByTag("home") != null) {
            //if the fragment exists, show it.
            fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag("home")).commit();
        } else {
            //if the fragment does not exist, add it to fragment manager.

            Log.e(TAG,"homeFragmentAdded");
            fragmentManager.beginTransaction().add(R.id.container, new HomeFragment(), "home").commit();
        }
        if (fragmentManager.findFragmentByTag("dashboard") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("dashboard")).commit();
        }
        if (fragmentManager.findFragmentByTag("requests") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("requests")).commit();
        }

    }

    public void handleDashboardFragmentVisibility(){
        FragmentManager fragmentManager=  getSupportFragmentManager();
        if (fragmentManager.findFragmentByTag("dashboard") != null) {
            //if the fragment exists, show it.
            fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag("dashboard")).commit();
        } else {
            //if the fragment does not exist, add it to fragment manager.

            fragmentManager.beginTransaction().add(R.id.container, new DashboardFragment(), "dashboard").commit();
        }
        if (fragmentManager.findFragmentByTag("home") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("home")).commit();
        }
        if (fragmentManager.findFragmentByTag("requests") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("requests")).commit();
        }

    }
    public void handleNotificationFragmentVisibility(){
        FragmentManager fragmentManager=  getSupportFragmentManager();
        if (fragmentManager.findFragmentByTag("requests") != null) {
            //if the fragment exists, show it.
            fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag("requests")).commit();
        } else {
            //if the fragment does not exist, add it to fragment manager.

            fragmentManager.beginTransaction().add(R.id.container, new NotificationFragment(), "requests").commit();
        }
        if (fragmentManager.findFragmentByTag("home") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("home")).commit();
        }
        if (fragmentManager.findFragmentByTag("dashboard") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("dashboard")).commit();
        }
    }

 bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                switch (item.getItemId()) {
                    case R.id.navigation_home:
                        selectedId=0;
                       handleHomeFragmentVisibility();
                        break;
                    case R.id.navigation_dashboard:
                    selectedId=1;
                     handleDashboardFragmentVisibility();

                        break;
                    case R.id.navigation_notifications:
                   selectedId=2;
                      handleNotificationFragmentVisibility();
                        break;

                }

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

答:
A first note on your code: Avoid boilerplate! Write only one method instead of three and use a signature of the type handleFragmentVisibility(String show, String hide1, String hide2, int container). In case the fragment to be shown is null, instantiate it by testing for show, something like:

```<code>Fragment newFragment = (show == "home") ? new HomeFragment() : (show == "dashboard") ? new DashboardFragment() : new NotificationFragment();
</code>```

However, none of your fragments should ever get null through hiding (please check for yourself), since you don't remove them from your activity or replace them with other fragments. Instead of using show and hide you could also use attach and detach, both sets of methods keep state. I don't see an efficiency problem and you do indeed need to call three FragmentTransactions. It only can be done with less code:

```<code>public void handleFragmentVisibility(String show, String hide1, String hide2){
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag(show)).commit();
    fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(hide1)).commit();
    fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(hide2)).commit();
    }
</code>```

Please note, that although this method keeps the state of the fragment while hiding or detaching them, other events like orientation change still make it necessary that you take care of saving state in onSaveInstanceState(Bundle savedInstanceState).

Body:
I have an activity which hosts three Fragment's and I can switch between Fragment's using BottomNavigationView.The mechanism that I use to switch between Fragment's is using show and hide functions of FragmentTransaction instead of replace function of FragmentTransaction. I am doing so because I want some network operations to be done only once and also to inflate Layout only once.

The problem that I am facing using this mechanism is that when I start another Activity from any of the Fragment and then hit the back button the selectedItem of the BottomNavigationView and the Fragment shown are mismatching.

I was able to solve this problem though but I feel it has less efficiency. The procedure was that whenever I clicked a tab in BottomNavigation while switching Fragment's I gave it some predecided number and saved in a static variable(X) and whenever I clicked back button in the OnResume() method of the hosting activity I made a switch-case block using X to know which Fragment was visible before starting the new Activity and then finally making three FragmentTransaction's to show and hide required Fragment's.

protected void onResume() {
        super.onResume();

        if(selectedId!=63){
           switch(selectedId){
               case 0:if(bottomNavigationView.getSelectedItemId()==R.id.navigation_home){handleHomeFragmentVisibility();}
                   break;
               case 1:if(bottomNavigationView.getSelectedItemId()==R.id.navigation_dashboard)
               {handleDashboardFragmentVisibility();}
                   break;
               case 2:if(bottomNavigationView.getSelectedItemId()==R.id.navigation_notifications)
               {handleNotificationFragmentVisibility();}
                   break;
           }

        }

I feel using three FragmentTransaction's is costly and I was looking for some efficient way. Can you tell me one if you know ?

public void handleHomeFragmentVisibility(){
        FragmentManager fragmentManager=  getSupportFragmentManager();
        if (fragmentManager.findFragmentByTag("home") != null) {
            //if the fragment exists, show it.
            fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag("home")).commit();
        } else {
            //if the fragment does not exist, add it to fragment manager.

            Log.e(TAG,"homeFragmentAdded");
            fragmentManager.beginTransaction().add(R.id.container, new HomeFragment(), "home").commit();
        }
        if (fragmentManager.findFragmentByTag("dashboard") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("dashboard")).commit();
        }
        if (fragmentManager.findFragmentByTag("requests") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("requests")).commit();
        }

    }

    public void handleDashboardFragmentVisibility(){
        FragmentManager fragmentManager=  getSupportFragmentManager();
        if (fragmentManager.findFragmentByTag("dashboard") != null) {
            //if the fragment exists, show it.
            fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag("dashboard")).commit();
        } else {
            //if the fragment does not exist, add it to fragment manager.

            fragmentManager.beginTransaction().add(R.id.container, new DashboardFragment(), "dashboard").commit();
        }
        if (fragmentManager.findFragmentByTag("home") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("home")).commit();
        }
        if (fragmentManager.findFragmentByTag("requests") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("requests")).commit();
        }

    }
    public void handleNotificationFragmentVisibility(){
        FragmentManager fragmentManager=  getSupportFragmentManager();
        if (fragmentManager.findFragmentByTag("requests") != null) {
            //if the fragment exists, show it.
            fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag("requests")).commit();
        } else {
            //if the fragment does not exist, add it to fragment manager.

            fragmentManager.beginTransaction().add(R.id.container, new NotificationFragment(), "requests").commit();
        }
        if (fragmentManager.findFragmentByTag("home") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("home")).commit();
        }
        if (fragmentManager.findFragmentByTag("dashboard") != null) {
            //if the other fragment is visible, hide it.
            fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag("dashboard")).commit();
        }
    }

 bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                switch (item.getItemId()) {
                    case R.id.navigation_home:
                        selectedId=0;
                       handleHomeFragmentVisibility();
                        break;
                    case R.id.navigation_dashboard:
                    selectedId=1;
                     handleDashboardFragmentVisibility();

                        break;
                    case R.id.navigation_notifications:
                   selectedId=2;
                      handleNotificationFragmentVisibility();
                        break;

                }

                return true;
            }
        });

Body:
A first note on your code: Avoid boilerplate! Write only one method instead of three and use a signature of the type handleFragmentVisibility(String show, String hide1, String hide2, int container). In case the fragment to be shown is null, instantiate it by testing for show, something like:

Fragment newFragment = (show == "home") ? new HomeFragment() : (show == "dashboard") ? new DashboardFragment() : new NotificationFragment();

However, none of your fragments should ever get null through hiding (please check for yourself), since you don't remove them from your activity or replace them with other fragments. Instead of using show and hide you could also use attach and detach, both sets of methods keep state. I don't see an efficiency problem and you do indeed need to call three FragmentTransactions. It only can be done with less code:

public void handleFragmentVisibility(String show, String hide1, String hide2){
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag(show)).commit();
    fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(hide1)).commit();
    fragmentManager.beginTransaction().hide(fragmentManager.findFragmentByTag(hide2)).commit();
    }

Please note, that although this method keeps the state of the fragment while hiding or detaching them, other events like orientation change still make it necessary that you take care of saving state in onSaveInstanceState(Bundle savedInstanceState).


来源: stackexchange

ContentLicense: CC BY-SA 3.0

Title: How to scale clipPath to svg bounding box

Body:
I'm trying to add a hexagonal shape over my image, which is working fine, however, the svg path size is much larger than my intended image size. I'd like the clipPath to be 108px 120px by the time it's loaded. My image is 240x240 for retina sake so it should scale down to 120px by 120px and fill the clipPath.

<svg width="108" height="120" viewBox="0 0 108 120">
  <defs>
    <clipPath id="svgPath">
      <path d="M73.61215932167728 7.499999999999999Q86.60254037844386 0 99.59292143521044 7.5L160.21469970012114 42.5Q173.20508075688772 50 173.20508075688772 65L173.20508075688772 135Q173.20508075688772 150 160.21469970012114 157.5L99.59292143521044 192.5Q86.60254037844386 200 73.61215932167728 192.5L12.990381056766578 157.5Q0 150 0 135L0 65Q0 50 12.99038105676658 42.5Z"></path>
    </clipPath>
  </defs>
  <foreignObject clip-path="url(#svgPath)" width="100%" height="100%">

  </foreignObject>
</svg>

So far, I've applied a transform to the clipPath, which had better results, but it wasn't pixel perfect by any means, so I decided to keep looking. I also at one point converted the path to work with objectBoundingBox (which is this)

M0.751144482874 0.107142857143Q0.883699391617 0 1.01625430036 0.107142857143L1.63484387449 0.607142857143Q1.76739878323 0.714285714286 1.76739878323 0.928571428571L1.76739878323 1.92857142857Q1.76739878323 2.14285714286 1.63484387449 2.25L1.01625430036 2.75Q0.883699391617 2.85714285714 0.751144482874 2.75L0.132554908743 2.25Q0 2.14285714286 0 1.92857142857L0 0.928571428571Q0 0.714285714286 0.132554908743 0.607142857143Z

I thought this would enable me to be able to scale the clipPath up to the SVG container, but it didn't work. Otherwise, I've played around with width and height on img, foreignObject, clipPath, and svg to try and do what I'm wanting to do. I also have messed with viewBox. Anyway, I've been testing on Safari, so maybe that's part of my problem, but I was hoping that if it worked in Safari that it would also work in Firefox and Chrome.

Anyone have experience with this? I may just need to create the mask in Photoshop, but I was trying to challenge myself to do it this way.

Body:
Few corrected your first option. Add viewport svg - width="240" height="240"
and added a transformation to the clippath transform="translate(30 0) scale(1.2)"

<svg width="240" height="240" viewBox="0 0 240 240">
  <defs>
    <clipPath id="svgPath" transform="translate(15 0) scale(1.2)">
      <path d="M73.61215932167728 7.499999999999999Q86.60254037844386 0 99.59292143521044 7.5L160.21469970012114 42.5Q173.20508075688772 50 173.20508075688772 65L173.20508075688772 135Q173.20508075688772 150 160.21469970012114 157.5L99.59292143521044 192.5Q86.60254037844386 200 73.61215932167728 192.5L12.990381056766578 157.5Q0 150 0 135L0 65Q0 50 12.99038105676658 42.5Z"></path>
    </clipPath>
  </defs>
  <foreignObject clip-path="url(#svgPath)" width="100%" height="100%">
    <img src="https://avatars3.githubusercontent.com/u/5648875?v=2&amp;s=240">
  </foreignObject>
</svg>

If you need a responsive avatar, replace the digits viewport svg with percentages - width="25%" height="25%"

<svg width="25%" height="25%" viewBox="0 0 240 240">
  <defs>
    <clipPath id="svgPath" transform="translate(15 0) scale(1.2)">
      <path d="M73.61215932167728 7.499999999999999Q86.60254037844386 0 99.59292143521044 7.5L160.21469970012114 42.5Q173.20508075688772 50 173.20508075688772 65L173.20508075688772 135Q173.20508075688772 150 160.21469970012114 157.5L99.59292143521044 192.5Q86.60254037844386 200 73.61215932167728 192.5L12.990381056766578 157.5Q0 150 0 135L0 65Q0 50 12.99038105676658 42.5Z"></path>
    </clipPath>
  </defs>
  <foreignObject clip-path="url(#svgPath)" width="100%" height="100%">
    <img src="https://avatars3.githubusercontent.com/u/5648875?v=2&amp;s=240">
  </foreignObject>
</svg>

option without <foreignObject>

<svg width="50%" height="50%" viewBox="0 0 240 240">
  <defs>
    <clipPath id="svgPath" transform="translate(15 0) scale(1.2)">
      <path d="M73.61215932167728 7.499999999999999Q86.60254037844386 0 99.59292143521044 7.5L160.21469970012114 42.5Q173.20508075688772 50 173.20508075688772 65L173.20508075688772 135Q173.20508075688772 150 160.21469970012114 157.5L99.59292143521044 192.5Q86.60254037844386 200 73.61215932167728 192.5L12.990381056766578 157.5Q0 150 0 135L0 65Q0 50 12.99038105676658 42.5Z"></path>
    </clipPath>
  </defs>

  <image xlink:href="https://avatars3.githubusercontent.com/u/5648875?v=2&amp;s=240" clip-path="url(#svgPath)" width="240" height="240"> </image>
  </svg>

UPD

If necessary, you can change the scale and positioning of the picture relative to the frame, changing the digits of the image transformation command

transform="translate(15 0) scale(1.2)"

Example of an avatar with a shadow

As a shadow, the second hexagon will be used, which moves to the right and down 4 pixels relative to the first hexagon.

The edges of the hexagon are blurred with a Gaussian filter.

<filter id="Filtershadow" height="120%" width="120%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>

<svg width="50%" height="50%" viewBox="0 0 300 300">
  <defs>
    <clipPath id="svgPath" transform="translate(10 0) scale(1.2)">
      <path d="M73.61215932167728 7.499999999999999Q86.60254037844386 0 99.59292143521044 7.5L160.21469970012114 42.5Q173.20508075688772 50 173.20508075688772 65L173.20508075688772 135Q173.20508075688772 150 160.21469970012114 157.5L99.59292143521044 192.5Q86.60254037844386 200 73.61215932167728 192.5L12.990381056766578 157.5Q0 150 0 135L0 65Q0 50 12.99038105676658 42.5Z"></path>
    </clipPath> -->

  <filter id="Filtershadow" height="120%" width="120%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
  </defs>

  <path id="shadow" transform="translate(14 4) scale(1.2)" fill="grey"  filter="url(#Filtershadow)" d="M73.61215932167728 7.499999999999999Q86.60254037844386 0 99.59292143521044 7.5L160.21469970012114 42.5Q173.20508075688772 50 173.20508075688772 65L173.20508075688772 135Q173.20508075688772 150 160.21469970012114 157.5L99.59292143521044 192.5Q86.60254037844386 200 73.61215932167728 192.5L12.990381056766578 157.5Q0 150 0 135L0 65Q0 50 12.99038105676658 42.5Z"></path>

  <image xlink:href="https://avatars3.githubusercontent.com/u/5648875?v=2&amp;s=240" clip-path="url(#svgPath)" width="240" height="240"> </image> -->
  </svg>


问:
How do you define an operator in prolog to make a list?
I want to define an operator "++>" in a way so that typing "a ++> b" will make a list of [a,b].

I've written the following code, but it doesn't appear to do the job.

```<code>++>(X,Y) :-
 [X,Y].

:- op(500,xfy,++>).
</code>```

答:
```<code>:- op(500,xfy,++>).
++>(X,Y,[X,Y]).
</code>```

And use it like

```<code>?- ++>(1,2,X).
X = [1, 2].
</code>```

Actually, Prolog is not oriented calculations, so operators is just synonyms to the terms.
You want a term\3, where one element is list of two another. So, you can't use 2-placed operator in that case. Btw, you can't use is in this situation, because it used only in arithmetic cases.

Body:
I want to define an operator "++>" in a way so that typing "a ++> b" will make a list of [a,b].

I've written the following code, but it doesn't appear to do the job.

++>(X,Y) :-
 [X,Y].

:- op(500,xfy,++>).

Body:
:- op(500,xfy,++>).
++>(X,Y,[X,Y]).

And use it like

?- ++>(1,2,X).
X = [1, 2].

Actually, Prolog is not oriented calculations, so operators is just synonyms to the terms.
You want a term\3, where one element is list of two another. So, you can't use 2-placed operator in that case. Btw, you can't use is in this situation, because it used only in arithmetic cases.

ContentLicense: CC BY-SA 2.5


问:
jq: Turn json object values into arrays
I have got the following array of objects (this is just an excerpt, also the objects are bigger):

```<code>[{
    "DATE": "10.10.2017 01:00",
    "ID": "X",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "X",
    "VALUE_ONE": 30,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "X",
    "VALUE_ONE": 25,
    "VALUE_TWO": 2
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Y",
    "VALUE_ONE": 10,
    "VALUE_TWO": 9
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Y",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Y",
    "VALUE_ONE": 50,
    "VALUE_TWO": 5
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Z",
    "VALUE_ONE": 55,
    "VALUE_TWO": 3
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Z",
    "VALUE_ONE": 60,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Z",
    "VALUE_ONE": 15,
    "VALUE_TWO": 7
  }
]
</code>```

To simplify this for a web application, and also to reduce file size, I would like to convert the "VALUE_ONE","VALUE_TWO" and "DATE" values to arrays for each "ID" just like this:

```<code>[{
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "X",
    "VALUE_ONE": [20, 30, 25],
    "VALUE_TWO": [5, 7, 2]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Y",
    "VALUE_ONE": [10, 20, 50],
    "VALUE_TWO": [9, 5, 5]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Z",
    "VALUE_ONE": [55, 60, 15],
    "VALUE_TWO": [3, 7, 7]
  }
]
</code>```

Here it is important that you need to be able find the values that are linked to a certain time (date). As the input values for "DATE" are consecutive, you most probably do not need the DATE value anymore to find the requested "VALUE.." value. You can probably just use the index of the array for that (index=0 is always 10.10.2017 01:00, index=1 is ... 02:00 etc.).
Is it possible to do it like that? This would keep the file size even smaller.
Thanks!

答:
Here is a solution using reduce, setpath, getpath, del and symbolic variable destructuring.  It will collect all the values for keys other than ID and DATE (eliminating the need to hardcode VALUE_ONE, etc.) in parallel arrays.

```<code>reduce (.[] | [.ID, .DATE, del(.ID,.DATE)]) as [$id,$date,$v] ({};
    (getpath([$id, "DATE"])|length) as $idx
  | setpath([$id, "ID"]; $id)
  | setpath([$id, "DATE", $idx]; $date)
  | reduce ($v|keys[]) as $k (.; setpath([$id, $k, $idx]; $v[$k]))
)
| map(.)
</code>```

Try it online!

Title: jq: Turn json object values into arrays

Body:
I have got the following array of objects (this is just an excerpt, also the objects are bigger):

[{
    "DATE": "10.10.2017 01:00",
    "ID": "X",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "X",
    "VALUE_ONE": 30,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "X",
    "VALUE_ONE": 25,
    "VALUE_TWO": 2
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Y",
    "VALUE_ONE": 10,
    "VALUE_TWO": 9
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Y",
    "VALUE_ONE": 20,
    "VALUE_TWO": 5
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Y",
    "VALUE_ONE": 50,
    "VALUE_TWO": 5
  },

  {
    "DATE": "10.10.2017 01:00",
    "ID": "Z",
    "VALUE_ONE": 55,
    "VALUE_TWO": 3
  },
  {
    "DATE": "10.10.2017 02:00",
    "ID": "Z",
    "VALUE_ONE": 60,
    "VALUE_TWO": 7
  },
  {
    "DATE": "10.10.2017 03:00",
    "ID": "Z",
    "VALUE_ONE": 15,
    "VALUE_TWO": 7
  }
]

To simplify this for a web application, and also to reduce file size, I would like to convert the "VALUE_ONE","VALUE_TWO" and "DATE" values to arrays for each "ID" just like this:

[{
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "X",
    "VALUE_ONE": [20, 30, 25],
    "VALUE_TWO": [5, 7, 2]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Y",
    "VALUE_ONE": [10, 20, 50],
    "VALUE_TWO": [9, 5, 5]
  },
  {
    "DATE": ["10.10.2017 01:00", "10.10.2017 02:00", "10.10.2017 03:00"],
    "ID": "Z",
    "VALUE_ONE": [55, 60, 15],
    "VALUE_TWO": [3, 7, 7]
  }
]

Here it is important that you need to be able find the values that are linked to a certain time (date). As the input values for "DATE" are consecutive, you most probably do not need the DATE value anymore to find the requested "VALUE.." value. You can probably just use the index of the array for that (index=0 is always 10.10.2017 01:00, index=1 is ... 02:00 etc.).
Is it possible to do it like that? This would keep the file size even smaller.
Thanks!

Body:
Here is a solution using reduce, setpath, getpath, del and symbolic variable destructuring.  It will collect all the values for keys other than ID and DATE (eliminating the need to hardcode VALUE_ONE, etc.) in parallel arrays.

reduce (.[] | [.ID, .DATE, del(.ID,.DATE)]) as [$id,$date,$v] ({};
    (getpath([$id, "DATE"])|length) as $idx
  | setpath([$id, "ID"]; $id)
  | setpath([$id, "DATE", $idx]; $date)
  | reduce ($v|keys[]) as $k (.; setpath([$id, $k, $idx]; $v[$k]))
)
| map(.)

Try it online!


问:
Article within the image
I would like to have something along the lines of (the bordered thing is a a picture and text has inverse coloring so that it is easy to read)

Mind you the image is a simple div tag that is going to live in

```<code>    <div class = "row">
        <div class = "col-md-6">
            <h3>Title</h3>
            <p>
                Short and nice paragraph
            </p>
        </div>
    </div>
</code>```

However I do not know a first thing of where to start from. I tried reading bootstrap tutorials and they didn't provide much. I understand that I haven't provided any piece of code to show my work, but I honestly do not even know where to start, or what to search for or what to do. So I am not really asking  for a full solution or anything, but if you could point me in right direction I will be ever so grateful

答:
Quillion, I don't understand what your question is. The code above should render almost what you want. Nevertheless maybe this helps you:

I wrapped your code in a main container .container-fluid and in a .card element, both can be found in the bootstrap documentation.

I just added one additional style for a wider border. You can play with it a little and should be quickly get the style you need. Here is a link to the pen: https://codepen.io/scheinercc/pen/pdwdvx

Hope that helps.

```<code><style>
    .custom-border-width-3 {
        border-width: 3px;
    }
<style>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-6">
            <div class="card mt-2 custom-border-width-3">
                <div class="card-body">
                    <h1>Title</h1>
                    <p>
                        Short and nice paragraph
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Title: Article within the image

Body:
I would like to have something along the lines of (the bordered thing is a a picture and text has inverse coloring so that it is easy to read)

Mind you the image is a simple div tag that is going to live in

Title

                Short and nice paragraph

However I do not know a first thing of where to start from. I tried reading bootstrap tutorials and they didn't provide much. I understand that I haven't provided any piece of code to show my work, but I honestly do not even know where to start, or what to search for or what to do. So I am not really asking  for a full solution or anything, but if you could point me in right direction I will be ever so grateful

Body:
Quillion, I don't understand what your question is. The code above should render almost what you want. Nevertheless maybe this helps you:

I wrapped your code in a main container .container-fluid and in a .card element, both can be found in the bootstrap documentation.

I just added one additional style for a wider border. You can play with it a little and should be quickly get the style you need. Here is a link to the pen: https://codepen.io/scheinercc/pen/pdwdvx

Hope that helps.

<style>
    .custom-border-width-3 {
        border-width: 3px;
    }
<style>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-6">
            <div class="card mt-2 custom-border-width-3">
                <div class="card-body">
                    <h1>Title</h1>
                    <p>
                        Short and nice paragraph
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>


问:
Can I create more than one repository for github pages?
I  created a repository for hosting a blog on github.Is there any way that I can create more to host multiple blogs?Am I limited to just one repository for hosting(since username.github.com can only be used once?)

答: I found a workaround if you don't want to make separate repositories for your different sites but just want to host them. In your io repo, create an index.html file on your master branch that acts as a table of contents linking to your other sites(subDirectories) index.html files. The username.github.io master branch seems to be the landing page that enables the hosting, so if it doesn't see an index file linking out to your separate projects, it won't register your subdirectories. After this all you need is the URL to whatever project you want to view. The io basically behaves like a giant single website with all your separate projects on it. Of course, if you would rather have separate repositories, gh-pages is the way to go.</p>


问:
How can I get a link to a Facebook or Twitter avatar by username?
How can I get a link to a Facebook or Twitter avatar by username?</p>

答:
you have to use facebook's graph API to get profile pictures. You'll have to register your app with facebook to get an API key, and then you can access most of the information on a given user's profile.check out their developer page to see some examples

Twitter just changed the way they handle API call. Looks like you'll have to register your app with them as well to get access to the avatars. I haven't used the twitter API since they changed it, so i'm not a sure about what goes on, but check out the docs page to read up on what you'd have to do.

hope this helps!


问:
Only show prime numbers in a NumericUpDown control
```<code>    private void numericUpDown1_ValueChanged_1(object sender, EventArgs e)
    {
        //my numeric up down var name is numrsa1//
    }

    static bool IsPrimeNumber(int value)
    {
        bool result = true;

        for (int i = 2; i < value; i++)
        {
            if (value % i == 0)
            {
                result = false;
                break;
            }
        }

        if (value <= 1)
            result = false;

        return result;
    }`
</code>```

I would like to know if there's a way to show in the Numeric Up Down only prime numbers. I'm trying to make a crypthography work for university and I need give only prime numbers options for the user.

答:
here you have it :) it will show only prime numbers

```<code>private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
    //suposing you have this code
    int numrsa1 = (int)this.numericUpDown2.Value;

    //or add the rest 8 lines to your code
    if (IsPrimeNumber(numrsa1))
    {
        numericUpDown2.Value = numrsa1;
    }
    else
    {
        numericUpDown2.UpButton();
    }
}
</code>```

//the rest is your code without changes, I am using you function declaration IsPrimeNumber() in order to validate the number and print the result there. It will go up for the moment and show only a prime number by increasing in ascending order the value of the control.

This is a very simple solution I could test fast enough to post asap :)

Body:
    private void numericUpDown1_ValueChanged_1(object sender, EventArgs e)
    {
        //my numeric up down var name is numrsa1//
    }

    static bool IsPrimeNumber(int value)
    {
        bool result = true;

        for (int i = 2; i < value; i++)
        {
            if (value % i == 0)
            {
                result = false;
                break;
            }
        }

        if (value <= 1)
            result = false;

        return result;
    }`

I would like to know if there's a way to show in the Numeric Up Down only prime numbers. I'm trying to make a crypthography work for university and I need give only prime numbers options for the user.

Body:
here you have it :) it will show only prime numbers

private void numericUpDown2_ValueChanged(object sender, EventArgs e)
{
    //suposing you have this code
    int numrsa1 = (int)this.numericUpDown2.Value;

    //or add the rest 8 lines to your code
    if (IsPrimeNumber(numrsa1))
    {
        numericUpDown2.Value = numrsa1;
    }
    else
    {
        numericUpDown2.UpButton();
    }
}

//the rest is your code without changes, I am using you function declaration IsPrimeNumber() in order to validate the number and print the result there. It will go up for the moment and show only a prime number by increasing in ascending order the value of the control.

This is a very simple solution I could test fast enough to post asap :)


问:
How to QThread in PyQT
I am having a lot of trouble with my code - specifically, implementing some sort of signal/slot/threading. I am new to this and the things I read online have not been too helpful.

Anyways, I used PyQT Designer to make a simple GUI. This is what it is:

```<code>from PySide2 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(687, 514)
        self.browse_btn = QtWidgets.QPushButton(Dialog)
        self.browse_btn.setGeometry(QtCore.QRect(20, 440, 61, 27))
        self.browse_btn.setObjectName("browse_btn")
        self.play_btn = QtWidgets.QPushButton(Dialog)
        self.play_btn.setGeometry(QtCore.QRect(100, 440, 61, 27))
        self.play_btn.setObjectName("play_btn")
        self.cur_scene_header = QtWidgets.QTextEdit(Dialog)
        self.cur_scene_header.setGeometry(QtCore.QRect(20, 20, 191, 21))
        self.cur_scene_header.setObjectName("cur_scene_header")
        self.prev_scene_header = QtWidgets.QTextEdit(Dialog)
        self.prev_scene_header.setGeometry(QtCore.QRect(20, 90, 191, 21))
        self.prev_scene_header.setObjectName("prev_scene_header")
        self.pause_btn = QtWidgets.QPushButton(Dialog)
        self.pause_btn.setGeometry(QtCore.QRect(180, 440, 61, 27))
        self.pause_btn.setObjectName("pause_btn")
        self.reset_btn = QtWidgets.QPushButton(Dialog)
        self.reset_btn.setGeometry(QtCore.QRect(260, 440, 61, 27))
        self.reset_btn.setObjectName("reset_btn")
        self.prev_scenes = QtWidgets.QListWidget(Dialog)
        self.prev_scenes.setGeometry(QtCore.QRect(20, 120, 331, 301))
        self.prev_scenes.setObjectName("prev_scenes")
        self.current_scene = QtWidgets.QListWidget(Dialog)
        self.current_scene.setGeometry(QtCore.QRect(20, 50, 331, 31))
        self.current_scene.setObjectName("current_scene")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtWidgets.QApplication.translate("Dialog", "Dialog", None, -1))
        self.browse_btn.setText(QtWidgets.QApplication.translate("Dialog", "Browse", None, -1))
        self.play_btn.setText(QtWidgets.QApplication.translate("Dialog", "Play", None, -1))
        self.cur_scene_header.setHtml(QtWidgets.QApplication.translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Sans Serif\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Current Scene</p></body></html>", None, -1))
        self.prev_scene_header.setHtml(QtWidgets.QApplication.translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'Sans Serif\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Previous Scenes</p></body></html>", None, -1))
        self.pause_btn.setText(QtWidgets.QApplication.translate("Dialog", "Pause", None, -1))
        self.reset_btn.setText(QtWidgets.QApplication.translate("Dialog", "Reset", None, -1))
</code>```

Nothing really important there. There are four buttons: Browse, Play, Reset, and Pause. I have not yet immplemented the Reset and Pause buttons, but I will later on.

There are two QWidgetList. The first on, "curr_scene" (current scene), displays one string. The second one, "prev_scenes" is a list of previous scenes (past current_scenes).

When a user clicks the "Browse" button, they are allowed to choose a file (a csv file) using the TKinter filedialogue module. Once that is chosen, the program loads the content of the csv file. What I want to happen next is that it goes to the first row (of the csv file), puts that text in the current_scene List, then it waits fives seconds, sends that line to the previous_scene list, and then takes the next row from the csv file, puts it in current_scene, and so on, until it reaches the last one.

What is happening now is what I want - except it isn't displayed. It doesn't show that happening on the gui. I can only either get the prev_scene to display the text, or the current_scene to display the text, and not both, and this is done by using repaint.

I know I have to use Threading. But I really have no idea how. Can you show me? Here is the code for the rest of the program:

```<code>import sys
import PySide2
from PySide2.QtCore import *
from PySide2.QtWidgets import *
import pull_csv_data
import main
import time
from tkinter import filedialog

class MainDialog(QWidget, main.Ui_Dialog):

    def __init__(self, parent = None):
        super(MainDialog, self).__init__(parent)
        self.setupUi(self)

        self.connect(self.browse_btn, SIGNAL("clicked()"), self.browse_for_file)
        self.list = []
        self.connect(self.play_btn, SIGNAL("clicked()"), self.list_items)
        self.csv_path = ""
        self.file_watch = QFileSystemWatcher()

    def browse_for_file(self):
        if not self.list:
            self.csv_path = filedialog.askopenfilename()
            self.list = pull_csv_data.pull_data(self.csv_path)
            self.update_watcher()

    def update_watcher(self):
        self.file_watch.addPath(self.csv_path)
        self.file_watch.connect(self.file_watch, SIGNAL('fileChanged(QString)'), self.update_list)

    def update_list(self):
        print("here1")
        old_list = self.list
        self.list = pull_csv_data.pull_data(self.csv_path)
        print("here2")
        if len(old_list) < len(self.list):
            for i in range(len(old_list), len(self.list)):
                item = QListWidgetItem(self.list[i][0])
                self.prev_scenes.addItem(item)
                print("here6")
        else:
            self.list = pull_csv_data.pull_data(self.csv_path)
            self.prev_scenes.clear()
            for i in self.list:
                item = QListWidgetItem(i[0])
                self.prev_scenes.addItem(item)

    def list_items(self):
        if self.prev_scenes.count() == 0:
            for i in self.list:
                item = QListWidgetItem(i[0])
                self.update_current(item)

    def update_current(self, item):
        self.current_scene.addItem(item)
        time.sleep(0.5)
        self.update_prev(item)
        self.current_scene.clear()

    def update_prev(self, item):
        print("hello")
        self.prev_scenes.addItem(item)
        self.prev_scenes.repaint()
        self.prev_scenes.repaint()

app = QApplication(sys.argv)
form = MainDialog()
form.show()
sys.exit(app.exec_())
</code>```

Here is pull_csv_data:

```<code>def pull_data(file_path):
    king = []
    with open(file_path) as csvDataFile:
        csvReader = csv.reader(csvDataFile)
        for row in csvReader:
            king.append(row)
    return king
</code>```

答:
It is not recommended to combine libraries that perform the same task, and worse libraries that can be blocked as tkinter and Qt and both create an internal mainloop. Qt is a library that has components for many things and also has it to select files: QFileDialog.getOpenFileName()

```<code>def browse_for_file(self):
    if not self.list:
        self.csv_path, _ = QFileDialog.getOpenFileName()
        self.list = pull_csv_data.pull_data(self.csv_path)
        self.update_watcher()
</code>```

Another thing that should not be done is to do blocking tasks such as sleep(), these tasks do not let the GUI work, each GUI library proposes options for not having to use those functions, and in our case the combination of QEvenLoop with QTimer is the right option In addition you can not assign an item from one QListWidget to another, you must first remove it from one with takeItem() and assign it to the other:

```<code>def update_current(self, item):
    self.current_scene.addItem(item)
    loop = QEventLoop()
    QTimer.singleShot(500, loop.quit)
    loop.exec_()
    it = self.current_scene.takeItem(0)
    self.update_prev(it)

def update_prev(self, item):
    self.prev_scenes.addItem(item)
</code>```

Title: How to QThread in PyQT

Body:
I am having a lot of trouble with my code - specifically, implementing some sort of signal/slot/threading. I am new to this and the things I read online have not been too helpful.

Anyways, I used PyQT Designer to make a simple GUI. This is what it is:

from PySide2 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(687, 514)
        self.browse_btn = QtWidgets.QPushButton(Dialog)
        self.browse_btn.setGeometry(QtCore.QRect(20, 440, 61, 27))
        self.browse_btn.setObjectName("browse_btn")
        self.play_btn = QtWidgets.QPushButton(Dialog)
        self.play_btn.setGeometry(QtCore.QRect(100, 440, 61, 27))
        self.play_btn.setObjectName("play_btn")
        self.cur_scene_header = QtWidgets.QTextEdit(Dialog)
        self.cur_scene_header.setGeometry(QtCore.QRect(20, 20, 191, 21))
        self.cur_scene_header.setObjectName("cur_scene_header")
        self.prev_scene_header = QtWidgets.QTextEdit(Dialog)
        self.prev_scene_header.setGeometry(QtCore.QRect(20, 90, 191, 21))
        self.prev_scene_header.setObjectName("prev_scene_header")
        self.pause_btn = QtWidgets.QPushButton(Dialog)
        self.pause_btn.setGeometry(QtCore.QRect(180, 440, 61, 27))
        self.pause_btn.setObjectName("pause_btn")
        self.reset_btn = QtWidgets.QPushButton(Dialog)
        self.reset_btn.setGeometry(QtCore.QRect(260, 440, 61, 27))
        self.reset_btn.setObjectName("reset_btn")
        self.prev_scenes = QtWidgets.QListWidget(Dialog)
        self.prev_scenes.setGeometry(QtCore.QRect(20, 120, 331, 301))
        self.prev_scenes.setObjectName("prev_scenes")
        self.current_scene = QtWidgets.QListWidget(Dialog)
        self.current_scene.setGeometry(QtCore.QRect(20, 50, 331, 31))
        self.current_scene.setObjectName("current_scene")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtWidgets.QApplication.translate("Dialog", "Dialog", None, -1))
        self.browse_btn.setText(QtWidgets.QApplication.translate("Dialog", "Browse", None, -1))
        self.play_btn.setText(QtWidgets.QApplication.translate("Dialog", "Play", None, -1))
        self.cur_scene_header.setHtml(QtWidgets.QApplication.translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
Current Scene
", None, -1))
        self.prev_scene_header.setHtml(QtWidgets.QApplication.translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
Previous Scenes
", None, -1))
        self.pause_btn.setText(QtWidgets.QApplication.translate("Dialog", "Pause", None, -1))
        self.reset_btn.setText(QtWidgets.QApplication.translate("Dialog", "Reset", None, -1))

Nothing really important there. There are four buttons: Browse, Play, Reset, and Pause. I have not yet immplemented the Reset and Pause buttons, but I will later on.

There are two QWidgetList. The first on, "curr_scene" (current scene), displays one string. The second one, "prev_scenes" is a list of previous scenes (past current_scenes).

When a user clicks the "Browse" button, they are allowed to choose a file (a csv file) using the TKinter filedialogue module. Once that is chosen, the program loads the content of the csv file. What I want to happen next is that it goes to the first row (of the csv file), puts that text in the current_scene List, then it waits fives seconds, sends that line to the previous_scene list, and then takes the next row from the csv file, puts it in current_scene, and so on, until it reaches the last one.

What is happening now is what I want - except it isn't displayed. It doesn't show that happening on the gui. I can only either get the prev_scene to display the text, or the current_scene to display the text, and not both, and this is done by using repaint.

I know I have to use Threading. But I really have no idea how. Can you show me? Here is the code for the rest of the program:

import sys
import PySide2
from PySide2.QtCore import *
from PySide2.QtWidgets import *
import pull_csv_data
import main
import time
from tkinter import filedialog

class MainDialog(QWidget, main.Ui_Dialog):

    def __init__(self, parent = None):
        super(MainDialog, self).__init__(parent)
        self.setupUi(self)

        self.connect(self.browse_btn, SIGNAL("clicked()"), self.browse_for_file)
        self.list = []
        self.connect(self.play_btn, SIGNAL("clicked()"), self.list_items)
        self.csv_path = ""
        self.file_watch = QFileSystemWatcher()

    def browse_for_file(self):
        if not self.list:
            self.csv_path = filedialog.askopenfilename()
            self.list = pull_csv_data.pull_data(self.csv_path)
            self.update_watcher()

    def update_watcher(self):
        self.file_watch.addPath(self.csv_path)
        self.file_watch.connect(self.file_watch, SIGNAL('fileChanged(QString)'), self.update_list)

    def update_list(self):
        print("here1")
        old_list = self.list
        self.list = pull_csv_data.pull_data(self.csv_path)
        print("here2")
        if len(old_list) < len(self.list):
            for i in range(len(old_list), len(self.list)):
                item = QListWidgetItem(self.list[i][0])
                self.prev_scenes.addItem(item)
                print("here6")
        else:
            self.list = pull_csv_data.pull_data(self.csv_path)
            self.prev_scenes.clear()
            for i in self.list:
                item = QListWidgetItem(i[0])
                self.prev_scenes.addItem(item)

    def list_items(self):
        if self.prev_scenes.count() == 0:
            for i in self.list:
                item = QListWidgetItem(i[0])
                self.update_current(item)

    def update_current(self, item):
        self.current_scene.addItem(item)
        time.sleep(0.5)
        self.update_prev(item)
        self.current_scene.clear()

    def update_prev(self, item):
        print("hello")
        self.prev_scenes.addItem(item)
        self.prev_scenes.repaint()
        self.prev_scenes.repaint()

app = QApplication(sys.argv)
form = MainDialog()
form.show()
sys.exit(app.exec_())

Here is pull_csv_data:

def pull_data(file_path):
    king = []
    with open(file_path) as csvDataFile:
        csvReader = csv.reader(csvDataFile)
        for row in csvReader:
            king.append(row)
    return king

Body:
It is not recommended to combine libraries that perform the same task, and worse libraries that can be blocked as tkinter and Qt and both create an internal mainloop. Qt is a library that has components for many things and also has it to select files: QFileDialog.getOpenFileName()

def browse_for_file(self):
    if not self.list:
        self.csv_path, _ = QFileDialog.getOpenFileName()
        self.list = pull_csv_data.pull_data(self.csv_path)
        self.update_watcher()

Another thing that should not be done is to do blocking tasks such as sleep(), these tasks do not let the GUI work, each GUI library proposes options for not having to use those functions, and in our case the combination of QEvenLoop with QTimer is the right option In addition you can not assign an item from one QListWidget to another, you must first remove it from one with takeItem() and assign it to the other:

def update_current(self, item):
    self.current_scene.addItem(item)
    loop = QEventLoop()
    QTimer.singleShot(500, loop.quit)
    loop.exec_()
    it = self.current_scene.takeItem(0)
    self.update_prev(it)

def update_prev(self, item):
    self.prev_scenes.addItem(item)


问:
MKMapView's scale is not shown
I'm doing an iOS application. In Xcode 9.1 I create a MKMapView by

```<code>let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
mapView.isUserInteractionEnabled = false
mapView.mapType = .satellite
mapView.showsCompass = false
mapView.showsScale = true
view.addSubview(mapView)
</code>```

but when I run it in the simulator the scale is not shown and I get three messages in the log:

Could not inset compass from edges 9

Could not inset scale from edge 9

Could not inset legal attribution from corner 4

The compass is not shown (as expected) but it's not shown if I change mapView.showsCompass to trueeither. However, the Legal link is shown. What am I missing here? I'm guessing it's something about the new safe areas introduced with iOS 11, but I fail to see how that is important for a view I want to be covering the whole screen.

答:
In iOS 10 or lower

As @Paulw11 says, the scale is only shown while zooming by default.

In iOS 11

You can use scaleVisibility.
https://developer.apple.com/documentation/mapkit/mkscaleview/2890254-scalevisibility

```<code>let scale = MKScaleView(mapView: mapView)
scale.scaleVisibility = .visible // always visible
view.addSubview(scale)
</code>```

Title: MKMapView's scale is not shown

Body:
I'm doing an iOS application. In Xcode 9.1 I create a MKMapView by

let mapView = MKMapView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))
mapView.isUserInteractionEnabled = false
mapView.mapType = .satellite
mapView.showsCompass = false
mapView.showsScale = true
view.addSubview(mapView)

but when I run it in the simulator the scale is not shown and I get three messages in the log:

Could not inset compass from edges 9

Could not inset scale from edge 9

Could not inset legal attribution from corner 4

The compass is not shown (as expected) but it's not shown if I change mapView.showsCompass to trueeither. However, the Legal link is shown. What am I missing here? I'm guessing it's something about the new safe areas introduced with iOS 11, but I fail to see how that is important for a view I want to be covering the whole screen.

Body:
In iOS 10 or lower

As @Paulw11 says, the scale is only shown while zooming by default.

In iOS 11

You can use scaleVisibility.
https://developer.apple.com/documentation/mapkit/mkscaleview/2890254-scalevisibility

let scale = MKScaleView(mapView: mapView)
scale.scaleVisibility = .visible // always visible
view.addSubview(scale)


问:
Java code style for open stream try/finally block
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

```<code>InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}
</code>```

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

```<code>InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}
</code>```

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

答:
I would use

```<code> InputStream in = null;
 try {
     in = acquireStream();
     ...
 } finally {
     if (in != null) in.close();
 }
</code>```

if aquireStream() throws any checked exception and I am planning to handle it.

Else, I will use this

```<code>InputStream in = acquireStream();
try {
     ...
} finally {
     in.close();
}
</code>```

on NPE:

I would rather let NPE to propagate and not handle any run-time exception.

Body:
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

Body:
I would use

 InputStream in = null;
 try {
     in = acquireStream();
     ...
 } finally {
     if (in != null) in.close();
 }

if aquireStream() throws any checked exception and I am planning to handle it.

Else, I will use this

InputStream in = acquireStream();
try {
     ...
} finally {
     in.close();
}

on NPE:

I would rather let NPE to propagate and not handle any run-time exception.


问:
How to convert varchar to datetime in SQL Server
I would like to convert varchar data to datetime format. So, can anyone let me know the way. this is the sample data available in column.

I tried following things

```<code>SELECT
    CASE WHEN [EntryTime] = ''
       THEN NULL
       ELSE CONVERT(datetime2, [EntryTime])
    END [EntryTime]
FROM
    table
</code>```

I get this result:

But, I don't need additional milliseconds.

So, can anyone let me know how should I convert it to a datetime format?

For all other tries, I am getting error as

Conversion failed when converting date and/or time from character string

So, can anyone please help me? Thanks.

Body:
I would like to convert varchar data to datetime format. So, can anyone let me know the way. this is the sample data available in column.

I tried following things

SELECT
    CASE WHEN [EntryTime] = ''
       THEN NULL
       ELSE CONVERT(datetime2, [EntryTime])
    END [EntryTime]
FROM
    table

I get this result:

But, I don't need additional milliseconds.

So, can anyone let me know how should I convert it to a datetime format?

For all other tries, I am getting error as

Conversion failed when converting date and/or time from character string

So, can anyone please help me? Thanks.

Body:
LEFT and Concat (SQL2012+)/ or use standard concatenation
then Cast or Convert (for formatting)

declare @mytable as table (
entrytime varchar(100)
)

insert into @mytable
values ('2017-08-31 08:23:23'),
('2017-11-10 08:28:37.75000000'),
('2017-10-30 08:23:37.32000000')

select cast(left(concat(entrytime,'.000'),23) as datetime) from @mytable

Result

2017-08-31 08:23:23.000
2017-11-10 08:28:37.750
2017-10-30 08:23:37.320


问:
How to run filter on demand scala play framework
I'm developing a scala application with play frame work, i have created a filter that filters every request coming from outside server,but now i'm stuck on how can i run a filter on demand since two days,i have 80 APIs 30 of them needs to run a specific filter, how can i read the request route template while the requests like this

```<code> GET /api/v1/:locale/:uuid core.controllers.MyClass.myAction1(locale: String)
 GET /api/v1/:locale/:uuid/MyRoute core.controllers.MyClass.myAction2(locale: String)
 GET /api/v1/:locale/:uuid/Foo core.controllers.MyClass.myAction3(locale: String)
 GET /api/v1/:locale/orders/:orderId core.controllers.MyClass.myAction4(locale: String)
</code>```

well, those routes are placed in routes file,
in filter i need to check weather if the route has :uuid variable or :orderId in order to run its specific filter, because both of their ids, i getting them as uuid so i couldn't expect the request, could i read the route template ?

答:
If you want to choose 30 out of 80 actions to run some common logic, you could also consider using "action builders" to provide that logic.

When you use Action { ... } you get a vanilla action. You can also make your own MyAction { ... } that wraps a normal Action and runs custom logic. This is an ActionBuilder. If you use this approach you just need to update your 30 actions to use that custom action builder.

See: https://www.playframework.com/documentation/2.6.x/ScalaActionsComposition#Custom-action-builders

Body:
I'm developing a scala application with play frame work, i have created a filter that filters every request coming from outside server,but now i'm stuck on how can i run a filter on demand since two days,i have 80 APIs 30 of them needs to run a specific filter, how can i read the request route template while the requests like this

 GET /api/v1/:locale/:uuid core.controllers.MyClass.myAction1(locale: String)
 GET /api/v1/:locale/:uuid/MyRoute core.controllers.MyClass.myAction2(locale: String)
 GET /api/v1/:locale/:uuid/Foo core.controllers.MyClass.myAction3(locale: String)
 GET /api/v1/:locale/orders/:orderId core.controllers.MyClass.myAction4(locale: String)

well, those routes are placed in routes file,
in filter i need to check weather if the route has :uuid variable or :orderId in order to run its specific filter, because both of their ids, i getting them as uuid so i couldn't expect the request, could i read the route template ?


问:
How to develop performance benchmark program
Probably everybody heard about different software used to measure performance of the hardware it is running on. I mean stuff like Windows Experience Rating, PCMark, Futuremark and so on. They are measuring different aspects of computer performance: CPU and GPU speed, memory access time, disk access time, and so on.

Could anybody explain how to develop such program, so it's result would be reliable? CPU, memory and disk access speed are of most importance for me, GPU and other stuff is not necessary. I suppose, there could be plenty of caveats there, like multi-core CPU, or CPU with dynamic frequency. Or different read and write speed in different sectors of HDD. Or something else.

I'd appreciate information about different aspects, not necessarily about all of what I mentioned, though it would be great.

P.S. I'm interested mostly in Windows environment, if it matters. But probably not.

答:
I am working on something similar myself for my role at work.  I have a few tests for CPU Integer performance, one of which is a Mersenne Prime search.  This can double up as a load/stability test for the CPU.  The legendary stability testing software Prime95 was using Mersenne prime searches.

I found this Microsoft samples site to be incredibly helpful.  I modified this Mersenne Prime search for my needs, but it works out of the box:

https://code.msdn.microsoft.com/BigInteger-Multitasking-eb319df1

When testing a CPU you also want to test floating point operations, haven't yet found anything useful on those, but will update this post if I do.

There was also a helpful comment on a similar question about testing RAM here:

Benchmarking RAM performance - UWP and C#


问:
Selenium or Watir for Javascript Testing in Rails
We're using RSpec and Cucumber in our Rails apps with good results. Webrat is great for non-AJAX interactions, but we're getting ready to get back into writing tests for our Javascript.

Webrat has Selenium support built in, and we've used Selenium before, but I'm curious if anyone has had good results using Watir with Cucumber and what the pros and cons are of Watir versus Selenium.

答:
You may want to try WebDriver. It will become part of Selenium in the future. Works with JRuby.

It is different than Selenium, Sahi or Watir in the way that it controls the browser natively, not using JavaScript, and is not affected by many issues other solutions have.

OwnerDisplayName: Abie

LastEditorDisplayName: Abie


问:
generic call of class in c#
```<code>SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
</code>```

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

```<code>if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...
</code>```

i want to make something like

```<code>(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...
</code>```

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.

答:
I would investigate using a factory class to create your query managers.

Pseudo-code:

```<code>var factory= new QueryManagerFactory();
var queryManager = factory.Create("Slovenian");
</code>```

In your factory create method return the type of query manager you want based upon the input.

Title: generic call of class in c#

Body:
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...

i want to make something like

(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.

Body:
I would investigate using a factory class to create your query managers.

Pseudo-code:

var factory= new QueryManagerFactory();
var queryManager = factory.Create("Slovenian");

In your factory create method return the type of query manager you want based upon the input.

ContentLicense: CC BY-SA 4.0


问:
pandas python replace column values
Suppose that I have a data frame with a column a: 1, 2, 3, 4, 5, .... How can I replace the values so that every number is 1 less (new a is 0, 1, 2, 3, 4). Thank you all.

Title: pandas python replace column values

Body:
Just += 1:

In [11]: df = pd.DataFrame({'a': [1, 2, 3, 4, 5]})

In [12]: df
Out[12]:
   a
0  1
1  2
2  3
3  4
4  5

In [13]: df['a'] += 1

In [14]: df
Out[14]:
   a
0  2
1  3
2  4
3  5
4  6


问:
mysqld performance high cpu and memory usage
I appreciate if you can help with the mysqld performance problem as seen below. top shows 2 mysqld with 99% cpu usage and 73% mem usage.

I have 6CPU's and 8GB of RAM in total. You can easily see the CPU's performance in last 24h.

I am sending the mysql tuner's output as well.

CPU usage 24h

top output

--> mysqltuner output:

```<code>[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 10.1.24-MariaDB
[OK] Operating on 64-bit architecture

-------- Log file Recommendations ------------------------------------------------------------------
[--] Log file: (0B)
[!!] Log file  doesn't exist
[!!] Log file  isn't readable.

-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +Aria +CSV +InnoDB +MEMORY +MRG_MyISAM +MyISAM +PERFORMANCE_SCHEMA +SEQUENCE
[--] Data in InnoDB tables: 15G (Tables: 121)
[--] Data in MEMORY tables: 0B (Tables: 2)
[OK] Total fragmented tables: 0

-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] User 'kepmark_readonly@%' hasn't specific host restriction.
[!!] User 'kpm_zeus_fsm@%' hasn't specific host restriction.
[!!] User 'root@%' hasn't specific host restriction.
[--] There are 612 basic passwords in the list.

-------- CVE Security Recommendations --------------------------------------------------------------
[OK] NO SECURITY CVE FOUND FOR YOUR VERSION

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 11d 19h 19m 33s (37M q [36.944 qps], 3M conn, TX: 30G, RX: 3G)
[--] Reads / Writes: 50% / 50%
[--] Binary logging is disabled
[--] Physical Memory     : 11.7G
[--] Max MySQL memory    : 8.7G
[--] Other process memory: 702.6M
[--] Total buffers: 8.3G global + 2.9M per thread (151 max threads)
[--] P_S Max memory usage: 0B
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 8.5G (72.61% of installed RAM)
[OK] Maximum possible memory usage: 8.7G (74.32% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (18K/37M)
[OK] Highest usage of available connections: 52% (80/151)
[OK] Aborted connections: 0.35%  (10593/3009097)
[!!] Query cache may be disabled by default due to mutex contention.
[!!] Query cache efficiency: 0.0% (0 cached / 16M selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (165 temp sorts / 34K sorts)
[OK] No joins without indexes
[OK] Temporary tables created on disk: 0% (1K on disk / 4M total)
[!!] Thread cache is disabled
[!!] Table cache hit rate: 11% (398 open / 3K opened)
[OK] Open file limit used: 0% (66/16K)
[OK] Table locks acquired immediately: 99% (41M immediate / 41M locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Performance schema is disabled.
[--] Memory used by P_S: 0B
[--] Sys schema isn't installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is enabled.
[--] Thread Pool Size: 6 thread(s).
[--] Using default value is good enough for your version (10.1.24-MariaDB)

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.2% (24M used / 134M cache)
[OK] Key buffer size / total MyISAM indexes: 128.0M/126.0K
[OK] Read Key buffer hit rate: 100.0% (709K cached / 50 reads)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[!!] InnoDB buffer pool / data size: 8.0G/15.2G
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (1.171875 %): 48.0M * 2/8.0G should be equal 25%
[!!] InnoDB buffer pool instances: 6
[--] InnoDB Buffer Pool Chunk Size not used or defined in your version
[OK] InnoDB Read buffer efficiency: 100.00% (299698901815 hits/ 299706339317 total)
[!!] InnoDB Write Log efficiency: 22.18% (1601644 hits/ 7221004 total)
[OK] InnoDB log waits: 0.00% (0 waits / 5619360 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is enabled.
[OK] Aria pagecache size / total Aria indexes: 128.0M/1B
[!!] Aria pagecache hit rate: 75.8% (4K cached / 1K reads)

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] This is a standalone server.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Restrict Host for user@% to user@SpecificDNSorIp
    Set thread_cache_size to 4 as a starting value
    Increase table_open_cache gradually to avoid file descriptor limits
    Read this before increasing table_open_cache over 64:
    Beware that open_files_limit (16364) variable
    should be greater than table_open_cache (2000)
    Performance should be activated for better diagnostics
    Consider installing Sys schema from https://github.com/mysql/mysql-sys
Variables to adjust:
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_limit (> 4M, or use smaller result sets)
    thread_cache_size (start at 4)
    table_open_cache (> 2000)
    performance_schema = ON enable PFS
    innodb_buffer_pool_size (>= 15G) if possible.
    innodb_log_file_size * innodb_log_files_in_group should be equal to 1/4 of buffer pool size (=4G) if possible.
    innodb_buffer_pool_instances(=8)
</code>```

答:
"99% cpu usage" -- "You cannot tune your way out of a performance problem."

So, find the slowest query.  Fix it.  Rinse and repeat.  After (usually) 2-3 queries, the CPU will drop to maybe 10%.

How to find them?  Turn on the slowlog, with long_query_time=1.

How to fix the queries?  Show us a query and EXPLAIN ... and SHOW CREATE TABLE.  Meanwhile, read about 'composite' indexes.

(73% mem usage is OK.)

Body:
I appreciate if you can help with the mysqld performance problem as seen below. top shows 2 mysqld with 99% cpu usage and 73% mem usage.

I have 6CPU's and 8GB of RAM in total. You can easily see the CPU's performance in last 24h.

I am sending the mysql tuner's output as well.

CPU usage 24h

top output

--> mysqltuner output:

[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 10.1.24-MariaDB
[OK] Operating on 64-bit architecture

-------- Log file Recommendations ------------------------------------------------------------------
[--] Log file: (0B)
[!!] Log file  doesn't exist
[!!] Log file  isn't readable.

-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +Aria +CSV +InnoDB +MEMORY +MRG_MyISAM +MyISAM +PERFORMANCE_SCHEMA +SEQUENCE
[--] Data in InnoDB tables: 15G (Tables: 121)
[--] Data in MEMORY tables: 0B (Tables: 2)
[OK] Total fragmented tables: 0

-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] User 'kepmark_readonly@%' hasn't specific host restriction.
[!!] User 'kpm_zeus_fsm@%' hasn't specific host restriction.
[!!] User 'root@%' hasn't specific host restriction.
[--] There are 612 basic passwords in the list.

-------- CVE Security Recommendations --------------------------------------------------------------
[OK] NO SECURITY CVE FOUND FOR YOUR VERSION

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 11d 19h 19m 33s (37M q [36.944 qps], 3M conn, TX: 30G, RX: 3G)
[--] Reads / Writes: 50% / 50%
[--] Binary logging is disabled
[--] Physical Memory     : 11.7G
[--] Max MySQL memory    : 8.7G
[--] Other process memory: 702.6M
[--] Total buffers: 8.3G global + 2.9M per thread (151 max threads)
[--] P_S Max memory usage: 0B
[--] Galera GCache Max memory usage: 0B
[OK] Maximum reached memory usage: 8.5G (72.61% of installed RAM)
[OK] Maximum possible memory usage: 8.7G (74.32% of installed RAM)
[OK] Overall possible memory usage with other process is compatible with memory available
[OK] Slow queries: 0% (18K/37M)
[OK] Highest usage of available connections: 52% (80/151)
[OK] Aborted connections: 0.35%  (10593/3009097)
[!!] Query cache may be disabled by default due to mutex contention.
[!!] Query cache efficiency: 0.0% (0 cached / 16M selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (165 temp sorts / 34K sorts)
[OK] No joins without indexes
[OK] Temporary tables created on disk: 0% (1K on disk / 4M total)
[!!] Thread cache is disabled
[!!] Table cache hit rate: 11% (398 open / 3K opened)
[OK] Open file limit used: 0% (66/16K)
[OK] Table locks acquired immediately: 99% (41M immediate / 41M locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Performance schema is disabled.
[--] Memory used by P_S: 0B
[--] Sys schema isn't installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is enabled.
[--] Thread Pool Size: 6 thread(s).
[--] Using default value is good enough for your version (10.1.24-MariaDB)

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.2% (24M used / 134M cache)
[OK] Key buffer size / total MyISAM indexes: 128.0M/126.0K
[OK] Read Key buffer hit rate: 100.0% (709K cached / 50 reads)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[!!] InnoDB buffer pool / data size: 8.0G/15.2G
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (1.171875 %): 48.0M * 2/8.0G should be equal 25%
[!!] InnoDB buffer pool instances: 6
[--] InnoDB Buffer Pool Chunk Size not used or defined in your version
[OK] InnoDB Read buffer efficiency: 100.00% (299698901815 hits/ 299706339317 total)
[!!] InnoDB Write Log efficiency: 22.18% (1601644 hits/ 7221004 total)
[OK] InnoDB log waits: 0.00% (0 waits / 5619360 writes)

-------- AriaDB Metrics ----------------------------------------------------------------------------
[--] AriaDB is enabled.
[OK] Aria pagecache size / total Aria indexes: 128.0M/1B
[!!] Aria pagecache hit rate: 75.8% (4K cached / 1K reads)

-------- TokuDB Metrics ----------------------------------------------------------------------------
[--] TokuDB is disabled.

-------- XtraDB Metrics ----------------------------------------------------------------------------
[--] XtraDB is disabled.

-------- RocksDB Metrics ---------------------------------------------------------------------------
[--] RocksDB is disabled.

-------- Spider Metrics ----------------------------------------------------------------------------
[--] Spider is disabled.

-------- Connect Metrics ---------------------------------------------------------------------------
[--] Connect is disabled.

-------- Galera Metrics ----------------------------------------------------------------------------
[--] Galera is disabled.

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] This is a standalone server.

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Restrict Host for user@% to user@SpecificDNSorIp
    Set thread_cache_size to 4 as a starting value
    Increase table_open_cache gradually to avoid file descriptor limits
    Read this before increasing table_open_cache over 64:
    Beware that open_files_limit (16364) variable
    should be greater than table_open_cache (2000)
    Performance should be activated for better diagnostics
    Consider installing Sys schema from https://github.com/mysql/mysql-sys
Variables to adjust:
    query_cache_size (=0)
    query_cache_type (=0)
    query_cache_limit (> 4M, or use smaller result sets)
    thread_cache_size (start at 4)
    table_open_cache (> 2000)
    performance_schema = ON enable PFS
    innodb_buffer_pool_size (>= 15G) if possible.
    innodb_log_file_size * innodb_log_files_in_group should be equal to 1/4 of buffer pool size (=4G) if possible.
    innodb_buffer_pool_instances(=8)


问:
Python list manipulation and comparison of lists
I am having a bit of trouble working out some code to update ranking points for player scores in a game with the use of lists. The first list I have is a list of positions that the players came in, for example:

```<code>results = [P2, P4, P3, P1, P5, P6]
</code>```

This list is in descending order (P2 came first, P4 came second etc) and is determined by other code that I have in the program. The second list I have is a list of ranking points that I want to assign to each player based on their position:

```<code>rankingPoints = [100, 50, 25, 10, 5, 0]
</code>```

(P2 would get 100, P4 would get 50, etc)

Lastly, I have a third list that contains nested lists for each player:

```<code>playerRank = [[P1], [P2], [P3], [P4], [P5], [P6]]
</code>```

Basically what I'm wanting to do is initialize each player in the 'playerRank' list with '0' ranking score (The players are read into the list from a csv file and I cannot initialize them with '0' manually) so that it looks something like this: [[P1, 0], [P2, 0], [P3, 0]] etc.

Then based on their position in the game, add the appropriate amount of ranking score to their current ranking score (there will be multiple games so ranking score will be constantly added on top of current ranking score for players), the desired outcome will look something like:

```<code>playerRank = [[P1, 10] [P2, 100], [P3, 25], [P4, 50], [P5, 5], [P6, 0]]
</code>```

Any help on this would be greatly appreciated as I am new to programming and struggling to work out the code and logic behind it

Thanks

答:
If you want to initialize your players ranks in the beginning and update them whenever is necessary, you can do something like this:

```<code>def updateScore(playerRank, rankingPoints):
    for ind, i in enumerate(rankingPoints):
        playerRank[ind][1] = playerRank[ind][1] + rankingPoints[ind]

results = ['P2', 'P4', 'P3', 'P1', 'P5', 'P6']
rankingPoints = [100, 50, 25, 10, 5, 0]

print("Initializing player ranks...")
playerRank = [[results[i],0] for i in range(0,len(results))]
print(playerRank)

print("Updating scores...")
updateScore(playerRank, rankingPoints)
playerRank = sorted(playerRank)
print(playerRank)
</code>```

Output:

```<code> Initializing player ranks...
[['P2', 0], ['P4', 0], ['P3', 0], ['P1', 0], ['P5', 0], ['P6', 0]]
Updating scores...
[['P1', 10], ['P2', 100], ['P3', 25], ['P4', 50], ['P5', 5], ['P6', 0]]
</code>```

You can call updateScore any time you want to update your players ranks.

Body:
I am having a bit of trouble working out some code to update ranking points for player scores in a game with the use of lists. The first list I have is a list of positions that the players came in, for example:

results = [P2, P4, P3, P1, P5, P6]

This list is in descending order (P2 came first, P4 came second etc) and is determined by other code that I have in the program. The second list I have is a list of ranking points that I want to assign to each player based on their position:

rankingPoints = [100, 50, 25, 10, 5, 0]

(P2 would get 100, P4 would get 50, etc)

Lastly, I have a third list that contains nested lists for each player:

playerRank = [[P1], [P2], [P3], [P4], [P5], [P6]]

Basically what I'm wanting to do is initialize each player in the 'playerRank' list with '0' ranking score (The players are read into the list from a csv file and I cannot initialize them with '0' manually) so that it looks something like this: [[P1, 0], [P2, 0], [P3, 0]] etc.

Then based on their position in the game, add the appropriate amount of ranking score to their current ranking score (there will be multiple games so ranking score will be constantly added on top of current ranking score for players), the desired outcome will look something like:

playerRank = [[P1, 10] [P2, 100], [P3, 25], [P4, 50], [P5, 5], [P6, 0]]

Any help on this would be greatly appreciated as I am new to programming and struggling to work out the code and logic behind it

Thanks

Body:
If you want to initialize your players ranks in the beginning and update them whenever is necessary, you can do something like this:

def updateScore(playerRank, rankingPoints):
    for ind, i in enumerate(rankingPoints):
        playerRank[ind][1] = playerRank[ind][1] + rankingPoints[ind]

results = ['P2', 'P4', 'P3', 'P1', 'P5', 'P6']
rankingPoints = [100, 50, 25, 10, 5, 0]

print("Initializing player ranks...")
playerRank = [[results[i],0] for i in range(0,len(results))]
print(playerRank)

print("Updating scores...")
updateScore(playerRank, rankingPoints)
playerRank = sorted(playerRank)
print(playerRank)

Output:

 Initializing player ranks...
[['P2', 0], ['P4', 0], ['P3', 0], ['P1', 0], ['P5', 0], ['P6', 0]]
Updating scores...
[['P1', 10], ['P2', 100], ['P3', 25], ['P4', 50], ['P5', 5], ['P6', 0]]

You can call updateScore any time you want to update your players ranks.


问:
Javascript only working in Firebug
I am using jQuery UI to build tabs on my page. That works well until I add this following piece of code.

```<code>$(function () {
    $('#tabs').children("div").each(function (index) {
        $('#tabs').tabs('load', index);
    });
});
</code>```

I'm trying to preload the tabs. What is interesting, is that if i run this through Firebug and put a breakpoint in that piece of code and step through, the code works perfectly. Otherwise the tabs are rendered, but the content within the tabs is not. This issue has been driving me crazy! Can anyone help?

答:
pretty simple solution - if you have any console.log(s) in your source, in Firefox this will break your application if Firebug is turned off.

You can do 2 things:

remove all console.logs(s) from your source by hand

better, use a little toConsole wrapper function, so that there is only one location where you have console.log in your code, so you can easily turn it off when you're finished with debugging:

```<code>toConsole: function( obj ) { console.log( obj ); }
</code>```

Title: Javascript only working in Firebug

Body:
I am using jQuery UI to build tabs on my page. That works well until I add this following piece of code.

$(function () {
    $('#tabs').children("div").each(function (index) {
        $('#tabs').tabs('load', index);
    });
});

I'm trying to preload the tabs. What is interesting, is that if i run this through Firebug and put a breakpoint in that piece of code and step through, the code works perfectly. Otherwise the tabs are rendered, but the content within the tabs is not. This issue has been driving me crazy! Can anyone help?

Body:
pretty simple solution - if you have any console.log(s) in your source, in Firefox this will break your application if Firebug is turned off.

You can do 2 things:

remove all console.logs(s) from your source by hand

better, use a little toConsole wrapper function, so that there is only one location where you have console.log in your code, so you can easily turn it off when you're finished with debugging:

toConsole: function( obj ) { console.log( obj ); }


问:
Why do I get empty reponse from this http request
I am working on my first node.js script which simply makes a http request to https://www.swapi.co/api/people/?search=Luke+ and parses the response data.

The endpoint is as follows:

```<code>var options = {
  host: 'www.swapi.co',
  path: `/api/people/?search=`+firstName+'+'+lastName
};
</code>```

The logic is to get the data from response and parse it to a person object:

```<code>makeRequest(options, function( data, error) {
    let person = data.results[0];
    if (person) {
        let height = person.height;
        let response = person.name + " is " + height + " centimeters tall.";
        callback(null, {"speech": response});
    }
    else {
        callback(null, {"speech": "I'm not sure!"});
    }
  });
</code>```

The definition of makerequest function is below:

```<code>function makeRequest(options, callback) {
    var request = http.request(options,
    function(response) {
        var responseString = '';
        response.on('data', function(data) {
            responseString += data;
        });
         response.on('end', function() {
            console.log('end: $$$' + responseString + '$$$');
            var responseJSON = JSON.parse(responseString);
            callback(responseJSON, null);
        });
    });
    request.end();
}
</code>```

When I run the script I got the error about parsing the JSON.

```<code>Unexpected end of JSON input
    at Object.parse (native)
    at IncomingMessage.<anonymous> (/var/task/index.js:42:37)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
</code>```

I tested the endpoint using Postman and got the following JSON as response:

```<code>{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "name": "Luke Skywalker",
            "height": "172",
            "mass": "77",
            "hair_color": "blond",
            "skin_color": "fair",
            "eye_color": "blue",
            "birth_year": "19BBY",
            "gender": "male",
            "homeworld": "https://www.swapi.co/api/planets/1/",
            "films": [
                "https://www.swapi.co/api/films/2/",
                "https://www.swapi.co/api/films/6/",
                "https://www.swapi.co/api/films/3/",
                "https://www.swapi.co/api/films/1/",
                "https://www.swapi.co/api/films/7/"
            ],
            "species": [
                "https://www.swapi.co/api/species/1/"
            ],
            "vehicles": [
                "https://www.swapi.co/api/vehicles/14/",
                "https://www.swapi.co/api/vehicles/30/"
            ],
            "starships": [
                "https://www.swapi.co/api/starships/12/",
                "https://www.swapi.co/api/starships/22/"
            ],
            "created": "2014-12-09T13:50:51.644000Z",
            "edited": "2014-12-20T21:17:56.891000Z",
            "url": "https://www.swapi.co/api/people/1/"
        }
    ]
}
</code>```

However, when I debug my code, the response data is an empty string. And that explains the JSON error.

What is wrong with my http request? Why am I not getting the correct response?

答:
It appears that the API you are targeting only supports SSL, but Node's HTTP library only supports plain-text requests. Try using their HTTPS library instead.</p>

```<code>var https = require('https');
var request = https.request(options, ...);
</code>```

Body:
I am working on my first node.js script which simply makes a http request to https://www.swapi.co/api/people/?search=Luke+ and parses the response data.

The endpoint is as follows:

var options = {
  host: 'www.swapi.co',
  path: `/api/people/?search=`+firstName+'+'+lastName
};

The logic is to get the data from response and parse it to a person object:

makeRequest(options, function( data, error) {
    let person = data.results[0];
    if (person) {
        let height = person.height;
        let response = person.name + " is " + height + " centimeters tall.";
        callback(null, {"speech": response});
    }
    else {
        callback(null, {"speech": "I'm not sure!"});
    }
  });

The definition of makerequest function is below:

function makeRequest(options, callback) {
    var request = http.request(options,
    function(response) {
        var responseString = '';
        response.on('data', function(data) {
            responseString += data;
        });
         response.on('end', function() {
            console.log('end: $$$' + responseString + '$$$');
            var responseJSON = JSON.parse(responseString);
            callback(responseJSON, null);
        });
    });
    request.end();
}

When I run the script I got the error about parsing the JSON.

Unexpected end of JSON input
    at Object.parse (native)
    at IncomingMessage.<anonymous> (/var/task/index.js:42:37)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)

I tested the endpoint using Postman and got the following JSON as response:

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "name": "Luke Skywalker",
            "height": "172",
            "mass": "77",
            "hair_color": "blond",
            "skin_color": "fair",
            "eye_color": "blue",
            "birth_year": "19BBY",
            "gender": "male",
            "homeworld": "https://www.swapi.co/api/planets/1/",
            "films": [
                "https://www.swapi.co/api/films/2/",
                "https://www.swapi.co/api/films/6/",
                "https://www.swapi.co/api/films/3/",
                "https://www.swapi.co/api/films/1/",
                "https://www.swapi.co/api/films/7/"
            ],
            "species": [
                "https://www.swapi.co/api/species/1/"
            ],
            "vehicles": [
                "https://www.swapi.co/api/vehicles/14/",
                "https://www.swapi.co/api/vehicles/30/"
            ],
            "starships": [
                "https://www.swapi.co/api/starships/12/",
                "https://www.swapi.co/api/starships/22/"
            ],
            "created": "2014-12-09T13:50:51.644000Z",
            "edited": "2014-12-20T21:17:56.891000Z",
            "url": "https://www.swapi.co/api/people/1/"
        }
    ]
}

However, when I debug my code, the response data is an empty string. And that explains the JSON error.

What is wrong with my http request? Why am I not getting the correct response?

Body:
It appears that the API you are targeting only supports SSL, but Node's HTTP library only supports plain-text requests. Try using their HTTPS library instead.

var https = require('https');
var request = https.request(options, ...);