问:
Return JSX from function
I have a a component that needs to check for multiple options and return based on those options. Therefore I have created an outside function that is called in my component return statement to determine the format that will be returned:

render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (

          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (

{ policy.displayName }

                    { this.renderSp4Policies(policy) }

                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>

      )
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let firmwareDropdownNames = this.formatFirmawareDropdownNames(policy);
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      let toggleOptions = []
      Object.keys(toggles).map(toggle => {
       if(typeof(toggles[toggle]) == "boolean"){
          var obj = {};
          obj[toggle] = toggles[toggle];
        toggleOptions.push(obj);
        }
      })
      return (
        toggleOptions.map(toggleOption => {
          let toggleName = Object.keys(toggleOption).toString();
          return (
            <Form.Field key={ toggleName }>
              { toggleName }
              <Checkbox toggle />
            </Form.Field>
          )
        })
      )
    } else {
        return (
          policy.values.map(value => {
            return(
              <Form.Field key={ value.name }>
                { value.displayName || value.name }
                <Checkbox toggle />
              </Form.Field>
            )
          }
        )
      )
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

EDIT

I have applied some of the answers given with moderate success.

Within renderSp4Policies what is being returned in the else statement displays, but the beginning if(policy.displayName == "Firmware Options") returns nothing.

Appreciate all advice, thank you in advance!

答:
Your map function doesn't return anything:

```<code>policy.values.map(value => {
            <Form.Field key={ value.name }>
              <label>{ value.displayName || value.name }</label>
              <Checkbox toggle />
            </Form.Field>
          }
</code>```

When using an arrow function block {} you should add an explicit return statement:

```<code>policy.values.map(value => {
            return(<Form.Field key={ value.name }>
              <label>{ value.displayName || value.name }</label>
              <Checkbox toggle />
            </Form.Field>)
          }
</code>```

Edit

As a followup to your comment.

As for the first if statement, don't use a forEach, use a map. same as you did in the second if statement (don't forget the return!)

```<code>renderSp4Policies(policy) {
  if (policy.displayName == "Firmware Options") {
    let toggles = policy.values[0][Object.keys(policy.values[0])];
    Object.keys(toggles).forEach(toggle => {
      if (typeof (toggles[toggle]) !== "boolean") {
        delete toggles[toggle];
      }
    })
    return (
      Object.keys(toggles).map(toggle => {
        return (
          <Form.Field key={toggle}>
            <label> {toggle} </label>
            <Checkbox toggle />
          </Form.Field>
        );
      })
    )
  } else {
    return (
      policy.values.map(value => {
        <Form.Field key={value.name}>
          <label>{value.displayName || value.name}</label>
          <Checkbox toggle />
        </Form.Field>
      })
    );
  }
}
</code>```

Title: Return JSX from function

Body:
I have a a component that needs to check for multiple options and return based on those options. Therefore I have created an outside function that is called in my component return statement to determine the format that will be returned:

render() {
    const { policy } = this.props;
    let deployment = policy.Deployment;
    let value = policy.value;
    let policyLegend = deployment.policyLegend;
    let policyObj = this.valueToPolicy(policyLegend, value);
    console.log(policyObj);
    if(policy.name == "SP4") {
      policyLegend[1].values = this.formatSp4Firmware(policyLegend[1]);
      return (

          <Form onSubmit={ (event) => this.handleSubmit(event, this.props) }>
            {
              policyLegend.map((policy) => {
                return (

{ policy.displayName }

                    { this.renderSp4Policies(policy) }

                );
              })
            }
            <Button name={ 'Submit' } type='submit'>Submit</Button>
            <Button onClick={ this.props.onCancel }>Cancel</Button>
          </Form>

      )
    }
  }

renderSp4Policies(policy) {
    if(policy.displayName == "Firmware Options") {
      let firmwareDropdownNames = this.formatFirmawareDropdownNames(policy);
      let toggles = policy.values[0][Object.keys(policy.values[0])];
      let toggleOptions = []
      Object.keys(toggles).map(toggle => {
       if(typeof(toggles[toggle]) == "boolean"){
          var obj = {};
          obj[toggle] = toggles[toggle];
        toggleOptions.push(obj);
        }
      })
      return (
        toggleOptions.map(toggleOption => {
          let toggleName = Object.keys(toggleOption).toString();
          return (
            <Form.Field key={ toggleName }>
              { toggleName }
              <Checkbox toggle />
            </Form.Field>
          )
        })
      )
    } else {
        return (
          policy.values.map(value => {
            return(
              <Form.Field key={ value.name }>
                { value.displayName || value.name }
                <Checkbox toggle />
              </Form.Field>
            )
          }
        )
      )
    }
  }

EDIT

I have applied some of the answers given with moderate success.

Within renderSp4Policies what is being returned in the else statement displays, but the beginning if(policy.displayName == "Firmware Options") returns nothing.

Appreciate all advice, thank you in advance!

Body:
Your map function doesn't return anything:

policy.values.map(value => {
            <Form.Field key={ value.name }>
              <label>{ value.displayName || value.name }</label>
              <Checkbox toggle />
            </Form.Field>
          }

When using an arrow function block {} you should add an explicit return statement:

policy.values.map(value => {
            return(<Form.Field key={ value.name }>
              <label>{ value.displayName || value.name }</label>
              <Checkbox toggle />
            </Form.Field>)
          }

Edit

As a followup to your comment.

As for the first if statement, don't use a forEach, use a map. same as you did in the second if statement (don't forget the return!)

renderSp4Policies(policy) {
  if (policy.displayName == "Firmware Options") {
    let toggles = policy.values[0][Object.keys(policy.values[0])];
    Object.keys(toggles).forEach(toggle => {
      if (typeof (toggles[toggle]) !== "boolean") {
        delete toggles[toggle];
      }
    })
    return (
      Object.keys(toggles).map(toggle => {
        return (
          <Form.Field key={toggle}>
            <label> {toggle} </label>
            <Checkbox toggle />
          </Form.Field>
        );
      })
    )
  } else {
    return (
      policy.values.map(value => {
        <Form.Field key={value.name}>
          <label>{value.displayName || value.name}</label>
          <Checkbox toggle />
        </Form.Field>
      })
    );
  }
}


来源: stackexchange

问:
Jest mock redux-store getState() used in module with redux-mock-store
So my implementation of the redux-store might not be the best and my knowledge of Jest is minimum-to-none..

I have three files which consists of...

A module

A React Component

The (a normal) store, exported as default

My test file looks like this:

```<code>// file.test.js

jest.mock( 'store', () => jest.fn() )

// external
import React from 'react'
import configureStore from 'redux-mock-store'

// internal
import Component from 'components/Component'
import store from 'store'

describe( 'Test My Component', () => {
    const mockStore = configureStore()

    it ( 'should equal true', () => {
        const initialState = { active: true }

        store.mockImplementation(() => mockStore( initialState ))

        expect( store.getState().active ).toBe( true )
    } )
} );
</code>```

The reason why I am mocking store is because inside <Component /> I am using a module which itself imports the same store and holds a few function that are making use of store.getState()...

So what this returns is

TypeError: _store2.default.getState is not a function

I did get around this by mocking the module call (which is used by the <Component />) instead, but I feel like I "should" be able to do this, as I have different initial states I want to try and not all are dependent on the module.

This is my very first post on SO, let me know If I should clarify anything!

答:
Do not import the store. We want to mock the store:

const store = mockStore(initialState);

ContentLicense: CC BY-SA 3.0

Body:
So my implementation of the redux-store might not be the best and my knowledge of Jest is minimum-to-none..

I have three files which consists of...

A module

A React Component

The (a normal) store, exported as default

My test file looks like this:

// file.test.js

jest.mock( 'store', () => jest.fn() )

// external
import React from 'react'
import configureStore from 'redux-mock-store'

// internal
import Component from 'components/Component'
import store from 'store'

describe( 'Test My Component', () => {
    const mockStore = configureStore()

    it ( 'should equal true', () => {
        const initialState = { active: true }

        store.mockImplementation(() => mockStore( initialState ))

        expect( store.getState().active ).toBe( true )
    } )
} );

The reason why I am mocking store is because inside <Component /> I am using a module which itself imports the same store and holds a few function that are making use of store.getState()...

So what this returns is

TypeError: _store2.default.getState is not a function

I did get around this by mocking the module call (which is used by the <Component />) instead, but I feel like I "should" be able to do this, as I have different initial states I want to try and not all are dependent on the module.

This is my very first post on SO, let me know If I should clarify anything!


问:
Image is not loading
I was wondering why the image here is not loading at all. The XML file does not show the image, it does however show the TextView and the Button.

Please help.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="177dp"
        android:layout_height="wrap_content"
        android:text="Middle Right Pop Up" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />

    <ImageView
        android:id="@+id/small_circle"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/small_compass" />

</LinearLayout>
</code>```

,

```<code>public class PopUpMiddleRight extends Activity{

    ImageView compass;
    private float currentDegree = 0f;
    private static SensorManager sensorService;
    private Sensor sensor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pop_up_middle_right);

        WindowManager.LayoutParams windowManager =
getWindow().getAttributes();
        windowManager.dimAmount = 0.75f;

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int width = dm.widthPixels;
        int height = dm.heightPixels;

        getWindow().setLayout((int)(width * .8), (int)(height * .6));

    }

}
</code>```

I am trying to make a pop up window so it would look something like this:

Also Please note that I am referencing the image in another place in my code, so it can read the image.

答:
Replace
  app:srcCompat="@drawable/small_compass" to android:src="@drawable/small_compass" instead

Title: Image is not loading

Body:
I was wondering why the image here is not loading at all. The XML file does not show the image, it does however show the TextView and the Button.

Please help.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="177dp"
        android:layout_height="wrap_content"
        android:text="Middle Right Pop Up" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />

    <ImageView
        android:id="@+id/small_circle"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/small_compass" />

</LinearLayout>

,

public class PopUpMiddleRight extends Activity{

    ImageView compass;
    private float currentDegree = 0f;
    private static SensorManager sensorService;
    private Sensor sensor;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_pop_up_middle_right);

        WindowManager.LayoutParams windowManager =
getWindow().getAttributes();
        windowManager.dimAmount = 0.75f;

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int width = dm.widthPixels;
        int height = dm.heightPixels;

        getWindow().setLayout((int)(width * .8), (int)(height * .6));

    }

}

I am trying to make a pop up window so it would look something like this:

Also Please note that I am referencing the image in another place in my code, so it can read the image.


问:
Benchmark variadic template function call
I used Quick bench (see link below) to measure the performance between decoding a buffer with call to a function with variadic template arguments versus decoding the same buffer with call to a function without variadic pack expansion.

Any idea on how to make the variadic implementation on par with the other implementation?

The result from the benchmark is a ratio of (CPU time / Noop time). The benchmark runs on a pool of AWS machines whose load is unknown. The purpose is to give a reasonnably good comparison between two snippet of code, run in the same conditions. The CPU time for the non variadic template function was 5.9 and for the variadic implementation it was 21.3. Compiler: Clang 5.0 with optimization level O3.

```<code>#include <cstdint>
#include <cstring>
#include <string>
#include <type_traits>

namespace core { namespace decoder
{
   class LittleEndian
   {
   public:
      LittleEndian(const LittleEndian&) = delete;
      LittleEndian& operator=(const LittleEndian&) = delete;

   public:
      constexpr LittleEndian(const std::uint8_t* buffer, size_t size) noexcept
      : m_buffer(buffer),
        m_size(size)
      {}

      constexpr bool decodeU8(
        size_t& offset, std::uint8_t& decodedValue) const noexcept
      {
        if (offset >= m_size)
            return false;

        decodedValue = m_buffer[offset];
        offset += sizeof(std::uint8_t);
        return true;
      }

      constexpr bool decodeU16(
        size_t& offset, std::uint16_t& decodedValue) const noexcept
      {
        if (offset + sizeof(std::uint16_t) > m_size)
            return false;

        const uint8_t b0 = m_buffer[offset], b1 = m_buffer[offset + 1];
        decodedValue = (b0 << 0) | (b1 << 8);
        offset += sizeof(std::uint16_t);
        return true;
      }

      constexpr bool decodeU32(
        size_t& offset, std::uint32_t& decodedValue) const noexcept
      {
        if (offset + sizeof(std::uint32_t) > m_size)
            return false;

        const uint8_t b0 = m_buffer[offset], b1 = m_buffer[offset + 1], b2 = m_buffer[offset + 2], b3 = m_buffer[offset + 3];
        decodedValue = (b0 << 0) | (b1 << 8) | (b2 << 16) | (b3 << 24);
        offset += sizeof(std::uint32_t);
        return true;
      }

      constexpr bool decodeU64(
        size_t& offset, std::uint64_t& decodedValue) const noexcept
      {
        if (offset + sizeof(std::uint64_t) > m_size)
            return false;

        const uint8_t b0 = m_buffer[offset], b1 = m_buffer[offset + 1],
            b2 = m_buffer[offset + 2], b3 = m_buffer[offset + 3],
            b4 = m_buffer[offset + 4], b5 = m_buffer[offset + 5],
            b6 = m_buffer[offset + 6], b7 = m_buffer[offset + 7];

        decodedValue = (static_cast<std::uint64_t>(b0) << 0) |
            (static_cast<std::uint64_t>(b1) << 8) |
            (static_cast<std::uint64_t>(b2) << 16) |
            (static_cast<std::uint64_t>(b3) << 24) |
            (static_cast<std::uint64_t>(b4) << 32) |
            (static_cast<std::uint64_t>(b5) << 40) |
            (static_cast<std::uint64_t>(b6) << 48) |
            (static_cast<std::uint64_t>(b7) << 56);

        offset += sizeof(std::uint64_t);
        return true;
      }

  private:
    const std::uint8_t* m_buffer;
    const size_t m_size;
  };

  template<typename EndianDecoderT>
  class ByteDecoder
  {
  public:
    ByteDecoder(const ByteDecoder&) = delete;
    ByteDecoder& operator=(const ByteDecoder&) = delete;

  public:
    constexpr ByteDecoder(const std::uint8_t* buffer, size_t size)
      : m_buffer(buffer),
        m_size(size),
        m_endianDecoder(buffer, size)
    {}

    template<typename ...Args>
    constexpr bool decode(size_t offset, Args&... args) const noexcept
    {
        bool success = true;

        using expand_type = int[];
        expand_type
        {
            ([&success] (auto result) noexcept
            {
                success = (!success || !result) ? false : true;

            } (decodeValue(offset, args)), 0)...
        };

        return success;

      }

      template<typename T>
      constexpr bool decode(size_t offset, T& decodedValue) const noexcept
      {
        return decodeValue(offset, decodedValue);
      }

   private:
    template<typename T>
    constexpr bool decodeValue(
        size_t &offset, T& decodedValue) const noexcept
    {
        if constexpr (std::is_same< std::decay_t<T>, std::uint8_t>::value)
            return m_endianDecoder.decodeU8(offset, decodedValue);

        if constexpr (std::is_same< std::decay_t<T>, std::uint16_t>::value)
            return m_endianDecoder.decodeU16(offset, decodedValue);

        if constexpr (std::is_same< std::decay_t<T>, std::uint32_t>::value)
            return m_endianDecoder.decodeU32(offset, decodedValue);

        if constexpr (std::is_same< std::decay_t<T>, std::uint64_t>::value)
            return m_endianDecoder.decodeU64(offset, decodedValue);

        if constexpr (std::is_same<char *, typename std::decay<T>::type>::value ||
                      std::is_same<char const *, typename std::decay<T>::type>::value)
            return decodeCHR(offset, decodedValue);

        return false;
      }

      template<size_t SIZE>
      constexpr bool decodeCHR(
        size_t &offset, char (&buffer)[SIZE]) const noexcept
      {
        if (offset + SIZE > m_size)
            return false;

        memset(&buffer[0], 0x00, sizeof(char) * SIZE);
        memcpy(&buffer[0], &m_buffer[offset], sizeof(char) * (std::min)(SIZE, std::extent<decltype(buffer)>::value - 1));
        offset += SIZE;
        return true;
      }

  private:
    const std::uint8_t* m_buffer;
    const size_t m_size;
    EndianDecoderT m_endianDecoder;
  };

}} // namespace core::decoder
</code>```

```<code>static void NonVariadicDecoding(benchmark::State& state) {
// Code inside this loop is measured repeatedly
constexpr std::uint8_t littleEndian[] = { 0x0D, 0x0C, 0x84, 0x03, 0x00, 0x00, 'H', 'e', 'l', 'l', 'o', '\0',  0x84, 0x03, 0x84, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
core::decoder::ByteDecoder<core::decoder::LittleEndian> decoder(littleEndian, sizeof(littleEndian));

for (auto _ : state) {

  size_t offset = 0;

  struct DecodedValue
  {
      std::uint16_t v1_U16;
      std::uint32_t v2_U32;
      char v3_CHR[6];
      std::uint16_t v4_U16;
      std::uint64_t v5_U64;
  };
  DecodedValue dv;

  decoder.decode(offset, dv.v1_U16);
  offset += sizeof(dv.v1_U16);
  decoder.decode(offset, dv.v2_U32);
  offset += sizeof(dv.v2_U32);
  decoder.decode(offset, dv.v3_CHR);
  offset += sizeof(dv.v3_CHR);
  decoder.decode(offset, dv.v4_U16);
  offset += sizeof(dv.v4_U16);
  decoder.decode(offset, dv.v5_U64);

  benchmark::DoNotOptimize(dv);
  }
}
// Register the function as a benchmark
BENCHMARK(NonVariadicDecoding);
</code>```

```<code>static void VariadicDecoding(benchmark::State& state) {
// Code before the loop is not measured
constexpr std::uint8_t littleEndian[] = { 0x0D, 0x0C, 0x84, 0x03, 0x00, 0x00, 'H', 'e', 'l', 'l', 'o', '\0',  0x84, 0x03, 0x84, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
core::decoder::ByteDecoder<core::decoder::LittleEndian> decoder(littleEndian, sizeof(littleEndian));

for (auto _ : state) {

  struct DecodedValue
  {
      std::uint16_t v1_U16;
      std::uint32_t v2_U32;
      char v3_CHR[6];
      std::uint16_t v4_U16;
      std::uint64_t v5_U64;
  };

  DecodedValue dv;
  decoder.decode(0, dv.v1_U16, dv.v2_U32, dv.v3_CHR, dv.v4_U16, dv.v5_U64);
  benchmark::DoNotOptimize(dv);
  }
}
BENCHMARK(VariadicDecoding);
</code>```

Quick-Bench

答:
If you have recursive calls to your variadic implementation and use perfect forwarding then you can have better performance:

```<code>    template <typename Type>
    constexpr bool decode_impl(size_t offset, Type&& value) const noexcept
    {
      return decodeValue(offset, std::forward<Type>(value));
    }

    template <typename First, typename Second, typename... Other>
    constexpr bool decode_impl(size_t offset, First&& first, Second&& second, Other&&... others) const noexcept
    {
      return decode_impl(offset, std::forward<First>(first)) && decode_impl(offset, std::forward<Second>(second), std::forward<Other>(others)...);
    }

    template<typename ...Args>
    constexpr bool decode(size_t offset, Args&&... args) const noexcept
    {
      return decode_impl(offset, std::forward<Args>(args)...);
    }
</code>```

See there.

Body:
I used Quick bench (see link below) to measure the performance between decoding a buffer with call to a function with variadic template arguments versus decoding the same buffer with call to a function without variadic pack expansion.

Any idea on how to make the variadic implementation on par with the other implementation?

The result from the benchmark is a ratio of (CPU time / Noop time). The benchmark runs on a pool of AWS machines whose load is unknown. The purpose is to give a reasonnably good comparison between two snippet of code, run in the same conditions. The CPU time for the non variadic template function was 5.9 and for the variadic implementation it was 21.3. Compiler: Clang 5.0 with optimization level O3.

#include <cstdint>
#include <cstring>
#include <string>
#include <type_traits>

namespace core { namespace decoder
{
   class LittleEndian
   {
   public:
      LittleEndian(const LittleEndian&) = delete;
      LittleEndian& operator=(const LittleEndian&) = delete;

   public:
      constexpr LittleEndian(const std::uint8_t* buffer, size_t size) noexcept
      : m_buffer(buffer),
        m_size(size)
      {}

      constexpr bool decodeU8(
        size_t& offset, std::uint8_t& decodedValue) const noexcept
      {
        if (offset >= m_size)
            return false;

        decodedValue = m_buffer[offset];
        offset += sizeof(std::uint8_t);
        return true;
      }

      constexpr bool decodeU16(
        size_t& offset, std::uint16_t& decodedValue) const noexcept
      {
        if (offset + sizeof(std::uint16_t) > m_size)
            return false;

        const uint8_t b0 = m_buffer[offset], b1 = m_buffer[offset + 1];
        decodedValue = (b0 << 0) | (b1 << 8);
        offset += sizeof(std::uint16_t);
        return true;
      }

      constexpr bool decodeU32(
        size_t& offset, std::uint32_t& decodedValue) const noexcept
      {
        if (offset + sizeof(std::uint32_t) > m_size)
            return false;

        const uint8_t b0 = m_buffer[offset], b1 = m_buffer[offset + 1], b2 = m_buffer[offset + 2], b3 = m_buffer[offset + 3];
        decodedValue = (b0 << 0) | (b1 << 8) | (b2 << 16) | (b3 << 24);
        offset += sizeof(std::uint32_t);
        return true;
      }

      constexpr bool decodeU64(
        size_t& offset, std::uint64_t& decodedValue) const noexcept
      {
        if (offset + sizeof(std::uint64_t) > m_size)
            return false;

        const uint8_t b0 = m_buffer[offset], b1 = m_buffer[offset + 1],
            b2 = m_buffer[offset + 2], b3 = m_buffer[offset + 3],
            b4 = m_buffer[offset + 4], b5 = m_buffer[offset + 5],
            b6 = m_buffer[offset + 6], b7 = m_buffer[offset + 7];

        decodedValue = (static_cast<std::uint64_t>(b0) << 0) |
            (static_cast<std::uint64_t>(b1) << 8) |
            (static_cast<std::uint64_t>(b2) << 16) |
            (static_cast<std::uint64_t>(b3) << 24) |
            (static_cast<std::uint64_t>(b4) << 32) |
            (static_cast<std::uint64_t>(b5) << 40) |
            (static_cast<std::uint64_t>(b6) << 48) |
            (static_cast<std::uint64_t>(b7) << 56);

        offset += sizeof(std::uint64_t);
        return true;
      }

  private:
    const std::uint8_t* m_buffer;
    const size_t m_size;
  };

  template<typename EndianDecoderT>
  class ByteDecoder
  {
  public:
    ByteDecoder(const ByteDecoder&) = delete;
    ByteDecoder& operator=(const ByteDecoder&) = delete;

  public:
    constexpr ByteDecoder(const std::uint8_t* buffer, size_t size)
      : m_buffer(buffer),
        m_size(size),
        m_endianDecoder(buffer, size)
    {}

    template<typename ...Args>
    constexpr bool decode(size_t offset, Args&... args) const noexcept
    {
        bool success = true;

        using expand_type = int[];
        expand_type
        {
            ([&success] (auto result) noexcept
            {
                success = (!success || !result) ? false : true;

            } (decodeValue(offset, args)), 0)...
        };

        return success;

      }

      template<typename T>
      constexpr bool decode(size_t offset, T& decodedValue) const noexcept
      {
        return decodeValue(offset, decodedValue);
      }

   private:
    template<typename T>
    constexpr bool decodeValue(
        size_t &offset, T& decodedValue) const noexcept
    {
        if constexpr (std::is_same< std::decay_t<T>, std::uint8_t>::value)
            return m_endianDecoder.decodeU8(offset, decodedValue);

        if constexpr (std::is_same< std::decay_t<T>, std::uint16_t>::value)
            return m_endianDecoder.decodeU16(offset, decodedValue);

        if constexpr (std::is_same< std::decay_t<T>, std::uint32_t>::value)
            return m_endianDecoder.decodeU32(offset, decodedValue);

        if constexpr (std::is_same< std::decay_t<T>, std::uint64_t>::value)
            return m_endianDecoder.decodeU64(offset, decodedValue);

        if constexpr (std::is_same<char *, typename std::decay<T>::type>::value ||
                      std::is_same<char const *, typename std::decay<T>::type>::value)
            return decodeCHR(offset, decodedValue);

        return false;
      }

      template<size_t SIZE>
      constexpr bool decodeCHR(
        size_t &offset, char (&buffer)[SIZE]) const noexcept
      {
        if (offset + SIZE > m_size)
            return false;

        memset(&buffer[0], 0x00, sizeof(char) * SIZE);
        memcpy(&buffer[0], &m_buffer[offset], sizeof(char) * (std::min)(SIZE, std::extent<decltype(buffer)>::value - 1));
        offset += SIZE;
        return true;
      }

  private:
    const std::uint8_t* m_buffer;
    const size_t m_size;
    EndianDecoderT m_endianDecoder;
  };

}} // namespace core::decoder

static void NonVariadicDecoding(benchmark::State& state) {
// Code inside this loop is measured repeatedly
constexpr std::uint8_t littleEndian[] = { 0x0D, 0x0C, 0x84, 0x03, 0x00, 0x00, 'H', 'e', 'l', 'l', 'o', '\0',  0x84, 0x03, 0x84, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
core::decoder::ByteDecoder<core::decoder::LittleEndian> decoder(littleEndian, sizeof(littleEndian));

for (auto _ : state) {

  size_t offset = 0;

  struct DecodedValue
  {
      std::uint16_t v1_U16;
      std::uint32_t v2_U32;
      char v3_CHR[6];
      std::uint16_t v4_U16;
      std::uint64_t v5_U64;
  };
  DecodedValue dv;

  decoder.decode(offset, dv.v1_U16);
  offset += sizeof(dv.v1_U16);
  decoder.decode(offset, dv.v2_U32);
  offset += sizeof(dv.v2_U32);
  decoder.decode(offset, dv.v3_CHR);
  offset += sizeof(dv.v3_CHR);
  decoder.decode(offset, dv.v4_U16);
  offset += sizeof(dv.v4_U16);
  decoder.decode(offset, dv.v5_U64);

  benchmark::DoNotOptimize(dv);
  }
}
// Register the function as a benchmark
BENCHMARK(NonVariadicDecoding);

static void VariadicDecoding(benchmark::State& state) {
// Code before the loop is not measured
constexpr std::uint8_t littleEndian[] = { 0x0D, 0x0C, 0x84, 0x03, 0x00, 0x00, 'H', 'e', 'l', 'l', 'o', '\0',  0x84, 0x03, 0x84, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
core::decoder::ByteDecoder<core::decoder::LittleEndian> decoder(littleEndian, sizeof(littleEndian));

for (auto _ : state) {

  struct DecodedValue
  {
      std::uint16_t v1_U16;
      std::uint32_t v2_U32;
      char v3_CHR[6];
      std::uint16_t v4_U16;
      std::uint64_t v5_U64;
  };

  DecodedValue dv;
  decoder.decode(0, dv.v1_U16, dv.v2_U32, dv.v3_CHR, dv.v4_U16, dv.v5_U64);
  benchmark::DoNotOptimize(dv);
  }
}
BENCHMARK(VariadicDecoding);

Quick-Bench

Body:
If you have recursive calls to your variadic implementation and use perfect forwarding then you can have better performance:

    template <typename Type>
    constexpr bool decode_impl(size_t offset, Type&& value) const noexcept
    {
      return decodeValue(offset, std::forward<Type>(value));
    }

    template <typename First, typename Second, typename... Other>
    constexpr bool decode_impl(size_t offset, First&& first, Second&& second, Other&&... others) const noexcept
    {
      return decode_impl(offset, std::forward<First>(first)) && decode_impl(offset, std::forward<Second>(second), std::forward<Other>(others)...);
    }

    template<typename ...Args>
    constexpr bool decode(size_t offset, Args&&... args) const noexcept
    {
      return decode_impl(offset, std::forward<Args>(args)...);
    }

See there.


问:
Strict Alternation for 3 processes
Well, Recently I have come to learn Strict Alternation while studying operating systems concepts. To reduce chances of race condition and handle two processes we go like this:

Process 0:

```<code>While (TRUE) {

    while (turn != 0); // wait
    critical_section();
    turn = 1;
    noncritical_section();}

}
</code>```

Process 1:

```<code>While (TRUE) {

    while (turn != 1); // wait
    critical_section();
    turn = 0;
    noncritical_section();

}
</code>```

But I'm wondering how I can handle 3 processes to reduce racing condition even more?

My approach is:
Process 0:

```<code>while (turn != 0 && turn != 2); // wait
critical_section();
turn = 1;
noncritical_section();}
</code>```

Process 1:

```<code>while (turn != 1 && turn != 0); // wait
critical_section();
turn = 2;
noncritical_section();}
</code>```

Process 3:

```<code>while (turn != 1 && turn != 2); // wait
critical_section();
turn = 0;
noncritical_section();}
</code>```

Is my approach okay? what do you guys suggest? and are there anything better out there?

Thanks

答: With what you have it wouldn't necessarily strictly alternate anyway, for instance, it could go into turn = 0 and the turn = 1 or turn = 2 code could follow. My suggestion would be to use OS-level events, one for each code path and each process triggers the one that follows.</p>

Title: Strict Alternation for 3 processes

Body:
Well, Recently I have come to learn Strict Alternation while studying operating systems concepts. To reduce chances of race condition and handle two processes we go like this:

Process 0:

While (TRUE) {

    while (turn != 0); // wait
    critical_section();
    turn = 1;
    noncritical_section();}

}

Process 1:

While (TRUE) {

    while (turn != 1); // wait
    critical_section();
    turn = 0;
    noncritical_section();

}

But I'm wondering how I can handle 3 processes to reduce racing condition even more?

My approach is:
Process 0:

while (turn != 0 && turn != 2); // wait
critical_section();
turn = 1;
noncritical_section();}

Process 1:

while (turn != 1 && turn != 0); // wait
critical_section();
turn = 2;
noncritical_section();}

Process 3:

while (turn != 1 && turn != 2); // wait
critical_section();
turn = 0;
noncritical_section();}

Is my approach okay? what do you guys suggest? and are there anything better out there?

Thanks


问:
Failure to connect to odbc database in R
I've been trying to connect my company's DMS to R using the odbcConnect command, but get the following message:

```<code>myConn <-odbcConnect("NZSQL", uid="cejacobson", pwd="password")
Warning messages:
1: In odbcDriverConnect("DSN=NZSQL;UID=cejacobson;PWD=password") :
  [RODBC] ERROR: state IM002, code 0, message [unixODBC][Driver Manager]Data source name not found, and no default driver specified
2: In odbcDriverConnect("DSN=NZSQL;UID=cejacobson;PWD=password") :
  ODBC connection failed
</code>```

The thing is, I'm positive the Data source name is NZSQL and my uid and password are correct as well. Any insight as to why R may not be finding my data source / driver (the driver is, by the way, specified and working).

How can I fix this?

答:
This is IM02 error which means name of the DSN is incorrect.

GO to ODBC and check the USER/System DSN that you should be using. Once your name of DSN is correct, you might get IM014 state error which is archtecture mismatch. In that case,

The simpler solution is
IN r studio - go to tools and change the version of R to 32 bit.

It should be ready to work

ContentLicense: CC BY-SA 4.0

Body:
I've been trying to connect my company's DMS to R using the odbcConnect command, but get the following message:

myConn <-odbcConnect("NZSQL", uid="cejacobson", pwd="password")
Warning messages:
1: In odbcDriverConnect("DSN=NZSQL;UID=cejacobson;PWD=password") :
  [RODBC] ERROR: state IM002, code 0, message [unixODBC][Driver Manager]Data source name not found, and no default driver specified
2: In odbcDriverConnect("DSN=NZSQL;UID=cejacobson;PWD=password") :
  ODBC connection failed

The thing is, I'm positive the Data source name is NZSQL and my uid and password are correct as well. Any insight as to why R may not be finding my data source / driver (the driver is, by the way, specified and working).

How can I fix this?


问:
How to iterate in SVG?
I would like to render a watch in SVG. I have the circles and now I would like to render the index for the hours and minutes.

svg {
  width: 100vmin;
  height: 100vmin;
  overflow: hidden;
}

line, circle {
  stroke: black;
  stroke-width: 0.3px;
}

circle {
  fill: none;
}

circle.filled {
  stroke: none;
  fill: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg viewBox="0 0 100 100">
  <!-- center dot -->
  <circle cx="50" cy="50" r="1" class="filled" />
  <!-- hour circle -->
  <circle cx="50" cy="50" r="35" />
  <line x1="50" y1="17" x2="50" y2="15" />
  <!-- minute circle -->
  <circle cx="50" cy="50" r="40" />
  <line x1="50" y1="10" x2="50" y2="8" />
</svg></code>```

I know that I can use the transform attribute to rotate the lines around the center. But how to express the loop in SVG to do it 59 times for the minutes and 11 times for the hours? Do I have to use JavaScript for this, or is it possible to draw the lines directly in SVG without writing 72 line elements? Something less verbose than this:

```<code>  <line x1='50' y1='17' x2='50' y2='15' id='h0' />
  <use href='#h0' transform='rotate ( 30, 50, 50)' />
  <use href='#h0' transform='rotate ( 60, 50, 50)' />
  <use href='#h0' transform='rotate ( 90, 50, 50)' />
  <use href='#h0' transform='rotate (120, 50, 50)' />
  <use href='#h0' transform='rotate (150, 50, 50)' />
  <use href='#h0' transform='rotate (180, 50, 50)' />
  <use href='#h0' transform='rotate (210, 50, 50)' />
  <use href='#h0' transform='rotate (240, 50, 50)' />
  <use href='#h0' transform='rotate (270, 50, 50)' />
  <use href='#h0' transform='rotate (300, 50, 50)' />
  <use href='#h0' transform='rotate (330, 50, 50)' />
</code>```

and this

```<code>  <line x1='50' y1='10' x2='50' y2='8' id='m0' />
  <use href='#h0' transform='rotate ( 30, 50, 50)' />
  <use href='#m0' transform='rotate (  6, 50, 50)' />
  <use href='#m0' transform='rotate ( 12, 50, 50)' />
  <use href='#m0' transform='rotate ( 18, 50, 50)' />
  <use href='#m0' transform='rotate ( 24, 50, 50)' />
  <use href='#m0' transform='rotate ( 30, 50, 50)' />
  <use href='#m0' transform='rotate ( 36, 50, 50)' />
  <use href='#m0' transform='rotate ( 42, 50, 50)' />
  <use href='#m0' transform='rotate ( 48, 50, 50)' />
  <use href='#m0' transform='rotate ( 54, 50, 50)' />
  <use href='#m0' transform='rotate ( 60, 50, 50)' />
  <use href='#m0' transform='rotate ( 66, 50, 50)' />
  <use href='#m0' transform='rotate ( 72, 50, 50)' />
  <use href='#m0' transform='rotate ( 78, 50, 50)' />
  <use href='#m0' transform='rotate ( 84, 50, 50)' />
  <use href='#m0' transform='rotate ( 90, 50, 50)' />
  <use href='#m0' transform='rotate ( 96, 50, 50)' />
  <use href='#m0' transform='rotate (102, 50, 50)' />
  <use href='#m0' transform='rotate (108, 50, 50)' />
  <use href='#m0' transform='rotate (114, 50, 50)' />
  <use href='#m0' transform='rotate (120, 50, 50)' />
  <use href='#m0' transform='rotate (126, 50, 50)' />
  <use href='#m0' transform='rotate (132, 50, 50)' />
  <use href='#m0' transform='rotate (138, 50, 50)' />
  <use href='#m0' transform='rotate (144, 50, 50)' />
  <use href='#m0' transform='rotate (150, 50, 50)' />
  <use href='#m0' transform='rotate (156, 50, 50)' />
  <use href='#m0' transform='rotate (162, 50, 50)' />
  <use href='#m0' transform='rotate (168, 50, 50)' />
  <use href='#m0' transform='rotate (174, 50, 50)' />
  <use href='#m0' transform='rotate (180, 50, 50)' />
  <use href='#m0' transform='rotate (186, 50, 50)' />
  <use href='#m0' transform='rotate (192, 50, 50)' />
  <use href='#m0' transform='rotate (198, 50, 50)' />
  <use href='#m0' transform='rotate (204, 50, 50)' />
  <use href='#m0' transform='rotate (210, 50, 50)' />
  <use href='#m0' transform='rotate (216, 50, 50)' />
  <use href='#m0' transform='rotate (222, 50, 50)' />
  <use href='#m0' transform='rotate (228, 50, 50)' />
  <use href='#m0' transform='rotate (234, 50, 50)' />
  <use href='#m0' transform='rotate (240, 50, 50)' />
  <use href='#m0' transform='rotate (246, 50, 50)' />
  <use href='#m0' transform='rotate (252, 50, 50)' />
  <use href='#m0' transform='rotate (258, 50, 50)' />
  <use href='#m0' transform='rotate (264, 50, 50)' />
  <use href='#m0' transform='rotate (270, 50, 50)' />
  <use href='#m0' transform='rotate (276, 50, 50)' />
  <use href='#m0' transform='rotate (282, 50, 50)' />
  <use href='#m0' transform='rotate (288, 50, 50)' />
  <use href='#m0' transform='rotate (294, 50, 50)' />
  <use href='#m0' transform='rotate (300, 50, 50)' />
  <use href='#m0' transform='rotate (306, 50, 50)' />
  <use href='#m0' transform='rotate (312, 50, 50)' />
  <use href='#m0' transform='rotate (318, 50, 50)' />
  <use href='#m0' transform='rotate (324, 50, 50)' />
  <use href='#m0' transform='rotate (330, 50, 50)' />
  <use href='#m0' transform='rotate (336, 50, 50)' />
  <use href='#m0' transform='rotate (342, 50, 50)' />
  <use href='#m0' transform='rotate (348, 50, 50)' />
  <use href='#m0' transform='rotate (354, 50, 50)' />
</code>```

答:
You can nest use blocks, which might save you some lines, e.g.

circle {
  fill: none;
  stroke: black;
  }
line {
  stroke: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">

  <!-- center dot -->
  <circle cx="50" cy="50" r="1" class="filled" />
  <!-- hour circle -->
  <circle cx="50" cy="50" r="35" />
  <!-- minute circle -->
  <circle cx="50" cy="50" r="40" />

  <g id='five-block'>
    <line x1="50" y1="17" x2="50" y2="15" />
    <line id="minute" x1="50" y1="10" x2="50" y2="8" />
    <use href='#minute' transform='rotate (6, 50, 50)' />
    <use href='#minute' transform='rotate (12, 50, 50)' />
    <use href='#minute' transform='rotate (18, 50, 50)' />
    <use href='#minute' transform='rotate (24, 50, 50)' />
  </g>

  <g id="quarter-block">
    <use href='#five-block' transform='rotate (30, 50, 50)' />
    <use href='#five-block' transform='rotate (60, 50, 50)' />
    <use href='#five-block' transform='rotate (90, 50, 50)' />
  </g>

  <use href='#quarter-block' transform='rotate (90, 50, 50)' />
  <use href='#quarter-block' transform='rotate (180, 50, 50)' />
  <use href='#quarter-block' transform='rotate (270, 50, 50)' />

</svg></code>```

You could nest the use blocks even more if you wanted to make it slightly less verbose.

Or you could use Javascript to create the elements.

Title: How to iterate in SVG?

Body:
I would like to render a watch in SVG. I have the circles and now I would like to render the index for the hours and minutes.

svg {
  width: 100vmin;
  height: 100vmin;
  overflow: hidden;
}

line, circle {
  stroke: black;
  stroke-width: 0.3px;
}

circle {
  fill: none;
}

circle.filled {
  stroke: none;
  fill: black;
}

<svg viewBox="0 0 100 100">

  <circle cx="50" cy="50" r="1" class="filled" />

  <circle cx="50" cy="50" r="35" />
  <line x1="50" y1="17" x2="50" y2="15" />

  <circle cx="50" cy="50" r="40" />
  <line x1="50" y1="10" x2="50" y2="8" />
</svg>

I know that I can use the transform attribute to rotate the lines around the center. But how to express the loop in SVG to do it 59 times for the minutes and 11 times for the hours? Do I have to use JavaScript for this, or is it possible to draw the lines directly in SVG without writing 72 line elements? Something less verbose than this:

  <line x1='50' y1='17' x2='50' y2='15' id='h0' />
  <use href='#h0' transform='rotate ( 30, 50, 50)' />
  <use href='#h0' transform='rotate ( 60, 50, 50)' />
  <use href='#h0' transform='rotate ( 90, 50, 50)' />
  <use href='#h0' transform='rotate (120, 50, 50)' />
  <use href='#h0' transform='rotate (150, 50, 50)' />
  <use href='#h0' transform='rotate (180, 50, 50)' />
  <use href='#h0' transform='rotate (210, 50, 50)' />
  <use href='#h0' transform='rotate (240, 50, 50)' />
  <use href='#h0' transform='rotate (270, 50, 50)' />
  <use href='#h0' transform='rotate (300, 50, 50)' />
  <use href='#h0' transform='rotate (330, 50, 50)' />

and this

  <line x1='50' y1='10' x2='50' y2='8' id='m0' />
  <use href='#h0' transform='rotate ( 30, 50, 50)' />
  <use href='#m0' transform='rotate (  6, 50, 50)' />
  <use href='#m0' transform='rotate ( 12, 50, 50)' />
  <use href='#m0' transform='rotate ( 18, 50, 50)' />
  <use href='#m0' transform='rotate ( 24, 50, 50)' />
  <use href='#m0' transform='rotate ( 30, 50, 50)' />
  <use href='#m0' transform='rotate ( 36, 50, 50)' />
  <use href='#m0' transform='rotate ( 42, 50, 50)' />
  <use href='#m0' transform='rotate ( 48, 50, 50)' />
  <use href='#m0' transform='rotate ( 54, 50, 50)' />
  <use href='#m0' transform='rotate ( 60, 50, 50)' />
  <use href='#m0' transform='rotate ( 66, 50, 50)' />
  <use href='#m0' transform='rotate ( 72, 50, 50)' />
  <use href='#m0' transform='rotate ( 78, 50, 50)' />
  <use href='#m0' transform='rotate ( 84, 50, 50)' />
  <use href='#m0' transform='rotate ( 90, 50, 50)' />
  <use href='#m0' transform='rotate ( 96, 50, 50)' />
  <use href='#m0' transform='rotate (102, 50, 50)' />
  <use href='#m0' transform='rotate (108, 50, 50)' />
  <use href='#m0' transform='rotate (114, 50, 50)' />
  <use href='#m0' transform='rotate (120, 50, 50)' />
  <use href='#m0' transform='rotate (126, 50, 50)' />
  <use href='#m0' transform='rotate (132, 50, 50)' />
  <use href='#m0' transform='rotate (138, 50, 50)' />
  <use href='#m0' transform='rotate (144, 50, 50)' />
  <use href='#m0' transform='rotate (150, 50, 50)' />
  <use href='#m0' transform='rotate (156, 50, 50)' />
  <use href='#m0' transform='rotate (162, 50, 50)' />
  <use href='#m0' transform='rotate (168, 50, 50)' />
  <use href='#m0' transform='rotate (174, 50, 50)' />
  <use href='#m0' transform='rotate (180, 50, 50)' />
  <use href='#m0' transform='rotate (186, 50, 50)' />
  <use href='#m0' transform='rotate (192, 50, 50)' />
  <use href='#m0' transform='rotate (198, 50, 50)' />
  <use href='#m0' transform='rotate (204, 50, 50)' />
  <use href='#m0' transform='rotate (210, 50, 50)' />
  <use href='#m0' transform='rotate (216, 50, 50)' />
  <use href='#m0' transform='rotate (222, 50, 50)' />
  <use href='#m0' transform='rotate (228, 50, 50)' />
  <use href='#m0' transform='rotate (234, 50, 50)' />
  <use href='#m0' transform='rotate (240, 50, 50)' />
  <use href='#m0' transform='rotate (246, 50, 50)' />
  <use href='#m0' transform='rotate (252, 50, 50)' />
  <use href='#m0' transform='rotate (258, 50, 50)' />
  <use href='#m0' transform='rotate (264, 50, 50)' />
  <use href='#m0' transform='rotate (270, 50, 50)' />
  <use href='#m0' transform='rotate (276, 50, 50)' />
  <use href='#m0' transform='rotate (282, 50, 50)' />
  <use href='#m0' transform='rotate (288, 50, 50)' />
  <use href='#m0' transform='rotate (294, 50, 50)' />
  <use href='#m0' transform='rotate (300, 50, 50)' />
  <use href='#m0' transform='rotate (306, 50, 50)' />
  <use href='#m0' transform='rotate (312, 50, 50)' />
  <use href='#m0' transform='rotate (318, 50, 50)' />
  <use href='#m0' transform='rotate (324, 50, 50)' />
  <use href='#m0' transform='rotate (330, 50, 50)' />
  <use href='#m0' transform='rotate (336, 50, 50)' />
  <use href='#m0' transform='rotate (342, 50, 50)' />
  <use href='#m0' transform='rotate (348, 50, 50)' />
  <use href='#m0' transform='rotate (354, 50, 50)' />

Body:
You can nest use blocks, which might save you some lines, e.g.

circle {
  fill: none;
  stroke: black;
  }
line {
  stroke: black;
}

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">

  <!-- center dot -->
  <circle cx="50" cy="50" r="1" class="filled" />
  <!-- hour circle -->
  <circle cx="50" cy="50" r="35" />
  <!-- minute circle -->
  <circle cx="50" cy="50" r="40" />

  <g id='five-block'>
    <line x1="50" y1="17" x2="50" y2="15" />
    <line id="minute" x1="50" y1="10" x2="50" y2="8" />
    <use href='#minute' transform='rotate (6, 50, 50)' />
    <use href='#minute' transform='rotate (12, 50, 50)' />
    <use href='#minute' transform='rotate (18, 50, 50)' />
    <use href='#minute' transform='rotate (24, 50, 50)' />
  </g>

  <g id="quarter-block">
    <use href='#five-block' transform='rotate (30, 50, 50)' />
    <use href='#five-block' transform='rotate (60, 50, 50)' />
    <use href='#five-block' transform='rotate (90, 50, 50)' />
  </g>

  <use href='#quarter-block' transform='rotate (90, 50, 50)' />
  <use href='#quarter-block' transform='rotate (180, 50, 50)' />
  <use href='#quarter-block' transform='rotate (270, 50, 50)' />

</svg>

You could nest the use blocks even more if you wanted to make it slightly less verbose.

Or you could use Javascript to create the elements.


问:
if statement seems to not be working with multiple conditions
I'm not sure if I'm overloading anything but when I add all the conditions I need to one if statement it always returns true. It seems to always show my error message, but when I only add one condition it works perfectly fine. Also, I know my code is messy I'm just a novice, go easy on me.</p>

```<code>Console.ForegroundColor = ConsoleColor.Green;
string[] Class = new string[] { "AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM", "NN", "OO" };
double[] Rate = new double[] { .015, .023, .010, .042, .051, .004, .022, .030, .001, .010, .020, .030, .045, .033, .050 };
Console.Write("Please enter vehicle classification: ");
string Vclass = Console.ReadLine();
if (Vclass != "AA" || Vclass != "BB" || Vclass != "CC" || Vclass != "DD" || Vclass != "EE" || Vclass != "FF" || Vclass != "GG" || Vclass != "HH" || Vclass != "II" || Vclass != "JJ" || Vclass != "KK" || Vclass != "LL" || Vclass != "MM" || Vclass != "NN" || Vclass != "OO")
{
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("There is an error with the vehicle class.");
        Console.ForegroundColor = ConsoleColor.Green;
}
</code>```

答:
I've got a bowl of fruits. I want to make sure there are no fruits in it that I dont like. The fruits I like are: apples, bananas, grapes and kiwis.

So the ones I don't like are those that are not apples AND are not bananas AND are not grapes AND are not a kiwis.

The ones I don't like are most definitely not the ones that arent apples OR  bananas OR grapes OR kiwis.

|| is the equivalent of a lazy OR. Your condition should be using a lazy AND: &&.

```<code>if (Vclass != "AA" &&
    Vclass != "BB" &&
    Vclass != "CC" &&
    Vclass != "DD" && /*..etc*/)
</code>```

Body:
I'm not sure if I'm overloading anything but when I add all the conditions I need to one if statement it always returns true. It seems to always show my error message, but when I only add one condition it works perfectly fine. Also, I know my code is messy I'm just a novice, go easy on me.

Console.ForegroundColor = ConsoleColor.Green;
string[] Class = new string[] { "AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM", "NN", "OO" };
double[] Rate = new double[] { .015, .023, .010, .042, .051, .004, .022, .030, .001, .010, .020, .030, .045, .033, .050 };
Console.Write("Please enter vehicle classification: ");
string Vclass = Console.ReadLine();
if (Vclass != "AA" || Vclass != "BB" || Vclass != "CC" || Vclass != "DD" || Vclass != "EE" || Vclass != "FF" || Vclass != "GG" || Vclass != "HH" || Vclass != "II" || Vclass != "JJ" || Vclass != "KK" || Vclass != "LL" || Vclass != "MM" || Vclass != "NN" || Vclass != "OO")
{
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("There is an error with the vehicle class.");
        Console.ForegroundColor = ConsoleColor.Green;
}

Body:
I've got a bowl of fruits. I want to make sure there are no fruits in it that I dont like. The fruits I like are: apples, bananas, grapes and kiwis.

So the ones I don't like are those that are not apples AND are not bananas AND are not grapes AND are not a kiwis.

The ones I don't like are most definitely not the ones that arent apples OR  bananas OR grapes OR kiwis.

|| is the equivalent of a lazy OR. Your condition should be using a lazy AND: &&.

if (Vclass != "AA" &&
    Vclass != "BB" &&
    Vclass != "CC" &&
    Vclass != "DD" && /*..etc*/)


问:
Queue.Queue vs semaphores, locks, etc. in multithreaded Python code

The principal challenge of
  multi-threaded applications is
  coordinating threads that share data
  or other resources. To that end, the
  threading module provides a number of
  synchronization primitives including
  locks, events, condition variables,
  and semaphores.

While those tools are powerful, minor
  design errors can result in problems
  that are difficult to reproduce. So,
  the preferred approach to task
  coordination is to concentrate all
  access to a resource in a single
  thread and then use the Queue module
  to feed that thread with requests from
  other threads. Applications using
  Queue.Queue objects for inter-thread
  communication and coordination are
  easier to design, more readable, and
  more reliable.

It, basically, states to use Queue.Queue for inter-thread communication and coordination, instead of the powerful tools such as semaphores, locks, etc.

My question is, what's the drawback of the suggested method?  When should one use the more "powerful tools" instead, and why?

Edit

To be clear, I know what semaphores are.  I was just wondering why the Python documentation suggests to use the Queue.Queue method instead of the "powerful tools" -- I'm simply using the documentation's own verbiage, not coming up with my own.

答:
I'm not sure I'd consider semaphores and locks "more powerful methods", as you suggest.

Queues are generally a higher-order abstraction.  In other words, you could use semaphores and locks to build thread-safe queues.

Which you'd use where depends on your application.  Queues are good for passing "work" between threads and processes, and semaphores/locks are good for protecting critical sections or shared resources, so only one thread can access at a time.

ContentLicense: CC BY-SA 2.5


问:
CSS solution - always scroll overflow doc to bottom
I have a div that has overflow: scroll, and I want it to always scroll to bottom along Y-axis no matter what content it has. (think about a chat thread, which always displays the latest message at the bottom.)

I saw there are some jQuery solutions that scrolls the div to its height when new messages get added, but I am wondering if there's any pure CSS solution to this?

Thank you!

答:
Unfortunately, not possible with pure CSS but you can use pure js to get the total scrollable height of element with elem.scrollHeight and scroll the element to that position with elem.scrollTop

you can see in this example

the js code is:

```<code>var elem = document.querySelector("theElementClass");
var elemHeight = elem.scrollHeight;
elem.scrollTop = elemHeight;
</code>```

hope this helps. =D

Body:
Unfortunately, not possible with pure CSS but you can use pure js to get the total scrollable height of element with elem.scrollHeight and scroll the element to that position with elem.scrollTop

you can see in this example

the js code is:

var elem = document.querySelector("theElementClass");
var elemHeight = elem.scrollHeight;
elem.scrollTop = elemHeight;

hope this helps. =D


问:
How to specialize std::hash<T> for user defined types?
The Question

What is a good specialization of std::hash for use in the third template parameter of std::unordered_map or std::unordered_set for a user defined type for which all member data types already have a good specialization of std::hash?

For this question, I define "good" as simple to implement and understand, reasonably efficient, and unlikely to produce hash table collisions. The definition of good does not include any statements about security.

The State of What is Google'able

At the moment, two StackOverflow questions are the first hits for a Google search of "std hash specialization".

The first, How to specialize std::hash::operator() for user-defined type in unordered containers?, addresses whether it is legal to open the std namespace and add template specializations.

The second, How to specialize std::hash for type from other library, essentially addresses that same question.

This leaves the current question. Given that implementations of the C++ Standard Library defined hash functions for primitive types and types in the Standard Library, what is a simple and effective way of specializing std::hash for user defined types? Is there a good way to combine hash functions provided by a Standard Library implementation?

(Edit thanks to dyp.) Another question on StackOverflow addresses how to combine a pair of hash functions.

The other Google results are of no more help.

This Dr. Dobbs article states that XOR of two satisfactory hashes will produce a new satisfactory hash.

This articles seems to speak from knowledge and implies many things but is light on details. It contradicts the Dr. Dobbs article in a brief remark in the first example, saying that using XOR to combine hash functions makes for a weak resulting hash function.

Because XOR applied to any two equal values results in 0, I can see why XOR by itself is weak.

The Meta Question

A well reasoned answer explaining why this question is invalid and cannot be answered generally would also be welcome.

答:
Your operation is required to

Return a value of type size_t

Be consistent with the == operator.

Have a low probability of a hash collision for unequal values.

There is no explicit requirement that the hash values are evenly distributed over the range of size_t integers. cppreference.com notes that

some implementations [of the standard library] use trivial (identity) hash functions which map an integer to itself

Avoiding hash collisions coupled with that weakness means that a specialization of std::hash for your types should never simply use a (fast) bitwise XOR (^) to combine the sub hashses of your data-members. Consider this example:

```<code> struct Point {
    uint8_t x;
    uint8_t y;
 };

 namespace std {
    template<>
    struct hash< Point > {
       size_t operator()(const Point &p) const {
          return hash< uint8_t >(p.x) ^ hash< uint8_t >(p.y);
       }
    };
 }
</code>```

The hashes of p.x will be in the range [0,255], and so will the hashes of p.y. Therefore the hashes of a Point will also be in the range [0,255], with 256 (=2^8) possible values. There are 256*256  (=2^16) unique Point objects (a std::size_t will typically support 2^32 or 2^64 values). So the probability of a hash collision for a good hashing function should be approximately 2^(-16). Our function gives the probability of a hash collision of just under 2^(-8). This is terrible: our hash provides only 8 bits of information, but a good hash should provide 16 bits of information.

If the hashing functions of your data-members provide only hash values in the low parts of the std::size_t range, you must "shift" the bits of the component hash before combining them, so they each contribute independent bits of information. Doing a left-wise shift looks simple

```<code>       return (hash< uint8_t >(p.x) << 8) ^ hash< uint8_t >(p.y);
</code>```

but that will discard information (due to overflow) if the implementation of hash< uint8_t > (in this case) attempts to spread the hash-code values over the std::size_t range.

Accumulating component hash-code values using a multiply-by-prime-and-add method, as typically done in Java, probably works better in general:

```<code> namespace std {
    template<>
    struct hash< Point > {
       size_t operator()(const Point &p) const {
          const size_t prime = 257;
          size_t h {hash< uint8_t >(p.x)};
          h = h * prime + hash< uint8_t >(p.y);
          return h;
       }
    };
 }
</code>```

Body:
Your operation is required to

Return a value of type size_t

Be consistent with the == operator.

Have a low probability of a hash collision for unequal values.

There is no explicit requirement that the hash values are evenly distributed over the range of size_t integers. cppreference.com notes that

some implementations [of the standard library] use trivial (identity) hash functions which map an integer to itself

Avoiding hash collisions coupled with that weakness means that a specialization of std::hash for your types should never simply use a (fast) bitwise XOR (^) to combine the sub hashses of your data-members. Consider this example:

 struct Point {
    uint8_t x;
    uint8_t y;
 };

 namespace std {
    template<>
    struct hash< Point > {
       size_t operator()(const Point &p) const {
          return hash< uint8_t >(p.x) ^ hash< uint8_t >(p.y);
       }
    };
 }

The hashes of p.x will be in the range [0,255], and so will the hashes of p.y. Therefore the hashes of a Point will also be in the range [0,255], with 256 (=2^8) possible values. There are 256*256  (=2^16) unique Point objects (a std::size_t will typically support 2^32 or 2^64 values). So the probability of a hash collision for a good hashing function should be approximately 2^(-16). Our function gives the probability of a hash collision of just under 2^(-8). This is terrible: our hash provides only 8 bits of information, but a good hash should provide 16 bits of information.

If the hashing functions of your data-members provide only hash values in the low parts of the std::size_t range, you must "shift" the bits of the component hash before combining them, so they each contribute independent bits of information. Doing a left-wise shift looks simple

       return (hash< uint8_t >(p.x) << 8) ^ hash< uint8_t >(p.y);

but that will discard information (due to overflow) if the implementation of hash< uint8_t > (in this case) attempts to spread the hash-code values over the std::size_t range.

Accumulating component hash-code values using a multiply-by-prime-and-add method, as typically done in Java, probably works better in general:

 namespace std {
    template<>
    struct hash< Point > {
       size_t operator()(const Point &p) const {
          const size_t prime = 257;
          size_t h {hash< uint8_t >(p.x)};
          h = h * prime + hash< uint8_t >(p.y);
          return h;
       }
    };
 }


问:
Why does this loop with scanf always quit?
```<code>#include <stdio.h>

int main(){

  char quit = 'n';

  do{
    printf("Quit? (Y/N)");
    scanf("%c", &quit);
  }while(quit=='n' || quit=='N');
}
</code>```

<p>Why does my program quit after inputting anything? </p>

答:
Just change your code to:

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

int main(){

  char quit = 'n';

  do{
    printf("Quit? (Y/N)");
    scanf(" %c", &quit);
  }while(quit=='n' || quit=='N');
}
</code>```

For more information read this link

Body:
#include <stdio.h>

int main(){

  char quit = 'n';

  do{
    printf("Quit? (Y/N)");
    scanf("%c", &quit);
  }while(quit=='n' || quit=='N');
}

Why does my program quit after inputting anything?

Body:
Just change your code to:

#include <stdio.h>

int main(){

  char quit = 'n';

  do{
    printf("Quit? (Y/N)");
    scanf(" %c", &quit);
  }while(quit=='n' || quit=='N');
}

For more information read this link


问:
NameError: name 'unicode' is not defined when compile with python3
I am trying to compiled caffe with python3. After the compilation when I am trying to import caffe I am getting follwing error

```<code>In [1]: import caffe
Failed to include caffe_pb2, things might go wrong!
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-1cca3aa1f8c5> in <module>()
----> 1 import caffe

/library_install_dir/caffe/python/caffe/__init__.py in <module>()
      1 from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver
      2 from ._caffe import set_mode_cpu, set_mode_gpu, set_device, Layer, get_solver, layer_type_list
----> 3 from .proto.caffe_pb2 import TRAIN, TEST
      4 from .classifier import Classifier
      5 from .detector import Detector

/library_install_dir/caffe/python/caffe/proto/caffe_pb2.py in <module>()
    975       name='type', full_name='caffe.FillerParameter.type', index=0,
    976       number=1, type=9, cpp_type=9, label=1,
--> 977       has_default_value=True, default_value=unicode("constant", "utf-8"),
    978       message_type=None, enum_type=None, containing_type=None,
    979       is_extension=False, extension_scope=None,

NameError: name 'unicode' is not defined
</code>```

The issue is Python 3 renamed the unicode type to str, the old str type has been replaced by bytes.

I tried to modify the proto/caffe_pb2 but it is not working.

Anyone having similar issue with caffe. I have a working caffe with python3 support in my bare metal Now I am trying to dockerize it.

Thanks in advance.

答:
I had the same problem. unicode is for Python2. After make pycaffe command you can check /opt/caffe-1.0/python/caffe/proto/caffe_pb2.py file and if there is any unicode in the file the problem still exists. You can delete caffe_pb2.py and run make pycaffe again.

The solution is installing appropriate versions of protoc and protobuf.

A) install protoc >= 2.6.1

(protoc == 2.5.0 not working)

https://cuongba.com/protocol-buffers-and-rabbitmq-on-ubuntu-14-04-part-1

```<code>wget https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz
tar -xzvf protobuf-2.6.1.tar.gz
cd protobuf-2.6.1
sudo ./configure
make
make check
sudo make install
sudo ldconfig
protoc --version
</code>```

B) install protobuf>=3.4.0

```<code>pip3 install protobuf>=3.4.0
</code>```

Body:
I am trying to compiled caffe with python3. After the compilation when I am trying to import caffe I am getting follwing error

In [1]: import caffe
Failed to include caffe_pb2, things might go wrong!
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-1cca3aa1f8c5> in <module>()
----> 1 import caffe

/library_install_dir/caffe/python/caffe/__init__.py in <module>()
      1 from .pycaffe import Net, SGDSolver, NesterovSolver, AdaGradSolver, RMSPropSolver, AdaDeltaSolver, AdamSolver
      2 from ._caffe import set_mode_cpu, set_mode_gpu, set_device, Layer, get_solver, layer_type_list
----> 3 from .proto.caffe_pb2 import TRAIN, TEST
      4 from .classifier import Classifier
      5 from .detector import Detector

/library_install_dir/caffe/python/caffe/proto/caffe_pb2.py in <module>()
    975       name='type', full_name='caffe.FillerParameter.type', index=0,
    976       number=1, type=9, cpp_type=9, label=1,
--> 977       has_default_value=True, default_value=unicode("constant", "utf-8"),
    978       message_type=None, enum_type=None, containing_type=None,
    979       is_extension=False, extension_scope=None,

NameError: name 'unicode' is not defined

The issue is Python 3 renamed the unicode type to str, the old str type has been replaced by bytes.

I tried to modify the proto/caffe_pb2 but it is not working.

Anyone having similar issue with caffe. I have a working caffe with python3 support in my bare metal Now I am trying to dockerize it.

Thanks in advance.

Body:
I had the same problem. unicode is for Python2. After make pycaffe command you can check /opt/caffe-1.0/python/caffe/proto/caffe_pb2.py file and if there is any unicode in the file the problem still exists. You can delete caffe_pb2.py and run make pycaffe again.

The solution is installing appropriate versions of protoc and protobuf.

A) install protoc >= 2.6.1

(protoc == 2.5.0 not working)

https://cuongba.com/protocol-buffers-and-rabbitmq-on-ubuntu-14-04-part-1

wget https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz
tar -xzvf protobuf-2.6.1.tar.gz
cd protobuf-2.6.1
sudo ./configure
make
make check
sudo make install
sudo ldconfig
protoc --version

B) install protobuf>=3.4.0

pip3 install protobuf>=3.4.0


问:
pocketsphinx python give wrong timestamp
I am using pocketsphinx to convert audio into text. It works fine. Now I want to get timestamp of each word. This is my code:

```<code>import speech_recognition as sr

r = sr.Recognizer()
framerate = 100
with sr.AudioFile("1.wav") as source:

    audio = r.record(source)

    decoder = r.recognize_sphinx(audio, show_all=False)

    print ([(seg.word, seg.start_frame/framerate)for seg in decoder.seg()])
</code>```

According to their documentation, the default framerate is 100. I got the starting time of each word. However, it is incorrect. The difference is 2 seconds, sometimes more than 3 seconds.

It is known issue or Am I missing something?

答:
I read somewhere that the rate was 1/100 So, with my project I divided by, on accident, 1/10 instead of 1/100 but the results were actually fine for what I was doing. I would suggest dividing by 0.1 or 0.01 and see what that provides you.

So for your code just try out those variables:

```<code>framerate = .1
</code>```

OR

```<code>framerate = .01
</code>```

Body:
I am using pocketsphinx to convert audio into text. It works fine. Now I want to get timestamp of each word. This is my code:

import speech_recognition as sr

r = sr.Recognizer()
framerate = 100
with sr.AudioFile("1.wav") as source:

    audio = r.record(source)

    decoder = r.recognize_sphinx(audio, show_all=False)

    print ([(seg.word, seg.start_frame/framerate)for seg in decoder.seg()])

According to their documentation, the default framerate is 100. I got the starting time of each word. However, it is incorrect. The difference is 2 seconds, sometimes more than 3 seconds.

It is known issue or Am I missing something?

Body:
I read somewhere that the rate was 1/100 So, with my project I divided by, on accident, 1/10 instead of 1/100 but the results were actually fine for what I was doing. I would suggest dividing by 0.1 or 0.01 and see what that provides you.

So for your code just try out those variables:

framerate = .1

OR

framerate = .01


问:
Creating Group via Microsoft Graph returns Error "An unexpected PrimitiveValue node was found when reading from the JSON reader"
Am trying to create group using my admin account via Microsoft Graph. I have implemented all the required parameters/variables but when I tried making calls to the API, it displays error below:

```<code>{
    "error": {
        "code": "Request_BadRequest",
        "message": "An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartArray' node was expected.",
        "innerError": {
            "request-id": "02bfcc43-5982-4c49-8484-da9d6cc61bab",
            "date": "2017-12-05T17:53:57"
        }
    }
}
</code>```

My code:

<?php
session_start();

echo $acc= $_SESSION['access_token'];

$data_string = array("description" => "An Awesome New Group", "displayName" => "Awesome Group", "groupTypes" => "Unified", "mailEnabled" => "true", "mailNickname" => "awesomeGroup", "securityEnabled" => "fasle");
$data = json_encode($data_string);
//$data = $data_string;
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "https://graph.microsoft.com/v1.0/groups",

CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"authorization: Bearer $acc",
"content-type: application/json; charset=utf-8"
),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

print_r($response);

if ($err) {
echo "cURL Error #:" . $err;
} else {
//echo $response;
}
?>
```

Note that my real tenant id was replaced with admin@secx34fake.onmicrosoft.com so that its not displayed to public.

答:
The error is telling you that the URL you're using is invalid.

This is accurate as /v1.0/admin@secx34fake.onmicrosoft.com/groups isn't a valid endpoint. Specifically it rejecting the userPrincipalName of  admin@secx34fake.onmicrosoft.com. I'm not exactly sure where you were going with this but a Group is not a child of a User object. A User can be a member of a Group but they are both top-level elements within your Active Directory.

As an aside, a "segment" in the context of a URL is the elements separated by a /. You can think of a URL as a / delimited string with each column being a "segment". For example, /v1.0/me/events contains 3 segments: v1.0, me and events. The error you got is telling you one of these "segments" is either invalid or not in the proper order (i.e. /v1.0/events/me has the right segments in the wrong order).

For creating a Group, the proper URI looks like this:

```<code>POST https://graph.microsoft.com/v1.0/groups
</code>```

Within the body of your POST you define the properties of the group. For example:

{
  "description": "An Awesome New Group",
  "displayName": "Awesome Group",
  "groupTypes": ["Unified"],
  "mailEnabled": true,
  "mailNickname": "awesomeGroup",
  "securityEnabled": false
}
```

Body:
Am trying to create group using my admin account via Microsoft Graph. I have implemented all the required parameters/variables but when I tried making calls to the API, it displays error below:

{
    "error": {
        "code": "Request_BadRequest",
        "message": "An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartArray' node was expected.",
        "innerError": {
            "request-id": "02bfcc43-5982-4c49-8484-da9d6cc61bab",
            "date": "2017-12-05T17:53:57"
        }
    }
}

My code:

<?php
session_start();

echo $acc= $_SESSION['access_token'];

$data_string = array("description" => "An Awesome New Group", "displayName" => "Awesome Group", "groupTypes" => "Unified", "mailEnabled" => "true", "mailNickname" => "awesomeGroup", "securityEnabled" => "fasle");
$data = json_encode($data_string);
//$data = $data_string;
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "https://graph.microsoft.com/v1.0/groups",

CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "$data",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"authorization: Bearer $acc",
"content-type: application/json; charset=utf-8"
),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

print_r($response);

if ($err) {
echo "cURL Error #:" . $err;
} else {
//echo $response;
}
?>

Note that my real tenant id was replaced with admin@secx34fake.onmicrosoft.com so that its not displayed to public.

Body:
The error is telling you that the URL you're using is invalid.

This is accurate as /v1.0/admin@secx34fake.onmicrosoft.com/groups isn't a valid endpoint. Specifically it rejecting the userPrincipalName of  admin@secx34fake.onmicrosoft.com. I'm not exactly sure where you were going with this but a Group is not a child of a User object. A User can be a member of a Group but they are both top-level elements within your Active Directory.

As an aside, a "segment" in the context of a URL is the elements separated by a /. You can think of a URL as a / delimited string with each column being a "segment". For example, /v1.0/me/events contains 3 segments: v1.0, me and events. The error you got is telling you one of these "segments" is either invalid or not in the proper order (i.e. /v1.0/events/me has the right segments in the wrong order).

For creating a Group, the proper URI looks like this:

POST https://graph.microsoft.com/v1.0/groups

Within the body of your POST you define the properties of the group. For example:

{
  "description": "An Awesome New Group",
  "displayName": "Awesome Group",
  "groupTypes": ["Unified"],
  "mailEnabled": true,
  "mailNickname": "awesomeGroup",
  "securityEnabled": false
}


问:
parallels and meridians doesn't show up on baseman
parallels and meridians doesn't show up on baseman. What should I do? I guess it's been totally covered? I tried setting zorder=1 when creating the map but it didn't work

```<code>map = Basemap(llcrnrlon=pr.bounds[0],llcrnrlat=pr.bounds[1],urcrnrlon=pr.bounds[2],urcrnrlat=pr.bounds[3],epsg=4326)
map.arcgisimage(service='World_Street_Map',xpixels=1500,verbose=True)

map.scatter(ht.lng,ht.lat,c=ht_labels,alpha=0.5)

map.drawparallels(np.arange(pr.bounds[0],pr.bounds[2],0.2),labels=[1,0,0,0])
map.drawmeridians(np.arange(pr.bounds[1],pr.bounds[3],0.2),labels=[0,0,0,1])

plt.savefig('./fig/ht_clust1.png',dpi=1000)
plt.clf()
</code>```

答:
You are using the longitude bounds to plot parallels and the latitude lines to plot the meridians - the wrong way round! Switch your calls around:</p>

```<code>map.drawmeridians(np.arange(pr.bounds[0],pr.bounds[2],0.2),labels=[1,0,0,0])
map.drawparallels(np.arange(pr.bounds[1],pr.bounds[3],0.2),labels=[0,0,0,1])
</code>```

Body:
parallels and meridians doesn't show up on baseman. What should I do? I guess it's been totally covered? I tried setting zorder=1 when creating the map but it didn't work

map = Basemap(llcrnrlon=pr.bounds[0],llcrnrlat=pr.bounds[1],urcrnrlon=pr.bounds[2],urcrnrlat=pr.bounds[3],epsg=4326)
map.arcgisimage(service='World_Street_Map',xpixels=1500,verbose=True)

map.scatter(ht.lng,ht.lat,c=ht_labels,alpha=0.5)

map.drawparallels(np.arange(pr.bounds[0],pr.bounds[2],0.2),labels=[1,0,0,0])
map.drawmeridians(np.arange(pr.bounds[1],pr.bounds[3],0.2),labels=[0,0,0,1])

plt.savefig('./fig/ht_clust1.png',dpi=1000)
plt.clf()

Body:
You are using the longitude bounds to plot parallels and the latitude lines to plot the meridians - the wrong way round! Switch your calls around:

map.drawmeridians(np.arange(pr.bounds[0],pr.bounds[2],0.2),labels=[1,0,0,0])
map.drawparallels(np.arange(pr.bounds[1],pr.bounds[3],0.2),labels=[0,0,0,1])


问:
Array method versus hashes
I have an object (returned from and API) that is either a hash or an array of hashes. I want to enclose it in an array if it is not already an array.

I tried to apply Array on it, which functions in an expected way with numbers or arrays:

```<code>Array(1) # => [1]
Array([1, 2]) # => [1, 2]
Array([{a: 1}, {b: 2}]) # => [{:a=>1}, {:b=>2}]
</code>```

but it fails with hashes:

```<code>Array({a: 1}) # => [[:a, 1]]
</code>```

which should be [{:a=>1}].

Alternatively, I could add a type check:

```<code>responses = [responses] if responses.is_a?(Hash)
</code>```

Is there a better solution?

答:
ActiveSupport introduces Array#wrap that does exactly what you want:

```<code>Array.wrap(responses)
</code>```

I personally prefer to never use any Rails helpers for many reasons, so I would stick with [responses].flatten, or, even better, with the most explicit version:

```<code>case responses
when Hash then [responses]
when Array then responses
else raise "shit happened"
end
</code>```

Title: Array method versus hashes

Body:
I have an object (returned from and API) that is either a hash or an array of hashes. I want to enclose it in an array if it is not already an array.

I tried to apply Array on it, which functions in an expected way with numbers or arrays:

Array(1) # => [1]
Array([1, 2]) # => [1, 2]
Array([{a: 1}, {b: 2}]) # => [{:a=>1}, {:b=>2}]

but it fails with hashes:

Array({a: 1}) # => [[:a, 1]]

which should be [{:a=>1}].

Alternatively, I could add a type check:

responses = [responses] if responses.is_a?(Hash)

Is there a better solution?

Body:
ActiveSupport introduces Array#wrap that does exactly what you want:

Array.wrap(responses)

I personally prefer to never use any Rails helpers for many reasons, so I would stick with [responses].flatten, or, even better, with the most explicit version:

case responses
when Hash then [responses]
when Array then responses
else raise "shit happened"
end


问:
Number validation for JavaScript simple calculator with RegEx
I am making a simple calculator with HTML, CSS and JavaScript. The input field must be validated with regex to accept only numbers and the mathematical signs + - * / .

This is the input field in the HTML code:

```<code><input type="text" name="answer" id="answer-field" oninput="checking()" />
</code>```

And this is the JavaScript function checking():

```<code>function checking(){
  var x = document.calculator.answer.value;  // the value of the input field
  var regex=/[0-9]\b/;  // my failing regex
    if (x.match(regex) || (x==="+") || (x==="-") || (x==="*") || (x==="/"))
    {
      document.getElementById("problemWithInputMessage").innerHTML="";
      console.log("true, it IS a number");
      return true;
    }
    else if(!(x.match(regex))){
      console.log("false, not a number");
      document.getElementById("problemWithInputMessage").innerHTML="You can only input numbers and the following signs + - * /";
      x = x.substring(0, x.length - 1);   // removing the wrong symbol
      document.calculator.answer.value = x;
      return false;
    }
}
</code>```

The problems are several. For starters, the regular expression is not working properly, because it only searches at the beginnings and endings of the input string. Also, some signs, different than +-*/. do stay inside the input field and don't get excluded.

Can you help me to validate the input field properly for numbers and the signs +-*/. only?

答:
I ended up submitting this code:

```<code>function checking() {
  var x = document.calculator.answer.value;
  document.getElementById("problemWithInputMessage").innerHTML="";
    var regexNumbers = /[0-9]+$/;                       //Regular Expression for the numbers
    var regexSigns = new RegExp(/[\+\-\/\*]+$/g);       //Regular Expression for the Special Signs

    if(x.match(regexSigns) || x.match(regexNumbers)) {  //checking for Numbers and the Special allowed signs
        return true;
    }
    else {
      document.getElementById("problemWithInputMessage").innerHTML="You can only input numbers and the following signs + - * /";
      x = x.substring(0, x.length - 1); //Deleting the last symbol if it is not allowed
      document.calculator.answer.value = x;
      return false;
    }
}
</code>```

I separated the 2 tasks in 2 different Regular Expressions. The first one

/[0-9]+$/

checks for numbers only, and the second one

/[+-/*]+$/g

checks for the special symbols +-/* (although I forgot to put in the dot .) Thanks for the answer, it helped a lot :)

It is not 100%-proofed because if you type at the back of the string it is all ok, but if you put the cursor inside a string of numbers you entered, it will still allow you to enter letters and other symbols in the middle.

Body:
I am making a simple calculator with HTML, CSS and JavaScript. The input field must be validated with regex to accept only numbers and the mathematical signs + - * / .

This is the input field in the HTML code:

<input type="text" name="answer" id="answer-field" oninput="checking()" />

And this is the JavaScript function checking():

function checking(){
  var x = document.calculator.answer.value;  // the value of the input field
  var regex=/[0-9]\b/;  // my failing regex
    if (x.match(regex) || (x==="+") || (x==="-") || (x==="*") || (x==="/"))
    {
      document.getElementById("problemWithInputMessage").innerHTML="";
      console.log("true, it IS a number");
      return true;
    }
    else if(!(x.match(regex))){
      console.log("false, not a number");
      document.getElementById("problemWithInputMessage").innerHTML="You can only input numbers and the following signs + - * /";
      x = x.substring(0, x.length - 1);   // removing the wrong symbol
      document.calculator.answer.value = x;
      return false;
    }
}

The problems are several. For starters, the regular expression is not working properly, because it only searches at the beginnings and endings of the input string. Also, some signs, different than +-*/. do stay inside the input field and don't get excluded.

Can you help me to validate the input field properly for numbers and the signs +-*/. only?

Body:
I ended up submitting this code:

function checking() {
  var x = document.calculator.answer.value;
  document.getElementById("problemWithInputMessage").innerHTML="";
    var regexNumbers = /[0-9]+$/;                       //Regular Expression for the numbers
    var regexSigns = new RegExp(/[\+\-\/\*]+$/g);       //Regular Expression for the Special Signs

    if(x.match(regexSigns) || x.match(regexNumbers)) {  //checking for Numbers and the Special allowed signs
        return true;
    }
    else {
      document.getElementById("problemWithInputMessage").innerHTML="You can only input numbers and the following signs + - * /";
      x = x.substring(0, x.length - 1); //Deleting the last symbol if it is not allowed
      document.calculator.answer.value = x;
      return false;
    }
}

I separated the 2 tasks in 2 different Regular Expressions. The first one

/[0-9]+$/

checks for numbers only, and the second one

/[+-/*]+$/g

checks for the special symbols +-/* (although I forgot to put in the dot .) Thanks for the answer, it helped a lot :)

It is not 100%-proofed because if you type at the back of the string it is all ok, but if you put the cursor inside a string of numbers you entered, it will still allow you to enter letters and other symbols in the middle.


问:
MySQL select avg reading every hour even if there is no reading
I'm having a hard time making a MySQL statement from a Postgres one for a project we are migrating. I won't give the exact use case since it's pretty involved, but I can create a simple comparable situation.

We have a graphing tool that needs somewhat raw output for our data in hourly intervals. In Postgres, the SQL would generate a series for the date and hour over a time span, then it would join a query against that for the average where that date an hour existed. We were able to get for example the average sales by hour, even if that number is 0.

Here's a table example:

```<code>Sales
datetime            | sale
2017-12-05 08:34:00 | 10
2017-12-05 08:52:00 | 20
2017-12-05 09:15:00 | 5
2017-12-05 10:22:00 | 10
2017-12-05 10:49:00 | 10
</code>```

Where something like

```<code>SELECT DATE_FORMAT(s.datetime,'%Y%m%d%H') as "byhour", AVG(s.sale) as "avg sales" FROM sales s  GROUP BY byhour
</code>```

would produce

```<code>byhour     | avg sales
2017120508 | 10
2017120509 | 5
2017120510 | 10
</code>```

I'd like something that gives me the last 24 hours, even the 0/NULL values like

```<code>byhour     | avg sales
2017120501 | null
2017120502 | null
2017120503 | null
2017120504 | null
2017120505 | null
2017120506 | null
2017120507 | null
2017120508 | 10
2017120509 | 5
2017120510 | 10
...
2017120600 | null
</code>```

Does anyone have any ideas how I could do this in MySQL?

答:
Join the result on a table that you know contains all the desired hours

someting like this:

```<code>SELECT
* FROM (
SELECT
    DATE_FORMAT(s.datetime, '%Y%m%d%H') AS 'byhour'
FROM
    table_that_has_hours
GROUP BY byhour) hours LEFT OUTER JOIN (
SELECT
    DATE_FORMAT(s.datetime, '%Y%m%d%H') AS 'byhour',
        AVG(s.sale) AS 'avg sales'
FROM
    sales s
GROUP BY byhour) your_stuff ON your_stuff.byhour = hours.by_hours
</code>```

if you don't have a table like that you can create one.
like this:

CREATE TABLE ref (h INT);

INSERT INTO ref (h)
    -> VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),
    -> (12),(13),(14),(15),(16),(17),(18),(19),(20),(21),(22),(23)

and then you can just  DATE_FORMAT(date(now()),'%Y%m%d%H') to the values

Body:
I'm having a hard time making a MySQL statement from a Postgres one for a project we are migrating. I won't give the exact use case since it's pretty involved, but I can create a simple comparable situation.

We have a graphing tool that needs somewhat raw output for our data in hourly intervals. In Postgres, the SQL would generate a series for the date and hour over a time span, then it would join a query against that for the average where that date an hour existed. We were able to get for example the average sales by hour, even if that number is 0.

Here's a table example:

Sales
datetime            | sale
2017-12-05 08:34:00 | 10
2017-12-05 08:52:00 | 20
2017-12-05 09:15:00 | 5
2017-12-05 10:22:00 | 10
2017-12-05 10:49:00 | 10

Where something like

SELECT DATE_FORMAT(s.datetime,'%Y%m%d%H') as "byhour", AVG(s.sale) as "avg sales" FROM sales s  GROUP BY byhour

would produce

byhour     | avg sales
2017120508 | 10
2017120509 | 5
2017120510 | 10

I'd like something that gives me the last 24 hours, even the 0/NULL values like

byhour     | avg sales
2017120501 | null
2017120502 | null
2017120503 | null
2017120504 | null
2017120505 | null
2017120506 | null
2017120507 | null
2017120508 | 10
2017120509 | 5
2017120510 | 10
...
2017120600 | null

Does anyone have any ideas how I could do this in MySQL?

Body:
Join the result on a table that you know contains all the desired hours

someting like this:

SELECT
* FROM (
SELECT
    DATE_FORMAT(s.datetime, '%Y%m%d%H') AS 'byhour'
FROM
    table_that_has_hours
GROUP BY byhour) hours LEFT OUTER JOIN (
SELECT
    DATE_FORMAT(s.datetime, '%Y%m%d%H') AS 'byhour',
        AVG(s.sale) AS 'avg sales'
FROM
    sales s
GROUP BY byhour) your_stuff ON your_stuff.byhour = hours.by_hours

if you don't have a table like that you can create one.
like this:

CREATE TABLE ref (h INT);

INSERT INTO ref (h)
    -> VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),
    -> (12),(13),(14),(15),(16),(17),(18),(19),(20),(21),(22),(23)

and then you can just  DATE_FORMAT(date(now()),'%Y%m%d%H') to the values


问:
Does ReactJS reuse imported packages?
Does ReactJS reuse imported packages?

Let's say I have a file called DisplayItems.js and EditItem.js. They are both imported into App.js.

If I import a package (like axios) at the top of my DisplayItem.js file (import axios from 'axios';), and I also import it in my EditItem.js file, does my Application grow by 13kb or 26kb (assuming axios is 13kb)?

答:
This behavior is controlled not by React, but by whatever build tool compiles and bundles your import statements into a JavaScript file for the browser.

The Create React App template currently uses Webpack as its build tool. Webpack avoids duplicating code that is imported multiple times; it only writes the definitions once. If you are using a different project setup for your React app, your project may use a different build tool.

Title: Does ReactJS reuse imported packages?


问:
VB - Newtonsoft.Json Currency Program Unexpected character "{." error
I am trying to build a api-based online currency program for School Project. I did it but I am trying to build a more functional program so I decided to add a second windows form to my program. This second form does currency exchange in past time. The api that I used in my project can do it so it is possible to do but in VB when I try to get currency names in dictionary I get an error like this:

'Newtonsoft.Json.JsonReaderException' türünde bir yakalanamayan özel durum, Newtonsoft.Json.dll öğesinde oluştu
  Unexpected character encountered while parsing value: {. Path 'rates', line 1, position 43.

And this is my code:

```<code>Dim rawResp As String
        Dim request As HttpWebRequest
        Dim response As HttpWebResponse = Nothing
        Dim reader As StreamReader
        Dim jsonResultToDict As Dictionary(Of String, String)
        Dim kurlar As String
        Dim kur As Object
        Dim kurs As String
        request = DirectCast(WebRequest.Create("http://api.fixer.io/" + DateTimePicker1.Value.ToString("yyyy-MM-dd")), HttpWebRequest)
        response = DirectCast(request.GetResponse(), HttpWebResponse)
        reader = New StreamReader(response.GetResponseStream())
        rawResp = reader.ReadToEnd
        jsonResultToDict = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(rawResp)
        kurlar = jsonResultToDict.Item("rates")
        kur = JObject.Parse(kurlar)
</code>```

By the way I didn't try to set currency names in combobox yet because I couldn't get the data for now.

This is the api : http://fixer.io/

Thanks for helping...

答:
I think because the json data for "rates" doesn't fit into your dictionary model of "String, String", Newtonsoft JSON can't convert from "String, Single" (note how currency code is in double quotes and the rate is not). So, you'll need to create a class object that can be easily converted from JSON.

For example, the class could look like this:

Public Class ForExRates
  Public base As String
  Public [date] As String   'enclose var in brackets; Date is a VB keyword.
  Public rates as Dictionary(Of String, Single)

  Public Sub New()
  End Sub
End Class

Then, replace any reference for Dictionary(Of String, String) with ForExRates.

Ok, so your code should like below:

```<code>    Dim rawResp As String
    Dim request As HttpWebRequest
    Dim response As HttpWebResponse = Nothing
    Dim reader As StreamReader
    Dim objForExRates As ForExRates

    request = DirectCast(WebRequest.Create("http://api.fixer.io/" + DateTimePicker1.Value.ToString("yyyy-MM-dd")), HttpWebRequest)
    response = DirectCast(request.GetResponse(), HttpWebResponse)
    reader = New StreamReader(response.GetResponseStream())
    rawResp = reader.ReadToEnd
    objForExRates = JsonConvert.DeserializeObject(Of ForExRates)(rawResp)
    Dim sCAD As String = "Rate for 'CAD': " + objForExRates.rates("CAD").ToString()
</code>```

Body:
I am trying to build a api-based online currency program for School Project. I did it but I am trying to build a more functional program so I decided to add a second windows form to my program. This second form does currency exchange in past time. The api that I used in my project can do it so it is possible to do but in VB when I try to get currency names in dictionary I get an error like this:

'Newtonsoft.Json.JsonReaderException' türünde bir yakalanamayan özel durum, Newtonsoft.Json.dll öğesinde oluştu
  Unexpected character encountered while parsing value: {. Path 'rates', line 1, position 43.

And this is my code:

Dim rawResp As String
        Dim request As HttpWebRequest
        Dim response As HttpWebResponse = Nothing
        Dim reader As StreamReader
        Dim jsonResultToDict As Dictionary(Of String, String)
        Dim kurlar As String
        Dim kur As Object
        Dim kurs As String
        request = DirectCast(WebRequest.Create("http://api.fixer.io/" + DateTimePicker1.Value.ToString("yyyy-MM-dd")), HttpWebRequest)
        response = DirectCast(request.GetResponse(), HttpWebResponse)
        reader = New StreamReader(response.GetResponseStream())
        rawResp = reader.ReadToEnd
        jsonResultToDict = JsonConvert.DeserializeObject(Of Dictionary(Of String, String))(rawResp)
        kurlar = jsonResultToDict.Item("rates")
        kur = JObject.Parse(kurlar)

By the way I didn't try to set currency names in combobox yet because I couldn't get the data for now.

This is the api : http://fixer.io/

Thanks for helping...

Body:
I think because the json data for "rates" doesn't fit into your dictionary model of "String, String", Newtonsoft JSON can't convert from "String, Single" (note how currency code is in double quotes and the rate is not). So, you'll need to create a class object that can be easily converted from JSON.

For example, the class could look like this:

Public Class ForExRates
  Public base As String
  Public [date] As String   'enclose var in brackets; Date is a VB keyword.
  Public rates as Dictionary(Of String, Single)

  Public Sub New()
  End Sub
End Class

Then, replace any reference for Dictionary(Of String, String) with ForExRates.

Ok, so your code should like below:

    Dim rawResp As String
    Dim request As HttpWebRequest
    Dim response As HttpWebResponse = Nothing
    Dim reader As StreamReader
    Dim objForExRates As ForExRates

    request = DirectCast(WebRequest.Create("http://api.fixer.io/" + DateTimePicker1.Value.ToString("yyyy-MM-dd")), HttpWebRequest)
    response = DirectCast(request.GetResponse(), HttpWebResponse)
    reader = New StreamReader(response.GetResponseStream())
    rawResp = reader.ReadToEnd
    objForExRates = JsonConvert.DeserializeObject(Of ForExRates)(rawResp)
    Dim sCAD As String = "Rate for 'CAD': " + objForExRates.rates("CAD").ToString()


答:
So, basically, you're looking for this:</p>

```<code>Console.ForegroundColor = ConsoleColor.Green;
string[] Class = new string[] { "AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM", "NN", "OO" };
double[] Rate = new double[] { .015, .023, .010, .042, .051, .004, .022, .030, .001, .010, .020, .030, .045, .033, .050 };
Console.Write("Please enter vehicle classification: ");
string Vclass = Console.ReadLine();
if (!Class.Contains(Vclass))
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("There is an error with the vehicle class.");
    Console.ForegroundColor = ConsoleColor.Green;
}
</code>```

Title: if statement seems to not be working with multiple conditions

Body:
I'm not sure if I'm overloading anything but when I add all the conditions I need to one if statement it always returns true. It seems to always show my error message, but when I only add one condition it works perfectly fine. Also, I know my code is messy I'm just a novice, go easy on me.

Console.ForegroundColor = ConsoleColor.Green;
string[] Class = new string[] { "AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM", "NN", "OO" };
double[] Rate = new double[] { .015, .023, .010, .042, .051, .004, .022, .030, .001, .010, .020, .030, .045, .033, .050 };
Console.Write("Please enter vehicle classification: ");
string Vclass = Console.ReadLine();
if (Vclass != "AA" || Vclass != "BB" || Vclass != "CC" || Vclass != "DD" || Vclass != "EE" || Vclass != "FF" || Vclass != "GG" || Vclass != "HH" || Vclass != "II" || Vclass != "JJ" || Vclass != "KK" || Vclass != "LL" || Vclass != "MM" || Vclass != "NN" || Vclass != "OO")
{
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("There is an error with the vehicle class.");
        Console.ForegroundColor = ConsoleColor.Green;
}

Body:
So, basically, you're looking for this:

Console.ForegroundColor = ConsoleColor.Green;
string[] Class = new string[] { "AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ", "KK", "LL", "MM", "NN", "OO" };
double[] Rate = new double[] { .015, .023, .010, .042, .051, .004, .022, .030, .001, .010, .020, .030, .045, .033, .050 };
Console.Write("Please enter vehicle classification: ");
string Vclass = Console.ReadLine();
if (!Class.Contains(Vclass))
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("There is an error with the vehicle class.");
    Console.ForegroundColor = ConsoleColor.Green;
}