问:
StringBuilder.append() causes java.lang.NullPointerException
I'm experiencing a strange issue using the append() method of StringBuilder class; here is the method:

```<code>public StringBuilder toStringBuilder(byte[] b)
{
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < b.length; i++)
        {
            s.append(Integer.toString((b[i] & 0xff) + 0x100,16).substring(1));
        }
    System.out.println(s);
    return s;
}
</code>```

It takes a byte array and converts it into a StringBuilder (doing other stuff in the meanwhile).

Everything seems OK, when I run the program it prints the correct result, but shows also a NullPointerException that doesn't let me continue using the program; the exception is pointed to the fourth line

```<code>(for (int i = 0; i < b.length; i++))
</code>```

Here is a screenshot:

答:
Try adding () brackets after length like so:</p>

```<code>for (int i = 0; i < b.length(); i++)
        {
</code>```

Body:
I'm experiencing a strange issue using the append() method of StringBuilder class; here is the method:

public StringBuilder toStringBuilder(byte[] b)
{
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < b.length; i++)
        {
            s.append(Integer.toString((b[i] & 0xff) + 0x100,16).substring(1));
        }
    System.out.println(s);
    return s;
}

It takes a byte array and converts it into a StringBuilder (doing other stuff in the meanwhile).

Everything seems OK, when I run the program it prints the correct result, but shows also a NullPointerException that doesn't let me continue using the program; the exception is pointed to the fourth line

(for (int i = 0; i < b.length; i++))

Here is a screenshot:

Body:
Try adding () brackets after length like so:

for (int i = 0; i < b.length(); i++)
        {


来源: stackexchange

问:
AutoLogout after 5 minutes of inactivity Swift
Before posting, i did look on google but found no answer. I would like to pop an alert after 5 minutes of inactivity and autologout if user is idle. But in Swift, I am unable to find any guide or resource for it. Anyone able to give some guide on how to achieve this?</p>

答:
```<code>import UIKit

class ViewController: UIViewController {

var timer = Timer()

override func viewDidLoad() {
    super.viewDidLoad()
    timer = Timer.scheduledTimer(timeInterval: 300, target: self, selector: #selector(userIsInactive), userInfo: nil, repeats: true)
    let timerGesture = UITapGestureRecognizer(target: self, action: #selector(resetTimer))
    self.view.isUserInteractionEnabled = true
    self.view.addGestureRecognizer(timerGesture)
 }

@objc func userIsInactive() {
    // Alert user
    let alert = UIAlertController(title: "You have been inactive for 5 minutes. We're going to log you off for security reasons.", message: nil, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: { (UIAlertAction) in
    //Log user off
    }))
    present(alert, animated: true)

    timer.invalidate()
 }

@objc func resetTimer() {
    print("Reset")
    timer.invalidate()
    timer = Timer.scheduledTimer(timeInterval: 300, target: self, selector: #selector(userIsInactive), userInfo: nil, repeats: true)
 }

}
</code>```

Hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
import UIKit

class ViewController: UIViewController {

var timer = Timer()

override func viewDidLoad() {
    super.viewDidLoad()
    timer = Timer.scheduledTimer(timeInterval: 300, target: self, selector: #selector(userIsInactive), userInfo: nil, repeats: true)
    let timerGesture = UITapGestureRecognizer(target: self, action: #selector(resetTimer))
    self.view.isUserInteractionEnabled = true
    self.view.addGestureRecognizer(timerGesture)
 }

@objc func userIsInactive() {
    // Alert user
    let alert = UIAlertController(title: "You have been inactive for 5 minutes. We're going to log you off for security reasons.", message: nil, preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: { (UIAlertAction) in
    //Log user off
    }))
    present(alert, animated: true)

    timer.invalidate()
 }

@objc func resetTimer() {
    print("Reset")
    timer.invalidate()
    timer = Timer.scheduledTimer(timeInterval: 300, target: self, selector: #selector(userIsInactive), userInfo: nil, repeats: true)
 }

}

Hope this helps!


问:
Custom Font not working as Expected in xamrain forms
I am using font awesome or trying to in Xamarin forms. I was following this guide here.

https://medium.com/@tsjdevapps/use-fontawesome-in-a-xamarin-forms-app-2edf25311db4

But my button is being rendered wrong. Im just using the boiler app to test it working. I Download the font awesome cs as directed by the site

I placed the following into my app xaml.

```<code><?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="LattestFeaturesXamarin.App">
    <Application.Resources>
        <ResourceDictionary>
            <OnPlatform x:TypeArguments="x:String"
                x:Key="FontAwesomeBrands">
                <On Platform="Android"
          Value="FontAwesome5FreeRegular.otf#Regular" />
                <On Platform="iOS"
          Value="FontAwesome5FreeRegular" />
                <On Platform="UWP"
          Value="/Assets/FontAwesome5Brands.otf#Font Awesome 5 Brands" />
            </OnPlatform>

            <OnPlatform x:TypeArguments="x:String"
                x:Key="FontAwesomeSolid">
                <On Platform="Android"
          Value="FontAwesome5FreeRegular.otf#Regular" />
                <On Platform="iOS"
          Value="FontAwesome5FreeRegular" />
                <On Platform="UWP"
          Value="/Assets/FontAwesome5Solid.otf#Font Awesome 5 Free" />
            </OnPlatform>

            <OnPlatform x:TypeArguments="x:String"
                x:Key="FontAwesomeRegular">
                <On Platform="Android"
          Value="FontAwesome5FreeRegular.otf#Regular" />
                <On Platform="iOS"
          Value="FontAwesome5FreeRegular" />
                <On Platform="UWP"
          Value="/Assets/FontAwesome5Regular.otf#Font Awesome 5 Free" />
            </OnPlatform>
        </ResourceDictionary>
    </Application.Resources>
</Application>
</code>```

I have my fonts saved here and am using just the regular on ios and andriod for now so i can get this working.

You see here i have set it correct for android but yet you see im the simulator the button is not showing the correct font icon is it because i have not set the correct font face?

答:
It seems to be a key-value mismatch.Try to change your Application.Resources to below:

```<code><Application.Resources>
    <ResourceDictionary>
        <OnPlatform x:TypeArguments="x:String"
            x:Key="FontAwesomeBrands">
            <On Platform="Android"
      Value="FontAwesome5BrandsRegular.otf#Regular" />
            <On Platform="iOS"
      Value="FontAwesome5BrandsRegular" />
            <On Platform="UWP"
      Value="/Assets/FontAwesome5Brands.otf#Font Awesome 5 Brands" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="FontAwesomeSolid">
            <On Platform="Android"
      Value="FontAwesome5FreeSolid.otf#Regular" />
            <On Platform="iOS"
      Value="FontAwesome5FreeSolid" />
            <On Platform="UWP"
      Value="/Assets/FontAwesome5Solid.otf#Font Awesome 5 Free" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="FontAwesomeRegular">
            <On Platform="Android"
      Value="FontAwesome5FreeRegular.otf#Regular" />
            <On Platform="iOS"
      Value="FontAwesome5FreeRegular" />
            <On Platform="UWP"
      Value="/Assets/FontAwesome5Regular.otf#Font Awesome 5 Free" />
        </OnPlatform>
    </ResourceDictionary>
</Application.Resources>
</code>```

and use like:

```<code><Button Text="" FontFamily="{StaticResource FontAwesomeRegular}">
</code>```

Body:
I am using font awesome or trying to in Xamarin forms. I was following this guide here.

https://medium.com/@tsjdevapps/use-fontawesome-in-a-xamarin-forms-app-2edf25311db4

But my button is being rendered wrong. Im just using the boiler app to test it working. I Download the font awesome cs as directed by the site

I placed the following into my app xaml.

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="LattestFeaturesXamarin.App">
    <Application.Resources>
        <ResourceDictionary>
            <OnPlatform x:TypeArguments="x:String"
                x:Key="FontAwesomeBrands">
                <On Platform="Android"
          Value="FontAwesome5FreeRegular.otf#Regular" />
                <On Platform="iOS"
          Value="FontAwesome5FreeRegular" />
                <On Platform="UWP"
          Value="/Assets/FontAwesome5Brands.otf#Font Awesome 5 Brands" />
            </OnPlatform>

            <OnPlatform x:TypeArguments="x:String"
                x:Key="FontAwesomeSolid">
                <On Platform="Android"
          Value="FontAwesome5FreeRegular.otf#Regular" />
                <On Platform="iOS"
          Value="FontAwesome5FreeRegular" />
                <On Platform="UWP"
          Value="/Assets/FontAwesome5Solid.otf#Font Awesome 5 Free" />
            </OnPlatform>

            <OnPlatform x:TypeArguments="x:String"
                x:Key="FontAwesomeRegular">
                <On Platform="Android"
          Value="FontAwesome5FreeRegular.otf#Regular" />
                <On Platform="iOS"
          Value="FontAwesome5FreeRegular" />
                <On Platform="UWP"
          Value="/Assets/FontAwesome5Regular.otf#Font Awesome 5 Free" />
            </OnPlatform>
        </ResourceDictionary>
    </Application.Resources>
</Application>

I have my fonts saved here and am using just the regular on ios and andriod for now so i can get this working.

You see here i have set it correct for android but yet you see im the simulator the button is not showing the correct font icon is it because i have not set the correct font face?

Body:
It seems to be a key-value mismatch.Try to change your Application.Resources to below:

<Application.Resources>
    <ResourceDictionary>
        <OnPlatform x:TypeArguments="x:String"
            x:Key="FontAwesomeBrands">
            <On Platform="Android"
      Value="FontAwesome5BrandsRegular.otf#Regular" />
            <On Platform="iOS"
      Value="FontAwesome5BrandsRegular" />
            <On Platform="UWP"
      Value="/Assets/FontAwesome5Brands.otf#Font Awesome 5 Brands" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="FontAwesomeSolid">
            <On Platform="Android"
      Value="FontAwesome5FreeSolid.otf#Regular" />
            <On Platform="iOS"
      Value="FontAwesome5FreeSolid" />
            <On Platform="UWP"
      Value="/Assets/FontAwesome5Solid.otf#Font Awesome 5 Free" />
        </OnPlatform>

        <OnPlatform x:TypeArguments="x:String"
            x:Key="FontAwesomeRegular">
            <On Platform="Android"
      Value="FontAwesome5FreeRegular.otf#Regular" />
            <On Platform="iOS"
      Value="FontAwesome5FreeRegular" />
            <On Platform="UWP"
      Value="/Assets/FontAwesome5Regular.otf#Font Awesome 5 Free" />
        </OnPlatform>
    </ResourceDictionary>
</Application.Resources>

and use like:

<Button Text="&#xf2b9;" FontFamily="{StaticResource FontAwesomeRegular}">


问:
NavigationDuplicated Navigating to current location ("/search") is not allowed
When I want to do a search multiple times it shows me the NavigationDuplicated error. My search is in the navbar and the way I have configured the search is to take the value using a model and then pass the value as a parameter to the ContentSearched component, and then receive the value of the search in that component.

I know the right way is to use an emitter, but I still don't know how to learn to use it. To access the emit is context.emit('', someValue)

NavigationDuplicated {_name: "NavigationDuplicated", name: "NavigationDuplicated", message: "Navigating to current location ("/search") is not allowed", stack: "Error↵    at new NavigationDuplicated (webpack-int…node_modules/vue/dist/vue.runtime.esm.js:1853:26)"}
```
<p><strong>NavBar.vue</strong></p>
```<template>

      <router-link to="/" class="navbar-brand">

      </router-link>

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" v-on:click.prevent="toggleNavbar">

      </button>

            <router-link class="nav-link" to="/" > Series</router-link>

            <router-link class="nav-link" :to="{name: 'EpisodesSection'}" > Episodios</router-link>

            <router-link class="nav-link" :to="{name: 'MovieSection'}" > Peliculas</router-link>

          <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" v-model="query" type="search" placeholder="Buscar películas, series ..." aria-label="Search">
            <button class="btn btn-main my-2 my-sm-0" @click.prevent="goto()" type="submit"></button>
          </form>

</template>

```
<p><strong>ContentSearched.vue</strong></p>
<pre class="lang-js prettyprint-override"><code><template>
   <div class="container">
     <BoxLink/>
    <main class="Main">
      <div class="alert alert-primary" role="alert">
        Resultados para "{{query}}"
      </div>
      <div v-if="isLoading">
        <!-- <img class="loading" src="../assets/loading.gif" alt="loading"> -->
      </div>
      <div v-else>
        <ul class="ListEpisodios AX Rows A06 C04 D02">
          <li v-for="(content, index) in contentSearched" :key="index">
            <div v-if="content.type === 'serie'">
              <Series :series="content"/>
            </div>
            <div v-if="content.type === 'pelicula'">
              <Movies :movies="content"/>
            </div>
          </li>
        </ul>
      </div>
    </main>
  </div>
</template>

<script>
  import {onCreated} from "vue-function-api"
  import {useState , useRouter , useStore} from '@u3u/vue-hooks';
  import BoxLink from "../components/BoxLink";
  import Movies from "../components/Movies";
  import Series from "../components/Series";

  export default{
    name: 'ContentSearched',
    components:{
      BoxLink,
      Movies,
      Series
    },
    setup(context){
      const store = useStore();
      const {route} = useRouter();

      const state = {
        ...useState(['contentSearched' , 'isLoading'])
      };

      const query = route.value.params.query;

      onCreated(() =>{
        store.value.dispatch('GET_CONTENT_SEARCH' , query.value);
      });
      return{
        ...state,
        query,
      }
    }
  };
</script>
</code>```

答:
I encountered the same problem while searching. My solution is to add timestamp to the this.$route.query parameters of the search page.

```<code>this.$router.push({
    path: "/search",
    query: {
      q: this.searchQuery,
      t: new Date().getTime(),
    }
  });
</code>```

Hope it helps you.

Body:
When I want to do a search multiple times it shows me the NavigationDuplicated error. My search is in the navbar and the way I have configured the search is to take the value using a model and then pass the value as a parameter to the ContentSearched component, and then receive the value of the search in that component.

I know the right way is to use an emitter, but I still don't know how to learn to use it. To access the emit is context.emit('', someValue)

NavigationDuplicated {_name: "NavigationDuplicated", name: "NavigationDuplicated", message: "Navigating to current location ("/search") is not allowed", stack: "Error↵    at new NavigationDuplicated (webpack-int…node_modules/vue/dist/vue.runtime.esm.js:1853:26)"}

NavBar.vue

<template>

      <router-link to="/" class="navbar-brand">

      </router-link>

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" v-on:click.prevent="toggleNavbar">

      </button>

            <router-link class="nav-link" to="/" > Series</router-link>

            <router-link class="nav-link" :to="{name: 'EpisodesSection'}" > Episodios</router-link>

            <router-link class="nav-link" :to="{name: 'MovieSection'}" > Peliculas</router-link>

          <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" v-model="query" type="search" placeholder="Buscar películas, series ..." aria-label="Search">
            <button class="btn btn-main my-2 my-sm-0" @click.prevent="goto()" type="submit"></button>
          </form>

</template>

ContentSearched.vue

<template>

     <BoxLink/>

        Resultados para "{{query}}"

              <Series :series="content"/>

              <Movies :movies="content"/>

</template>

Body:
I encountered the same problem while searching. My solution is to add timestamp to the this.$route.query parameters of the search page.

this.$router.push({
    path: "/search",
    query: {
      q: this.searchQuery,
      t: new Date().getTime(),
    }
  });

Hope it helps you.


问:
Should every part of a web app be a react component?
I haven't touched React in over 2 years, and a bit confused looking back at my old code. For example, if I were to build an instagram clone, would I utilize html templates and inject javascript as such as

```<code><div id="reactEntry">
    Loading ...
</div>
</code>```

for the login page, profile page, etc.
and use react components for main logic? for example, dynamically rendering posts and comments?

Or would it be smarter to make everything a react component-- login page, profile page, etc.

答:
Or would it be smarter to make everything a react component-- login
  page, profile page, etc.

There are benefits of using react components over the traditional multi-page web apps.

Since most react apps are Single Page Applications(SPA), hence they are fetched once, and then virtual dom handles the rendering of various components. This is faster than the tree-based document rendering.

Components are re-usable. Say you need a Document upload form - consisting of a drag and drop file field and an upload button. You could simply create a component, and keep using it at multiple places. All components have their internal logic, which makes it easier to manipulate and define them. Such an approach ensures a consistent app look and facilitates codebase maintenance and growth.

Plugins like react-router can handle page transitions, by using its navigational components. You could do partial renders too, giving you a faster UI/UX experience than rendering the entire pages.

Body:
I haven't touched React in over 2 years, and a bit confused looking back at my old code. For example, if I were to build an instagram clone, would I utilize html templates and inject javascript as such as

    Loading ...

for the login page, profile page, etc.
and use react components for main logic? for example, dynamically rendering posts and comments?

Or would it be smarter to make everything a react component-- login page, profile page, etc.


问:
ViewBinding has a conflict with DataBinding
In my project, ViewBinding has a conflict with DataBinding when compiling.

LayoutListCoverMaskBinding is a subclass of ViewBinding, but the parameter requires a type of DataBinding

My layout file:

Both DataBinding and ViewBinding are enable

```<code>viewBinding {
    enabled = true
}
dataBinding {
    enabled = true
}
</code>```

Can someone clarify me why this happen and if there is a way to solve it?

答: You should do as Guni suggested if you want to maintain then both. But, I will suggest to use only viewBinding  because it is much faster and with it you don't have to wrap any view groups with   and its syntax is simplified. If you want to use two ways binding then you can combine both (viewBinding and dataBinding). Chose only one to avoid troubles.</p>

Body:
In my project, ViewBinding has a conflict with DataBinding when compiling.

LayoutListCoverMaskBinding is a subclass of ViewBinding, but the parameter requires a type of DataBinding

My layout file:

Both DataBinding and ViewBinding are enable

viewBinding {
    enabled = true
}
dataBinding {
    enabled = true
}

Can someone clarify me why this happen and if there is a way to solve it?


问:
How To Have a Microsoft Report on Remote Server Network- Microsoft Report 2010 [rdlc]?
Hi
Really Iam very new to Microsoft Report. Before I used only Crystal report only. So I have no any idea.

Actaully from my system I used the below code and it works fine. But my program has to be accessed by 2 more users on network. On Network my program is working fine, no problem except report. For that I have no any idea, what else I need?
May be I need to install anything on my sqlserver installed machine in network?
or I have to install reportviewer to my users system ?
And any sample code for that?

Any Guidences will be happy.

Thanks For The Ideas.

Thanks & Regards
PARAMU

```
reportViewer1.RefreshReport();
Microsoft.Reporting.WinForms.ReportDataSource VehRDS = new Microsoft.Reporting.WinForms.ReportDataSource();
RepDS.Name = "DataSet1";
RepDS.Value = MyDataTable1;
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(VehRDS);
reportViewer1.LocalReport.ReportPath ="C:\\Documents and Settings\\...\\My Documents\\Visual Studio 2010\\Projects\\MyProject\\My_Report.rdlc";
reportViewer1.RefreshReport();
reportViewer1.Visible = true;

```

答:
I think you need to install Merge Module for Crystal Report.

Crystal Report MergeModule

Then on your Deployment Project you need

How to: Add Merge Modules to a Deployment Project

Regards

ContentLicense: CC BY-SA 3.0

Body:
Hi
Really Iam very new to Microsoft Report. Before I used only Crystal report only. So I have no any idea.

Actaully from my system I used the below code and it works fine. But my program has to be accessed by 2 more users on network. On Network my program is working fine, no problem except report. For that I have no any idea, what else I need?
May be I need to install anything on my sqlserver installed machine in network?
or I have to install reportviewer to my users system ?
And any sample code for that?

Any Guidences will be happy.

Thanks For The Ideas.

Thanks & Regards
PARAMU

reportViewer1.RefreshReport();
Microsoft.Reporting.WinForms.ReportDataSource VehRDS = new Microsoft.Reporting.WinForms.ReportDataSource();
RepDS.Name = "DataSet1";
RepDS.Value = MyDataTable1;
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(VehRDS);
reportViewer1.LocalReport.ReportPath ="C:\\Documents and Settings\\...\\My Documents\\Visual Studio 2010\\Projects\\MyProject\\My_Report.rdlc";
reportViewer1.RefreshReport();
reportViewer1.Visible = true;


问:
How to make widget stick to top of keyboard
I'd like to make a widget that sticks to the bottom of the page, and then is pinned to the top of the keyboard (when it appears).

Note how the input textfield is pinned to the keyboard in the image below:

How would I do this? I tried putting it in the bottomNavigationBar, but this (obviously) didn't work. Is there a builtin way to do this?

答:
there is a lib for that:

https://pub.dev/packages/keyboard_attachable

Widget build(BuildContext context) => FooterLayout(
    footer: MyFooterWidget(),
    child: PageMainContent(),
);
```


问:
Javascript/Typescript - Remove elements of an array that exists in another array
I have two arrays:

```<code>const arr1 = ['abc', 'def', 'ghi', 'jkl'];
const arr2 = ['123', 'abc', 'jkl', '456', '789'];
</code>```

What would be the cleanest way to return arr2 without the elements of arr1?

I guess arr2.filter(x => arr1.indexOf(x) < 0) would work, but is there a cleaner way?

答:
Your code is correct. You can also use include Method. Make sure to switch to ES7 to use it. Refer to below snippet - </p>

```<code>var arr1 = [ 1, 2, 3, 4, 5 ];
var arr2  = [ 4, 5, 6 ];

var difference = arr1.filter(x => !arr2.includes(x));
console.log(difference);

/*
    Output: [ 1, 2, 3]
*/
</code>```

Body:
I have two arrays:

const arr1 = ['abc', 'def', 'ghi', 'jkl'];
const arr2 = ['123', 'abc', 'jkl', '456', '789'];

What would be the cleanest way to return arr2 without the elements of arr1?

I guess arr2.filter(x => arr1.indexOf(x) < 0) would work, but is there a cleaner way?

Body:
Your code is correct. You can also use include Method. Make sure to switch to ES7 to use it. Refer to below snippet -

var arr1 = [ 1, 2, 3, 4, 5 ];
var arr2  = [ 4, 5, 6 ];

var difference = arr1.filter(x => !arr2.includes(x));
console.log(difference);

/*
    Output: [ 1, 2, 3]
*/


问:
Type 'string[]' is not assignable to type 'never[]'
In typescript, I got error of
Type 'string[]' is not assignable to type 'never[]'.

I want to add 'abc' into the array, what's wrong with it?

```<code>export default function App() {
  const [text, setText] = React.useState("abc");
  const [arr, setArr] = React.useState([]);

  const xx = () => setArr([...arr, text]);

  return <div className="App">{text}</div>;
}
</code>```

https://codesandbox.io/s/boring-spence-08g8r?file=/src/App.tsx:56-272

答:
```<code>  const initArr: string[] = [];
  const [text, setText] = React.useState("abc");
  const [arr, setArr] = React.useState(initArr);
</code>```

just try to define your init array

Body:
In typescript, I got error of
Type 'string[]' is not assignable to type 'never[]'.

I want to add 'abc' into the array, what's wrong with it?

export default function App() {
  const [text, setText] = React.useState("abc");
  const [arr, setArr] = React.useState([]);

  const xx = () => setArr([...arr, text]);

  return
{text}
;
}

https://codesandbox.io/s/boring-spence-08g8r?file=/src/App.tsx:56-272

Body:
  const initArr: string[] = [];
  const [text, setText] = React.useState("abc");
  const [arr, setArr] = React.useState(initArr);

just try to define your init array


问:
react native chart/graph library that supports user onPress?
I am currently working on a react native project where I need to present a bar chart with 4 data and I need my chart to be clickable so that users can click on every data. Is there any libraries to recommend? I have tried using react-native-chart-kit and it seems like they do not support user clicks. Thanks in advance!</p>

答:
I think you should try

https://github.com/wuxudong/react-native-charts-wrapper

I have been using it for my project. I support column click on the bar chart just like you asked it still well-maintained.


问:
r: Displaying Eastern Russia and North America on one map rnaturalearth
I'm still learning how to use R. I'm trying to display points in North America and Eastern Russia using the package "rnaturalearth". I'd like to just show Russia and North America, rather than all of Europe. I've included a picture with the area of the world that I want in a box here. I get this error whenever I input positive and negative longitude values.

```<code>Error in st_normalize.sfc(x, c(x_range[1], y_range[1], x_range[2], y_range[2])) :
  domain must have a positive range
</code>```

I couldn't find anything online, although I'm sure it's probably pretty simple. Any help would be appreciated!

Here is the code for the general mapping:

```<code>world <- ne_countries(scale = "medium", returnclass = "sf")

ggplot(data = world)+
  geom_sf()+
coord_sf(xlim = c(160, -60), ylim = c(20, 90), expand = FALSE)
</code>```

答:
I had almost the exact same challenge to try and solve and found your question while trying to figure it out. Here are the links which helped me get the output I wanted. I won't give an exact solution myself as I think these links already have the solution well laid out.

This question contains almost the exact process you are looking for:

https://gis.stackexchange.com/questions/332106/union-anti-meridian-multipolygons-after-re-centering-world-map

This is what the individual in the above question used as a reference to edit the code from (which also includes the packages needed to do this):

https://github.com/valentinitnelav/valentinitnelav.github.io/blob/master/gallery/Shift%20central%20(prime)%20meridian.R#L73

Once you have the polygons shifted you can use "coord_sf()" as you tried before to get the subset of the map you want.

The only issue I have with this specific solution is that it will shift the longitude values on the map. This means they do not accurately represent the actual longitude values. So make sure to take that into account if you want to show the longitude values on the map.

I hope this helps you get the map you want!

Edit: I just remembered this site has a different way to get a similar solution under "Example of a failed transformation", depending on the map projection you want.
https://mgimond.github.io/Spatial/coordinate-systems-in-r.html

Body:
I'm still learning how to use R. I'm trying to display points in North America and Eastern Russia using the package "rnaturalearth". I'd like to just show Russia and North America, rather than all of Europe. I've included a picture with the area of the world that I want in a box here. I get this error whenever I input positive and negative longitude values.

Error in st_normalize.sfc(x, c(x_range[1], y_range[1], x_range[2], y_range[2])) :
  domain must have a positive range

I couldn't find anything online, although I'm sure it's probably pretty simple. Any help would be appreciated!

Here is the code for the general mapping:

world <- ne_countries(scale = "medium", returnclass = "sf")

ggplot(data = world)+
  geom_sf()+
coord_sf(xlim = c(160, -60), ylim = c(20, 90), expand = FALSE)


问:
Too many images in android app
In my android app i have got something like 70-80 images. This is making my app very heavy. What are my options to reduce the size without loing any image. I mean any way to compress them or anything like that?</p>

答:
Try storing them in the database,

https://web.archive.org/web/20200718180158/http://www.tutorialforandroid.com/2009/10/how-to-insert-image-data-to-sqlite.html

Title: Too many images in android app


答:
const [arr, setArr] = React.useState([] as string[]);

The compiler needs to know the type of the array.

Title: Type 'string[]' is not assignable to type 'never[]'


问:
R get the means for all columns in a data frame while ignoring zeroes
I have a dataframe with columns of simulation data.
I want the means of each column.
The issue is some columns have a bunch of zeroes on the bottom and these need to be ignored.

I can ignore the zeroes and look at one column with

```<code>mean(which(df$colname >0))
</code>```

But I want a vector of every column's mean, gotten with sapply.
Is there a clean way to ignore the zeroes and get these values within a sapply function?

Or do I have to write a custom function and call that in the sapply?

答:
You can use :

```<code>sapply(df, function(x) mean(x[x != 0], na.rm = TRUE))
</code>```

Or using dplyr :

```<code>library(dplyr)
df %>% summarise_all(~mean(.[. != 0], na.rm = TRUE))
</code>```

A better/efficient approach would be to set all 0 values to NA and use colMeans

```<code>df[df == 0] <- NA
colMeans(df, na.rm = TRUE)
</code>```

Body:
I have a dataframe with columns of simulation data.
I want the means of each column.
The issue is some columns have a bunch of zeroes on the bottom and these need to be ignored.

I can ignore the zeroes and look at one column with

mean(which(df$colname >0))

But I want a vector of every column's mean, gotten with sapply.
Is there a clean way to ignore the zeroes and get these values within a sapply function?

Or do I have to write a custom function and call that in the sapply?

Body:
You can use :

sapply(df, function(x) mean(x[x != 0], na.rm = TRUE))

Or using dplyr :

library(dplyr)
df %>% summarise_all(~mean(.[. != 0], na.rm = TRUE))

A better/efficient approach would be to set all 0 values to NA and use colMeans

df[df == 0] <- NA
colMeans(df, na.rm = TRUE)


问:
stat() function only works in the current directory C language
i'm using C on windows to read the contents of a directory and info about each entry, however the stat() function only works if i opened the current directory "."

directory = opendir(".")

whenever i try something like this "C:\Users\User\Desktop\programming" it does not work and outputs -1

directory = opendir("C:\\Users\\User\\Desktop\\programming")

can you pleas guide me here

```<code>#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
void perror(const char *str);// for error detail

int main()
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;

    // entering the directory
    directory = opendir("C:\\Users\\User\\Desktop\\programming");//also C:\\Users\\User\\Desktop\\programming\\ didn't work
    if ( directory == NULL )
        {
            puts("the directory couldn't be accessed or does not exist");
          return(2);
        }

    printf("No   type         name              size           TimeStamp \n\n");
    while((file=readdir(directory))!= NULL)
    {

        entries++;

              //  problem : the stat is not working properly
        stat(file->d_name,&info);
        if ((stat(file->d_name,&info)) == -1){
            printf("can't find %s\n", file->d_name);
            perror("ERROR");
           }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else

            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10d",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");

    }

    return(0);
}
</code>```

the output pic link : https://i.stack.imgur.com/tORZU.png

答:
the following proposed code:

includes all the needed header files

performs the desired functionality

properly checks for and handles errors

properly sets up the path for the stat() function

note: the code is being run from the /home/richard/documents/forum directory.  This shows that the proposed code properly handles cross directory references.

hidden files are kept hidden by ignoring entries that start with '.'

and now, the proposed code

```<code>#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h>

int main( void )
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;

    // entering the directory
    directory = opendir("//home//richard" );
    if ( directory == NULL )
    {
        perror("the directory couldn't be accessed or does not exist");
        return(2);
    }

    printf("No   type         name              size           TimeStamp \n\n");
    while((file = readdir(directory)))
    {
        if( file->d_name[0] == '.' )
        { // then hidden file, so leave hidden
            continue;
        }

        entries++;

        char buffer[1024];
        strcpy( buffer, "//home//richard//" );
        strcat( buffer, file->d_name );
        if (stat( buffer, &info ) == -1)
        {
            perror( buffer );
            continue;
        }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else
            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10ld",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");
    }
    return(0);
}
</code>```

Part of the output from a typical run of the code is:

```<code>No   type         name              size           TimeStamp

 1  Dir                Music      4096

 2  Dir             projects      4096

 3  Dir         scull-master      4096

 4  Dir         slickeditpro      4096

 5  Dir                 snap      4096

 6  File   clamscanParms.txt       171     Sat May 20 10:06:43 2017

 7  Dir              OpenMPI      4096

 8  Dir        clamav.0.99.2      4096

 9  Dir               Public      4096

10  Dir            Documents      4096

11  Dir              Desktop      4096

12  Dir            Downloads     20480

13  Dir             Pictures      4096

14  Dir            Templates      4096

15  Dir               Videos      4096

16  File        clamscan.log     42952     Tue Feb 18 13:24:58 2020
</code>```

As you can see, there are still some alignment between column headers and column data discrepancies that need correction.  I'm sure you can handle that detail.

Body:
i'm using C on windows to read the contents of a directory and info about each entry, however the stat() function only works if i opened the current directory "."

directory = opendir(".")

whenever i try something like this "C:\Users\User\Desktop\programming" it does not work and outputs -1

directory = opendir("C:\\Users\\User\\Desktop\\programming")

can you pleas guide me here

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
void perror(const char *str);// for error detail

int main()
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;

    // entering the directory
    directory = opendir("C:\\Users\\User\\Desktop\\programming");//also C:\\Users\\User\\Desktop\\programming\\ didn't work
    if ( directory == NULL )
        {
            puts("the directory couldn't be accessed or does not exist");
          return(2);
        }

    printf("No   type         name              size           TimeStamp \n\n");
    while((file=readdir(directory))!= NULL)
    {

        entries++;

              //  problem : the stat is not working properly
        stat(file->d_name,&info);
        if ((stat(file->d_name,&info)) == -1){
            printf("can't find %s\n", file->d_name);
            perror("ERROR");
           }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else

            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10d",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");

    }

    return(0);
}

the output pic link : https://i.stack.imgur.com/tORZU.png

Body:
the following proposed code:

includes all the needed header files

performs the desired functionality

properly checks for and handles errors

properly sets up the path for the stat() function

note: the code is being run from the /home/richard/documents/forum directory.  This shows that the proposed code properly handles cross directory references.

hidden files are kept hidden by ignoring entries that start with '.'

and now, the proposed code

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <time.h>
#include <string.h>

int main( void )
{
    DIR *directory;
    struct dirent *file;
    struct stat info;
    int entries = 0 ;

    // entering the directory
    directory = opendir("//home//richard" );
    if ( directory == NULL )
    {
        perror("the directory couldn't be accessed or does not exist");
        return(2);
    }

    printf("No   type         name              size           TimeStamp \n\n");
    while((file = readdir(directory)))
    {
        if( file->d_name[0] == '.' )
        { // then hidden file, so leave hidden
            continue;
        }

        entries++;

        char buffer[1024];
        strcpy( buffer, "//home//richard//" );
        strcat( buffer, file->d_name );
        if (stat( buffer, &info ) == -1)
        {
            perror( buffer );
            continue;
        }
        // show the number of the entry
        printf("%2d  ",entries);

        // determine if file or directory
        if(S_ISDIR(info.st_mode))
            printf("Dir ");
        else
            printf("File");

        // display the name of the file
        printf("%20s",file->d_name);

        // display the size of the file
        printf("%10ld",info.st_size);

        // show the last modified time
        if(!(S_ISDIR(info.st_mode)))
            printf("%30s\n",ctime(&info.st_mtime));
        else puts("\n");
    }
    return(0);
}

Part of the output from a typical run of the code is:

No   type         name              size           TimeStamp

 1  Dir                Music      4096

 2  Dir             projects      4096

 3  Dir         scull-master      4096

 4  Dir         slickeditpro      4096

 5  Dir                 snap      4096

 6  File   clamscanParms.txt       171     Sat May 20 10:06:43 2017

 7  Dir              OpenMPI      4096

 8  Dir        clamav.0.99.2      4096

 9  Dir               Public      4096

10  Dir            Documents      4096

11  Dir              Desktop      4096

12  Dir            Downloads     20480

13  Dir             Pictures      4096

14  Dir            Templates      4096

15  Dir               Videos      4096

16  File        clamscan.log     42952     Tue Feb 18 13:24:58 2020

As you can see, there are still some alignment between column headers and column data discrepancies that need correction.  I'm sure you can handle that detail.


问:
My function is stopping at a specific point
```<code>void changeSubstringCase(char str[], char a[]) {
/**
* If `a` is a substring of `str`, then change the case (capitalization) of
* the corresponding substring in `str`. Special characters (' ', '.', ...)
* do not need to be handled. You should only change the letters.
*
* For example:
*
*    char str[100] = "This IS a SENTence WITH BAd CAPITalizaTION";
*    changeSubstringCase(str, "IS a SENTence WI");
*    printf("%s\n", str);
*
* should print out "This is A sentENCE wiTH BAd CAPITalizaTION".
*/
int slen = 0;
int alen = 0;
int scount = 0;
int counter = 0;
char alpha[1024] = "abcdefghijklmnopqrstuvwxyz";
char Calpha[1024] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
slen = strlen(str);

alen = strlen(a);
for(int i = 0; i < slen; i++)
{
   //printf("a\n");
   if(a[counter] == str[i])
   {
       counter++;
       if(counter == alen)
       {
           //printf("l\n");
            scount = i - counter;
            break;
       }
   }
   else
   {
       counter = 0;
   }
}
printf("Bad boy\n");
if(counter != alen)
{
    printf("bye\n");
    return;
}
int m = 0;
int f = 0;
while(a[m] != '\0')
{
    for(int i = 0 ; i < 26; i++)
    {
        if(a[m] == alpha[i])
        {
            printf("a\n");
            a[m] = Calpha[i];
            break;
        }
        else if(a[m] == Calpha[i])
        {
            printf("b\n");
            a[m] = alpha[i];
            break;
        }
    }
    m++;
}
for(int i = 0; i < alen; i++)
{
   printf("hel");
   str[scount] = a[i];
   scount++;
}

return;  // Not returning anything. `str` is modified directly.
}
int main() {
char str[MAX_STRING_LEN] = "CSCA48 Exercise 1";

// This should replace the substring:
replaceSubstring(str, "A48 Ex", "A48 sUMMER 2020 Ex");

// This should NOT replace anything, since some of the letters
// in `a` have a different capitalization than in the string, so it is
// NOT a valid substring.
replaceSubstring(str, "summer 2020", "Winter 2020");

// This should change the capitalization of the substring:
changeSubstringCase(str, "sUMMER 2020");

// This should NOT change the capitalization, since the corresponding letters
// in `a` are lowercase, and it is not a valid substring.
changeSubstringCase(str, "csca48");

printf("Expected result: \"CSCA48 sUMMER 2020 Exercise 1\"\n");
printf("Your solution: \"%s\"\n", str);
return 0;
}
</code>```

for some reason the code stops int the nested for loop conditional statement. I have tested all I can but I cannot see the problem as to why it would stop after that point. Especially because all im doing is trying to replace the alphabet with the capital counter part.

Any Help would be appreciated.

I am new to programming so anything complex will be wasted on me

答:
you return from your code because after the first loop  counter != alen and so you print 'bye' and return.

I am not sure what you are trying to do but thats why it 'stops' for no apparent reason.

PS - I found this using my debugger (gdb in this case)

Body:
void changeSubstringCase(char str[], char a[]) {
/**
* If `a` is a substring of `str`, then change the case (capitalization) of
* the corresponding substring in `str`. Special characters (' ', '.', ...)
* do not need to be handled. You should only change the letters.
*
* For example:
*
*    char str[100] = "This IS a SENTence WITH BAd CAPITalizaTION";
*    changeSubstringCase(str, "IS a SENTence WI");
*    printf("%s\n", str);
*
* should print out "This is A sentENCE wiTH BAd CAPITalizaTION".
*/
int slen = 0;
int alen = 0;
int scount = 0;
int counter = 0;
char alpha[1024] = "abcdefghijklmnopqrstuvwxyz";
char Calpha[1024] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
slen = strlen(str);

alen = strlen(a);
for(int i = 0; i < slen; i++)
{
   //printf("a\n");
   if(a[counter] == str[i])
   {
       counter++;
       if(counter == alen)
       {
           //printf("l\n");
            scount = i - counter;
            break;
       }
   }
   else
   {
       counter = 0;
   }
}
printf("Bad boy\n");
if(counter != alen)
{
    printf("bye\n");
    return;
}
int m = 0;
int f = 0;
while(a[m] != '\0')
{
    for(int i = 0 ; i < 26; i++)
    {
        if(a[m] == alpha[i])
        {
            printf("a\n");
            a[m] = Calpha[i];
            break;
        }
        else if(a[m] == Calpha[i])
        {
            printf("b\n");
            a[m] = alpha[i];
            break;
        }
    }
    m++;
}
for(int i = 0; i < alen; i++)
{
   printf("hel");
   str[scount] = a[i];
   scount++;
}

return;  // Not returning anything. `str` is modified directly.
}
int main() {
char str[MAX_STRING_LEN] = "CSCA48 Exercise 1";

// This should replace the substring:
replaceSubstring(str, "A48 Ex", "A48 sUMMER 2020 Ex");

// This should NOT replace anything, since some of the letters
// in `a` have a different capitalization than in the string, so it is
// NOT a valid substring.
replaceSubstring(str, "summer 2020", "Winter 2020");

// This should change the capitalization of the substring:
changeSubstringCase(str, "sUMMER 2020");

// This should NOT change the capitalization, since the corresponding letters
// in `a` are lowercase, and it is not a valid substring.
changeSubstringCase(str, "csca48");

printf("Expected result: \"CSCA48 sUMMER 2020 Exercise 1\"\n");
printf("Your solution: \"%s\"\n", str);
return 0;
}

for some reason the code stops int the nested for loop conditional statement. I have tested all I can but I cannot see the problem as to why it would stop after that point. Especially because all im doing is trying to replace the alphabet with the capital counter part.

Any Help would be appreciated.

I am new to programming so anything complex will be wasted on me


问:
OpenMPI java bindings in Windows 10 Cygwin
I'm trying to get OpenMPI working on windows 10 with java bindings.  I've gotten OpenMPI working with cygwin, but I want to get the java bindings working on cygwin as well.  I've looked online but can't seem to find any good resources on how to get this working.  Does anyone know how to do this, or have a good source on how to do it?

I know normally you can find the ompi directory and use
./configure --enable-mpi-java

But I can't seem to figure out how to find the correct directory/command with cygwin.  Any tips?

答:
You can't.

There is no Java compiler as Cygwin package.

For this reason OpenMPI on Cygwin is only available with C and Fortran bindings.

If you need it, try a Virtual Machine with Linux installed


问:
how can i use from methods in other pages?
HI,
i have 2 php pages.first page has some functions like Connect(),... .i want to use from Connect() function in second page but when use from Connect() can not recognize it.i use from header("first.php") but have same error.
how can i solve that problem?</p>

答:
You don't tell us which error you get.

A solution would be to put all the functions you want to share in their own file, e.g. functions.php and then use require in both files to have access to those functions:

```<code>require 'functions.php';
</code>```

Body:
You don't tell us which error you get.

A solution would be to put all the functions you want to share in their own file, e.g. functions.php and then use require in both files to have access to those functions:

require 'functions.php';


问:
pg-promise quick way to delete set of tuples
Is there a better way to write the following:

```<code>DELETE FROM
    table
WHERE
    _id = $<id>
    AND (
        item_id = $<item_id>
        AND map_id = $<map_id>
        OR
        item_id = $<another_id>
        AND map_id = $<another_map_id>
        ...
    )
</code>```

The dataset format I have is:

```<code>[
    {
        item_id: "some_id",
        map_id: "other_id"
    }
    ...
]
</code>```

What would be a good way to write this in pg-promise, or even just plain postgreSQL?

答:
Postgres supports tuple equality, so you could write this as:</p>

```<code>DELETE FROM table
WHERE
    _id = $<id>
    AND (item_id, map_id) IN (
        ($<item_id>, $<map_id>),
        ($<another_id>, $<another_map_id>),
        ...
    )
</code>```

Body:
Is there a better way to write the following:

DELETE FROM
    table
WHERE
    _id = $<id>
    AND (
        item_id = $<item_id>
        AND map_id = $<map_id>
        OR
        item_id = $<another_id>
        AND map_id = $<another_map_id>
        ...
    )

The dataset format I have is:

[
    {
        item_id: "some_id",
        map_id: "other_id"
    }
    ...
]

What would be a good way to write this in pg-promise, or even just plain postgreSQL?

Body:
Postgres supports tuple equality, so you could write this as:

DELETE FROM table
WHERE
    _id = $<id>
    AND (item_id, map_id) IN (
        ($<item_id>, $<map_id>),
        ($<another_id>, $<another_map_id>),
        ...
    )


问:
Mocking es6 class constructor attribute with mocha/sinon
I have a small wrapper class which adds promises to some mysql functionality.

```<code>const mysql = require('mysql');

export default class MySQL {
    constructor(host, user, password, database, port = 3306) {
        this.conn = mysql.createConnection({
            host,
            port,
            user,
            password,
            database,
        });
    }

    query(sql, args) {
        return new Promise((resolve, reject) => {
            // eslint-disable-next-line consistent-return
            this.conn.query(sql, args, (err, rows) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(rows);
            });
        });
    }

    close() {
        return new Promise((resolve, reject) => {
            this.conn.end((err) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve();
            });
        });
    }
}
</code>```

I am trying to write a unit test for this class but am completely stuck trying to mock this.conn.

I have tried various mixes of proxyquire, sinon, and both combined.  When I use proxyquire in a beforeEach hook:

```<code>beforeEach(function () {
    createConnectionStub = sinon.stub();
    MySQL = proxyquire('../../lib/utils/mysql', {
        mysql: {
            createConnection: createConnectionStub,
        },
    }).default;
});
</code>```

and try to set a stub to the conn object:

```<code>it('Returns query results', async function () {
            stubDb = new MySQL('host', 'user', 'password', 'database');
            stubDb.conn = sinon.stub();

            const results = await stubDb.query('SELECT * FROM whatever');
        });
</code>```

I keep getting TypeError: this.conn.query is not a function

what is the best way to setup a mock as the this.conn attributes so I can easily assert method calls against it?  Any help would be much appreciated

答:
You don't need to use proxyquire module, this module is mainly used to mock/stub standalone functions from a module. The unit test should be:

index.js:

const mysql = require('mysql');

export default class MySQL {
  conn;
  constructor(host, user, password, database, port = 3306) {
    this.conn = mysql.createConnection({
      host,
      port,
      user,
      password,
      database,
    });
  }

  query(sql, args) {
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line consistent-return
      this.conn.query(sql, args, (err, rows) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(rows);
      });
    });
  }

  close() {
    return new Promise((resolve, reject) => {
      this.conn.end((err) => {
        if (err) {
          reject(err);
          return;
        }
        resolve();
      });
    });
  }
}
```

<p><code>index.test.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>import MySQL from '.';
import sinon from 'sinon';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
const expect = chai.expect;
const mysql = require('mysql');

describe('62124221', () => {
  afterEach(() => {
    sinon.restore();
  });
  it('should return query results', async () => {
    const mRows = [1, 2];
    const mConn = {
      query: sinon.stub().callsFake((sql, args, callback) => {
        callback(null, mRows);
      }),
    };
    sinon.stub(mysql, 'createConnection').returns(mConn);
    const db = new MySQL('host', 'user', 'password', 'database');
    const actual = await db.query('select 1;', 'args');
    expect(actual).to.be.deep.equal([1, 2]);
    sinon.assert.calledWithExactly(mysql.createConnection, {
      host: 'host',
      port: 3306,
      user: 'user',
      password: 'password',
      database: 'database',
    });
    sinon.assert.calledWithExactly(mConn.query, 'select 1;', 'args', sinon.match.func);
  });

  it('should return handle error', async () => {
    const mError = new Error('network');
    const mConn = {
      query: sinon.stub().callsFake((sql, args, callback) => {
        callback(mError);
      }),
    };
    sinon.stub(mysql, 'createConnection').returns(mConn);
    const db = new MySQL('host', 'user', 'password', 'database');
    await expect(db.query('select 1;', 'args')).to.be.rejectedWith('network');
    sinon.assert.calledWithExactly(mysql.createConnection, {
      host: 'host',
      port: 3306,
      user: 'user',
      password: 'password',
      database: 'database',
    });
    sinon.assert.calledWithExactly(mConn.query, 'select 1;', 'args', sinon.match.func);
  });
});
</code>```

unit test results with coverage report:

  62124221
    ✓ should return query results
    ✓ should return handle error

  2 passing (20ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |      60 |       60 |   57.14 |      60 |
 index.ts |      60 |       60 |   57.14 |      60 | 29-35
----------|---------|----------|---------|---------|-------------------
```

Here only demonstrates how to test the query method, the test method of the close method is the same.

Body:
I have a small wrapper class which adds promises to some mysql functionality.

const mysql = require('mysql');

export default class MySQL {
    constructor(host, user, password, database, port = 3306) {
        this.conn = mysql.createConnection({
            host,
            port,
            user,
            password,
            database,
        });
    }

    query(sql, args) {
        return new Promise((resolve, reject) => {
            // eslint-disable-next-line consistent-return
            this.conn.query(sql, args, (err, rows) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(rows);
            });
        });
    }

    close() {
        return new Promise((resolve, reject) => {
            this.conn.end((err) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve();
            });
        });
    }
}

I am trying to write a unit test for this class but am completely stuck trying to mock this.conn.

I have tried various mixes of proxyquire, sinon, and both combined.  When I use proxyquire in a beforeEach hook:

beforeEach(function () {
    createConnectionStub = sinon.stub();
    MySQL = proxyquire('../../lib/utils/mysql', {
        mysql: {
            createConnection: createConnectionStub,
        },
    }).default;
});

and try to set a stub to the conn object:

it('Returns query results', async function () {
            stubDb = new MySQL('host', 'user', 'password', 'database');
            stubDb.conn = sinon.stub();

            const results = await stubDb.query('SELECT * FROM whatever');
        });

I keep getting TypeError: this.conn.query is not a function

what is the best way to setup a mock as the this.conn attributes so I can easily assert method calls against it?  Any help would be much appreciated

Body:
You don't need to use proxyquire module, this module is mainly used to mock/stub standalone functions from a module. The unit test should be:

index.js:

const mysql = require('mysql');

export default class MySQL {
  conn;
  constructor(host, user, password, database, port = 3306) {
    this.conn = mysql.createConnection({
      host,
      port,
      user,
      password,
      database,
    });
  }

  query(sql, args) {
    return new Promise((resolve, reject) => {
      // eslint-disable-next-line consistent-return
      this.conn.query(sql, args, (err, rows) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(rows);
      });
    });
  }

  close() {
    return new Promise((resolve, reject) => {
      this.conn.end((err) => {
        if (err) {
          reject(err);
          return;
        }
        resolve();
      });
    });
  }
}

index.test.js:

import MySQL from '.';
import sinon from 'sinon';
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
const expect = chai.expect;
const mysql = require('mysql');

describe('62124221', () => {
  afterEach(() => {
    sinon.restore();
  });
  it('should return query results', async () => {
    const mRows = [1, 2];
    const mConn = {
      query: sinon.stub().callsFake((sql, args, callback) => {
        callback(null, mRows);
      }),
    };
    sinon.stub(mysql, 'createConnection').returns(mConn);
    const db = new MySQL('host', 'user', 'password', 'database');
    const actual = await db.query('select 1;', 'args');
    expect(actual).to.be.deep.equal([1, 2]);
    sinon.assert.calledWithExactly(mysql.createConnection, {
      host: 'host',
      port: 3306,
      user: 'user',
      password: 'password',
      database: 'database',
    });
    sinon.assert.calledWithExactly(mConn.query, 'select 1;', 'args', sinon.match.func);
  });

  it('should return handle error', async () => {
    const mError = new Error('network');
    const mConn = {
      query: sinon.stub().callsFake((sql, args, callback) => {
        callback(mError);
      }),
    };
    sinon.stub(mysql, 'createConnection').returns(mConn);
    const db = new MySQL('host', 'user', 'password', 'database');
    await expect(db.query('select 1;', 'args')).to.be.rejectedWith('network');
    sinon.assert.calledWithExactly(mysql.createConnection, {
      host: 'host',
      port: 3306,
      user: 'user',
      password: 'password',
      database: 'database',
    });
    sinon.assert.calledWithExactly(mConn.query, 'select 1;', 'args', sinon.match.func);
  });
});

unit test results with coverage report:

  62124221
    ✓ should return query results
    ✓ should return handle error

  2 passing (20ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |      60 |       60 |   57.14 |      60 |
 index.ts |      60 |       60 |   57.14 |      60 | 29-35
----------|---------|----------|---------|---------|-------------------

Here only demonstrates how to test the query method, the test method of the close method is the same.


问:
List container images in Kubernetes cluster with SIZE (like docker image ls)
In the Kubernetes documentation List All Container Images Running in a Cluster we can list all containers by:

```<code>kubectl get pods --all-namespaces -o jsonpath="{..image}" |\
tr -s '[[:space:]]' '\n' |\
sort |\
uniq -c
</code>```

Here is an example of output:

```<code>  1 cdkbot/addon-resizer-amd64:1.8.1
  1 cdkbot/hostpath-provisioner-amd64:1.0.0
  1 cdkbot/registry-amd64:2.6
  1 coredns/coredns:1.6.6
  1 docker.io/cdkbot/addon-resizer-amd64:1.8.1
  1 docker.io/cdkbot/hostpath-provisioner-amd64:1.0.0
  1 docker.io/cdkbot/registry-amd64:2.6
  1 docker.io/coredns/coredns:1.6.6
  1 docker.io/grafana/grafana:6.4.3
  2 docker.io/istio/citadel:1.5.1
  2 docker.io/istio/examples-bookinfo-details-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-productpage-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-ratings-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v2:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v3:1.15.0
  2 docker.io/istio/galley:1.5.1
  4 docker.io/istio/kubectl:1.5.1
  4 docker.io/istio/mixer:1.5.1
  2 docker.io/istio/pilot:1.5.1
 34 docker.io/istio/proxyv2:1.5.1
  2 docker.io/istio/sidecar_injector:1.5.1
  2 docker.io/jaegertracing/all-in-one:1.16
  1 docker.io/kubernetesui/dashboard:v2.0.0
  1 docker.io/kubernetesui/metrics-scraper:v1.0.4
  2 docker.io/library/nginx:latest
  2 docker.io/prom/prometheus:v2.12.0
  1 docker.io/radial/busyboxplus:curl
  1 grafana/grafana:6.4.3
  2 k8s.gcr.io/metrics-server-amd64:v0.2.1
  1 kubernetesui/dashboard:v2.0.0
  1 kubernetesui/metrics-scraper:v1.0.4
  2 nginx
  2 quay.io/kiali/kiali:v1.9
  1 radial/busyboxplus:curl
</code>```

Unfortunately the size of the docker image is missing. Is there a way to get the container image size? Pretty much like docker image ls. Copy of the output from this example for convenience:

```<code>$ docker image ls
REPOSITORY                  TAG                 IMAGE ID            CREATED             SIZE
docker.io/ubuntu            latest              3556258649b2        7 days ago          64.2 MB
docker.io/alpine            latest              b7b28af77ffe        2 weeks ago         5.58 MB
docker.io/centos            latest              9f38484d220f        4 months ago        202 MB
docker.io/hello-world       latest              fce289e99eb9        7 months ago        1.84 kB
</code>```

答:
On my k8s system kubectl describe pod ABC doesn't show the image size, but you can create a script that:

gets the name of the image (I assuming you have one container in the pod, otherwise the script will be slightly more complicated depending on what you want to print actually)

runs docker image ls on the same machine. This assumes that you actually have that docker image on the machine you're running this command.

You slight format the output of that command to "catch" the image size

All-in-all it looks like this:

```<code>docker image ls `kubectl get pod YOUR_POD_NAME_GOES_HERE  -o jsonpath='{.spec.containers[0].image}'` --format='{{println .Size}}'
</code>```

Body:
In the Kubernetes documentation List All Container Images Running in a Cluster we can list all containers by:

kubectl get pods --all-namespaces -o jsonpath="{..image}" |\
tr -s '[[:space:]]' '\n' |\
sort |\
uniq -c

Here is an example of output:

  1 cdkbot/addon-resizer-amd64:1.8.1
  1 cdkbot/hostpath-provisioner-amd64:1.0.0
  1 cdkbot/registry-amd64:2.6
  1 coredns/coredns:1.6.6
  1 docker.io/cdkbot/addon-resizer-amd64:1.8.1
  1 docker.io/cdkbot/hostpath-provisioner-amd64:1.0.0
  1 docker.io/cdkbot/registry-amd64:2.6
  1 docker.io/coredns/coredns:1.6.6
  1 docker.io/grafana/grafana:6.4.3
  2 docker.io/istio/citadel:1.5.1
  2 docker.io/istio/examples-bookinfo-details-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-productpage-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-ratings-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v1:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v2:1.15.0
  2 docker.io/istio/examples-bookinfo-reviews-v3:1.15.0
  2 docker.io/istio/galley:1.5.1
  4 docker.io/istio/kubectl:1.5.1
  4 docker.io/istio/mixer:1.5.1
  2 docker.io/istio/pilot:1.5.1
 34 docker.io/istio/proxyv2:1.5.1
  2 docker.io/istio/sidecar_injector:1.5.1
  2 docker.io/jaegertracing/all-in-one:1.16
  1 docker.io/kubernetesui/dashboard:v2.0.0
  1 docker.io/kubernetesui/metrics-scraper:v1.0.4
  2 docker.io/library/nginx:latest
  2 docker.io/prom/prometheus:v2.12.0
  1 docker.io/radial/busyboxplus:curl
  1 grafana/grafana:6.4.3
  2 k8s.gcr.io/metrics-server-amd64:v0.2.1
  1 kubernetesui/dashboard:v2.0.0
  1 kubernetesui/metrics-scraper:v1.0.4
  2 nginx
  2 quay.io/kiali/kiali:v1.9
  1 radial/busyboxplus:curl

Unfortunately the size of the docker image is missing. Is there a way to get the container image size? Pretty much like docker image ls. Copy of the output from this example for convenience:

$ docker image ls
REPOSITORY                  TAG                 IMAGE ID            CREATED             SIZE
docker.io/ubuntu            latest              3556258649b2        7 days ago          64.2 MB
docker.io/alpine            latest              b7b28af77ffe        2 weeks ago         5.58 MB
docker.io/centos            latest              9f38484d220f        4 months ago        202 MB
docker.io/hello-world       latest              fce289e99eb9        7 months ago        1.84 kB

Body:
On my k8s system kubectl describe pod ABC doesn't show the image size, but you can create a script that:

gets the name of the image (I assuming you have one container in the pod, otherwise the script will be slightly more complicated depending on what you want to print actually)

runs docker image ls on the same machine. This assumes that you actually have that docker image on the machine you're running this command.

You slight format the output of that command to "catch" the image size

All-in-all it looks like this:

docker image ls `kubectl get pod YOUR_POD_NAME_GOES_HERE  -o jsonpath='{.spec.containers[0].image}'` --format='{{println .Size}}'


问:
ViewBinding class not generated
I have enabled view binding in my build.gradle file:

```<code>android {
    ...
    viewBinding {
        enabled = true
    }
}
</code>```

and I've split my layout folders to maintain an order because it is a big project. However, my ViewBinding class isn't being generated.

How to solve this error?

答: I encountered the same issue. I had to update my android studio to a version 3.6 or greater. It will resolve the issue.</p>

Title: ViewBinding class not generated

Body:
I have enabled view binding in my build.gradle file:

android {
    ...
    viewBinding {
        enabled = true
    }
}

and I've split my layout folders to maintain an order because it is a big project. However, my ViewBinding class isn't being generated.

How to solve this error?


问:
how to convert objectid of mongodb child collection to string inplace during aggregation
I have two collections like this:

# col1
[
  {
    _id: '5ec878f79c87a300127ec503',
    name: 'dim'
  },
  {...},
]
```

<pre class="lang-py prettyprint-override"><code># col2
[
  {
    _id: ObjectId('5ec8da619c87a30012f41d0b'),
    record_id: '5ec878f79c87a300127ec503',
    tags: 'authenticated'
  },
  {
    _id: ObjectId('5ec8da619c87a30012ffdsk1'),
    record_id: '5ec878f79c87a300127ec503',
    tags: 'pre'
  },
]
</code>```

I want to join two collections into one and convert col2._id from objectid to string.

heres my aggregate query:

col1.aggregate(
  [
    {'$lookup': {
       'from': 'col2',
       'localField': '_id',
       'foreignField': 'record_id',
       'as': 'records'
    }},
    {'$project': {'records._id': {'$toString': '$records._id'}}}
  ]
)
```

<p>The result I except should be like this:</p>

<pre class="lang-py prettyprint-override"><code># result
[
  {
    '_id': '5ec878f79c87a300127ec503',
    'name': 'dim',
    'records': [
        {
          '_id': '5ec8da619c87a30012f41d0b',
          'record_id': '5ec878f79c87a300127ec503',
          'tags': 'authenticated'
        },
        {
          '_id': '5ec8da619c87a30012ffdsk1',
          'record_id': '5ec878f79c87a300127ec503',
          'tags': 'pre'
        },
      ]
  }
]
</code>```

but I got an error.

Unsupported conversion from array to string in $convert with no onError value
```

<p>I also tried <strong>$addFields</strong> and <strong>$map</strong>. It either override records and return an array, or create a new field. that not what I want.</p>

<pre class="lang-py prettyprint-override"><code>{'$addFields': {
  'records': {
    '$map': {
        'input': '$records',
        'as': 'r',
        'in': {'$toString': '$$r._id'}
      }
    }
}}
</code>```

So my question is: how to convert col2._id from objectid to string inplace during aggregate?

答:
you can try below option where we first convert id to String and store as a convertedIdStr and then using that we do a lookup.

```<code>[
 {
  "$addFields": {
     "convertedIdStr": {
        "$toString": "$_id"
     }
  }
    },
 {
  "$lookup": {
     "from": "test",
     "localField": "convertedIdStr",
     "foreignField": "record_id",
     "as": "records"
  }
 }
]
</code>```

Hope this helps!
Note We run this aggregation on col1 (collection1)

Body:
I have two collections like this:

# col1
[
  {
    _id: '5ec878f79c87a300127ec503',
    name: 'dim'
  },
  {...},
]

# col2
[
  {
    _id: ObjectId('5ec8da619c87a30012f41d0b'),
    record_id: '5ec878f79c87a300127ec503',
    tags: 'authenticated'
  },
  {
    _id: ObjectId('5ec8da619c87a30012ffdsk1'),
    record_id: '5ec878f79c87a300127ec503',
    tags: 'pre'
  },
]

I want to join two collections into one and convert col2._id from objectid to string.

heres my aggregate query:

col1.aggregate(
  [
    {'$lookup': {
       'from': 'col2',
       'localField': '_id',
       'foreignField': 'record_id',
       'as': 'records'
    }},
    {'$project': {'records._id': {'$toString': '$records._id'}}}
  ]
)

The result I except should be like this:

# result
[
  {
    '_id': '5ec878f79c87a300127ec503',
    'name': 'dim',
    'records': [
        {
          '_id': '5ec8da619c87a30012f41d0b',
          'record_id': '5ec878f79c87a300127ec503',
          'tags': 'authenticated'
        },
        {
          '_id': '5ec8da619c87a30012ffdsk1',
          'record_id': '5ec878f79c87a300127ec503',
          'tags': 'pre'
        },
      ]
  }
]

but I got an error.

Unsupported conversion from array to string in $convert with no onError value

I also tried $addFields and $map. It either override records and return an array, or create a new field. that not what I want.

{'$addFields': {
  'records': {
    '$map': {
        'input': '$records',
        'as': 'r',
        'in': {'$toString': '$$r._id'}
      }
    }
}}

So my question is: how to convert col2._id from objectid to string inplace during aggregate?

Body:
you can try below option where we first convert id to String and store as a convertedIdStr and then using that we do a lookup.

[
 {
  "$addFields": {
     "convertedIdStr": {
        "$toString": "$_id"
     }
  }
    },
 {
  "$lookup": {
     "from": "test",
     "localField": "convertedIdStr",
     "foreignField": "record_id",
     "as": "records"
  }
 }
]

Hope this helps!
Note We run this aggregation on col1 (collection1)


问:
How to call a function after closing a popover?
I hope someone can give a beginner some guidance, my problem is this:

I have a popover window
I open that popover with a segue from the mainViewController
I want to trigger a function in the mainViewController when the popover is closed
Inside the popover I have a button to close the popover with the following code:

```<code>@IBAction func closeButton(_ sender: Any) {

        dismiss(animated: true, completion: {checkIfPopoverDismissed()}) // I want to trigger this function in the mainView
    }
</code>```

In the mainViewController I have the following function, that I want to be triggered by the closure of the above popover

```<code> func checkIfPopoverDismissed()
    {
      print("the function is triggered")
    }
</code>```

So with the above I get:

```<code> Use of unresolved identifier 'checkIfPopoverDismissed'
</code>```

Because obviously checkIfPopoverDismissed() is in the mainViewController and does not exist in the popover view.

Any idea how I can make this work simply?

答:
you may use delegation to achieve that:

```<code>// 1. create a protocol before your PopoverViewController:
// (imagine the delegate is your helper and the protocol is the requirement of your helper)

protocol PopoverViewControllerDelegate: class {
    func popoverDidDismissed()
}

class PopoverViewController: UIViewController {
    //2. make a delegate in your view controller
    //(you need a this helper in your class to help you...)
    weak var delegate: PopoverViewControllerDelegate?

    //...

    @IBAction func closeButton(_ sender: Any) {
        //3. ask the delegate to perform its function
        //(when the time is right, ask you helper to do what he is meant to do...)
        dismiss(
            animated: true,
            completion: delegate?.popoverDidDismissed
        )
    }
}
</code>```

Meanwhile in the mainViewController...

```<code>class mainViewController: UIViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destinationVC = segue.destination as? PopoverViewController {
            //4. setup the delegation
            //(say that I (mainViewController) will be the helper of destinationVC)
            destinationVC.delegate = self
        }
    }
}

//5. Conform the protocol
//(need to meet the requirement as this helper, by having a function called popoverDidDismissed...)

extension mainViewController: PopoverViewControllerDelegate {
    func popoverDidDismissed() {
        // do what you want to do here in the main view controller,
        // this function will be called by PopoverViewController when the time is right
    }
}
</code>```

Body:
I hope someone can give a beginner some guidance, my problem is this:

I have a popover window
I open that popover with a segue from the mainViewController
I want to trigger a function in the mainViewController when the popover is closed
Inside the popover I have a button to close the popover with the following code:

@IBAction func closeButton(_ sender: Any) {

        dismiss(animated: true, completion: {checkIfPopoverDismissed()}) // I want to trigger this function in the mainView
    }

In the mainViewController I have the following function, that I want to be triggered by the closure of the above popover

 func checkIfPopoverDismissed()
    {
      print("the function is triggered")
    }

So with the above I get:

 Use of unresolved identifier 'checkIfPopoverDismissed'

Because obviously checkIfPopoverDismissed() is in the mainViewController and does not exist in the popover view.

Any idea how I can make this work simply?

Body:
you may use delegation to achieve that:

// 1. create a protocol before your PopoverViewController:
// (imagine the delegate is your helper and the protocol is the requirement of your helper)

protocol PopoverViewControllerDelegate: class {
    func popoverDidDismissed()
}

class PopoverViewController: UIViewController {
    //2. make a delegate in your view controller
    //(you need a this helper in your class to help you...)
    weak var delegate: PopoverViewControllerDelegate?

    //...

    @IBAction func closeButton(_ sender: Any) {
        //3. ask the delegate to perform its function
        //(when the time is right, ask you helper to do what he is meant to do...)
        dismiss(
            animated: true,
            completion: delegate?.popoverDidDismissed
        )
    }
}

Meanwhile in the mainViewController...

class mainViewController: UIViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destinationVC = segue.destination as? PopoverViewController {
            //4. setup the delegation
            //(say that I (mainViewController) will be the helper of destinationVC)
            destinationVC.delegate = self
        }
    }
}

//5. Conform the protocol
//(need to meet the requirement as this helper, by having a function called popoverDidDismissed...)

extension mainViewController: PopoverViewControllerDelegate {
    func popoverDidDismissed() {
        // do what you want to do here in the main view controller,
        // this function will be called by PopoverViewController when the time is right
    }
}


问:
Timeseries showing date as month of the year
I have dataset and I want to visualize timeseries. However, date axis show dates as timestamps. I want it to show like month of the year (Jan-December). How can i format date in timeseries?

答:
There's a feature that automatically optimizes the x-axis for you. The matplotlib.dates.AutoDateLocator matplotlib.dates.AutoDateLocatoris used. Does your quality match your intentions?

```<code>fig = plt.figure(figsize=(16,9),dpi=144)
ax = fig.add_subplot(111)

plt.plot(df.index, df['data'], linestyle='dashed')

locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

plt.show()
</code>```

Body:
There's a feature that automatically optimizes the x-axis for you. The matplotlib.dates.AutoDateLocator matplotlib.dates.AutoDateLocatoris used. Does your quality match your intentions?

fig = plt.figure(figsize=(16,9),dpi=144)
ax = fig.add_subplot(111)

plt.plot(df.index, df['data'], linestyle='dashed')

locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)

ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

plt.show()


问:
How to run a shell script at startup
On an Amazon S3 Linux instance, I have two scripts called start_my_app and stop_my_app which start and stop forever (which in turn runs my Node.js application). I use these scripts to manually start and stop my Node.js application. So far so good.

My problem: I also want to set it up such that start_my_app is run whenever the system boots up. I know that I need to add a file inside init.d and I know how to symlink it to the proper directory within rc.d, but I can't figure out what actually needs to go inside the file that I place in init.d. I'm thinking it should be just one line, like, start_my_app, but that hasn't been working for me.

答:
Here is a simpler method!

First: write a shell script and save it a .sh
here is an example

```<code>#!/bin/bash
Icoff='/home/akbar/keyboardONOFF/icon/Dt6hQ.png'
id=13
fconfig=".keyboard"
echo "disabled" > $fconfig
xinput float $id
notify-send -i $Icoff "Internal Keyboard disabled";
</code>```

this script will disable the internal keyboard at startup.

Second: Open the application " Startup Application Preferences"

enter image description here

enter image description here

Third: click Add.
fourth: in the NAME section give a name.
fifth: In the command section browse to your .sh .
sixth: edit your command section to:

```<code>bash <space> path/to/file/<filename>.sh <space> --start
</code>```

seventh: click Add. Thats it! Finished!

Now confirm by rebooting your pc.

cheers!

Title: How to run a shell script at startup

Body:
Here is a simpler method!

First: write a shell script and save it a .sh
here is an example

#!/bin/bash
Icoff='/home/akbar/keyboardONOFF/icon/Dt6hQ.png'
id=13
fconfig=".keyboard"
echo "disabled" > $fconfig
xinput float $id
notify-send -i $Icoff "Internal Keyboard disabled";

this script will disable the internal keyboard at startup.

Second: Open the application " Startup Application Preferences"

enter image description here

enter image description here

Third: click Add.
fourth: in the NAME section give a name.
fifth: In the command section browse to your .sh .
sixth: edit your command section to:

bash <space> path/to/file/<filename>.sh <space> --start

seventh: click Add. Thats it! Finished!

Now confirm by rebooting your pc.

cheers!


问:
How to write Laravel One to One relationship model and migration
With One To One relationship, I'm supposed to have only one phone entry per user.

So, why am I able to add multiple phone numbers ?

Does it mean that App\User::find(1)->phone only returns the first phone found in the database ?

Should I add a unique constraint to the user_id column in the phones migration ?

User Model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}
</code>```

Phone model

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}
</code>```

Users table migration:

```<code>Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});
</code>```

Phone migration:

```<code>Schema::create('phones', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->string('phone');
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
</code>```

答:
1) So, why am I able to add multiple phone numbers?

**  While adding a phone number to the database, simply search if the current user has a phone number. If yes, then update it. Else, create a new one. Check updateOrCreate

```<code>// If there is a user with id 2 then SET the phone to 7897897890.
// If no user with id 2 found, then CREATE one with user_id 2 and phone number to 7897897890
Phone::updateOrCreate(
    ['user_id' => 2],
    ['phone' => '7897897890']
);
</code>```

2) Does it mean that App\User::find(1)->phone only returns the first phone found in the database?

**  As long as your relation is hasOne, you fetched data will be one where user_id = current user. If you are planning to have one phone number for each user throughout the project then might I suggest to simply add the phone number column to the users table.

3) Should I add a unique constraint to the user_id column in the phones migration?

**   Yes, you can. However, as I suggested in the second point, just have a phone column in the users table (if you want to, otherwise this will work too)

Body:
With One To One relationship, I'm supposed to have only one phone entry per user.

So, why am I able to add multiple phone numbers ?

Does it mean that App\User::find(1)->phone only returns the first phone found in the database ?

Should I add a unique constraint to the user_id column in the phones migration ?

User Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the phone record associated with the user.
     */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

Phone model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    /**
     * Get the user that owns the phone.
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Users table migration:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Phone migration:

Schema::create('phones', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->string('phone');
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Body:
1) So, why am I able to add multiple phone numbers?

**  While adding a phone number to the database, simply search if the current user has a phone number. If yes, then update it. Else, create a new one. Check updateOrCreate

// If there is a user with id 2 then SET the phone to 7897897890.
// If no user with id 2 found, then CREATE one with user_id 2 and phone number to 7897897890
Phone::updateOrCreate(
    ['user_id' => 2],
    ['phone' => '7897897890']
);

2) Does it mean that App\User::find(1)->phone only returns the first phone found in the database?

**  As long as your relation is hasOne, you fetched data will be one where user_id = current user. If you are planning to have one phone number for each user throughout the project then might I suggest to simply add the phone number column to the users table.

3) Should I add a unique constraint to the user_id column in the phones migration?

**   Yes, you can. However, as I suggested in the second point, just have a phone column in the users table (if you want to, otherwise this will work too)


问:
Change connect.offsets kafka connector error
I sync data from binlog mysql to kafka, and sometime binlog file has been removed, and i get an error when restart connector

org.apache.kafka.connect.errors.ConnectException: The connector is trying to read binlog starting at binlog file 'mysql-bin.000003', pos=154, skipping 0 events plus 0 rows

I change /tmp/connect.offsets to current binlog file. But it loads all data from database push topic again. I want to prevent this, I only want to load changes from binlog file.

答:
this is expected behaviour. The Debezium should never be down that long that any binlog that has not beens seen was removed as this would lead to data inconsistency so the error message is correct.

The right remedy to this situation is using snapshot.mode=when_needed. The other solution you've correctl mentioned is offset manipulation. But here you must have mady any mistake as what you describes sounds like the connecotr was unable to find offsets at all so it think it statrs from scratch and initiates a new snapshot.


问:
Python json.decoder.JSONDecodeError: Extra data
I'm writing a simple program that acts as a login screen. As part of it, I'm having the user create an account that will hold their name, age, city and login info in a JSON document. I've been able to write to the JSON easy enough, however whenever I read from the file it throws the 'Extra Data Error' and says it's on line 2 column 14

I'm using python 3.8.2, if that helps

This is the code in main.py

```<code>import json

def read(accList):
    with open('acc.json') as accountFile:
        first = accountFile.read(1)
        if not first:
            print("No accounts")
        else:
            accList["account"]=json.load(accountFile)
    accountFile.close()
    return(accList)

def write(accList):
    with open('acc.json',"w") as accountFile:
        accountFile.write(json.dumps(accList, indent = 4, sort_keys=True))
    accountFile.close()

def login(accList):
    accList=read(accList)
    user=input("Please enter your username: ")
    password=input("Please enter your password: ")

def create(accList):
    accList=read(accList)
    name=input("Please enter your name: ")
    age =input("How old are you: ")
    city = input("What city do you live in: ")
    user=input("Please create a username: ")
    password=input("Please create a  password: ")
    accList["account"].append({
        "name": name,
        "age": age,
        "city": city,
        "username": user,
        "password": password
    })
    write(accList)

def main():
    accList = {}
    accList["account"] = []
    returning=input("Welcome to Cael's login screen.\nDo you already have an account? ")
    if(returning.lower()=="yes"):
        login(accList)
    elif(returning.lower()=="no"):
        create(accList)
    #else:
     #   print("Sorry that's not a valid answer. Please only type \'Yes\' or \'No\'.")
main()
</code>```

And here's the output that I have in the JSON (NOTE: It works fine adding one account but throws the error after that)

```<code>{
    "account": [
        {
            "age": "52",
            "city": "Jerome",
            "name": "Maynard",
            "password": "pass",
            "username": "mjkeenan"
        }
    ]
}
</code>```

Sorry if this seems like a bit of a stupid question, or if there's an obvious mistake. I'm still new to JSON files as a whole

答:
That error is because once you read a file the pointer will be at the end, so that is the reason why that error occurs, and after debugging that an another error has been thrown that dict object does not have append method and i just debugged it </p>

```<code>import json

def read(accList):
    with open('acc.json') as accountFile:
        first = accountFile.read(1)
        # This will make the pointer to point at the beggining of the file
        accountFile.seek(0)

        if not first:
            print("No accounts")
        else:
            # this is to access only the account list and not the whole dictionary
            accList["account"]=json.load(accountFile)["account"]
    accountFile.close()
    return(accList)

def write(accList):
    with open('acc.json',"w") as accountFile:
        accountFile.write(json.dumps(accList, indent = 4, sort_keys=True))
    accountFile.close()

def login(accList):
    accList=read(accList)
    user=input("Please enter your username: ")
    password=input("Please enter your password: ")

def create(accList):
    accList=read(accList)
    name=input("Please enter your name: ")
    age =input("How old are you: ")
    city = input("What city do you live in: ")
    user=input("Please create a username: ")
    password=input("Please create a  password: ")
    accList["account"].append({
        "name": name,
        "age": age,
        "city": city,
        "username": user,
        "password": password
    })
    write(accList)

def main():
    accList = {}
    accList["account"] = []
    returning=input("Welcome to Cael's login screen.\nDo you already have an account? ")
    if(returning.lower()=="yes"):
        login(accList)
    elif(returning.lower()=="no"):
        create(accList)
    #else:
     #   print("Sorry that's not a valid answer. Please only type \'Yes\' or \'No\'.")
main()
</code>```

Body:
I'm writing a simple program that acts as a login screen. As part of it, I'm having the user create an account that will hold their name, age, city and login info in a JSON document. I've been able to write to the JSON easy enough, however whenever I read from the file it throws the 'Extra Data Error' and says it's on line 2 column 14

I'm using python 3.8.2, if that helps

This is the code in main.py

import json

def read(accList):
    with open('acc.json') as accountFile:
        first = accountFile.read(1)
        if not first:
            print("No accounts")
        else:
            accList["account"]=json.load(accountFile)
    accountFile.close()
    return(accList)

def write(accList):
    with open('acc.json',"w") as accountFile:
        accountFile.write(json.dumps(accList, indent = 4, sort_keys=True))
    accountFile.close()

def login(accList):
    accList=read(accList)
    user=input("Please enter your username: ")
    password=input("Please enter your password: ")

def create(accList):
    accList=read(accList)
    name=input("Please enter your name: ")
    age =input("How old are you: ")
    city = input("What city do you live in: ")
    user=input("Please create a username: ")
    password=input("Please create a  password: ")
    accList["account"].append({
        "name": name,
        "age": age,
        "city": city,
        "username": user,
        "password": password
    })
    write(accList)

def main():
    accList = {}
    accList["account"] = []
    returning=input("Welcome to Cael's login screen.\nDo you already have an account? ")
    if(returning.lower()=="yes"):
        login(accList)
    elif(returning.lower()=="no"):
        create(accList)
    #else:
     #   print("Sorry that's not a valid answer. Please only type \'Yes\' or \'No\'.")
main()

And here's the output that I have in the JSON (NOTE: It works fine adding one account but throws the error after that)

{
    "account": [
        {
            "age": "52",
            "city": "Jerome",
            "name": "Maynard",
            "password": "pass",
            "username": "mjkeenan"
        }
    ]
}

Sorry if this seems like a bit of a stupid question, or if there's an obvious mistake. I'm still new to JSON files as a whole

Body:
That error is because once you read a file the pointer will be at the end, so that is the reason why that error occurs, and after debugging that an another error has been thrown that dict object does not have append method and i just debugged it

import json

def read(accList):
    with open('acc.json') as accountFile:
        first = accountFile.read(1)
        # This will make the pointer to point at the beggining of the file
        accountFile.seek(0)

        if not first:
            print("No accounts")
        else:
            # this is to access only the account list and not the whole dictionary
            accList["account"]=json.load(accountFile)["account"]
    accountFile.close()
    return(accList)

def write(accList):
    with open('acc.json',"w") as accountFile:
        accountFile.write(json.dumps(accList, indent = 4, sort_keys=True))
    accountFile.close()

def login(accList):
    accList=read(accList)
    user=input("Please enter your username: ")
    password=input("Please enter your password: ")

def create(accList):
    accList=read(accList)
    name=input("Please enter your name: ")
    age =input("How old are you: ")
    city = input("What city do you live in: ")
    user=input("Please create a username: ")
    password=input("Please create a  password: ")
    accList["account"].append({
        "name": name,
        "age": age,
        "city": city,
        "username": user,
        "password": password
    })
    write(accList)

def main():
    accList = {}
    accList["account"] = []
    returning=input("Welcome to Cael's login screen.\nDo you already have an account? ")
    if(returning.lower()=="yes"):
        login(accList)
    elif(returning.lower()=="no"):
        create(accList)
    #else:
     #   print("Sorry that's not a valid answer. Please only type \'Yes\' or \'No\'.")
main()