问:
How to dynamicaly generate variable names depending on 3 predefined lists (f'{list1}_{list2}_{list3} ') in Python?
I read many questions/answers, but it does not really fit with what I'm looking for...

Here's the "story" : I'm anonymizing 1000 time series and now, I need to analyze how it looks like between real patient time series and the anonymized ones. I have the following parameters to test :

```<code>list_patient = ['pa', 'pr']   # pa = anonymized patients / pr = real patients
list_param = ['avg', 'std', 'med', 'max', 'min'] # Measures that I want to do
list_param_physio = ['FC', 'PAS', 'PAM', 'PAD'] # Physiological parameters such as cardiac frequency (FC)
</code>```

And I would definitely prefer to avoid this... : "3 lessons to make developers cry..." or how looks like a big part of my code without automation.

Just a taste of it :

```<code>avg_pa_fc, avg_pa_pas, avg_pa_pam, avg_pa_pad, std_pa_fc, std_pa_pas, std_pa_pam, std_pa_pad = ([] for i in range(8))
med_pa_fc, med_pa_pas, med_pa_pam, med_pa_pad = ([] for i in range(4))
min_pa_fc, min_pa_pas, min_pa_pam, min_pa_pad, max_pa_fc, max_pa_pas, max_pa_pam, max_pa_pad = ([] for i in range(8))
...
# Calculte means and stdev for each pa file, add it to a np.array and convert it to a pd.df
avg_pa_fc, std_pa_fc = pd.DataFrame(np.append(avg_pa_fc, (statistics.mean(pa_series_fc)))), pd.DataFrame(np.append(std_pa_fc, (statistics.stdev(pa_series_fc))))
avg_pa_pas, std_pa_pas = pd.DataFrame(np.append(avg_pa_pas, (statistics.mean(pa_series_pas)))), pd.DataFrame(np.append(std_pa_pas, (statistics.stdev(pa_series_pas))))
avg_pa_pam, std_pa_pam = pd.DataFrame(np.append(avg_pa_pam, (statistics.mean(pa_series_pam)))), pd.DataFrame(np.append(std_pa_pam, (statistics.stdev(pa_series_pam))))
avg_pa_pad, std_pa_pad = pd.DataFrame(np.append(avg_pa_pad, (statistics.mean(pa_series_pad)))), pd.DataFrame(np.append(std_pa_pad, (statistics.stdev(pa_series_pad))))

</code>```

So, I would like to create automatically some empty lists with this format : {list1}_{list2}_{list3} = [] (underscores are between lists as below)

I tried many things, such as :

```<code>list = []
for i in range(40):
    list.append(f'{list_param}_{list_patient}_{list_param_physio}')
    print(list)
# Output : ["['pa', 'pr']_['avg', 'std', 'med', 'max', 'min']_['FC', 'PAS', 'PAM', 'PAD']", "['pa', 'pr']_....

for param, patient, param_phy in enumerate(list_param, list_patient, list_param_physio):
    list.append(f'{param}_{patient}_{param_phy}')
    print(list)
# TypeError: enumerate() takes at most 2 arguments (3 given)

# For anonymized patients :
for param, param_phy in enumerate(list_param, list_param_physio):
    list.append((f'{param}_pa_{param_phy}').aslist())
    print(list)
# TypeError: 'list' object cannot be interpreted as an integer

</code>```

I also tried to use dictionaries, but with 3 parameters, it begins to be too tricky for me...

If you have any idea, that would be great !

答:
You could do it with:

```<code>>>> list_patient = ['pa', 'pr']
>>> list_param = ['avg', 'std', 'med', 'max', 'min']
>>> list_param_physio = ['FC', 'PAS', 'PAM', 'PAD']

>>> {f"{x}_{y}_{z}": [] for x in list_patient for y in list_param for z in list_param_physio}
</code>```

This will give you following output:

```<code>{
    'pa_avg_FC': [],
    'pa_avg_PAS': [],
    'pa_avg_PAM': [],
    'pa_avg_PAD': [],
    'pa_std_FC': [],
    'pa_std_PAS': [],
    'pa_std_PAM': [],
    'pa_std_PAD': [],
    'pa_med_FC': [],
    'pa_med_PAS': [],
    'pa_med_PAM': [],
    'pa_med_PAD': [],
    'pa_max_FC': [],
    'pa_max_PAS': [],
    'pa_max_PAM': [],
    'pa_max_PAD': [],
    'pa_min_FC': [],
    'pa_min_PAS': [],
    'pa_min_PAM': [],
    'pa_min_PAD': [],
    'pr_avg_FC': [],
    'pr_avg_PAS': [],
    'pr_avg_PAM': [],
    'pr_avg_PAD': [],
    'pr_std_FC': [],
    'pr_std_PAS': [],
    'pr_std_PAM': [],
    'pr_std_PAD': [],
    'pr_med_FC': [],
    'pr_med_PAS': [],
    'pr_med_PAM': [],
    'pr_med_PAD': [],
    'pr_max_FC': [],
    'pr_max_PAS': [],
    'pr_max_PAM': [],
    'pr_max_PAD': [],
    'pr_min_FC': [],
    'pr_min_PAS': [],
    'pr_min_PAM': [],
    'pr_min_PAD': []
}
</code>```

You can also use the following code if you want to create the variables without creating a dictionary:

```<code>for x in list_patient:
    for y in list_param:
        for z in list_param_physio:
            exec(f"{x}_{y}_{z} = list()")
</code>```

However, be careful exec() is a dangerous function and should not be used recklessly.

Body:
I read many questions/answers, but it does not really fit with what I'm looking for...

Here's the "story" : I'm anonymizing 1000 time series and now, I need to analyze how it looks like between real patient time series and the anonymized ones. I have the following parameters to test :

list_patient = ['pa', 'pr']   # pa = anonymized patients / pr = real patients
list_param = ['avg', 'std', 'med', 'max', 'min'] # Measures that I want to do
list_param_physio = ['FC', 'PAS', 'PAM', 'PAD'] # Physiological parameters such as cardiac frequency (FC)

And I would definitely prefer to avoid this... : "3 lessons to make developers cry..." or how looks like a big part of my code without automation.

Just a taste of it :

avg_pa_fc, avg_pa_pas, avg_pa_pam, avg_pa_pad, std_pa_fc, std_pa_pas, std_pa_pam, std_pa_pad = ([] for i in range(8))
med_pa_fc, med_pa_pas, med_pa_pam, med_pa_pad = ([] for i in range(4))
min_pa_fc, min_pa_pas, min_pa_pam, min_pa_pad, max_pa_fc, max_pa_pas, max_pa_pam, max_pa_pad = ([] for i in range(8))
...
# Calculte means and stdev for each pa file, add it to a np.array and convert it to a pd.df
avg_pa_fc, std_pa_fc = pd.DataFrame(np.append(avg_pa_fc, (statistics.mean(pa_series_fc)))), pd.DataFrame(np.append(std_pa_fc, (statistics.stdev(pa_series_fc))))
avg_pa_pas, std_pa_pas = pd.DataFrame(np.append(avg_pa_pas, (statistics.mean(pa_series_pas)))), pd.DataFrame(np.append(std_pa_pas, (statistics.stdev(pa_series_pas))))
avg_pa_pam, std_pa_pam = pd.DataFrame(np.append(avg_pa_pam, (statistics.mean(pa_series_pam)))), pd.DataFrame(np.append(std_pa_pam, (statistics.stdev(pa_series_pam))))
avg_pa_pad, std_pa_pad = pd.DataFrame(np.append(avg_pa_pad, (statistics.mean(pa_series_pad)))), pd.DataFrame(np.append(std_pa_pad, (statistics.stdev(pa_series_pad))))

So, I would like to create automatically some empty lists with this format : {list1}_{list2}_{list3} = [] (underscores are between lists as below)

I tried many things, such as :

list = []
for i in range(40):
    list.append(f'{list_param}_{list_patient}_{list_param_physio}')
    print(list)
# Output : ["['pa', 'pr']_['avg', 'std', 'med', 'max', 'min']_['FC', 'PAS', 'PAM', 'PAD']", "['pa', 'pr']_....

for param, patient, param_phy in enumerate(list_param, list_patient, list_param_physio):
    list.append(f'{param}_{patient}_{param_phy}')
    print(list)
# TypeError: enumerate() takes at most 2 arguments (3 given)

# For anonymized patients :
for param, param_phy in enumerate(list_param, list_param_physio):
    list.append((f'{param}_pa_{param_phy}').aslist())
    print(list)
# TypeError: 'list' object cannot be interpreted as an integer

I also tried to use dictionaries, but with 3 parameters, it begins to be too tricky for me...

If you have any idea, that would be great !

Body:
You could do it with:

>>> list_patient = ['pa', 'pr']
>>> list_param = ['avg', 'std', 'med', 'max', 'min']
>>> list_param_physio = ['FC', 'PAS', 'PAM', 'PAD']

>>> {f"{x}_{y}_{z}": [] for x in list_patient for y in list_param for z in list_param_physio}

This will give you following output:

{
    'pa_avg_FC': [],
    'pa_avg_PAS': [],
    'pa_avg_PAM': [],
    'pa_avg_PAD': [],
    'pa_std_FC': [],
    'pa_std_PAS': [],
    'pa_std_PAM': [],
    'pa_std_PAD': [],
    'pa_med_FC': [],
    'pa_med_PAS': [],
    'pa_med_PAM': [],
    'pa_med_PAD': [],
    'pa_max_FC': [],
    'pa_max_PAS': [],
    'pa_max_PAM': [],
    'pa_max_PAD': [],
    'pa_min_FC': [],
    'pa_min_PAS': [],
    'pa_min_PAM': [],
    'pa_min_PAD': [],
    'pr_avg_FC': [],
    'pr_avg_PAS': [],
    'pr_avg_PAM': [],
    'pr_avg_PAD': [],
    'pr_std_FC': [],
    'pr_std_PAS': [],
    'pr_std_PAM': [],
    'pr_std_PAD': [],
    'pr_med_FC': [],
    'pr_med_PAS': [],
    'pr_med_PAM': [],
    'pr_med_PAD': [],
    'pr_max_FC': [],
    'pr_max_PAS': [],
    'pr_max_PAM': [],
    'pr_max_PAD': [],
    'pr_min_FC': [],
    'pr_min_PAS': [],
    'pr_min_PAM': [],
    'pr_min_PAD': []
}

You can also use the following code if you want to create the variables without creating a dictionary:

for x in list_patient:
    for y in list_param:
        for z in list_param_physio:
            exec(f"{x}_{y}_{z} = list()")

However, be careful exec() is a dangerous function and should not be used recklessly.


来源: stackexchange

问:
Problem with simple jQuery Tabs
I have a very simple jquery tabs functions that looks like this :

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

    //Default Action
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });

});
</code>```

and the HTML for it is :

```<code><div class="container">
  <ul class="tabs">
    <li><a href="#tab1">Tab 1</a></li>
    <li><a href="#tab2">Tab 2</a></li>
  </ul>
  <div class="tab_container">
    <div id="tab1" class="tab_content">
      <h2>Content</h2>
    </div>
    <div id="tab2" class="tab_content">
      <h2>Content</h2>
    </div>
    <div id="tab3" class="tab_content">
      <h2>Content</h2>
    </div>
    <div id="tab4" class="tab_content">
      <h2>Content</h2>
    </div>
  </div>
</div>
</code>```

What im trying to do here is add another tab navigation, so bacically repat the ul tag with content in it but different class so I can have something like this :

```<code><ul class="tabs">
        <li><a href="#tab1">Tab 1</a></li>
        <li><a href="#tab2">Tab 2</a></li>
</ul>
<ul class="markers">
        <li><a href="#tab1">Tab 1</a></li>
        <li><a href="#tab2">Tab 2</a></li>
</ul>
</code>```

..and whenever I click on any of the list it will affect
 in other  group.

Any help much appreciaated.

Thank you for your help in advance.

Dom

答:
you sholud use a class name or id or an element to use fadein() like this

```<code> $("#id").fadeIn("slow");
</code>```

but in your code you are trying to use href attribute .

here.................

```<code>var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active content
</code>```

i think you can't use like that

http://api.jquery.com/fadeIn/

ContentLicense: CC BY-SA 3.0

Title: Problem with simple jQuery Tabs

Body:
I have a very simple jquery tabs functions that looks like this :

$(document).ready(function() {

    //Default Action
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });

});

and the HTML for it is :

Tab 1

Tab 2

Content

Content

Content

Content

What im trying to do here is add another tab navigation, so bacically repat the ul tag with content in it but different class so I can have something like this :

Tab 1

Tab 2

Tab 1

Tab 2

..and whenever I click on any of the list it will affect
 in other  group.

Any help much appreciaated.

Thank you for your help in advance.

Dom

Body:
you sholud use a class name or id or an element to use fadein() like this

 $("#id").fadeIn("slow");

but in your code you are trying to use href attribute .

here.................

var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
$(activeTab).fadeIn(); //Fade in the active content

i think you can't use like that

http://api.jquery.com/fadeIn/


问:
Pyinstaller EXE Files are not independent?
I used pyinstaller to compile my pygame code into an exe file using this command:
pyinstaller --onefile -w gamename.py
But after moving it to a different directory and running it, it gives me file not found errors and file doesn't exist errors. ALL help is greatly appreciated. Thanks.

答:
Possibly, you have some file locations in your code as strings. These external files are not part of your code, so they are not compiled into exe.

Check this answer about adding files in pyinstaller

ContentLicense: CC BY-SA 4.0


问:
System.Text.Json serialize derived class property
I'm migrating a project from Newtonsoft.Json to System.Text.Json in .NET 5.

I have class:

abstract class Car
{
    public string Name { get; set; } = "Default Car Name";
}

class Tesla : Car
{
    public string TeslaEngineName { get; set; } = "My Tesla Engine";
}
```
<p>I tried:</p>
<pre class="lang-cs prettyprint-override"><code>var cars = new List<Car>
{
    new Tesla(),
    new Tesla(),
    new Tesla()
};

var json = JsonSerializer.Serialize(cars);

Console.WriteLine(json);
</code>```

The output is:

[
  {"Name":"Default Car Name"},
  {"Name":"Default Car Name"},
  {"Name":"Default Car Name"}
]
```

Which lost my property: TeslaEngineName.

So how can I serialize derived an object with all properties?

答:
I ran into this problem as well when I was generating some JSON for a personal project - I had a recursive polymorphic data model that I wanted turned into JSON, but the presence of sub-objects that were derived types of the root object in the root object made the serializer just spit out the base type's properties for all of the derived types. I fiddled around with a JsonConverter and reflection for a few hours and came up with a sledgehammer solution that did what I needed it to do.

Basically what this is doing is manually walking each object in the graph and serializing each member that is not a reference type  using the default serializer, but upon encountering an instance of a reference type (that is not a string) I dynamically generate a new JsonConverter to handle that type and add it to the "Converters" list, then recursively use that new instance to serialize the sub-object as its true runtime type.

You might be able to use it as a starting point towards a solution that can do what you need.

The converter:

```<code>/// <summary>
/// Instructs the JsonSerializer to serialize an object as its runtime type and not the type parameter passed into the Write function.
/// </summary>
public class RuntimeTypeJsonConverter<T> : JsonConverter<T>
{
    private static readonly Dictionary<Type, PropertyInfo[]> _knownProps = new Dictionary<Type, PropertyInfo[]>(); //cache mapping a Type to its array of public properties to serialize
    private static readonly Dictionary<Type, JsonConverter> _knownConverters = new Dictionary<Type, JsonConverter>(); //cache mapping a Type to its respective RuntimeTypeJsonConverter instance that was created to serialize that type.
    private static readonly Dictionary<Type, Type> _knownGenerics = new Dictionary<Type, Type>(); //cache mapping a Type to the type of RuntimeTypeJsonConverter generic type definition that was created to serialize that type

    public override bool CanConvert(Type typeToConvert)
    {
        return typeToConvert.IsClass && typeToConvert != typeof(string); //this converter is only meant to work on reference types that are not strings
    }

    public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var deserialized = JsonSerializer.Deserialize(ref reader, typeToConvert, options); //default read implementation, the focus of this converter is the Write operation
        return (T)deserialized;
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        if (value is IEnumerable) //if the value is an IEnumerable of any sorts, serialize it as a JSON array. Note that none of the properties of the IEnumerable are written, it is simply iterated over and serializes each object in the IEnumerable
        {
            WriteIEnumerable(writer, value, options);
        }
        else if (value != null && value.GetType().IsClass == true) //if the value is a reference type and not null, serialize it as a JSON object.
        {
            WriteObject(writer, value, ref options);
        }
        else //otherwise just call the default serializer implementation of this Converter is asked to serialize anything not handled in the other two cases
        {
            JsonSerializer.Serialize(writer, value);
        }
    }

    /// <summary>
    /// Writes the values for an object into the Utf8JsonWriter
    /// </summary>
    /// <param name="writer">The writer to write to.</param>
    /// <param name="value">The value to convert to Json.</param>
    /// <param name="options">An object that specifies the serialization options to use.</param>
    private void WriteObject(Utf8JsonWriter writer, T value, ref JsonSerializerOptions options)
    {
        var type = value.GetType();

        //get all the public properties that we will be writing out into the object
        PropertyInfo[] props = GetPropertyInfos(type);

        writer.WriteStartObject();

        foreach (var prop in props)
        {
            var propVal = prop.GetValue(value);
            if (propVal == null) continue; //don't include null values in the final graph

            writer.WritePropertyName(prop.Name);
            var propType = propVal.GetType(); //get the runtime type of the value regardless of what the property info says the PropertyType should be

            if (propType.IsClass && propType != typeof(string)) //if the property type is a valid type for this JsonConverter to handle, do some reflection work to get a RuntimeTypeJsonConverter appropriate for the sub-object
            {
                Type generic = GetGenericConverterType(propType); //get a RuntimeTypeJsonConverter<T> Type appropriate for the sub-object
                JsonConverter converter = GetJsonConverter(generic); //get a RuntimeTypeJsonConverter<T> instance appropriate for the sub-object

                //look in the options list to see if we don't already have one of these converters in the list of converters in use (we may already have a converter of the same type, but it may not be the same instance as our converter variable above)
                var found = false;
                foreach (var converterInUse in options.Converters)
                {
                    if (converterInUse.GetType() == generic)
                    {
                        found = true;
                        break;
                    }
                }

                if (found == false) //not in use, make a new options object clone and add the new converter to its Converters list (which is immutable once passed into the Serialize method).
                {
                    options = new JsonSerializerOptions(options);
                    options.Converters.Add(converter);
                }

                JsonSerializer.Serialize(writer, propVal, propType, options);
            }
            else //not one of our sub-objects, serialize it like normal
            {
                JsonSerializer.Serialize(writer, propVal);
            }
        }

        writer.WriteEndObject();
    }

    /// <summary>
    /// Gets or makes RuntimeTypeJsonConverter generic type to wrap the given type parameter.
    /// </summary>
    /// <param name="propType">The type to get a RuntimeTypeJsonConverter generic type for.</param>
    /// <returns></returns>
    private Type GetGenericConverterType(Type propType)
    {
        Type generic = null;
        if (_knownGenerics.ContainsKey(propType) == false)
        {
            generic = typeof(RuntimeTypeJsonConverter<>).MakeGenericType(propType);
            _knownGenerics.Add(propType, generic);
        }
        else
        {
            generic = _knownGenerics[propType];
        }

        return generic;
    }

    /// <summary>
    /// Gets or creates the corresponding RuntimeTypeJsonConverter that matches the given generic type defintion.
    /// </summary>
    /// <param name="genericType">The generic type definition of a RuntimeTypeJsonConverter.</param>
    /// <returns></returns>
    private JsonConverter GetJsonConverter(Type genericType)
    {
        JsonConverter converter = null;
        if (_knownConverters.ContainsKey(genericType) == false)
        {
            converter = (JsonConverter)Activator.CreateInstance(genericType);
            _knownConverters.Add(genericType, converter);
        }
        else
        {
            converter = _knownConverters[genericType];
        }

        return converter;
    }

    /// <summary>
    /// Gets all the public properties of a Type.
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    private PropertyInfo[] GetPropertyInfos(Type t)
    {
        PropertyInfo[] props = null;

        if (_knownProps.ContainsKey(t) == false)
        {
            props = t.GetProperties();
            _knownProps.Add(t, props);
        }
        else
        {
            props = _knownProps[t];
        }

        return props;
    }

    /// <summary>
    /// Writes the values for an object that implements IEnumerable into the Utf8JsonWriter
    /// </summary>
    /// <param name="writer">The writer to write to.</param>
    /// <param name="value">The value to convert to Json.</param>
    /// <param name="options">An object that specifies the serialization options to use.</param>
    private void WriteIEnumerable(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        writer.WriteStartArray();

        foreach (object item in value as IEnumerable)
        {
            if (item == null) //preserving null gaps in the IEnumerable
            {
                writer.WriteNullValue();
                continue;
            }

            JsonSerializer.Serialize(writer, item, item.GetType(), options);
        }

        writer.WriteEndArray();
    }
}
</code>```

To use:

```<code>        var cars = new List<Car>
        {
            new Tesla(),
            new Tesla(),
            new Tesla()
        };

        var options = new JsonSerializerOptions();
        options.Converters.Add(new RuntimeTypeJsonConverter<object>());

        var json = JsonSerializer.Serialize(cars, cars.GetType(), options);
</code>```

Body:
I'm migrating a project from Newtonsoft.Json to System.Text.Json in .NET 5.

I have class:

abstract class Car
{
    public string Name { get; set; } = "Default Car Name";
}

class Tesla : Car
{
    public string TeslaEngineName { get; set; } = "My Tesla Engine";
}

I tried:

var cars = new List<Car>
{
    new Tesla(),
    new Tesla(),
    new Tesla()
};

var json = JsonSerializer.Serialize(cars);

Console.WriteLine(json);

The output is:

[
  {"Name":"Default Car Name"},
  {"Name":"Default Car Name"},
  {"Name":"Default Car Name"}
]

Which lost my property: TeslaEngineName.

So how can I serialize derived an object with all properties?

Body:
I ran into this problem as well when I was generating some JSON for a personal project - I had a recursive polymorphic data model that I wanted turned into JSON, but the presence of sub-objects that were derived types of the root object in the root object made the serializer just spit out the base type's properties for all of the derived types. I fiddled around with a JsonConverter and reflection for a few hours and came up with a sledgehammer solution that did what I needed it to do.

Basically what this is doing is manually walking each object in the graph and serializing each member that is not a reference type  using the default serializer, but upon encountering an instance of a reference type (that is not a string) I dynamically generate a new JsonConverter to handle that type and add it to the "Converters" list, then recursively use that new instance to serialize the sub-object as its true runtime type.

You might be able to use it as a starting point towards a solution that can do what you need.

The converter:

/// <summary>
/// Instructs the JsonSerializer to serialize an object as its runtime type and not the type parameter passed into the Write function.
/// </summary>
public class RuntimeTypeJsonConverter<T> : JsonConverter<T>
{
    private static readonly Dictionary<Type, PropertyInfo[]> _knownProps = new Dictionary<Type, PropertyInfo[]>(); //cache mapping a Type to its array of public properties to serialize
    private static readonly Dictionary<Type, JsonConverter> _knownConverters = new Dictionary<Type, JsonConverter>(); //cache mapping a Type to its respective RuntimeTypeJsonConverter instance that was created to serialize that type.
    private static readonly Dictionary<Type, Type> _knownGenerics = new Dictionary<Type, Type>(); //cache mapping a Type to the type of RuntimeTypeJsonConverter generic type definition that was created to serialize that type

    public override bool CanConvert(Type typeToConvert)
    {
        return typeToConvert.IsClass && typeToConvert != typeof(string); //this converter is only meant to work on reference types that are not strings
    }

    public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var deserialized = JsonSerializer.Deserialize(ref reader, typeToConvert, options); //default read implementation, the focus of this converter is the Write operation
        return (T)deserialized;
    }

    public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        if (value is IEnumerable) //if the value is an IEnumerable of any sorts, serialize it as a JSON array. Note that none of the properties of the IEnumerable are written, it is simply iterated over and serializes each object in the IEnumerable
        {
            WriteIEnumerable(writer, value, options);
        }
        else if (value != null && value.GetType().IsClass == true) //if the value is a reference type and not null, serialize it as a JSON object.
        {
            WriteObject(writer, value, ref options);
        }
        else //otherwise just call the default serializer implementation of this Converter is asked to serialize anything not handled in the other two cases
        {
            JsonSerializer.Serialize(writer, value);
        }
    }

    /// <summary>
    /// Writes the values for an object into the Utf8JsonWriter
    /// </summary>
    /// <param name="writer">The writer to write to.</param>
    /// <param name="value">The value to convert to Json.</param>
    /// <param name="options">An object that specifies the serialization options to use.</param>
    private void WriteObject(Utf8JsonWriter writer, T value, ref JsonSerializerOptions options)
    {
        var type = value.GetType();

        //get all the public properties that we will be writing out into the object
        PropertyInfo[] props = GetPropertyInfos(type);

        writer.WriteStartObject();

        foreach (var prop in props)
        {
            var propVal = prop.GetValue(value);
            if (propVal == null) continue; //don't include null values in the final graph

            writer.WritePropertyName(prop.Name);
            var propType = propVal.GetType(); //get the runtime type of the value regardless of what the property info says the PropertyType should be

            if (propType.IsClass && propType != typeof(string)) //if the property type is a valid type for this JsonConverter to handle, do some reflection work to get a RuntimeTypeJsonConverter appropriate for the sub-object
            {
                Type generic = GetGenericConverterType(propType); //get a RuntimeTypeJsonConverter<T> Type appropriate for the sub-object
                JsonConverter converter = GetJsonConverter(generic); //get a RuntimeTypeJsonConverter<T> instance appropriate for the sub-object

                //look in the options list to see if we don't already have one of these converters in the list of converters in use (we may already have a converter of the same type, but it may not be the same instance as our converter variable above)
                var found = false;
                foreach (var converterInUse in options.Converters)
                {
                    if (converterInUse.GetType() == generic)
                    {
                        found = true;
                        break;
                    }
                }

                if (found == false) //not in use, make a new options object clone and add the new converter to its Converters list (which is immutable once passed into the Serialize method).
                {
                    options = new JsonSerializerOptions(options);
                    options.Converters.Add(converter);
                }

                JsonSerializer.Serialize(writer, propVal, propType, options);
            }
            else //not one of our sub-objects, serialize it like normal
            {
                JsonSerializer.Serialize(writer, propVal);
            }
        }

        writer.WriteEndObject();
    }

    /// <summary>
    /// Gets or makes RuntimeTypeJsonConverter generic type to wrap the given type parameter.
    /// </summary>
    /// <param name="propType">The type to get a RuntimeTypeJsonConverter generic type for.</param>
    /// <returns></returns>
    private Type GetGenericConverterType(Type propType)
    {
        Type generic = null;
        if (_knownGenerics.ContainsKey(propType) == false)
        {
            generic = typeof(RuntimeTypeJsonConverter<>).MakeGenericType(propType);
            _knownGenerics.Add(propType, generic);
        }
        else
        {
            generic = _knownGenerics[propType];
        }

        return generic;
    }

    /// <summary>
    /// Gets or creates the corresponding RuntimeTypeJsonConverter that matches the given generic type defintion.
    /// </summary>
    /// <param name="genericType">The generic type definition of a RuntimeTypeJsonConverter.</param>
    /// <returns></returns>
    private JsonConverter GetJsonConverter(Type genericType)
    {
        JsonConverter converter = null;
        if (_knownConverters.ContainsKey(genericType) == false)
        {
            converter = (JsonConverter)Activator.CreateInstance(genericType);
            _knownConverters.Add(genericType, converter);
        }
        else
        {
            converter = _knownConverters[genericType];
        }

        return converter;
    }

    /// <summary>
    /// Gets all the public properties of a Type.
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    private PropertyInfo[] GetPropertyInfos(Type t)
    {
        PropertyInfo[] props = null;

        if (_knownProps.ContainsKey(t) == false)
        {
            props = t.GetProperties();
            _knownProps.Add(t, props);
        }
        else
        {
            props = _knownProps[t];
        }

        return props;
    }

    /// <summary>
    /// Writes the values for an object that implements IEnumerable into the Utf8JsonWriter
    /// </summary>
    /// <param name="writer">The writer to write to.</param>
    /// <param name="value">The value to convert to Json.</param>
    /// <param name="options">An object that specifies the serialization options to use.</param>
    private void WriteIEnumerable(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
    {
        writer.WriteStartArray();

        foreach (object item in value as IEnumerable)
        {
            if (item == null) //preserving null gaps in the IEnumerable
            {
                writer.WriteNullValue();
                continue;
            }

            JsonSerializer.Serialize(writer, item, item.GetType(), options);
        }

        writer.WriteEndArray();
    }
}

To use:

        var cars = new List<Car>
        {
            new Tesla(),
            new Tesla(),
            new Tesla()
        };

        var options = new JsonSerializerOptions();
        options.Converters.Add(new RuntimeTypeJsonConverter<object>());

        var json = JsonSerializer.Serialize(cars, cars.GetType(), options);


问:
Error when trying to install react-twitter-embed
I'm trying to install react-twitter-embed on my react app.  I have tried deleting and reinstalling my node_modules folder and clearing my npm cache. I've tried upgrading my node and npm to the latest version as well.

Here's the error I'm getting:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: ant-design-pro@2.2.0
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"^17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^15.0.0 || ^16.0.0" from react-twitter-embed@3.0.3
npm ERR! node_modules/react-twitter-embed
npm ERR!   react-twitter-embed@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
```
<p>Here's the list of current dependencies in my package.json</p>
<pre class="lang-js prettyprint-override"><code>    "@ant-design/icons": "^4.7.0",
    "@antv/data-set": "^0.10.0",
    "@apollo/client": "^3.4.11",
    "@babel/runtime": "^7.2.0",
    "@ethersproject/abi": "^5.4.1",
    "@ethersproject/address": "^5.4.0",
    "@ethersproject/bignumber": "^5.4.0",
    "@ethersproject/bytes": "^5.4.0",
    "@ethersproject/constants": "^5.4.0",
    "@ethersproject/contracts": "^5.4.0",
    "@ethersproject/providers": "^5.4.1",
    "@ethersproject/solidity": "^5.4.0",
    "@ethersproject/units": "^5.4.0",
    "@material-ui/core": "^4.12.3",
    "@web3-react/core": "^6.1.9",
    "@web3-react/fortmatic-connector": "^6.1.6",
    "@web3-react/injected-connector": "^6.0.7",
    "@web3-react/ledger-connector": "^6.1.9",
    "@web3-react/network-connector": "^6.1.9",
    "@web3-react/portis-connector": "^6.1.9",
    "@web3-react/torus-connector": "^6.1.9",
    "@web3-react/trezor-connector": "^6.1.9",
    "@web3-react/walletconnect-connector": "^6.2.6",
    "@web3-react/walletlink-connector": "^6.2.6",
    "accounting-js": "^1.1.1",
    "antd": "^3.26.20",
    "apollo-boost": "^0.4.9",
    "axios": "^0.18.1",
    "bizcharts": "^3.4.2",
    "bizcharts-plugin-slider": "^2.1.1-beta.1",
    "bootstrap": "^5.0.2",
    "chalk": "^2.4.2",
    "classnames": "^2.2.6",
    "core-js": "^3.17.2",
    "crypto-js": "^4.1.1",
    "dayjs": "^1.10.7",
    "echarts": "^5.2.2",
    "echarts-for-react": "^3.0.1",
    "enquire-js": "^0.2.1",
    "graphql": "^15.5.3",
    "graphql-tag": "^2.12.5",
    "hash.js": "^1.1.5",
    "lodash": "^4.17.10",
    "lodash-decorators": "^6.0.0",
    "math.js": "^1.1.46",
    "memoize-one": "^5.0.0",
    "moment": "^2.22.2",
    "numeral": "^2.0.6",
    "nzh": "^1.0.3",
    "omit.js": "^1.0.0",
    "only-last-promise": "^1.0.0",
    "path-to-regexp": "^2.4.0",
    "prop-types": "^15.7.2",
    "qs": "^6.6.0",
    "rc-animate": "^2.4.4",
    "react": "^17.0.2",
    "react-apollo": "^3.1.5",
    "react-bootstrap": "^2.0.0-beta.4",
    "react-click-outside": "^3.0.1",
    "react-container-query": "^0.11.0",
    "react-copy-to-clipboard": "^5.0.1",
    "react-datepicker": "^4.2.1",
    "react-detect-click-outside": "^1.1.1",
    "react-device-detect": "^1.17.0",
    "react-document-title": "^2.0.3",
    "react-dom": "^17.0.2",
    "react-fittext": "^1.0.0",
    "react-media": "^1.8.0",
    "react-redux": "^7.2.3",
    "react-router-dom": "^4.3.1",
    "redux": "^4.0.5",
    "styled-components": "^5.3.3",
    "web3-eth": "^1.6.0",
    "web3-eth-contract": "^1.6.0",
    "web3-utils": "^1.6.0"
  },
</code>```

答:
New react version is now supported with recent version of react-twitter-embed along with types.

Events will be also added sooner to the package as I am working towards making  it cover all cases. :)

Body:
I'm trying to install react-twitter-embed on my react app.  I have tried deleting and reinstalling my node_modules folder and clearing my npm cache. I've tried upgrading my node and npm to the latest version as well.

Here's the error I'm getting:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: ant-design-pro@2.2.0
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"^17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^15.0.0 || ^16.0.0" from react-twitter-embed@3.0.3
npm ERR! node_modules/react-twitter-embed
npm ERR!   react-twitter-embed@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Here's the list of current dependencies in my package.json

    "@ant-design/icons": "^4.7.0",
    "@antv/data-set": "^0.10.0",
    "@apollo/client": "^3.4.11",
    "@babel/runtime": "^7.2.0",
    "@ethersproject/abi": "^5.4.1",
    "@ethersproject/address": "^5.4.0",
    "@ethersproject/bignumber": "^5.4.0",
    "@ethersproject/bytes": "^5.4.0",
    "@ethersproject/constants": "^5.4.0",
    "@ethersproject/contracts": "^5.4.0",
    "@ethersproject/providers": "^5.4.1",
    "@ethersproject/solidity": "^5.4.0",
    "@ethersproject/units": "^5.4.0",
    "@material-ui/core": "^4.12.3",
    "@web3-react/core": "^6.1.9",
    "@web3-react/fortmatic-connector": "^6.1.6",
    "@web3-react/injected-connector": "^6.0.7",
    "@web3-react/ledger-connector": "^6.1.9",
    "@web3-react/network-connector": "^6.1.9",
    "@web3-react/portis-connector": "^6.1.9",
    "@web3-react/torus-connector": "^6.1.9",
    "@web3-react/trezor-connector": "^6.1.9",
    "@web3-react/walletconnect-connector": "^6.2.6",
    "@web3-react/walletlink-connector": "^6.2.6",
    "accounting-js": "^1.1.1",
    "antd": "^3.26.20",
    "apollo-boost": "^0.4.9",
    "axios": "^0.18.1",
    "bizcharts": "^3.4.2",
    "bizcharts-plugin-slider": "^2.1.1-beta.1",
    "bootstrap": "^5.0.2",
    "chalk": "^2.4.2",
    "classnames": "^2.2.6",
    "core-js": "^3.17.2",
    "crypto-js": "^4.1.1",
    "dayjs": "^1.10.7",
    "echarts": "^5.2.2",
    "echarts-for-react": "^3.0.1",
    "enquire-js": "^0.2.1",
    "graphql": "^15.5.3",
    "graphql-tag": "^2.12.5",
    "hash.js": "^1.1.5",
    "lodash": "^4.17.10",
    "lodash-decorators": "^6.0.0",
    "math.js": "^1.1.46",
    "memoize-one": "^5.0.0",
    "moment": "^2.22.2",
    "numeral": "^2.0.6",
    "nzh": "^1.0.3",
    "omit.js": "^1.0.0",
    "only-last-promise": "^1.0.0",
    "path-to-regexp": "^2.4.0",
    "prop-types": "^15.7.2",
    "qs": "^6.6.0",
    "rc-animate": "^2.4.4",
    "react": "^17.0.2",
    "react-apollo": "^3.1.5",
    "react-bootstrap": "^2.0.0-beta.4",
    "react-click-outside": "^3.0.1",
    "react-container-query": "^0.11.0",
    "react-copy-to-clipboard": "^5.0.1",
    "react-datepicker": "^4.2.1",
    "react-detect-click-outside": "^1.1.1",
    "react-device-detect": "^1.17.0",
    "react-document-title": "^2.0.3",
    "react-dom": "^17.0.2",
    "react-fittext": "^1.0.0",
    "react-media": "^1.8.0",
    "react-redux": "^7.2.3",
    "react-router-dom": "^4.3.1",
    "redux": "^4.0.5",
    "styled-components": "^5.3.3",
    "web3-eth": "^1.6.0",
    "web3-eth-contract": "^1.6.0",
    "web3-utils": "^1.6.0"
  },


问:
unix - head AND tail of file
Say you have a txt file, what is the command to view the top 10 lines and bottom 10 lines of file simultaneously?

i.e. if the file is 200 lines long, then view lines 1-10 and 190-200 in one go.

答:
I did some more experimenting based mostly on suggestions here. After working a bit, I up with something very similar to another version in another comment, but with a focus more on formatting with multiple file args in addition to stdin.

This wraps nicely into a script (tentatively headtail) and uses the gnu awk. On macOs this can be installed via brew install gawk.

It can work on piped content OR a list of files as arguments.
Given files, it prints a header of the file name, the head N lines, a skipped lines maker, then the tail N lines. If the head and tail overlap or would line up, it neither includes a skip marker nor does it display any duplicate lines.

```<code>#!/bin/bash
headtail_awk() {
  N=10
  gawk -v "n=${N}" -- '\
  FNR == 1 && FILENAME != "-" {
    printf "\033[036m==> %s <==\033[0m\n", FILENAME;
  }
  # print head lines
  FNR <= n { print }
  # store lines in a circular buffer
  { a[FNR % n]=$0 }
  # print non-overlapping tail lines from circular buffer.
  ENDFILE {
    if ( FNR > 2 * n ) {
      printf "\033[0;36m>>> %s lines skipped <<<\033[0m\n", FNR - 2 * n
    }
    for (i=FNR-n+1;i<=FNR;i++) {
      if ( i > n) {
        print a[i % n]
      }
    }
  }
' "$@"
}
headtail_awk "$@"
</code>```

I'll leave any getopts and/or enhancements of the N=10 line window as an exercise for the reader.

sample output of multiple files (with n=3):

```<code>$ headtail -n 3 /usr/share/dict/words /usr/share/dict/propernames
==> /usr/share/dict/words <==
A
a
aa
>>> 235880 lines skipped <<<
zythum
Zyzomys
Zyzzogeton
==> /usr/share/dict/propernames <==
Aaron
Adam
Adlai
>>> 1302 lines skipped <<<
Wolfgang
Woody
Yvonne
</code>```

Title: unix - head AND tail of file

Body:
I did some more experimenting based mostly on suggestions here. After working a bit, I up with something very similar to another version in another comment, but with a focus more on formatting with multiple file args in addition to stdin.

This wraps nicely into a script (tentatively headtail) and uses the gnu awk. On macOs this can be installed via brew install gawk.

It can work on piped content OR a list of files as arguments.
Given files, it prints a header of the file name, the head N lines, a skipped lines maker, then the tail N lines. If the head and tail overlap or would line up, it neither includes a skip marker nor does it display any duplicate lines.

#!/bin/bash
headtail_awk() {
  N=10
  gawk -v "n=${N}" -- '\
  FNR == 1 && FILENAME != "-" {
    printf "\033[036m==> %s <==\033[0m\n", FILENAME;
  }
  # print head lines
  FNR <= n { print }
  # store lines in a circular buffer
  { a[FNR % n]=$0 }
  # print non-overlapping tail lines from circular buffer.
  ENDFILE {
    if ( FNR > 2 * n ) {
      printf "\033[0;36m>>> %s lines skipped <<<\033[0m\n", FNR - 2 * n
    }
    for (i=FNR-n+1;i<=FNR;i++) {
      if ( i > n) {
        print a[i % n]
      }
    }
  }
' "$@"
}
headtail_awk "$@"

I'll leave any getopts and/or enhancements of the N=10 line window as an exercise for the reader.

sample output of multiple files (with n=3):

$ headtail -n 3 /usr/share/dict/words /usr/share/dict/propernames
==> /usr/share/dict/words <==
A
a
aa
>>> 235880 lines skipped <<<
zythum
Zyzomys
Zyzzogeton
==> /usr/share/dict/propernames <==
Aaron
Adam
Adlai
>>> 1302 lines skipped <<<
Wolfgang
Woody
Yvonne


问:
Why is node-gyp rebuild failing on Mac OSX El Capitan
I recently bought a mac, which uses Mac OSX El Capitan v10.11.4. Installed node with homebrew, and am using node v6.2.2 and npm v3.9.5. I'm getting an error with bcrypt during npm install, which I believe derives from a node-gyp rebuild error. I also recently downloaded xcode-select(version 2343) and xcode(7.3.1) (in that order).

Here is the full error output after i run npm install:

https://gist.github.com/varunjayaraman/5734af617d616437cd5b3456b20bc503

Not sure what's going wrong. I come from linux land and do tend to be wary of not installing from source myself, so maybe that is the cause of these issues? Anyway, any advice would be super appreciated. I also saw this error springing up for others, but none of their solutions seemed to work (when i type xcode-select --print-path, I get /Applications/Xcode.app/Contents/Developer)

答:
I had a similar issue.

A lot of folks have recommended that you install Xcode, and point xcode-select to the /Applications/Xcode.app/Contents/Developer. However, there is one more step.

That is to confirm that the /Applications/Xcode.app/Contents/Developer folder has SDK version corresponding to the MacOS version your actual computer is running on.

If it does not, go into /Library/Developer/CommandLineTools and copy that over.


问:
Transform table structure
Hello is any sensible algorithm for transforming data table (Table A to Table B) ?

I trying to moving cells , but have no idea how to calculate a place where I should place additional row after my key field Name.

Table A origin

Name
Salary
Bonus
Amount

John S.
5000
Bonus A
50

John S.

Bonus B
100

Alex G.
7000
Bonus C
150

Alex G.

Bonus D
300

Table B (Expected outcome)

Name
Salary
Bonus
Amount

John S.

5000

John S.

Bonus A
50

John S.

Bonus B
100

Alex G.

7000

Alex G.

Bonus C
150

Alex G.

Bonus D
300

```<code>Sub TransformTable()

' Setting variables
Dim Name As String
Dim BaseSalary As String
Dim BonusName As String
Dim BonusAmount As Double

'Setting worksheet object
Dim SheetData As Worksheet
Set SheetData = Sheets("SheetData")

'counter for main loop
Dim x As Long

'Setting main object array
Dim MyArray As Variant

Dim Item As Integer
    Item = 1

'reading values from table
    MyArray = Worksheets("SheetData").ListObjects("Table1").DataBodyRange.Value

'counting last row value

'main loop
    For x = LBound(MyArray) To UBound(MyArray)

'condition check how many costcenter ids with fixed value
     lstRowSrs = SheetData.Cells(Rows.Count, 1).End(xlUp).Row
     Worksheets("SheetData").Cells(Item + 1, 13).Value = MyArray(x, 1)
     Worksheets("SheetData").Cells(Item + 1, 14).Value = MyArray(x, 2)

    If MyArray(x, 3) <> "" Then

    ' Cells(x, lstRowSrs).EntireRow.Insert

     Worksheets("SheetData").Cells(Item + 2, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 2, 16).Value = MyArray(x, 4)
     Item = Item + 1

    Else
     Worksheets("SheetData").Cells(Item + 1, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 1, 16).Value = MyArray(x, 4)

      Item = Item + 1
    End If
    Next x

End Sub
</code>```

答:
You can obtain your desired output using Power Query, available in Windows Excel 2010+ and Office 365 Excel

Select some cell in your original table

Data => Get&Transform => From Table/Range

When the PQ UI opens, navigate to Home => Advanced Editor

Make note of the Table Name in Line 2 of the code.

Replace the existing code with the M-Code below

Change the table name in line 2 of the pasted code to your "real" table name

Examine any comments, and also the Applied Steps window, to better understand the algorithm and steps

The basic algorithm:

Unpivot the Salary and Amount columns which puts them all into a single column

the Bonus column will have some duplicates -- remove them if the Attribute column contains "Salary"

Remove the contents of the Salary column; rename and reorder the columns

M Code

```<code>let

//change table name in next line to actual name in your workbook
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],

//set the data types
    #"Changed Type" = Table.TransformColumnTypes(Source,{
        {"Name", type text}, {"Salary", Int64.Type}, {"Bonus", type text}, {"Amount", Int64.Type}}),

//Unpivot the columns other than Name and Bonus
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Name", "Bonus"}, "Attribute", "Value"),

//blank the "bonus" if attribute=salary
    #"Replace Bonus with null" = Table.ReplaceValue(#"Unpivoted Other Columns",
        each [Bonus],
        each if [Attribute]="Salary" then null else [Bonus],
        Replacer.ReplaceValue,{"Bonus"}),

//set columns in correct order
    #"Reordered Columns" = Table.ReorderColumns(#"Replace Bonus with null",{"Name", "Attribute", "Bonus", "Value"}),

//rename "Attribute"=>"Salary" and blank the contents
    Rename = Table.RenameColumns(#"Reordered Columns",{{"Attribute","Salary"},{"Value","Amount"}}),
    blankIt = Table.ReplaceValue(Rename, each [Salary],null, Replacer.ReplaceValue,{"Salary"})

in
    blankIt
</code>```

Title: Transform table structure

Body:
Hello is any sensible algorithm for transforming data table (Table A to Table B) ?

I trying to moving cells , but have no idea how to calculate a place where I should place additional row after my key field Name.

Table A origin

Name
Salary
Bonus
Amount

John S.
5000
Bonus A
50

John S.

Bonus B
100

Alex G.
7000
Bonus C
150

Alex G.

Bonus D
300

Table B (Expected outcome)

Name
Salary
Bonus
Amount

John S.

5000

John S.

Bonus A
50

John S.

Bonus B
100

Alex G.

7000

Alex G.

Bonus C
150

Alex G.

Bonus D
300

Sub TransformTable()

' Setting variables
Dim Name As String
Dim BaseSalary As String
Dim BonusName As String
Dim BonusAmount As Double

'Setting worksheet object
Dim SheetData As Worksheet
Set SheetData = Sheets("SheetData")

'counter for main loop
Dim x As Long

'Setting main object array
Dim MyArray As Variant

Dim Item As Integer
    Item = 1

'reading values from table
    MyArray = Worksheets("SheetData").ListObjects("Table1").DataBodyRange.Value

'counting last row value

'main loop
    For x = LBound(MyArray) To UBound(MyArray)

'condition check how many costcenter ids with fixed value
     lstRowSrs = SheetData.Cells(Rows.Count, 1).End(xlUp).Row
     Worksheets("SheetData").Cells(Item + 1, 13).Value = MyArray(x, 1)
     Worksheets("SheetData").Cells(Item + 1, 14).Value = MyArray(x, 2)

    If MyArray(x, 3) <> "" Then

    ' Cells(x, lstRowSrs).EntireRow.Insert

     Worksheets("SheetData").Cells(Item + 2, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 2, 16).Value = MyArray(x, 4)
     Item = Item + 1

    Else
     Worksheets("SheetData").Cells(Item + 1, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 1, 16).Value = MyArray(x, 4)

      Item = Item + 1
    End If
    Next x

End Sub

Body:
You can obtain your desired output using Power Query, available in Windows Excel 2010+ and Office 365 Excel

Select some cell in your original table

Data => Get&Transform => From Table/Range

When the PQ UI opens, navigate to Home => Advanced Editor

Make note of the Table Name in Line 2 of the code.

Replace the existing code with the M-Code below

Change the table name in line 2 of the pasted code to your "real" table name

Examine any comments, and also the Applied Steps window, to better understand the algorithm and steps

The basic algorithm:

Unpivot the Salary and Amount columns which puts them all into a single column

the Bonus column will have some duplicates -- remove them if the Attribute column contains "Salary"

Remove the contents of the Salary column; rename and reorder the columns

M Code

let

//change table name in next line to actual name in your workbook
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],

//set the data types
    #"Changed Type" = Table.TransformColumnTypes(Source,{
        {"Name", type text}, {"Salary", Int64.Type}, {"Bonus", type text}, {"Amount", Int64.Type}}),

//Unpivot the columns other than Name and Bonus
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"Name", "Bonus"}, "Attribute", "Value"),

//blank the "bonus" if attribute=salary
    #"Replace Bonus with null" = Table.ReplaceValue(#"Unpivoted Other Columns",
        each [Bonus],
        each if [Attribute]="Salary" then null else [Bonus],
        Replacer.ReplaceValue,{"Bonus"}),

//set columns in correct order
    #"Reordered Columns" = Table.ReorderColumns(#"Replace Bonus with null",{"Name", "Attribute", "Bonus", "Value"}),

//rename "Attribute"=>"Salary" and blank the contents
    Rename = Table.RenameColumns(#"Reordered Columns",{{"Attribute","Salary"},{"Value","Amount"}}),
    blankIt = Table.ReplaceValue(Rename, each [Salary],null, Replacer.ReplaceValue,{"Salary"})

in
    blankIt


问:
Atalasoft DotImage - Resize a stream
I'm grabbing an image over the internet via WebClient into a stream.

I need to resize the image (constraining proportions but with max width 120px) and then return as another stream.

Can someone show me the code to do this.  I've dug through the developer guide but can't find the answer.

答:
With this code available here:

http://snippets.dzone.com/posts/show/1485

You can resize a image stored in a file. You just need to save the stream to a file, modify it and send it back again. Of course you can also work directly in memory modifying the code.

Title: Atalasoft DotImage - Resize a stream


问:
DB2 to Snowflake Migration - SQL: Deriving a result table using 'values' clause
We are migrating off DB2 to Snowflake, and we have run into an issue with a lack of scope when using the 'values' clause.  DB2 scope extends to all tables within the select query; while Snowflake is limited to that within the clause:

Valid in DB2:

```<code>select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2
</code>```

Not valid in Snowflake (slightly different syntax - remove 'table'):

```<code>select * from
t_1
join

(values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2
</code>```

This throws an error saying "...t_1 is undefined".

Does anyone know of an equivalent capability in Snowflake?

For some context:  This construct sits behind a well embedded process for our business, and to rework it would mean significant investment.

It forms the basis for a dynamic ETL query which is passed into an ADF pipeline.  There is a frontend which deploys components into this query - this deployable piece needs to be kept as simple as possible.  It is the equivalent to the "(t_1.c1, ‘foo’)" line, so ideally any solution would keep this piece the same.

EDIT:

For some additional context...

In the example above, we have a placeholder which identifies the insert point of newly deployed items from the front end, like this:

```<code>select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
/*client_X_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

union

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
,(t_1.c2, 'barfoo')
/*client_Y_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2
</code>```

We are pulling a series of metrics associated with clients, where the label is t_2.c2 and the result is t2.c1.  This is still highly simplified relative to the real world.  We need a simple way to update the placeholder with a new metric and its calculation - t2.c1 may be wrapped in a pile of functions and/or reside inside case statements, etc.

答:
hmm, that string is almost correlated subquery/join with values:

The first thought I have is:

```<code>WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select t_1.*, t_1.c1 as c1, t_2.c2
from t_1
join values ('foo'),
  ('bar') as t_2(c2)
    on t_1.c5 = t_2.c2
;
</code>```

but the part you wanting would look like (if it works):

```<code>WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select t_1.*, t_1.c1 as c1, t_2.c2
from t_1
join values
    (t_1.c1, 'foo'),
    (t_1.c1, 'bar')
        as t_2(c1,c2)
    on t_1.c5 = t_2.c2
;
</code>```

but it doesn't work.... more thinking required.

So IF that block comes in as

```<code>(t_1.c1, 'foo'),
(t_1.c1, 'bar')
</code>```

then you can mash it into block with %%stuff%%

and then rip it apart and hoop jump..

```<code>WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
), magic as (
    SELECT
       split(t.value, ',') as p
       ,trim(get(p,0),'"') as p0
       ,trim(get(p,1),' \'")') as p1

    FROM table(split_to_table($$(t_1.c1, 'foo'),
                              (t_1.c1, 'bar')$$,'(')) as t
    WHERE t.value <> ''
), hoop_jumping(c1, c2) as (
    SELECT
        case p0
               WHEN 't_1.c1' then t_1.c1
               WHEN 't_1.c5' then t_1.c5
        end,
        p1
    FROM magic, t_1
)
SELECT t.*, h.*
FROM t_1 as t
JOIN hoop_jumping as h
   ON t.c5 = h.c2
</code>```

and as long as you are will to cover all the bases of what was selected:

C1
C5
C1
C2

a
bar
a
bar

but I suspect it makes more sense to inject that block into a snowflake scripting block, and use it as injected code.

Body:
We are migrating off DB2 to Snowflake, and we have run into an issue with a lack of scope when using the 'values' clause.  DB2 scope extends to all tables within the select query; while Snowflake is limited to that within the clause:

Valid in DB2:

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

Not valid in Snowflake (slightly different syntax - remove 'table'):

select * from
t_1
join

(values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

This throws an error saying "...t_1 is undefined".

Does anyone know of an equivalent capability in Snowflake?

For some context:  This construct sits behind a well embedded process for our business, and to rework it would mean significant investment.

It forms the basis for a dynamic ETL query which is passed into an ADF pipeline.  There is a frontend which deploys components into this query - this deployable piece needs to be kept as simple as possible.  It is the equivalent to the "(t_1.c1, ‘foo’)" line, so ideally any solution would keep this piece the same.

EDIT:

For some additional context...

In the example above, we have a placeholder which identifies the insert point of newly deployed items from the front end, like this:

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
/*client_X_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

union

select * from
t_1
join

table (values
(t_1.c1, ‘foo’)
,(t_1.c1, ‘bar’)
,(t_1.c2, 'barfoo')
/*client_Y_placeholder*/
) as t_2 (c1, c2)

on t_1.c5 = t_2.c2

We are pulling a series of metrics associated with clients, where the label is t_2.c2 and the result is t2.c1.  This is still highly simplified relative to the real world.  We need a simple way to update the placeholder with a new metric and its calculation - t2.c1 may be wrapped in a pile of functions and/or reside inside case statements, etc.

Body:
hmm, that string is almost correlated subquery/join with values:

The first thought I have is:

WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select t_1.*, t_1.c1 as c1, t_2.c2
from t_1
join values ('foo'),
  ('bar') as t_2(c2)
    on t_1.c5 = t_2.c2
;

but the part you wanting would look like (if it works):

WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
)
select t_1.*, t_1.c1 as c1, t_2.c2
from t_1
join values
    (t_1.c1, 'foo'),
    (t_1.c1, 'bar')
        as t_2(c1,c2)
    on t_1.c5 = t_2.c2
;

but it doesn't work.... more thinking required.

So IF that block comes in as

(t_1.c1, 'foo'),
(t_1.c1, 'bar')

then you can mash it into block with %%stuff%%

and then rip it apart and hoop jump..

WITH t_1 (c1, c5) as (
    SELECT 'a', 'bar'
), magic as (
    SELECT
       split(t.value, ',') as p
       ,trim(get(p,0),'"') as p0
       ,trim(get(p,1),' \'")') as p1

    FROM table(split_to_table($$(t_1.c1, 'foo'),
                              (t_1.c1, 'bar')$$,'(')) as t
    WHERE t.value <> ''
), hoop_jumping(c1, c2) as (
    SELECT
        case p0
               WHEN 't_1.c1' then t_1.c1
               WHEN 't_1.c5' then t_1.c5
        end,
        p1
    FROM magic, t_1
)
SELECT t.*, h.*
FROM t_1 as t
JOIN hoop_jumping as h
   ON t.c5 = h.c2

and as long as you are will to cover all the bases of what was selected:

C1
C5
C1
C2

a
bar
a
bar

but I suspect it makes more sense to inject that block into a snowflake scripting block, and use it as injected code.


问:
Example of migration logic for changing Property Types Objectbox Flutter
I have a flutter app that stores the data with objectbox but I need to change a class that has

```<code>// old:
int year;
// new:
double year;
</code>```

ObjectBox does not support migrating existing property data to a new
type. You will have to take care of this yourself, e.g. by keeping the
old property and adding some migration logic.

On the objectbox page they say it's possible through migration logic.
Data is already stored with int and I need to migrate this data to double but I have not succeeded. Could someone help me with an example. Thanks

答:
So as you've probably figured out already, doing a type migration while keeping the old data intact is not currently possible (as far as I'm aware).  So you'll have to work around that, one convoluted way I can think of is to create a field with your new type, and then on app start, iterate through all your current saves and use year.toDouble() and move any current values in the year to the yearDouble. (Sorry on phone so no real code)

Then when you need to pull that value again, check the original year value, if it's empty, then read the year value from your new yearDouble

You could also just ignore the original iteration all together and just do your check when you use that value.  So modify your current method to check if yearDouble is empty, then read original year.toDouble(), and then add the value to the yearDouble property at the same time

Body:
I have a flutter app that stores the data with objectbox but I need to change a class that has

// old:
int year;
// new:
double year;

ObjectBox does not support migrating existing property data to a new
type. You will have to take care of this yourself, e.g. by keeping the
old property and adding some migration logic.

On the objectbox page they say it's possible through migration logic.
Data is already stored with int and I need to migrate this data to double but I have not succeeded. Could someone help me with an example. Thanks


问:
Intersecting two sets, retaining all (up to) three parts efficiently
If you have two sets a and b and intersect them, there are three interesting parts (which may be empty): h(ead) elements of a not in b, i(ntersection) elements in both a and b, and t(ail) elements of b not in a.

For example: {1, 2, 3} & {2, 3, 4} -> h:{1}, i:{2, 3}, t:{4} (not actual Python code, clearly)

One very clean way to code that in Python:

```<code>h, i, t = a - b, a & b, b - a
</code>```

I figure that this can be slightly more efficient though:

```<code>h, t = a - (i := a & b), b - i
</code>```

Since it first computes the intersection and then subtracts only that from a and then b, which would help if i is small and a and b are large - although I suppose it depends on the implementation of the subtraction whether it's truly faster. It's not likely to be worse, as far as I can tell.

I was unable to find such an operator or function, but since I can imagine efficient implementations that would perform the three-way split of a and b into h, i, and t in fewer iterations, am I missing something like this, which may already exist?

```<code>from magical_set_stuff import hit

h, i, t = hit(a, b)
</code>```

答:
I won't accept my own answer unless nobody manages to beat my own solution or any of the good and concise Python ones.

But for anyone interested in some numbers:

```<code>from random import randint
from timeit import timeit

def grismar(a: set, b: set):
    h, i, t = set(), set(), b.copy()
    for x in a:
        if x in t:
            i.add(x)
            t.remove(x)
        else:
            h.add(x)
    return h, i, t

def good(a: set, b: set):
    return a - b, a & b, b - a

def better(a: set, b: set):
    h, t = a - (i := a & b), b - i
    return h, i, t

def ok(a: set, b: set):
    return a - (a & b), a & b, b - (a & b)

from collections import defaultdict
def tim(a, b):
    x2flags = defaultdict(int)
    for x in a:
        x2flags[x] = 1
    for x in b:
        x2flags[x] |= 2
    result = [None, set(), set(), set()]
    for x, flag in x2flags.items():
        result[flag].add(x)
    return result[1], result[3], result[2]

def pychopath(a, b):
    h, t = set(), b.copy()
    h_add = h.add
    t_remove = t.remove
    i = {x for x in a
         if x in t and not t_remove(x) or h_add(x)}
    return h, i, t

def enke(a, b):
    t = b - (i := a - (h := a - b))
    return h, i, t

xs = set(randint(0, 10000) for _ in range(10000))
ys = set(randint(0, 10000) for _ in range(10000))

# validation
g = (f(xs, ys) for f in (grismar, good, better, ok, tim, enke))
l = set(tuple(tuple(sorted(s)) for s in t) for t in g)
assert len(l) == 1, 'functions are equivalent'

# warmup, not competing
timeit(lambda: grismar(xs, ys), number=500)

# competition
print('a - b, a & b, b - a ', timeit(lambda: good(xs, ys), number=10000))
print('a - (i := a & b), b - i ', timeit(lambda: better(xs, ys), number=10000))
print('a - (a & b), a & b, b - (a & b) ', timeit(lambda: ok(xs, ys), number=10000))
print('tim ', timeit(lambda: tim(xs, ys), number=10000))
print('grismar ', timeit(lambda: grismar(xs, ys), number=10000))
print('pychopath ', timeit(lambda: pychopath(xs, ys), number=10000))
print('b - (i := a - (h := a - b)) ', timeit(lambda: enke(xs, ys), number=10000))
</code>```

Results:

a - b, a & b, b - a  5.6963334
a - (i := a & b), b - i  5.3934624
a - (a & b), a & b, b - (a & b)  9.7732018
tim  16.3080373
grismar  7.709292500000004
pychopath  6.76331460000074
b - (i := a - (h := a - b))  5.197220600000001
```
<p>So far, the optimisation proposed by @enke in the comments appears to win out:</p>
```t = b - (i := a - (h := a - b))
return h, i, t
```

Edit: added @Pychopath's results, which is indeed substantially faster than my own, although @enke's result is still the one to beat (and likely won't be with just Python). If @enke posts their own answer, I'd happily accept it as the answer.

Body:
If you have two sets a and b and intersect them, there are three interesting parts (which may be empty): h(ead) elements of a not in b, i(ntersection) elements in both a and b, and t(ail) elements of b not in a.

For example: {1, 2, 3} & {2, 3, 4} -> h:{1}, i:{2, 3}, t:{4} (not actual Python code, clearly)

One very clean way to code that in Python:

h, i, t = a - b, a & b, b - a

I figure that this can be slightly more efficient though:

h, t = a - (i := a & b), b - i

Since it first computes the intersection and then subtracts only that from a and then b, which would help if i is small and a and b are large - although I suppose it depends on the implementation of the subtraction whether it's truly faster. It's not likely to be worse, as far as I can tell.

I was unable to find such an operator or function, but since I can imagine efficient implementations that would perform the three-way split of a and b into h, i, and t in fewer iterations, am I missing something like this, which may already exist?

from magical_set_stuff import hit

h, i, t = hit(a, b)

Body:
I won't accept my own answer unless nobody manages to beat my own solution or any of the good and concise Python ones.

But for anyone interested in some numbers:

from random import randint
from timeit import timeit

def grismar(a: set, b: set):
    h, i, t = set(), set(), b.copy()
    for x in a:
        if x in t:
            i.add(x)
            t.remove(x)
        else:
            h.add(x)
    return h, i, t

def good(a: set, b: set):
    return a - b, a & b, b - a

def better(a: set, b: set):
    h, t = a - (i := a & b), b - i
    return h, i, t

def ok(a: set, b: set):
    return a - (a & b), a & b, b - (a & b)

from collections import defaultdict
def tim(a, b):
    x2flags = defaultdict(int)
    for x in a:
        x2flags[x] = 1
    for x in b:
        x2flags[x] |= 2
    result = [None, set(), set(), set()]
    for x, flag in x2flags.items():
        result[flag].add(x)
    return result[1], result[3], result[2]

def pychopath(a, b):
    h, t = set(), b.copy()
    h_add = h.add
    t_remove = t.remove
    i = {x for x in a
         if x in t and not t_remove(x) or h_add(x)}
    return h, i, t

def enke(a, b):
    t = b - (i := a - (h := a - b))
    return h, i, t

xs = set(randint(0, 10000) for _ in range(10000))
ys = set(randint(0, 10000) for _ in range(10000))

# validation
g = (f(xs, ys) for f in (grismar, good, better, ok, tim, enke))
l = set(tuple(tuple(sorted(s)) for s in t) for t in g)
assert len(l) == 1, 'functions are equivalent'

# warmup, not competing
timeit(lambda: grismar(xs, ys), number=500)

# competition
print('a - b, a & b, b - a ', timeit(lambda: good(xs, ys), number=10000))
print('a - (i := a & b), b - i ', timeit(lambda: better(xs, ys), number=10000))
print('a - (a & b), a & b, b - (a & b) ', timeit(lambda: ok(xs, ys), number=10000))
print('tim ', timeit(lambda: tim(xs, ys), number=10000))
print('grismar ', timeit(lambda: grismar(xs, ys), number=10000))
print('pychopath ', timeit(lambda: pychopath(xs, ys), number=10000))
print('b - (i := a - (h := a - b)) ', timeit(lambda: enke(xs, ys), number=10000))

Results:

a - b, a & b, b - a  5.6963334
a - (i := a & b), b - i  5.3934624
a - (a & b), a & b, b - (a & b)  9.7732018
tim  16.3080373
grismar  7.709292500000004
pychopath  6.76331460000074
b - (i := a - (h := a - b))  5.197220600000001

So far, the optimisation proposed by @enke in the comments appears to win out:

t = b - (i := a - (h := a - b))
return h, i, t

Edit: added @Pychopath's results, which is indeed substantially faster than my own, although @enke's result is still the one to beat (and likely won't be with just Python). If @enke posts their own answer, I'd happily accept it as the answer.


问:
How to delete a Discord.js commands (v13)
I been looking all over google but still haven't find a way to delete a command I accidentally created. So I have this command call "ping" and I want to delete it. Here the code I use to create it:

// importing stuff
const DiscordJS = require("discord.js");
const dotenv = require("dotenv");
dotenv.config();

console.log("Starting up");

const client = new DiscordJS.Client({
  intents: [DiscordJS.Intents.FLAGS.GUILDS, DiscordJS.Intents.FLAGS.GUILD_MESSAGES]
});

console.log("Waiting for bot to log in...");

client.on("ready", () => {
  console.log("Bot Login");

  const guild = client.guilds.cache.get("913238101902630983");
  let commands;

  if (guild) {
    commands = guild.commands;
  } else {
    commands = client.application.commands;
  }

  commands.create({
    name: "ping",
    description: "Reply with pong"
  });
});

client.login(process.env.token);
```

So now I want to delete that ping command. After searching google I come across 2 way to do so.

Use client.api.applications(client.user.id).commands("command-id (interaction.data.id)").delete() the problem with this solution is I don't know how to get the commandId google searching still doesn't help. Source

Use commands.cache.find(c => c.name === 'command name').delete();. The problem with this one is when I put the ping command name in so commands.cache.find(c => c.name === 'ping').delete(); it give me this error TypeError: Cannot read properties of undefined (reading 'delete'). Source

Please help me, Thanks in advance!

答:
An easy solution to this is to simply clear all slash commands, and then recreate them after. The following code will clear all global commands.

await client.application.commands.set([]);
```
<p>And to clear guild-specific commands do this:</p>
<pre class="lang-js prettyprint-override"><code>const guild = await client.guilds.fetch(/*Guild ID goes here*/);
guild.commands.set([]);
</code>```

Body:
I been looking all over google but still haven't find a way to delete a command I accidentally created. So I have this command call "ping" and I want to delete it. Here the code I use to create it:

// importing stuff
const DiscordJS = require("discord.js");
const dotenv = require("dotenv");
dotenv.config();

console.log("Starting up");

const client = new DiscordJS.Client({
  intents: [DiscordJS.Intents.FLAGS.GUILDS, DiscordJS.Intents.FLAGS.GUILD_MESSAGES]
});

console.log("Waiting for bot to log in...");

client.on("ready", () => {
  console.log("Bot Login");

  const guild = client.guilds.cache.get("913238101902630983");
  let commands;

  if (guild) {
    commands = guild.commands;
  } else {
    commands = client.application.commands;
  }

  commands.create({
    name: "ping",
    description: "Reply with pong"
  });
});

client.login(process.env.token);

So now I want to delete that ping command. After searching google I come across 2 way to do so.

Use client.api.applications(client.user.id).commands("command-id (interaction.data.id)").delete() the problem with this solution is I don't know how to get the commandId google searching still doesn't help. Source

Use commands.cache.find(c => c.name === 'command name').delete();. The problem with this one is when I put the ping command name in so commands.cache.find(c => c.name === 'ping').delete(); it give me this error TypeError: Cannot read properties of undefined (reading 'delete'). Source

Please help me, Thanks in advance!

Body:
An easy solution to this is to simply clear all slash commands, and then recreate them after. The following code will clear all global commands.

await client.application.commands.set([]);

And to clear guild-specific commands do this:

const guild = await client.guilds.fetch(/*Guild ID goes here*/);
guild.commands.set([]);


问:
How can I take output from the command line and input it into a file using write()?
I am trying to use the write() function from <unistd.h> to stream text from the command line into a file. I have tried multiple things along the lines of:

```<code>while(write(STDOUT_FILENO, argv[optind], strlen(STDIN_FILENO)) != 0)
{
    write(STDOUT_FILENO, "\n", sizeof("\n"));
}
</code>```

but continue to get segmentation faults or infinite loops without allowing me to enter anything. I am required to do this without using read(), the only permission allowed is write for the user. I am trying to use Ctrl + D to signal end of input.

An example of how it would run is:

./a.out file.h

This line will append to the end of the file

<ctrl + d>
```

Then, when I open the file it should have This line will append to the end of the file at the end of it.

答:
You would need to read() from STDIN_FILENO into a local buffer, and then write() that buffer to STDOUT_FILENO.  But you explicitly said that "I am required to do this without using read()", which means you are pretty much out of luck on this.  You can't get input from STDIN without reading from it.  If you can't use read(), can you use any other reading function, such as fread(), gets(), getline(), etc?

What is the point of passing in file.h an an input parameter?  When you execute the command /a.out file.h, the content of file.h is not sent to your program at all.  In your main() function, the string value "file.h" is provided in argv[1].  You would have to use that string to open the file yourself, such as with fopen(), then read/write that file as needed.

If you want the content of file.h to be sent to your program via STDIN, you would need to execute /a.out < file.h instead.  Notice the < redirection operator.

But, it sounds like your goal is to open file.h and then append STDIN input to it, in which case you would need something more like this:

```<code>FILE *f = fopen(argv[1], "w+");
if (!f) ...

char buffer[1024];
int nRead;

fwrite("\n", 1, 1, f);
while ((nRead = read(STDIN_FILENO, buffer, sizeof(buffer))) > 0)
{
    fwrite(buffer, 1, nRead, f);
}

fclose(f);
</code>```

Body:
I am trying to use the write() function from <unistd.h> to stream text from the command line into a file. I have tried multiple things along the lines of:

while(write(STDOUT_FILENO, argv[optind], strlen(STDIN_FILENO)) != 0)
{
    write(STDOUT_FILENO, "\n", sizeof("\n"));
}

but continue to get segmentation faults or infinite loops without allowing me to enter anything. I am required to do this without using read(), the only permission allowed is write for the user. I am trying to use Ctrl + D to signal end of input.

An example of how it would run is:

./a.out file.h

This line will append to the end of the file

<ctrl + d>

Then, when I open the file it should have This line will append to the end of the file at the end of it.

Body:
You would need to read() from STDIN_FILENO into a local buffer, and then write() that buffer to STDOUT_FILENO.  But you explicitly said that "I am required to do this without using read()", which means you are pretty much out of luck on this.  You can't get input from STDIN without reading from it.  If you can't use read(), can you use any other reading function, such as fread(), gets(), getline(), etc?

What is the point of passing in file.h an an input parameter?  When you execute the command /a.out file.h, the content of file.h is not sent to your program at all.  In your main() function, the string value "file.h" is provided in argv[1].  You would have to use that string to open the file yourself, such as with fopen(), then read/write that file as needed.

If you want the content of file.h to be sent to your program via STDIN, you would need to execute /a.out < file.h instead.  Notice the < redirection operator.

But, it sounds like your goal is to open file.h and then append STDIN input to it, in which case you would need something more like this:

FILE *f = fopen(argv[1], "w+");
if (!f) ...

char buffer[1024];
int nRead;

fwrite("\n", 1, 1, f);
while ((nRead = read(STDIN_FILENO, buffer, sizeof(buffer))) > 0)
{
    fwrite(buffer, 1, nRead, f);
}

fclose(f);


问:
Generated constants for enum values
I'd need to store some properties of the enum's entries in their constants. For example indicate whether a color is cold or warm.

```<code>enum Colors
{
  Yellow, // warm
  Blue,   // cold
  Gray,   // cold
  Red,    // warm
  // etc.
}
</code>```

In C++ I would define a macro to generate bitmasks for the constants.
Something like:

```<code>#define WARM 1
#define COLD 0

#define MAKECOLOR(index, type) ((index << 8) | type)

enum Colors
{
  Yellow = MAKECOLOR(0, WARM),
  Blue   = MAKECOLOR(1, COLD),
  Gray   = MAKECOLOR(2, COLD),
  Red    = MAKECOLOR(3, WARM),
  // etc.
}
</code>```

In C# this is not possible because there are no macros. I want to avoid writing bitmask expressions directly in the enum. Like this:

```<code>  ...
  Gray   = ((2 << 8) | 0),
  ...
</code>```

Any ideas?

P.S.

Yes, I'm a syntactic sugar freak. :D

答:
I do tend to write the bit expression directly in the enum:

```<code>enum Colors
{
    Yellow = (0 << 8) | ColorTemp.Warm,
    Blue   = (1 << 8) | ColorTemp.Cold,
    Gray   = (2 << 8) | ColorTemp.Cold,
    Red    = (3 << 8) | ColorTemp.Warm,
}

enum ColorTemp
{
    Cold = 0,
    Warm = 1,
}
</code>```

And then write a simple extension class at the bottom of the file, like this:

```<code>public static class ColorsExtensions
{
    public ColorTemp GetTemperature(this Colors color)
    {
        return (ColorTemp)(color & 0x01);
    }
}
</code>```

Title: Generated constants for enum values

Body:
I'd need to store some properties of the enum's entries in their constants. For example indicate whether a color is cold or warm.

enum Colors
{
  Yellow, // warm
  Blue,   // cold
  Gray,   // cold
  Red,    // warm
  // etc.
}

In C++ I would define a macro to generate bitmasks for the constants.
Something like:

#define WARM 1
#define COLD 0

#define MAKECOLOR(index, type) ((index << 8) | type)

enum Colors
{
  Yellow = MAKECOLOR(0, WARM),
  Blue   = MAKECOLOR(1, COLD),
  Gray   = MAKECOLOR(2, COLD),
  Red    = MAKECOLOR(3, WARM),
  // etc.
}

In C# this is not possible because there are no macros. I want to avoid writing bitmask expressions directly in the enum. Like this:

  ...
  Gray   = ((2 << 8) | 0),
  ...

Any ideas?

P.S.

Yes, I'm a syntactic sugar freak. :D

Body:
I do tend to write the bit expression directly in the enum:

enum Colors
{
    Yellow = (0 << 8) | ColorTemp.Warm,
    Blue   = (1 << 8) | ColorTemp.Cold,
    Gray   = (2 << 8) | ColorTemp.Cold,
    Red    = (3 << 8) | ColorTemp.Warm,
}

enum ColorTemp
{
    Cold = 0,
    Warm = 1,
}

And then write a simple extension class at the bottom of the file, like this:

public static class ColorsExtensions
{
    public ColorTemp GetTemperature(this Colors color)
    {
        return (ColorTemp)(color & 0x01);
    }
}


问:
Why are Angular directives considered classes and not functions?
The way the Ng directives are used within HTML tags (view) makes them look like functions to be invoked upon rather than instances of a class. Or maybe they are static methods that can be invoked without a class instance.
Sorry I am coming from backend, OOP languages (C++, Python, Java, C#) and now working to learn Javascript and Typescript and sometimes the philosophy of web-dev is a different paradigm to me.</p>

答: Well it's true that classes are a template for creating objects. They encapsulate data with code to work on that data. But also - Decorators are the functions that modify JavaScript classes. Directives allow us to extend or manipulate the DOM. At the core, a directive is a function that executes whenever the Angular compiler finds it in the DOM.


问:
Iframe creates extra space below
Why does an iframe add extra space under its element? Look at this weird behavior:

.border {
    background: red;
    width: 300px;
    height: 200px;
    border: 1px solid green;
    overflow: visible;
    margin: 0;
    padding: 0;
}

.border iframe {
    border: none;
    width: 300px;
    height: 100px;
    margin: 0;
    padding: 0;
    opacity: 0.8;
}

.border .lower {
    height: 100px;
    margin: 0;
    padding: 0;
    background: blue;
    opacity: 0.8;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border">
  <iframe src="https://example.com"></iframe>
  <div class="lower"></div>
</div></code>```

How to work around?

答:
02 2022 (Bootstrap 5.1)

I thought I will contribute to this question by using CSS and also with Bootstrap 5.1

I will be using Google Map as an example.

on iFrame

CSS method: you can use display:block in the style attribute

```<code>                                                                   ↓
                                                              -------------
<iframe src="SOURCE" width="600" height="450" style="border:0;display:block" allowfullscreen=""
loading="lazy"></iframe>
</code>```

Bootstrap method: use d-block class

```<code>                                                                      ↓
                                                                -------------
<iframe src="SOURCE" width="600" height="450" style="border:0;" class="d-block" allowfullscreen=""
loading="lazy"></iframe>
</code>```

on iFrame Parent

CSS method: If you wrap with a div you can use line-height:0 to your parent element.

```<code>                 ↓
            -------------
<div style="line-height:0">
  <iframe src="SOURCE" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
</div>
</code>```

Boostrap method: Speaking of line-height, bootstrap has four line-height classes lh-1, lh-sm, lh-base, lh-lg they are good for text but unfortunately they don't work on iframe. Also adding d-block to the parent doesn't work instead, you can use d-block on the iframe just like CSS.

```<code><div>
                                                                             ↓
                                                                       -------------
    <iframe src="SOURCE_HERE" width="600" height="450" style="border:0;display:block" allowfullscreen=""
loading="lazy"></iframe>
</div>
</code>```

Fixed Parent height

If your parent height is fixed then you can set the iframe to height="100%" which will expand the iframe height to match with your parent

```<code>.parent{
    height: 500px;
}
</code>```
```<code><div class="parent">
                                                   ↓
                                                 ------
    <iframe src="SOURCE_HERE" width="600" height="100%" style="border:0" allowfullscreen="" loading="lazy"></iframe>
</div>
</code>```

No access to the iframe element

If you do not have control of your iframe element then you can set your parent height to match with the iframe height.

```<code>.parent{
    height: 450px;
}
</code>```
```<code><div class="parent">
                                                   ↓
                                                 -----
    <iframe src="SOURCE_HERE" width="600" height="450" style="border:0;display:block" allowfullscreen="" loading="lazy"></iframe>
</div>
</code>```

Title: Iframe creates extra space below

Body:
Why does an iframe add extra space under its element? Look at this weird behavior:

.border {
    background: red;
    width: 300px;
    height: 200px;
    border: 1px solid green;
    overflow: visible;
    margin: 0;
    padding: 0;
}

.border iframe {
    border: none;
    width: 300px;
    height: 100px;
    margin: 0;
    padding: 0;
    opacity: 0.8;
}

.border .lower {
    height: 100px;
    margin: 0;
    padding: 0;
    background: blue;
    opacity: 0.8;
}

How to work around?

Body:
02 2022 (Bootstrap 5.1)

I thought I will contribute to this question by using CSS and also with Bootstrap 5.1

I will be using Google Map as an example.

on iFrame

CSS method: you can use display:block in the style attribute

                                                                   ↓
                                                              -------------
<iframe src="SOURCE" width="600" height="450" style="border:0;display:block" allowfullscreen=""
loading="lazy"></iframe>

Bootstrap method: use d-block class

                                                                      ↓
                                                                -------------
<iframe src="SOURCE" width="600" height="450" style="border:0;" class="d-block" allowfullscreen=""
loading="lazy"></iframe>

on iFrame Parent

CSS method: If you wrap with a div you can use line-height:0 to your parent element.

                 ↓
            -------------
<div style="line-height:0">
  <iframe src="SOURCE" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
</div>

Boostrap method: Speaking of line-height, bootstrap has four line-height classes lh-1, lh-sm, lh-base, lh-lg they are good for text but unfortunately they don't work on iframe. Also adding d-block to the parent doesn't work instead, you can use d-block on the iframe just like CSS.

<div>
                                                                             ↓
                                                                       -------------
    <iframe src="SOURCE_HERE" width="600" height="450" style="border:0;display:block" allowfullscreen=""
loading="lazy"></iframe>
</div>

Fixed Parent height

If your parent height is fixed then you can set the iframe to height="100%" which will expand the iframe height to match with your parent

.parent{
    height: 500px;
}

<div class="parent">
                                                   ↓
                                                 ------
    <iframe src="SOURCE_HERE" width="600" height="100%" style="border:0" allowfullscreen="" loading="lazy"></iframe>
</div>

No access to the iframe element

If you do not have control of your iframe element then you can set your parent height to match with the iframe height.

.parent{
    height: 450px;
}

<div class="parent">
                                                   ↓
                                                 -----
    <iframe src="SOURCE_HERE" width="600" height="450" style="border:0;display:block" allowfullscreen="" loading="lazy"></iframe>
</div>


问:
How to check if annotation is present without complex reflection field?
I have the following classes :

```<code>@Getter
@Setter
public class MyClassA extends MyClassB{
    private String name;
    private String firstName;
}

@Getter
@Setter
public class MyClassB {
   @MyCustomAnnotation
   private String age;
}

// MyCustomAnnotation class
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface MyCustomAnnotation{

}
</code>```

Then I can easily retrieve the property value by using org.apache.commons.beanutils.PropertyUtils for example.

```<code>MyClassA bean = new MyClassA("foo", "bar", 25);
String value = PropertyUtils.getProperty(bean, "age");
System.out.println(value);
</code>```

My question is, Is there any efficient way (like when retrieving the value above) to check if @MyCustomAnnotation is present on a field or its getter, and no matter if the field is on the current class or the sub-class, without using complex reflection ?
I've done some research on org.springframework.util.Reflectionutils, org.springframework.beans.BeanUtils and org.springframework.bean.BeanWrapper but they seems to not have any solution on my problem.

Note : To avoid confusion, I know that it is possible using reflection. Question is like PropertyUtils/Beanwrapper for retrieving value, is there library to get the annotation. I just don't want to have org.apache.commons.beanutils.PropertyUtils library to get the value and have some java reflection to get the annotation.

Thanks for your help and sorry for my english, it's not my mother language

答:
Your solution should look something like this:

UPDATE:

I created a utility class where you pass the target object, and the rest of the parameters from the previous example. The only differences are that

You have to set fields (and methods) accessible if they are not public.

If the declared field is not in the target's class, then you got to check the parent. Potentially, you might have to make this function recursive to go all the way up the hierarch tree, but for this simple example of one parent class, it works fine.

The parent class fields should not be private. They should be at least protected because private fields are not accessible by the child class.

With that, given the following classes with annotated field and with this custom annotation...

```<code>public class MyClassB {
    @MyCustomAnnotation
    protected String age;
}

public class MyClassA extends MyClassB {
    private String name;
    private String firstName;
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface MyCustomAnnotation{

}
</code>```
```<code>public class AnnotationCheck {
    public static boolean isFieldAnnotationPresent(Object target, Class annotation, String name) throws SecurityException, NoSuchFieldException {
        Field field = null;
        boolean isPresent = false;
        try {
            field =  target.getClass().getDeclaredField(name);
            field.setAccessible(true);
        } catch (NoSuchFieldException nsfe) {
            Class parent = target.getClass().getSuperclass();
            if(parent == null) {
                throw nsfe;
            } else {
                field = parent.getDeclaredField(name);
                field.setAccessible(true);
            }
        }
        return field.isAnnotationPresent(annotation);
    }
}
</code>```

If I run this test:

```<code>public class TestAnnotation {
    public static void main(String[] args) throws NoSuchFieldException {
        MyClassA target = new MyClassA();
        System.out.println(AnnotationCheck.isFieldAnnotationPresent(target, MyCustomAnnotation.class, "age"));
        System.out.println(AnnotationCheck.isFieldAnnotationPresent(target, MyCustomAnnotation.class, "firstName"));
    }
}
</code>```

I get the following output:

```<code>true
false
</code>```

Body:
I have the following classes :

@Getter
@Setter
public class MyClassA extends MyClassB{
    private String name;
    private String firstName;
}

@Getter
@Setter
public class MyClassB {
   @MyCustomAnnotation
   private String age;
}

// MyCustomAnnotation class
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface MyCustomAnnotation{

}

Then I can easily retrieve the property value by using org.apache.commons.beanutils.PropertyUtils for example.

MyClassA bean = new MyClassA("foo", "bar", 25);
String value = PropertyUtils.getProperty(bean, "age");
System.out.println(value);

My question is, Is there any efficient way (like when retrieving the value above) to check if @MyCustomAnnotation is present on a field or its getter, and no matter if the field is on the current class or the sub-class, without using complex reflection ?
I've done some research on org.springframework.util.Reflectionutils, org.springframework.beans.BeanUtils and org.springframework.bean.BeanWrapper but they seems to not have any solution on my problem.

Note : To avoid confusion, I know that it is possible using reflection. Question is like PropertyUtils/Beanwrapper for retrieving value, is there library to get the annotation. I just don't want to have org.apache.commons.beanutils.PropertyUtils library to get the value and have some java reflection to get the annotation.

Thanks for your help and sorry for my english, it's not my mother language

Body:
Your solution should look something like this:

UPDATE:

I created a utility class where you pass the target object, and the rest of the parameters from the previous example. The only differences are that

You have to set fields (and methods) accessible if they are not public.

If the declared field is not in the target's class, then you got to check the parent. Potentially, you might have to make this function recursive to go all the way up the hierarch tree, but for this simple example of one parent class, it works fine.

The parent class fields should not be private. They should be at least protected because private fields are not accessible by the child class.

With that, given the following classes with annotated field and with this custom annotation...

public class MyClassB {
    @MyCustomAnnotation
    protected String age;
}

public class MyClassA extends MyClassB {
    private String name;
    private String firstName;
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface MyCustomAnnotation{

}

public class AnnotationCheck {
    public static boolean isFieldAnnotationPresent(Object target, Class annotation, String name) throws SecurityException, NoSuchFieldException {
        Field field = null;
        boolean isPresent = false;
        try {
            field =  target.getClass().getDeclaredField(name);
            field.setAccessible(true);
        } catch (NoSuchFieldException nsfe) {
            Class parent = target.getClass().getSuperclass();
            if(parent == null) {
                throw nsfe;
            } else {
                field = parent.getDeclaredField(name);
                field.setAccessible(true);
            }
        }
        return field.isAnnotationPresent(annotation);
    }
}

If I run this test:

public class TestAnnotation {
    public static void main(String[] args) throws NoSuchFieldException {
        MyClassA target = new MyClassA();
        System.out.println(AnnotationCheck.isFieldAnnotationPresent(target, MyCustomAnnotation.class, "age"));
        System.out.println(AnnotationCheck.isFieldAnnotationPresent(target, MyCustomAnnotation.class, "firstName"));
    }
}

I get the following output:

true
false


问:
How to append data to a sub-dictionary in a JSON file?
I want to add some Python dictionary into a JSON file and append into a sub-dictionary
This is just a template of what my JSON file looks like:

```<code>{
    "playerInfo": {
    }
}
</code>```

Let's say I want to access the key "playerInfo" and append data, specifically another dictionary, into this JSON file. This would be a dictionary that I would append to "playerInfo"

```<code>"player1":{
    "name":"player1",
    "id":1
}
</code>```

The end result that I am looking for would be to have this

```<code>{
    "playerInfo":{
        "player1":{
            "name":"player1",
            "id":1
        }
    }
}
</code>```

And for any future data, I would append it after the "player1" dictionary. How would I be able to accomplish this?

答:
If you started with this:

x = {
    "playerInfo": {
    }
}
```
<p>And wanted to add a player, do this:</p>
<pre class="lang-py prettyprint-override"><code>x["playerInfo"]["player1"] = {
    # Enter player data here
}
</code>```

or

x["playerInfo"]["player1"] = {}

x["playerInfo"]["player1"]["name"] = "player1"
x["playerInfo"]["player1"]["id"] = i
```
<hr />
<p>To append more keys:</p>
<pre class="lang-py prettyprint-override"><code>x["playerInfo"]["player1"]["<new key>"] = "<new value>"
</code>```

And to add a new player

x["playerInfo"]["<new player>"]["<new key>"] = "<new value>"
```

This code only highlights the fact that a new player is created by adding a <new player> key to the playerInfo dictionary.

Body:
I want to add some Python dictionary into a JSON file and append into a sub-dictionary
This is just a template of what my JSON file looks like:

{
    "playerInfo": {
    }
}

Let's say I want to access the key "playerInfo" and append data, specifically another dictionary, into this JSON file. This would be a dictionary that I would append to "playerInfo"

"player1":{
    "name":"player1",
    "id":1
}

The end result that I am looking for would be to have this

{
    "playerInfo":{
        "player1":{
            "name":"player1",
            "id":1
        }
    }
}

And for any future data, I would append it after the "player1" dictionary. How would I be able to accomplish this?

Body:
If you started with this:

x = {
    "playerInfo": {
    }
}

And wanted to add a player, do this:

x["playerInfo"]["player1"] = {
    # Enter player data here
}

or

x["playerInfo"]["player1"] = {}

x["playerInfo"]["player1"]["name"] = "player1"
x["playerInfo"]["player1"]["id"] = i

To append more keys:

x["playerInfo"]["player1"]["<new key>"] = "<new value>"

And to add a new player

x["playerInfo"]["<new player>"]["<new key>"] = "<new value>"

This code only highlights the fact that a new player is created by adding a <new player> key to the playerInfo dictionary.