问:
how to efficiently handle multiple dictionaries to match specific criteria for a patient requirements without going through all possibilities?
Disclaimer: Bear with me for four and half minutes. what might look ridiculous, it's because I am a doctor of medicine not a programmer, though I am kinda addicted since first learning basic in 1996.

So, I am trying to design an application to help me (and my fellows) to quickly be able to design a meal plan for a patient.
the science in this is pretty straight forward:
1 - Age, Weight, Height, Gender, Fat percentage -> BMI, BMR -> Estimated Energy Requirement (EER)
2 - EER -> Calories (Carbs, Protein, Fat) -> Grams requirements (Carbs, Protein, Fat) <<== that's the goal.
so far, nothing fancy. the problem arise from the last point. there's no easy or scientific way to translate patients grams requirements into a meal. there are ton's of tables that's different on country level, and hospital levels with lots of variations.
That's because there are usually 7 classes of food:

```<code>[legume, milk, vegetables, fruits, starch, meat, oil]
</code>```

and each class of food there's specific serving size. and each serving unit represent specific values for each component in (Carbs, Protein, Fat) (which I need to match it with the patient's needs).

for example:

```<code>1 milk serving ={"carbs":15, "ptn":8, "fat":3}

</code>```
```<code>1 fruit serving ={"carbs":15, "ptn":0, "fat":0}
</code>```

so using only milk and fruits, if the patient grams requirement is (Carbs=31, Ptn=10, Fat=4), I'll try to create a meal with one milk serving + one fruit serving = (carbs=30, ptn=8, fat=3) to closely matches the patients needs (with 10% margin of error).

so that's the problem.
I tried to approach it systematically but it needed like 10e7 trial - i think -.
I tried to brutforce the values randomly using some logic, and that gave some results with 40% success and 60% infinite loop.

I have:
1 list of dictionaries 'Food' =  [legume, milk, vegetables, fruits, starch, meat, oil]
each dictionary contains some values for {"carbs":X, "ptn":Y, "fat":Z}
then I have patient needs dictionary: {"carbs":Xp, "ptn":Yp, "fat":Zp}
then I created an aggregate dictionary to add a random dictionary from the food list.
then check the total value of the aggregate dictionary.if it's overshooting the patient's needs, i'll remove it from the aggregate dictionary. if it's still below the patient's needs, then I add it.
in the end, it returns the aggregate dictionary (to compare it with patients needs) and how many food items have been used from each food class.

but that's not it. there is another problem with the random approach that the computer cheat its way to match the aggregate dict with the patient's requirement. so instead of creating a balanced diet, it would suggest creating a meal with 20 servings of oil, and 15 of starch. Theoretically it matches the patient requirements. but not practical.

I tried to add many logic to force the function to use the unused fooditem, and at least to use it once. also limiting certain items to maximum number of servings. I also tried to create some bias using np.random.choice ... didn't work.
here is a sample function with sample data:

Data:

```<code>ref_dict = {"carbs":274,"ptn":82,"fat":85} #patient's needs
aggre_dict = {"carbs":0,"ptn":0,"fat":0} #basket

legum ={"carbs":15, "ptn":7, "fat":0}
milk ={"carbs":15, "ptn":8, "fat":3}
veg ={"carbs":5, "ptn":2, "fat":0}
fruits ={"carbs":15, "ptn":0, "fat":0}
starch ={"carbs":15, "ptn":3, "fat":1}
meat ={"carbs":0, "ptn":7, "fat":3}
oil ={"carbs":0, "ptn":0, "fat":5}
</code>```

Function:

```<code>def update_aggregate_dict(ref_dict, aggre_dict, legum, milk, veg, fruits, starch, meat, oil, margin):
    dict_list = [legum, milk, veg, fruits, starch, meat, oil]
    dict_count = {'legum': 0, 'milk': 0, 'veg': 0, 'fruits': 0, 'starch': 0, 'meat': 0, 'oil': 0}
    counter = 0
    chosen_dict_A = random.choice(dict_list, size=1000)

    sm_list=[]
    while True:
        # Choose a random dictionary from the list
        while True:
            chosen_dict = choice(chosen_dict_A)
            dict_name = [k for k, v in locals().items() if v is chosen_dict][0]

            if dict_count[dict_name]==0: #make sure to use every food class at least once
                sm_list.append(dict_name)
                break
            elif len(set(sm_list))==7: #make sure to track the use of all 7 classes
                break

        if (dict_name == "oil" and dict_count[dict_name] < 10) \
                or (dict_name == "veg" and dict_count[dict_name] < 7)\
                or (dict_name == "fruits" and dict_count[dict_name] < 7)  \
                or (dict_name == "starch" and dict_count[dict_name] < 15) \
                or (dict_name == "milk" and dict_count[dict_name] < 4)\
                or (dict_name == "legum" and dict_count[dict_name] < 7)\
                or (dict_name == "meat" and dict_count[dict_name] < 11): #make sure that each food class doesn't exceed certain limit
            if any(aggre_dict[key] > ref_dict[key] for key in ref_dict):
                if dict_count[dict_name] > 0: #overshooting
                    dict_count[dict_name] -= 1
                    for key in chosen_dict:
                        aggre_dict[key] -= chosen_dict[key]
            else: #undershooting
                dict_count[dict_name] += 1
                for key in chosen_dict:
                    aggre_dict[key] += chosen_dict[key]

        # Check if the values in the aggregate dictionary are within the margin
        if all(abs(aggre_dict[key] - ref_dict[key]) <= margin for key in ref_dict):
            within_margin = True
        else:
            within_margin = False

        # If the values in the aggregate dictionary are within the margin, Exit
        if within_margin:
            return aggre_dict, dict_count

        # handle the infinite loops
        counter += 1
        if counter > 1000000:
            print("not found: breaking!")
            break

    return aggre_dict, dict_count
</code>```

sample return:

```<code>{'legum': 0, 'milk': 4, 'veg': 7, 'fruits': 7, 'starch': 5, 'meat': 3, 'oil': 10}
{'carbs': 275, 'ptn': 82, 'fat': 76}
</code>```

this results means that the patient needs to drink 50ml of oil, and 1 liter of milk [besides the others], which is unrealistic.

the question is: How to handle this more efficiently, and create more balanced results (or skewed based on my needs) without going through 10e7 probability or going randomly ?

thank you.

Body:
Disclaimer: Bear with me for four and half minutes. what might look ridiculous, it's because I am a doctor of medicine not a programmer, though I am kinda addicted since first learning basic in 1996.

So, I am trying to design an application to help me (and my fellows) to quickly be able to design a meal plan for a patient.
the science in this is pretty straight forward:
1 - Age, Weight, Height, Gender, Fat percentage -> BMI, BMR -> Estimated Energy Requirement (EER)
2 - EER -> Calories (Carbs, Protein, Fat) -> Grams requirements (Carbs, Protein, Fat) <<== that's the goal.
so far, nothing fancy. the problem arise from the last point. there's no easy or scientific way to translate patients grams requirements into a meal. there are ton's of tables that's different on country level, and hospital levels with lots of variations.
That's because there are usually 7 classes of food:

[legume, milk, vegetables, fruits, starch, meat, oil]

and each class of food there's specific serving size. and each serving unit represent specific values for each component in (Carbs, Protein, Fat) (which I need to match it with the patient's needs).

for example:

1 milk serving ={"carbs":15, "ptn":8, "fat":3}

1 fruit serving ={"carbs":15, "ptn":0, "fat":0}

so using only milk and fruits, if the patient grams requirement is (Carbs=31, Ptn=10, Fat=4), I'll try to create a meal with one milk serving + one fruit serving = (carbs=30, ptn=8, fat=3) to closely matches the patients needs (with 10% margin of error).

so that's the problem.
I tried to approach it systematically but it needed like 10e7 trial - i think -.
I tried to brutforce the values randomly using some logic, and that gave some results with 40% success and 60% infinite loop.

I have:
1 list of dictionaries 'Food' =  [legume, milk, vegetables, fruits, starch, meat, oil]
each dictionary contains some values for {"carbs":X, "ptn":Y, "fat":Z}
then I have patient needs dictionary: {"carbs":Xp, "ptn":Yp, "fat":Zp}
then I created an aggregate dictionary to add a random dictionary from the food list.
then check the total value of the aggregate dictionary.if it's overshooting the patient's needs, i'll remove it from the aggregate dictionary. if it's still below the patient's needs, then I add it.
in the end, it returns the aggregate dictionary (to compare it with patients needs) and how many food items have been used from each food class.

but that's not it. there is another problem with the random approach that the computer cheat its way to match the aggregate dict with the patient's requirement. so instead of creating a balanced diet, it would suggest creating a meal with 20 servings of oil, and 15 of starch. Theoretically it matches the patient requirements. but not practical.

I tried to add many logic to force the function to use the unused fooditem, and at least to use it once. also limiting certain items to maximum number of servings. I also tried to create some bias using np.random.choice ... didn't work.
here is a sample function with sample data:

Data:

ref_dict = {"carbs":274,"ptn":82,"fat":85} #patient's needs
aggre_dict = {"carbs":0,"ptn":0,"fat":0} #basket

legum ={"carbs":15, "ptn":7, "fat":0}
milk ={"carbs":15, "ptn":8, "fat":3}
veg ={"carbs":5, "ptn":2, "fat":0}
fruits ={"carbs":15, "ptn":0, "fat":0}
starch ={"carbs":15, "ptn":3, "fat":1}
meat ={"carbs":0, "ptn":7, "fat":3}
oil ={"carbs":0, "ptn":0, "fat":5}

Function:

def update_aggregate_dict(ref_dict, aggre_dict, legum, milk, veg, fruits, starch, meat, oil, margin):
    dict_list = [legum, milk, veg, fruits, starch, meat, oil]
    dict_count = {'legum': 0, 'milk': 0, 'veg': 0, 'fruits': 0, 'starch': 0, 'meat': 0, 'oil': 0}
    counter = 0
    chosen_dict_A = random.choice(dict_list, size=1000)

    sm_list=[]
    while True:
        # Choose a random dictionary from the list
        while True:
            chosen_dict = choice(chosen_dict_A)
            dict_name = [k for k, v in locals().items() if v is chosen_dict][0]

            if dict_count[dict_name]==0: #make sure to use every food class at least once
                sm_list.append(dict_name)
                break
            elif len(set(sm_list))==7: #make sure to track the use of all 7 classes
                break

        if (dict_name == "oil" and dict_count[dict_name] < 10) \
                or (dict_name == "veg" and dict_count[dict_name] < 7)\
                or (dict_name == "fruits" and dict_count[dict_name] < 7)  \
                or (dict_name == "starch" and dict_count[dict_name] < 15) \
                or (dict_name == "milk" and dict_count[dict_name] < 4)\
                or (dict_name == "legum" and dict_count[dict_name] < 7)\
                or (dict_name == "meat" and dict_count[dict_name] < 11): #make sure that each food class doesn't exceed certain limit
            if any(aggre_dict[key] > ref_dict[key] for key in ref_dict):
                if dict_count[dict_name] > 0: #overshooting
                    dict_count[dict_name] -= 1
                    for key in chosen_dict:
                        aggre_dict[key] -= chosen_dict[key]
            else: #undershooting
                dict_count[dict_name] += 1
                for key in chosen_dict:
                    aggre_dict[key] += chosen_dict[key]

        # Check if the values in the aggregate dictionary are within the margin
        if all(abs(aggre_dict[key] - ref_dict[key]) <= margin for key in ref_dict):
            within_margin = True
        else:
            within_margin = False

        # If the values in the aggregate dictionary are within the margin, Exit
        if within_margin:
            return aggre_dict, dict_count

        # handle the infinite loops
        counter += 1
        if counter > 1000000:
            print("not found: breaking!")
            break

    return aggre_dict, dict_count

sample return:

{'legum': 0, 'milk': 4, 'veg': 7, 'fruits': 7, 'starch': 5, 'meat': 3, 'oil': 10}
{'carbs': 275, 'ptn': 82, 'fat': 76}

this results means that the patient needs to drink 50ml of oil, and 1 liter of milk [besides the others], which is unrealistic.

the question is: How to handle this more efficiently, and create more balanced results (or skewed based on my needs) without going through 10e7 probability or going randomly ?

thank you.


来源: stackexchange

问:
How to fix different context between backgroundjs (chrome extension) and react app
I have chrome extension with next manifest:

{
  "name": "Page Redder",
  "version": "0.1",
  "description": "-",
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "scripting",
    "activeTab",
    "system.display"
  ],
  "host_permissions": [
    "<all_urls>"
  ],
  "manifest_version": 3,
  "action": {}
}
```
<p>I have background js:</p>
<pre class="lang-js prettyprint-override"><code>console.log("BACKGROUND LISTEN");

let myGlobalVariable = 'Hello from the background script';

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    console.log("changeInfo: ", changeInfo, "tabid:", tabId, "tab:", tab);

    if (changeInfo.status === 'complete' && tab.url && tab.url.includes('https://www.google.com/')) {
        console.log("tab.url = ", tab.url);
        if (tab.url.includes("google.com/")) {
            chrome.scripting.executeScript({
                target: {tabId: tab.id},
                files: ['contentScript.js']
            });

        }

    }
});

console.log(chrome.action)
chrome.action.onClicked.addListener(function (tab) {
    console.log("clicked event catched", chrome.system);
    chrome.system.display.getInfo(function(info) {
        var screenWidth = info[0].bounds.width;
        var screenHeight = info[0].bounds.height;
        var popupWidth = 500;
        var popupHeight = 300;

        chrome.windows.create({
            url: 'index.html',
            type: 'popup',
            width: popupWidth,
            height: popupHeight,
            left: screenWidth - popupWidth,  // position the window on the right side of the screen
            top: 0
        }, function(window) {
            // adjust the size of the browser window to make room for the popup
            chrome.windows.update(window.id, {
                width: screenWidth - popupWidth,
                height: screenHeight
            });
        });
    });
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('[background.js]. Message received', message, sender, sendResponse);
});

</code>```

I have tried to attach to my chrome extension reactjs app, I choose simple way to implement:

I added chrome extension files in react app and its works but as I understand, it works in different context and its main concern, because I can't send message from reactjs app to my background script:

my app.js for reactjs app:

import logo from './logo.svg';
import './App.css';

const chrome = window.chrome;

function messageFromExtension(response) {
  console.log(response);
}

function App() {

  //const backgroundPage = chrome.extension.getBackgroundPage();
  //console.log("background global var", backgroundPage.myGlobalVariable);
  console.log("chrome variable", chrome);

  chrome.tabs && chrome.tabs.query({
    active: true,
    currentWindow: true
  }, (tabs) => {
    console.log("chrome callback", tabs);
    chrome.tabs.sendMessage(tabs[0].id, { message: 'Hello from the extension' }, messageFromExtension);

  });

  return (

          Edit src/App.js and save to reload.

          Learn React

  );
}

export default App;

```

as I expected I when I clicked on extension button and open my popup, it will send message to backgroundjs but it doesn't work:

after undrstand that my application working in different context I tried to add common variable (myGlobalVariable) but it doest work too in reactjs:

my main goal now is getting message from reactjs in my backgroundjs, how can I do it?

ContentLicense: CC BY-SA 4.0

Body:
I have chrome extension with next manifest:

{
  "name": "Page Redder",
  "version": "0.1",
  "description": "-",
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "scripting",
    "activeTab",
    "system.display"
  ],
  "host_permissions": [
    "<all_urls>"
  ],
  "manifest_version": 3,
  "action": {}
}

I have background js:

console.log("BACKGROUND LISTEN");

let myGlobalVariable = 'Hello from the background script';

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    console.log("changeInfo: ", changeInfo, "tabid:", tabId, "tab:", tab);

    if (changeInfo.status === 'complete' && tab.url && tab.url.includes('https://www.google.com/')) {
        console.log("tab.url = ", tab.url);
        if (tab.url.includes("google.com/")) {
            chrome.scripting.executeScript({
                target: {tabId: tab.id},
                files: ['contentScript.js']
            });

        }

    }
});

console.log(chrome.action)
chrome.action.onClicked.addListener(function (tab) {
    console.log("clicked event catched", chrome.system);
    chrome.system.display.getInfo(function(info) {
        var screenWidth = info[0].bounds.width;
        var screenHeight = info[0].bounds.height;
        var popupWidth = 500;
        var popupHeight = 300;

        chrome.windows.create({
            url: 'index.html',
            type: 'popup',
            width: popupWidth,
            height: popupHeight,
            left: screenWidth - popupWidth,  // position the window on the right side of the screen
            top: 0
        }, function(window) {
            // adjust the size of the browser window to make room for the popup
            chrome.windows.update(window.id, {
                width: screenWidth - popupWidth,
                height: screenHeight
            });
        });
    });
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('[background.js]. Message received', message, sender, sendResponse);
});

I have tried to attach to my chrome extension reactjs app, I choose simple way to implement:

I added chrome extension files in react app and its works but as I understand, it works in different context and its main concern, because I can't send message from reactjs app to my background script:

my app.js for reactjs app:

import logo from './logo.svg';
import './App.css';

const chrome = window.chrome;

function messageFromExtension(response) {
  console.log(response);
}

function App() {

  //const backgroundPage = chrome.extension.getBackgroundPage();
  //console.log("background global var", backgroundPage.myGlobalVariable);
  console.log("chrome variable", chrome);

  chrome.tabs && chrome.tabs.query({
    active: true,
    currentWindow: true
  }, (tabs) => {
    console.log("chrome callback", tabs);
    chrome.tabs.sendMessage(tabs[0].id, { message: 'Hello from the extension' }, messageFromExtension);

  });

  return (

          Edit src/App.js and save to reload.

          Learn React

  );
}

export default App;

as I expected I when I clicked on extension button and open my popup, it will send message to backgroundjs but it doesn't work:

after undrstand that my application working in different context I tried to add common variable (myGlobalVariable) but it doest work too in reactjs:

my main goal now is getting message from reactjs in my backgroundjs, how can I do it?


问:
Gym CarRacnig-v2 adding obstacles on the track
I want to add obstacles on the track of the CarRacing-v2 environment found in the python gym library (version 0.26.1) https://www.gymlibrary.dev/environments/box2d/car_racing/#

The only clue that I found was this repo https://github.com/NotAnyMike/gym which, however, is quite confusing because there are multiple modifications at once and the gym version used is 0.10.9 which is like 4 years old.

Does anyone have an idea how to add any type of obstacle on the tracks? Thank you


问:
How to use Reflection when reading properties file
I am trying to use a properties file, named logging.properties, to instantiate an Handler while using java.util.logging libraries. In the logging.properties file i have the line "handlers=java.util.logging.FileHandler". So my code is like this:

```<code>Logger logger = Logger.getLogger(ErrorLogger.class.getName());
Properties prop = new Properties();
prop.load(new FileInputStream("C:\\Users\\user\\...\\logging.properties"));
String handlerClass = prop.getProperty("handlers");
logger.addHandler((Handler)Class.forName(handlerClass).getDeclaredConstructor().newInstance());
</code>```

FileHandler has a no-parameters constructor, but what happens if i change the properties file with some other handlers which classes does not have a no-parameters constructors? To me it seems that the reflection becomes useless. So i changed the code like this:

```<code>HashMap<String, Callable<Handler>> hm = new HashMap<>();
String firstClass = "FileHandler";
Callable<Handler> firstCall = () -> { return new FileHandler("C:\\Users\\sgate\\OneDrive\\Programmazione\\PetriNetsStudio\\log.log", true);
};
hm.put(firstClass, firstCall);
Logger logger = Logger.getLogger(ErrorLogger.class.getName());
Properties prop = new Properties();
prop.load(new FileInputStream("C:\\Users\\user\\...\\logging.properties"));
String handlerClass = prop.getProperty("handlers");
Handler handler = hm.get(handlerClass).call();
logger.addHandler(handler);
</code>```

with the properties file containing the line "handlers=FileHandler". So if the Handler change in the properties files i need to add to the HashMap a new String and a new Callable. Is this a good way to read properties from a properties file that can have the "handlers" line changed with other classes with parameters and no-parameters constructors? I do not like my code.

Body:
I am trying to use a properties file, named logging.properties, to instantiate an Handler while using java.util.logging libraries. In the logging.properties file i have the line "handlers=java.util.logging.FileHandler". So my code is like this:

Logger logger = Logger.getLogger(ErrorLogger.class.getName());
Properties prop = new Properties();
prop.load(new FileInputStream("C:\\Users\\user\\...\\logging.properties"));
String handlerClass = prop.getProperty("handlers");
logger.addHandler((Handler)Class.forName(handlerClass).getDeclaredConstructor().newInstance());

FileHandler has a no-parameters constructor, but what happens if i change the properties file with some other handlers which classes does not have a no-parameters constructors? To me it seems that the reflection becomes useless. So i changed the code like this:

HashMap<String, Callable<Handler>> hm = new HashMap<>();
String firstClass = "FileHandler";
Callable<Handler> firstCall = () -> { return new FileHandler("C:\\Users\\sgate\\OneDrive\\Programmazione\\PetriNetsStudio\\log.log", true);
};
hm.put(firstClass, firstCall);
Logger logger = Logger.getLogger(ErrorLogger.class.getName());
Properties prop = new Properties();
prop.load(new FileInputStream("C:\\Users\\user\\...\\logging.properties"));
String handlerClass = prop.getProperty("handlers");
Handler handler = hm.get(handlerClass).call();
logger.addHandler(handler);

with the properties file containing the line "handlers=FileHandler". So if the Handler change in the properties files i need to add to the HashMap a new String and a new Callable. Is this a good way to read properties from a properties file that can have the "handlers" line changed with other classes with parameters and no-parameters constructors? I do not like my code.


问:
Short dropouts while playing audio from microphone
I'm actually trying to make my own VoiceChat for game. So I decided to try first to get audio data from microphone and play it directly to the speakers.
I've done it in Java and C# but in both languages, in both after starting the record there is a dropout after about 0.5 seconds for about 0.25 seconds, after that dropout the audio works normally.

I'm using this code in C#, have I done something wrong?

```<code>using System;
using NAudio.Wave;

namespace VoiceChat
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            var mic = false;

            var recorder = new WaveInEvent
            {
                WaveFormat = new WaveFormat(96000, 2),
                BufferMilliseconds = 10,
                NumberOfBuffers = 10
            };
            var sound = new BufferedWaveProvider(recorder.WaveFormat);
            var playback = new WaveOutEvent();

            recorder.StartRecording();
            playback.Init(sound);
            playback.Play();

            recorder.DataAvailable += (sender, eventArgs) =>
            {
                if (mic)
                {
                    sound.AddSamples(eventArgs.Buffer, 0, eventArgs.BytesRecorded);
                }
            };

            while (true)
            {
                var key = Console.ReadKey();
                if (key.Key.Equals(ConsoleKey.A))
                {
                    mic = !mic;
                }
            }
        }
    }
}
</code>```

(I've added a switch to it and everytime I turn on the audio with this switch the same as described happens)

Thanks!

Body:
I'm actually trying to make my own VoiceChat for game. So I decided to try first to get audio data from microphone and play it directly to the speakers.
I've done it in Java and C# but in both languages, in both after starting the record there is a dropout after about 0.5 seconds for about 0.25 seconds, after that dropout the audio works normally.

I'm using this code in C#, have I done something wrong?

using System;
using NAudio.Wave;

namespace VoiceChat
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            var mic = false;

            var recorder = new WaveInEvent
            {
                WaveFormat = new WaveFormat(96000, 2),
                BufferMilliseconds = 10,
                NumberOfBuffers = 10
            };
            var sound = new BufferedWaveProvider(recorder.WaveFormat);
            var playback = new WaveOutEvent();

            recorder.StartRecording();
            playback.Init(sound);
            playback.Play();

            recorder.DataAvailable += (sender, eventArgs) =>
            {
                if (mic)
                {
                    sound.AddSamples(eventArgs.Buffer, 0, eventArgs.BytesRecorded);
                }
            };

            while (true)
            {
                var key = Console.ReadKey();
                if (key.Key.Equals(ConsoleKey.A))
                {
                    mic = !mic;
                }
            }
        }
    }
}

(I've added a switch to it and everytime I turn on the audio with this switch the same as described happens)

Thanks!


问:
What is a good way to mount instance storage or attached EBS volumes when instance type and ami is not known in advance
In AWS, I am looking for a robust and elegant way to have my cloud-init startup scripts find, prepare and mount any instance storage and/ or attached EBS volumes that might exist. I might like a "if instance storage exists use that; otherwise fall back to EBS" type logic.

I know about getting block device metadata from the instance metadata service, and I found aws ec2 describe-images too, but I am struggling to connect the dots here.

I have cloud-init bash that does a long if-else ladder for known instance types. I can even parse lsblk output in a crude way. Neither is satisfying, it is ugly and brittle.

So imagine I want thing I can run locally, prepare-instance, that takes instance type and AMI as parameters, and will either use instance storage if the type has it, or else attach 100GB EBS and use that (I can live with provisioning the EBS and not utilising it, i.e. have all the logic live in cloud-init bash).

```<code>$ prepare-instance m3.medium ami-0cc814d99c59f3789    # here I'd get the 100GB EBS
$ prepare-instance i3.2xlarge ami-0516faeafaf906b64   # here I'd take advantage of the 1900GB NVMe SSD
</code>```

There must be a Good Way™ to do this. Please help! :)

Body:
In AWS, I am looking for a robust and elegant way to have my cloud-init startup scripts find, prepare and mount any instance storage and/ or attached EBS volumes that might exist. I might like a "if instance storage exists use that; otherwise fall back to EBS" type logic.

I know about getting block device metadata from the instance metadata service, and I found aws ec2 describe-images too, but I am struggling to connect the dots here.

I have cloud-init bash that does a long if-else ladder for known instance types. I can even parse lsblk output in a crude way. Neither is satisfying, it is ugly and brittle.

So imagine I want thing I can run locally, prepare-instance, that takes instance type and AMI as parameters, and will either use instance storage if the type has it, or else attach 100GB EBS and use that (I can live with provisioning the EBS and not utilising it, i.e. have all the logic live in cloud-init bash).

$ prepare-instance m3.medium ami-0cc814d99c59f3789    # here I'd get the 100GB EBS
$ prepare-instance i3.2xlarge ami-0516faeafaf906b64   # here I'd take advantage of the 1900GB NVMe SSD

There must be a Good Way™ to do this. Please help! :)


问:
Quicksight how to configure a new incremental refresh but not overwrite existing data
I have a very long query that times out when running a full refresh for a year. So I want to use incremental refresh to reduce the running time.

My idea is that:

Step 1, upload first month data.
Step 2, using incremental refresh for the following months that append to the first month

expected result: a 12 month data.

But the problem is that every time I edit incremental refresh, it immediately runs a full refresh for that month which over writes step 1 or previous month. Thus, the result table will only have the last month's data even if I repeated 11 times.


问:
RBM is incapable of overfitting a single batch
I am currently working on my master's thesis on the use of deep learning models in recommender systems. I am using the ml-20m dataset, but for testing and debugging purposes, I am scaling down to ml-100k. I have implemented the RBM almost from scratch using pytorch.

The architecture of the network is as follows:

The visible layer is an N x 10 matrix of one-hot encoded movie ratings, where N is the number of movies in the dataset. Each user's ratings are one training example and there are 10 possible ratings for every movie.

The hidden layer is consisted of M binary hidden units.

The activation function of the hidden units is a sigmoid, while the activation of the visible units is a 10-way softmax.

The loss function I am using is the reconstruction error, in my case RMSE.

The problem is that my RBM is incapable of overfitting a single batch of 10 user's ratings. The larger the batch size, the higher the value of the loss function at which it plateaus. I have no problem overfitting a single training example.

Any ideas as to why this might happen. I will supply the essential functions used in the training process. Thanks in advance!

Here are the forward pass and backward pass implementations:

```<code>def forward_pass(
        self,
        v: torch.Tensor,
        activation=torch.sigmoid,
        sampler=torch.bernoulli,
    ) -> Tuple[torch.Tensor, torch.Tensor]:

        a = torch.mm(v.flatten(-2), self.w.flatten(end_dim=1))
        a = self.h + a
        ph = activation(a)
        return ph, sampler(ph)

def backward_pass(
        self,
        h: torch.Tensor,
        activation=ratings_softmax,
    ) -> torch.Tensor:

        a = torch.matmul(self.w, h.t())
        pv = self.v.unsqueeze(2) + a
        pv = activation(pv.permute(2, 0, 1))
        return pv
</code>```

The implementation of the Gibbs sampler:

```<code> def gibbs_sample(
        self, input: torch.Tensor, t: int = 1
    ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:

        ph0, h0 = self.forward_pass(input)
        hk = phk = h0

        # do Gibbs sampling for t steps
        for i in range(t):
            vk = self.backward_pass(hk)
            phk, hk = self.forward_pass(vk)

        vk[input.sum(dim=2) == 0] = input[input.sum(dim=2) == 0]

        return input, ph0, vk, phk
</code>```

And finaly the apply_gradient method that equates to one training step:

```<code>
def apply_gradient(
        self, minibatch: torch.Tensor, t: int = 1, decay=lambda x: x
    ) -> Tuple[float, float]

        v0 = minibatch

        v0, ph0, vt, pht = self.gibbs_sample(v0, t)

        hb_delta = (ph0 - pht).sum(dim=0) / len(minibatch)
        vb_delta = (v0 - vt).sum(dim=0) / len(minibatch)

        w_delta = torch.matmul(vb_delta.unsqueeze(2), hb_delta.unsqueeze(0))

        # apply learning rate decay
        self.alpha = decay(self.learning_rate)

        # update the parameters of the model
        self.v += vb_delta * self.alpha
        self.h += hb_delta * self.alpha
        self.w += w_delta * self.alpha

        se, ae, n = self.batch_error(minibatch)
        rmse = math.sqrt(se / n)
        mae = ae / n

        return rmse, mae
</code>```

Body:
I am currently working on my master's thesis on the use of deep learning models in recommender systems. I am using the ml-20m dataset, but for testing and debugging purposes, I am scaling down to ml-100k. I have implemented the RBM almost from scratch using pytorch.

The architecture of the network is as follows:

The visible layer is an N x 10 matrix of one-hot encoded movie ratings, where N is the number of movies in the dataset. Each user's ratings are one training example and there are 10 possible ratings for every movie.

The hidden layer is consisted of M binary hidden units.

The activation function of the hidden units is a sigmoid, while the activation of the visible units is a 10-way softmax.

The loss function I am using is the reconstruction error, in my case RMSE.

The problem is that my RBM is incapable of overfitting a single batch of 10 user's ratings. The larger the batch size, the higher the value of the loss function at which it plateaus. I have no problem overfitting a single training example.

Any ideas as to why this might happen. I will supply the essential functions used in the training process. Thanks in advance!

Here are the forward pass and backward pass implementations:

def forward_pass(
        self,
        v: torch.Tensor,
        activation=torch.sigmoid,
        sampler=torch.bernoulli,
    ) -> Tuple[torch.Tensor, torch.Tensor]:

        a = torch.mm(v.flatten(-2), self.w.flatten(end_dim=1))
        a = self.h + a
        ph = activation(a)
        return ph, sampler(ph)

def backward_pass(
        self,
        h: torch.Tensor,
        activation=ratings_softmax,
    ) -> torch.Tensor:

        a = torch.matmul(self.w, h.t())
        pv = self.v.unsqueeze(2) + a
        pv = activation(pv.permute(2, 0, 1))
        return pv

The implementation of the Gibbs sampler:

 def gibbs_sample(
        self, input: torch.Tensor, t: int = 1
    ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:

        ph0, h0 = self.forward_pass(input)
        hk = phk = h0

        # do Gibbs sampling for t steps
        for i in range(t):
            vk = self.backward_pass(hk)
            phk, hk = self.forward_pass(vk)

        vk[input.sum(dim=2) == 0] = input[input.sum(dim=2) == 0]

        return input, ph0, vk, phk

And finaly the apply_gradient method that equates to one training step:

def apply_gradient(
        self, minibatch: torch.Tensor, t: int = 1, decay=lambda x: x
    ) -> Tuple[float, float]

        v0 = minibatch

        v0, ph0, vt, pht = self.gibbs_sample(v0, t)

        hb_delta = (ph0 - pht).sum(dim=0) / len(minibatch)
        vb_delta = (v0 - vt).sum(dim=0) / len(minibatch)

        w_delta = torch.matmul(vb_delta.unsqueeze(2), hb_delta.unsqueeze(0))

        # apply learning rate decay
        self.alpha = decay(self.learning_rate)

        # update the parameters of the model
        self.v += vb_delta * self.alpha
        self.h += hb_delta * self.alpha
        self.w += w_delta * self.alpha

        se, ae, n = self.batch_error(minibatch)
        rmse = math.sqrt(se / n)
        mae = ae / n

        return rmse, mae


问:
Can I create a custom function in Excel that returns the value of a specific range of cells with a worksheet name as the input?
I am fairly new to VBA coding. What I am hoping to produce is a simple function I can use in any sheet of the workbook as I would a predefined function (like SUM, COUNT, etc), with the purpose being to return the sum of a range of cells in a specified worksheet.

What I have tried is:

Function fn_LastRow(ByVal Sht As Worksheet)
    Dim Sum1 As Long
    Sum1 = Application.WorksheetFunction.Sum(Sht.Range("B1:B10"))
    GetNumeric = Sum1

End Function

```
<p>My first issue is understanding how to be able to input a worksheet name, like "January 2022" as the input of my user defined function. Any tips?</p>
<p>-------- FOLLOW UP TO ORIGINAL --------</p>
<p>As a follow-up, I am now trying to create function that tells me the last row with the sheet name input. Based on google results I know finding last row/column is fairly basic, and there many ways to do it (and lots of do's and don'ts). That said, I am curious at my results and have been unable to find clarity in existing results.</p>
<p>What I now have is:</p>
<pre class="lang-vba prettyprint-override"><code>Function jm_cellvalue(ByVal Sht_name As String)

    Dim Sht As Worksheet
    Dim cell_value As Long
    Dim Adr As String
    Set Sht = Worksheets(Sht_name)
    cell_value = Sht.Cells.SpecialCells(xlLastCell).Row
    Adr = Sht.Cells.SpecialCells(xlLastCell).Address

    jm_cellvalue = cell_value
    MsgBox Adr

End Function
</code>```

The result I get for the variables is:
cell_value = 1
Adr = $1:$1048576

The particular last cell doesn't bother me at the moment, but I can't understand why the cell_value = ...xlLastCell).Row would return a 1 with that address?

----- FURTHER UPDATE -------

Running the same logic as a sub produces the correct result, it's only when run as a function the resulting "last cell" is incorrect, as well as the row incorrectly =1 as well.

Body:
I am fairly new to VBA coding. What I am hoping to produce is a simple function I can use in any sheet of the workbook as I would a predefined function (like SUM, COUNT, etc), with the purpose being to return the sum of a range of cells in a specified worksheet.

What I have tried is:

Function fn_LastRow(ByVal Sht As Worksheet)
    Dim Sum1 As Long
    Sum1 = Application.WorksheetFunction.Sum(Sht.Range("B1:B10"))
    GetNumeric = Sum1

End Function

My first issue is understanding how to be able to input a worksheet name, like "January 2022" as the input of my user defined function. Any tips?

-------- FOLLOW UP TO ORIGINAL --------

As a follow-up, I am now trying to create function that tells me the last row with the sheet name input. Based on google results I know finding last row/column is fairly basic, and there many ways to do it (and lots of do's and don'ts). That said, I am curious at my results and have been unable to find clarity in existing results.

What I now have is:

Function jm_cellvalue(ByVal Sht_name As String)

    Dim Sht As Worksheet
    Dim cell_value As Long
    Dim Adr As String
    Set Sht = Worksheets(Sht_name)
    cell_value = Sht.Cells.SpecialCells(xlLastCell).Row
    Adr = Sht.Cells.SpecialCells(xlLastCell).Address

    jm_cellvalue = cell_value
    MsgBox Adr

End Function

The result I get for the variables is:
cell_value = 1
Adr = $1:$1048576

The particular last cell doesn't bother me at the moment, but I can't understand why the cell_value = ...xlLastCell).Row would return a 1 with that address?

----- FURTHER UPDATE -------

Running the same logic as a sub produces the correct result, it's only when run as a function the resulting "last cell" is incorrect, as well as the row incorrectly =1 as well.


问:
Is there a way to deploy a node.js web app to GitHub pages using GitHub actions?
I have a web app that uses node.js and I want to deploy it to GitHub pages. I know that I will need to use actions, but I have no idea how to go about doing it. I know this was asked previously here, but it doesn't have the most recent answers. Any suggestions would be really appreciated.</p>


问:
Export a complete XUNIT formatted xml from a RobotFramework automated test
i'm working on robotframework-opensearch integration, currently im looking for a good start point from the source...
i've tried different methods to obtain data from the test(like gather them directly during the test,  or from the default output.xml file) but.. i've found that the Xunit.xml export is far more clean and organized (so less cleaning process to care about) BUT, the xunit output only shows the overall result without stats from the single steps

IM on Python 3.9 and RF 5.0.1

i use this command to generate the xunit along the other output files:

robot -d -x --xunit xunit.xml C:\roboresults  \Test\example.robot

it creates a xunit.xml like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<testsuite name="example" tests="1" errors="0" failures="0" skipped="0" time="46.390" timestamp="2023-01-03T18:14:49.327000">
<testcase classname="example" name="Test E-Commerce" time="46.203">
</testcase>
<properties>
<property name="Documentation" value="Test e-commerce -  Browser: Chrome (107) -- Target: example.com"/>
</properties>
</testsuite>

</code>```

but inside the test there are 12 steps
in the Log.html and output.xml all the steps are present
i've even tried to convert with rebot the output.xml to xunit.

Probably the solution is really really simple but sometimes happens that i lost myself inside a glass of water

Body:
i'm working on robotframework-opensearch integration, currently im looking for a good start point from the source...
i've tried different methods to obtain data from the test(like gather them directly during the test,  or from the default output.xml file) but.. i've found that the Xunit.xml export is far more clean and organized (so less cleaning process to care about) BUT, the xunit output only shows the overall result without stats from the single steps

IM on Python 3.9 and RF 5.0.1

i use this command to generate the xunit along the other output files:

robot -d -x --xunit xunit.xml C:\roboresults  \Test\example.robot

it creates a xunit.xml like this

<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="example" tests="1" errors="0" failures="0" skipped="0" time="46.390" timestamp="2023-01-03T18:14:49.327000">
<testcase classname="example" name="Test E-Commerce" time="46.203">
</testcase>
<properties>
<property name="Documentation" value="Test e-commerce -  Browser: Chrome (107) -- Target: example.com"/>
</properties>
</testsuite>

but inside the test there are 12 steps
in the Log.html and output.xml all the steps are present
i've even tried to convert with rebot the output.xml to xunit.

Probably the solution is really really simple but sometimes happens that i lost myself inside a glass of water


问:
How to display my pygame project on a web page?
I am making a a personal portfolio web page where I want to display my projects but I'm not sure how to make the GUI screen appear on a webpage. I built a little puzzle game on pygame for my 1st sem project n I'd like that to appear on my webpage as an interactive surface, but I'm a little lost on how to approach this problem

I'm currently using figma and I have knowledge of MERN stack, so it'll be really helpful of you could guide me on what I'll need to use or implement


问:
style.css and bootstrap.css gets mixed
I have a problem which my style.css gets mixed with the bootstrap.css and the classes get mixed up my website doesent work

i dont know what to try

Title: style.css and bootstrap.css gets mixed


问:
Spring JPA CriteriaQuery groupBy based on only one key in a Composite Primary Key (@EmbeddedId)
I am trying to write a criteriaQuery and group results based on emailId, which is one of the keys of a composite PK, embedded into one of my Entity classes.

The method that returns the specification is as follows :

```<code>public static Specification < User > getSpecification(Integer id) {
    return (root, query, criteriaBuilder) - > {
        var predicates = new ArrayList<Predicate()>;
        predicates.add(criteriaBuilder.equal(root.get("indexId"), id));
        query.groupBy(root.get("details").get("emailId"));
        return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
    };
}
</code>```

The entity class:

```<code>public class User {

    @EmbeddedId private Details details;
    private String name;
    private String status;
}
</code>```
```<code>@Embeddable
public class Details {
    private String emailId;
    private Integer branchId;
}
</code>```

I have skipped some annotations.
I want to group the results in a way where emailId remains unique, even if branchId changes. In essence for data where there are 3 rows of same emailId but different branchId, I should only fetch 1 result.
It seems it throws an error and asks for both components of the composite key to be passed in the query.groupBy statement.
If you could please help me figure out the issue.

Body:
I am trying to write a criteriaQuery and group results based on emailId, which is one of the keys of a composite PK, embedded into one of my Entity classes.

The method that returns the specification is as follows :

public static Specification < User > getSpecification(Integer id) {
    return (root, query, criteriaBuilder) - > {
        var predicates = new ArrayList<Predicate()>;
        predicates.add(criteriaBuilder.equal(root.get("indexId"), id));
        query.groupBy(root.get("details").get("emailId"));
        return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
    };
}

The entity class:

public class User {

    @EmbeddedId private Details details;
    private String name;
    private String status;
}

@Embeddable
public class Details {
    private String emailId;
    private Integer branchId;
}

I have skipped some annotations.
I want to group the results in a way where emailId remains unique, even if branchId changes. In essence for data where there are 3 rows of same emailId but different branchId, I should only fetch 1 result.
It seems it throws an error and asks for both components of the composite key to be passed in the query.groupBy statement.
If you could please help me figure out the issue.


问:
Sending the output of a docker container as a response to a post request in flask
I am trying to build an application which takes a post request and runs a docker container which executes a shell script.I want to send back the output of the shell script as a response to this post request.For example the output of the shell file is "hello world" and It should be sent back as response to the post request.Here is the code

```<code>from flask import Flask, request

app = Flask(__name__)

@app.get('/run')
def test():
    return 'running'

@app.post('/run')
def handle_request():

    lang='python'
    language = request.data
    code=language.decode('utf-8')
    if lang=='python':
        file = open('input.py', 'w')
        file.write(code)

    else:
        file = open('input.cpp', 'w')
        file.write(code)
    output=dockersandbox()
    return output

if __name__ == '__main__':
    app.run(debug=True)

import docker
import os
def dockersandbox():
    image = 'myimage'

    client = docker.from_env()

    container = client.containers.run(
        image=image,
        volumes={os.getcwd(): {'bind': '/container/files', 'mode': 'rw'}},
        remove=True,
        stdout=True
    )
    output = container.decode('utf-8')
    return output
</code>```

Here the expected response for the post request is "helloworld" as the output of the shell file execution is "helloworld" but when I send a post request from postman I get this "Error: connect ECONNREFUSED 127.0.0.1:5000".I have separately ran that dockersandbox function and it works as intended and gives the correct output.I have also tested by sending only a string like "Test" as ouput of the dockersandbox function without implementing any docker container logic and code,in that case it gives the correct response for that post request,this issue happens if I implement this docker client logic in the dockersandbox function.I am using python's docker library to implement the docker logic and run the container.

Body:
I am trying to build an application which takes a post request and runs a docker container which executes a shell script.I want to send back the output of the shell script as a response to this post request.For example the output of the shell file is "hello world" and It should be sent back as response to the post request.Here is the code

from flask import Flask, request

app = Flask(__name__)

@app.get('/run')
def test():
    return 'running'

@app.post('/run')
def handle_request():

    lang='python'
    language = request.data
    code=language.decode('utf-8')
    if lang=='python':
        file = open('input.py', 'w')
        file.write(code)

    else:
        file = open('input.cpp', 'w')
        file.write(code)
    output=dockersandbox()
    return output

if __name__ == '__main__':
    app.run(debug=True)

import docker
import os
def dockersandbox():
    image = 'myimage'

    client = docker.from_env()

    container = client.containers.run(
        image=image,
        volumes={os.getcwd(): {'bind': '/container/files', 'mode': 'rw'}},
        remove=True,
        stdout=True
    )
    output = container.decode('utf-8')
    return output

Here the expected response for the post request is "helloworld" as the output of the shell file execution is "helloworld" but when I send a post request from postman I get this "Error: connect ECONNREFUSED 127.0.0.1:5000".I have separately ran that dockersandbox function and it works as intended and gives the correct output.I have also tested by sending only a string like "Test" as ouput of the dockersandbox function without implementing any docker container logic and code,in that case it gives the correct response for that post request,this issue happens if I implement this docker client logic in the dockersandbox function.I am using python's docker library to implement the docker logic and run the container.


问:
Order of messages in Kafka
How exactly does setting enable.idempotence=true with max.in.flight.requests.per.connection > 1 (and less than 5) help in maintaining message ordering?

Each message gets a PID and sequence number to uniquely identify the message.
When a broker receives a message with same PID and sequence - it will reject the message and this solves the duplication issue.

But how does idempotent producer helps with message ordering?
In case message1 succeeds, message 2 fails and message 3 succeeds; that will result in message being retried again and in case it succeeds - the order gets disturbed.

Title: Order of messages in Kafka


问:
Scala Design Question - Unify 3 similar endpoints to retrieve from database
I'm designing a Scala service which has 3 endpoints which are very similar -
a. getUserByUserID(userIds: List[UserID]): List[User]
b. getUserByEmployeeID(employeeIDs: List[EmployeeID]): List[User]
c. getUserByDepartmentID(departmentIDs: List[DepartmentID]): List[User]

Think of User as a case class having many fields but 3 of them for the above endpoints are:

```<code>case class User(
  userId: UserID,
  employeeID: EmployeeID,
  departmentID: DepartmentID,
)
</code>```

All these IDs are of type java.util.UUID.

All 3 endpoints return the User object as a list where the appropriate IDs match.

My concern is that there's a lot of repetitive work in this. Only difference is that the WHERE clause in the query changes to one of userID, employeeID, departmentID.

I want to minimize this duplication. Is Scala generics a way to do that?

I was thinking of creating a coordinator service that takes in any form of ID and returns the List[User] from it

so something like

endpoint1, endpoint2, endpoint3 -> call CoordinatorService --> call Database service

Coordinator service only has 1 method
def getUserFromAnyID[A <: UUID](id: A): List[User]

and somehow match the generic A to ID to call appropriate database service. At a high level it would look like:

```<code>def getUserFromAnyID[A <: UUID](id: A): List[User] = {
  // A is a list
  A match {
    case Nil => List.empty()
    case someList =>
     // How to match the type of the object in someList?? It can be any of userId, employeeID, departmentID
     // After matching, it will call the database service:
     <type of list object> match {
        case userID: UserID => databaseService.getUsersByUserID(<pass list of userIds)
        case employeeIds: EmployeeID => databaseService.getUsersByEmployeeIDs(<pass list of employee IDs)
       .
       .
       .
     }
  }
}

</code>```

Is there an efficient pattern to achieve this?

Body:
I'm designing a Scala service which has 3 endpoints which are very similar -
a. getUserByUserID(userIds: List[UserID]): List[User]
b. getUserByEmployeeID(employeeIDs: List[EmployeeID]): List[User]
c. getUserByDepartmentID(departmentIDs: List[DepartmentID]): List[User]

Think of User as a case class having many fields but 3 of them for the above endpoints are:

case class User(
  userId: UserID,
  employeeID: EmployeeID,
  departmentID: DepartmentID,
)

All these IDs are of type java.util.UUID.

All 3 endpoints return the User object as a list where the appropriate IDs match.

My concern is that there's a lot of repetitive work in this. Only difference is that the WHERE clause in the query changes to one of userID, employeeID, departmentID.

I want to minimize this duplication. Is Scala generics a way to do that?

I was thinking of creating a coordinator service that takes in any form of ID and returns the List[User] from it

so something like

endpoint1, endpoint2, endpoint3 -> call CoordinatorService --> call Database service

Coordinator service only has 1 method
def getUserFromAnyID[A <: UUID](id: A): List[User]

and somehow match the generic A to ID to call appropriate database service. At a high level it would look like:

def getUserFromAnyID[A <: UUID](id: A): List[User] = {
  // A is a list
  A match {
    case Nil => List.empty()
    case someList =>
     // How to match the type of the object in someList?? It can be any of userId, employeeID, departmentID
     // After matching, it will call the database service:
     <type of list object> match {
        case userID: UserID => databaseService.getUsersByUserID(<pass list of userIds)
        case employeeIds: EmployeeID => databaseService.getUsersByEmployeeIDs(<pass list of employee IDs)
       .
       .
       .
     }
  }
}

Is there an efficient pattern to achieve this?


问:
How to build an Android app that listens and reacts to gestures globally?
I recently bought Galaxy Tab S8 and noticed that it's builtin gesture controls are pretty terrible.

I'd like to build my own system to react to two and three finger swipes to do things such as going back in the app and switch between apps no matter what app is in the foreground.

Is such thing possible? If it is, how to get started?


问:
Google Analytics 4 for Nuxt 2.x
Here's the solution I came up with for integrating Google Analytics 4 with Nuxt @ v2.15.8. Looking for some feedback. I think it's a good solution but would like some others to weigh in.

create an .env file in the root directory to hold the analytics variable. Put the following line in the .env file

NUXT_PUBLIC_GOOGLE_ANALYTICS=G-XXXXXXXXXX

add the following to your nuxt.config.js file:

env: {
NUXT_PUBLIC_GOOGLE_ANALYTICS: process.env.NUXT_PUBLIC_GOOGLE_ANALYTICS
},

Create a file in your plugins folder, I named mine "googleAnalytics.client.js" The reason the file name contains ".client" is so that it renders on the client side and not the server side. In this file, place the following code:

```<code>export default async ({ app }) => {
   /*
   ** Only run on client-side and only in production mode
   */
   if (process.env.NODE_ENV === 'production' && process.client) {

       const analyticsID = process.env.NUXT_PUBLIC_GOOGLE_ANALYTICS

       // first check to see if our script is already in the DOM
       const myScriptExists = Boolean(
           document.querySelector(
               `head > script[src="https://www.googletagmanager.com/gtag/js?id=${analyticsID}"]`
           )
       )

       if (!myScriptExists) {
           // if it isn't already in the DOM, create and insert our script
           const myScript = document.createElement('script')
           myScript.type = 'text/javascript'
           myScript.src = `https://www.googletagmanager.com/gtag/js?id=${analyticsID}`
           myScript.hid = 'gtm'
           myScript.async = true
           document.head.appendChild(myScript);
       }

       //part 2 of Google Analytics script
       window.dataLayer = window.dataLayer || [];
       function gtag() { dataLayer.push(arguments); }
       gtag('js', new Date());
       gtag('set', { cookie_flags: 'SameSite=None;Secure' });
       gtag('config', `${analyticsID}`);
   }
}
</code>```

Add the newly created plugin to the nuxt.config.js file:

```<code>plugins: ['~/plugins/googleAnalytics.client.js'],
</code>```

When I run this, Google Analytics is picking up all my routes although I'm not 100% sure why. Maybe someone else could explain why.

Title: Google Analytics 4 for Nuxt 2.x

Body:
Here's the solution I came up with for integrating Google Analytics 4 with Nuxt @ v2.15.8. Looking for some feedback. I think it's a good solution but would like some others to weigh in.

create an .env file in the root directory to hold the analytics variable. Put the following line in the .env file

NUXT_PUBLIC_GOOGLE_ANALYTICS=G-XXXXXXXXXX

add the following to your nuxt.config.js file:

env: {
NUXT_PUBLIC_GOOGLE_ANALYTICS: process.env.NUXT_PUBLIC_GOOGLE_ANALYTICS
},

Create a file in your plugins folder, I named mine "googleAnalytics.client.js" The reason the file name contains ".client" is so that it renders on the client side and not the server side. In this file, place the following code:

export default async ({ app }) => {
   /*
   ** Only run on client-side and only in production mode
   */
   if (process.env.NODE_ENV === 'production' && process.client) {

       const analyticsID = process.env.NUXT_PUBLIC_GOOGLE_ANALYTICS

       // first check to see if our script is already in the DOM
       const myScriptExists = Boolean(
           document.querySelector(
               `head > script[src="https://www.googletagmanager.com/gtag/js?id=${analyticsID}"]`
           )
       )

       if (!myScriptExists) {
           // if it isn't already in the DOM, create and insert our script
           const myScript = document.createElement('script')
           myScript.type = 'text/javascript'
           myScript.src = `https://www.googletagmanager.com/gtag/js?id=${analyticsID}`
           myScript.hid = 'gtm'
           myScript.async = true
           document.head.appendChild(myScript);
       }

       //part 2 of Google Analytics script
       window.dataLayer = window.dataLayer || [];
       function gtag() { dataLayer.push(arguments); }
       gtag('js', new Date());
       gtag('set', { cookie_flags: 'SameSite=None;Secure' });
       gtag('config', `${analyticsID}`);
   }
}

Add the newly created plugin to the nuxt.config.js file:

plugins: ['~/plugins/googleAnalytics.client.js'],

When I run this, Google Analytics is picking up all my routes although I'm not 100% sure why. Maybe someone else could explain why.


问:
How do i use authentication in nhost.io?
I am following the tutorial

In my App.js , i have this code

const nhost = new NhostClient({ subdomain: subdomain, region: region, });
I have wrapped my code with nhostprovider

```<code><NhostProvider nhost={nhost}>
      <View>
        <Text>hellooooooooo</Text>
        <Text>hello</Text>
        <Text>hello</Text>
        <Text>hello</Text>
        <TextInput
          label="Email"
          value={text}
          onChangeText={(text) => setText(text)}
        />
        <TextInput
          label="password"
          value={password}
          onChangeText={(text) => setPassword(text)}
        />
        <Button icon="login" mode="Contained" onPress={() => register()}>
          Press me
        </Button>
      </View>
    </NhostProvider>
</code>```

But on android emulator, i am getting error
ge.create is not a function  ....ge.create is undefined

I have one more question. I am writing  code in reat native, expo , android emulator. what should i put in client url and redirect url ?
https://prnt.sc/n45Ke9zY7v8c

I followed documentation. In youtube video, its something else and in documentation, its something else.

Body:
I am following the tutorial

In my App.js , i have this code

const nhost = new NhostClient({ subdomain: subdomain, region: region, });
I have wrapped my code with nhostprovider

<NhostProvider nhost={nhost}>
      <View>
        <Text>hellooooooooo</Text>
        <Text>hello</Text>
        <Text>hello</Text>
        <Text>hello</Text>
        <TextInput
          label="Email"
          value={text}
          onChangeText={(text) => setText(text)}
        />
        <TextInput
          label="password"
          value={password}
          onChangeText={(text) => setPassword(text)}
        />
        <Button icon="login" mode="Contained" onPress={() => register()}>
          Press me
        </Button>
      </View>
    </NhostProvider>

But on android emulator, i am getting error
ge.create is not a function  ....ge.create is undefined

I have one more question. I am writing  code in reat native, expo , android emulator. what should i put in client url and redirect url ?
https://prnt.sc/n45Ke9zY7v8c

I followed documentation. In youtube video, its something else and in documentation, its something else.


问:
unable to load certificates with openssl to convert to pxf
I need to convert a private key and a cert to a .p12 file. I got a valid certificate, which is also correct formatted. I got the openssl v1.1.1s.

server.crt

```<code>-----BEGIN CERTIFICATE-----
THE CERT
-----END CERTIFICATE-----
</code>```

server.key

```<code>-----BEGIN RSA PRIVATE KEY-----
The Private Key
-----END RSA PRIVATE KEY-----
</code>```

I tried to run this openssl command:

```<code>openssl pkcs12 -export -in server.crt -inkey server.key -out certificate.p12
</code>```

And got this error:

```<code>unable to load certificates
</code>```

Body:
I need to convert a private key and a cert to a .p12 file. I got a valid certificate, which is also correct formatted. I got the openssl v1.1.1s.

server.crt

-----BEGIN CERTIFICATE-----
THE CERT
-----END CERTIFICATE-----

server.key

-----BEGIN RSA PRIVATE KEY-----
The Private Key
-----END RSA PRIVATE KEY-----

I tried to run this openssl command:

openssl pkcs12 -export -in server.crt -inkey server.key -out certificate.p12

And got this error:

unable to load certificates


问:
SQLAlchemy could not translate host name none.postgres.database.azure.com
I have a PostgreSQL database I have set up on Azure and I am trying to update some tables using Alembic. The bulk of the code is based on a course found here, which creates a database using SQLAlchemy before updating via Alembic.

The problem...

I have built and tested a version on my local machine, and can update tables via alembic upgrade head. I have deployed a first version of this to Azure, and can successfully connect to it through PG Admin (so I know connection strings etc., are working). What I cannot work out is how I perform updates to the Azure version of the database (i.e., add/remove tables and columns). I am continuously encountering the following error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "None.postgres.database.azure.com" to address: Name or service not known

Clearly a problem detecting the host name...

What I have tried so far...

The first thing I tried was to make the changes to the database locally via alembic revision..., and then include alembic upgrade head in the steps section of my workflow .yml file (see below). I stored the location of the database (AZURE_DB_URL) as a secret. The format of the URL is as follows:

```<code>postgres://{user}:{password}@{db_host}.postgres.database.azure.com/{db_name}?sslmode=require
</code>```
```<code>jobs:
  build:
    runs-on: ubuntu-latest
    env:
      DATABASE_URL: ${{ secrets.AZURE_DB_URL }}

    steps:
      - uses: actions/checkout@v2

      - name: Set up Python version
        uses: actions/setup-python@v1
        with:
          python-version: '3.9'

      - name: Create and start virtual environment
        run: |
          python -m venv venv
          source venv/bin/activate

      - name: Install dependencies
        run: pip install -r requirements.txt

      - name: Upgrade postgreSQL tables via Alembic
        run: alembic upgrade head
</code>```

I have also tried adding --database=${{ secrets.AZURE_DB_URL }} to the end of alembic upgrade head as an alternative, but this generates the error: alembic: error: unrecognized arguments

Additionally, I have noticed that if I use a different connection string (see below), the GitHub-action does successfully deploy, although it does not appear to update the database.

postgresql://{db_host}.postgres.database.azure.com:5432/{db_name}?user={user}&password={password}&sslmode=require

I've been stuck on this for some time now, so any help would be great.

Body:
I have a PostgreSQL database I have set up on Azure and I am trying to update some tables using Alembic. The bulk of the code is based on a course found here, which creates a database using SQLAlchemy before updating via Alembic.

The problem...

I have built and tested a version on my local machine, and can update tables via alembic upgrade head. I have deployed a first version of this to Azure, and can successfully connect to it through PG Admin (so I know connection strings etc., are working). What I cannot work out is how I perform updates to the Azure version of the database (i.e., add/remove tables and columns). I am continuously encountering the following error:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not translate host name "None.postgres.database.azure.com" to address: Name or service not known

Clearly a problem detecting the host name...

What I have tried so far...

The first thing I tried was to make the changes to the database locally via alembic revision..., and then include alembic upgrade head in the steps section of my workflow .yml file (see below). I stored the location of the database (AZURE_DB_URL) as a secret. The format of the URL is as follows:

postgres://{user}:{password}@{db_host}.postgres.database.azure.com/{db_name}?sslmode=require

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      DATABASE_URL: ${{ secrets.AZURE_DB_URL }}

    steps:
      - uses: actions/checkout@v2

      - name: Set up Python version
        uses: actions/setup-python@v1
        with:
          python-version: '3.9'

      - name: Create and start virtual environment
        run: |
          python -m venv venv
          source venv/bin/activate

      - name: Install dependencies
        run: pip install -r requirements.txt

      - name: Upgrade postgreSQL tables via Alembic
        run: alembic upgrade head

I have also tried adding --database=${{ secrets.AZURE_DB_URL }} to the end of alembic upgrade head as an alternative, but this generates the error: alembic: error: unrecognized arguments

Additionally, I have noticed that if I use a different connection string (see below), the GitHub-action does successfully deploy, although it does not appear to update the database.

postgresql://{db_host}.postgres.database.azure.com:5432/{db_name}?user={user}&password={password}&sslmode=require

I've been stuck on this for some time now, so any help would be great.


问:
How to add an image to my picturebox using URL
This is my code to create a picturebox board using 2d array.

PictureBox[,] pb = new PictureBox[3, 3];

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        pb[i,j] = new PictureBox();
        pb[i, j].Location = new Point(i * 150 + 100, j * 150 + 100);
        pb[i, j].Width = 150;
        pb[i, j].Height = 150;
        pb[i, j].Visible = true;
        pb[i, j].BorderStyle = BorderStyle.FixedSingle;
        pb[i, j].BringToFront();
        this.Controls.Add(pb[i, j]);
    }
}
```

Now how can I also program it so it adds an image via URL. Before I tried using the file path but it just came out as a red X so I'm wondering how to do it using a URL instead.

Body:
This is my code to create a picturebox board using 2d array.

PictureBox[,] pb = new PictureBox[3, 3];

for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        pb[i,j] = new PictureBox();
        pb[i, j].Location = new Point(i * 150 + 100, j * 150 + 100);
        pb[i, j].Width = 150;
        pb[i, j].Height = 150;
        pb[i, j].Visible = true;
        pb[i, j].BorderStyle = BorderStyle.FixedSingle;
        pb[i, j].BringToFront();
        this.Controls.Add(pb[i, j]);
    }
}

Now how can I also program it so it adds an image via URL. Before I tried using the file path but it just came out as a red X so I'm wondering how to do it using a URL instead.


问:
How to create a histogram with specified Bins and Values in matplotlib?
matplotlib == 3.6.2
python == 3.9.15

I'm trying to create a historgram however I've already pre-computed the heights of each bin as a percentage.

Data Example

values=[0.5, 0.25, 0.25]
bins=[0.0, 1.0, 5.0, 7.0]
```

Histograms seem to wanted the raw dataset and I do not have that. Bar charts will let me set the height, but I can't specify varying bin values (which makes sense because bar charts don't have bins, histograms do).

Thoughts?

Body:
matplotlib == 3.6.2
python == 3.9.15

I'm trying to create a historgram however I've already pre-computed the heights of each bin as a percentage.

Data Example

values=[0.5, 0.25, 0.25]
bins=[0.0, 1.0, 5.0, 7.0]

Histograms seem to wanted the raw dataset and I do not have that. Bar charts will let me set the height, but I can't specify varying bin values (which makes sense because bar charts don't have bins, histograms do).

Thoughts?


问:
How to generate single html test result in multi module gradle project?
I am working on a multi module java gradle project. I am trying to create a Test report with test results coming from all modules. I tried to use Test Report Aggregation Plugin but its not working. Can anyone suggest how to use it or any other way to aggregate test results across multiple subprojects.</p>


问:
R XML doen't return full list of URLs
I was trying to extract all URLs from this webpage: https://marketplace.spp.org/pages/rtbm-lmp-by-location#%2F2022%2F12%2FBy_Day, specifically the csv links.

When I used "Inspect" in Google Chrome, I can see the csv links were embedded in html, for example:

```<code><a target="_self" href="/file-browser-api/download/rtbm-lmp-by-location?path=%2F2022%2F12%2FBy_Day%2FRTBM-LMP-DAILY-SL-20221201.csv" title="/2022/12/By_Day/RTBM-LMP-DAILY-SL-20221201.csv" class="files"><span class="icon file f-csv">.csv</span><span class="fname name">RTBM-LMP-DAILY-SL-20221201.csv</span> <span class="details">33 MB<br>12/22/2022 07:42:54 AM</span></a>
</code>```

However, when I tried to extract these links by following this blogpost:
https://www.geeksforgeeks.org/extract-all-the-urls-from-the-webpage-using-r-language/

The csv links were excluded in the output:

```<code>library("httr")
library("XML")

lmp_link <- "https://marketplace.spp.org/pages/rtbm-lmp-by-
location#%2F2022%2F12%2FBy_Day")

lmp_pg <- GET(lmp_link)
lmp_pg <- htmlParse(lmp_pg)
lmp_url <- xpathSApply(lmp_pg,path = "//a",xmlGetAttr,"href")

print(lmp_url)
</code>```

Do you know why the csv links were not extracted?

Title: R XML doen't return full list of URLs

Body:
I was trying to extract all URLs from this webpage: https://marketplace.spp.org/pages/rtbm-lmp-by-location#%2F2022%2F12%2FBy_Day, specifically the csv links.

When I used "Inspect" in Google Chrome, I can see the csv links were embedded in html, for example:

.csvRTBM-LMP-DAILY-SL-20221201.csv 33 MB
12/22/2022 07:42:54 AM

However, when I tried to extract these links by following this blogpost:
https://www.geeksforgeeks.org/extract-all-the-urls-from-the-webpage-using-r-language/

The csv links were excluded in the output:

library("httr")
library("XML")

lmp_link <- "https://marketplace.spp.org/pages/rtbm-lmp-by-
location#%2F2022%2F12%2FBy_Day")

lmp_pg <- GET(lmp_link)
lmp_pg <- htmlParse(lmp_pg)
lmp_url <- xpathSApply(lmp_pg,path = "//a",xmlGetAttr,"href")

print(lmp_url)

Do you know why the csv links were not extracted?


问:
How a people agent can use different mode of transports in AnyLogic
It's hard to describe but let me try!
I have people agents and facility agents. I want if distance to facility d<x, people will walk, if distance x>d<y, 70% people (chance) will use car and 30% use bus if available. What I did: created Car and Bus agent (initially empty). Created statechart in People agent (attached pic), created a function "sendMsg" to send msg "walk", "car", and "bus" in chart. Created an event where action:sendMsg(); Now on main, created discrete event blocks " Enter -> timeMeasurementStart->Move To->timeMeasurementEnd->sink" for both Car and Bus. Now on statechart, I say; main.enterCar.take(new Car()); same for Bus. Looks like it's not working. Error says: Caused by: NullPointerException
java.lang.RuntimeException: root.enterBus:
Error when trying to initialize new agent


问:
Adding a class path to jar file
I got a tester program that will run from a jar file the jar file needs to include a classpath to be able to fined the tests classes in the same directory where the jar file is. The test class will not be in the jar file but will be in the same folder as the the jar file

I searched and fined some usage of a manifest.txt file or a xml file with the classpath in but never knew how to add it to my jar file when I build it.

Title: Adding a class path to jar file


问:
Passing JAR files as CMD arguments that are required as dependencies
I have a program running in Intellij Idea. It has the following dependencies added as a jar file

I want to run it using the command line and want it to detect the jar files automatically as dependencies. Is there any way to achieve that without using Gradle or Maven? Or I could pass the dependencies as command-line arguments?

I have tried this command but it throws an error:

```<code> javac -classpath lib/*.jar -sourcepath src/*
</code>```

Error:

```<code>error: invalid flag: lib/okhttp-3.4.1.jar
</code>```

Using java -cp says this:

```<code> java -cp lib/* -sourcepath src/*
</code>```

error

```<code>Error: Could not find or load main class lib.okhttp-3.4.1.jar
Caused by: java.lang.ClassNotFoundException: lib.okhttp-3.4.1.jar
</code>```

Used the suggested command and it says:

```<code> java -cp lib/gson-2.10.jar:lib/okhttp-3.4.1.jar:lib/okio-3.2.0.jar:lib/slf4j-api-2.0.6.jar  src/Main.java
</code>```

Body:
I have a program running in Intellij Idea. It has the following dependencies added as a jar file

I want to run it using the command line and want it to detect the jar files automatically as dependencies. Is there any way to achieve that without using Gradle or Maven? Or I could pass the dependencies as command-line arguments?

I have tried this command but it throws an error:

 javac -classpath lib/*.jar -sourcepath src/*

Error:

error: invalid flag: lib/okhttp-3.4.1.jar

Using java -cp says this:

 java -cp lib/* -sourcepath src/*

error

Error: Could not find or load main class lib.okhttp-3.4.1.jar
Caused by: java.lang.ClassNotFoundException: lib.okhttp-3.4.1.jar

Used the suggested command and it says:

 java -cp lib/gson-2.10.jar:lib/okhttp-3.4.1.jar:lib/okio-3.2.0.jar:lib/slf4j-api-2.0.6.jar  src/Main.java


问:
Javascript Get dropdown selected value on each row of HTML Table and update it
I have a HTML table which has a dropdown control for Game_Type on the third column and a button below the table called "click me".

When user clicks the button, I want to loop through each row of the HTML table and check the current selected value. If its Type B or Type C, I want to update the selected dropdown value of the row to None. Type A should remain the same. Expected result shown after user has clicked the button.

I am confused of how to get the selected dropdown value of the row and also updating the row on HTML table.

What I have tried so far is creating a JavaScript function called "Check()" and it currently returns the full dropdown list per row.

My html and javascript code:

```<code>@model List<WebApplication5.Models.Game>

<table class="table" , id="Table_ID">
    <thead>
        <tr>
            <th>
                Game_ID
            </th>
            <th>
                Game_Name
            </th>
            <th>
                Game_Type
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @for (int i = 0; i < Model.Count(); i++)
        {
            <tr>
                <td>
                    @Html.DisplayFor(m => Model[i].Game_ID)
                </td>
                <td>
                    @Html.DisplayFor(m => Model[i].Game_Name)
                </td>
                <td>
                    @Html.DropDownListFor(m => Model[i].Game_Type_ID, Model[i].Game_Type_List, new { @class = "name" })
                </td>
            </tr>
        }
    </tbody>
</table>

<input type="button" value="Click me" onclick="Check()">

<script>

    function Check() {
        var table = $("table tbody");

        table.find('tr').each(function (i) {
            var $tds = $(this).find('td');
            var Game_Type_ID = $tds.eq(2).text();
            alert(Game_Type_ID);

            // Get the selected dropdown value.

            // Check if value is Type B or Type C

            // Then update cell to Game_Type_ID 1 (None).
        });
    };

</script>
</code>```

My controller method which returns the view:

```<code> public ActionResult Index()
        {
            List<Game_Type> typeList = new List<Game_Type>();
            typeList.Add(new Game_Type() { Game_Type_ID = 1, Game_Type_Name = "None" });
            typeList.Add(new Game_Type() { Game_Type_ID = 2, Game_Type_Name = "Type A" });
            typeList.Add(new Game_Type() { Game_Type_ID = 3, Game_Type_Name = "Type B" });
            typeList.Add(new Game_Type() { Game_Type_ID = 4, Game_Type_Name = "Type C" });
            typeList.Add(new Game_Type() { Game_Type_ID = 5, Game_Type_Name = "Type D" });

            List<Game> gameList = new List<Game>();
            gameList.Add(new Game() { Game_ID = 1, Game_Name = "Name A", Game_Type_List = new SelectList(typeList, "Game_Type_ID", "Game_Type_Name", "1") });
            gameList.Add(new Game() { Game_ID = 2, Game_Name = "Name B", Game_Type_List = new SelectList(typeList, "Game_Type_ID", "Game_Type_Name", "2") });
            gameList.Add(new Game() { Game_ID = 3, Game_Name = "Name C", Game_Type_List = new SelectList(typeList, "Game_Type_ID", "Game_Type_Name", "3") });

            return View(gameList);
        }
</code>```

My game type class:

```<code>   public class Game_Type
    {
        public int Game_Type_ID { get; set; }
        public string Game_Type_Name { get; set; }
    }
</code>```

My game class:

```<code>public class Game_Type
{
    public int Game_Type_ID { get; set; }
    public string Game_Type_Name { get; set; }
}
</code>```

Body:
I have a HTML table which has a dropdown control for Game_Type on the third column and a button below the table called "click me".

When user clicks the button, I want to loop through each row of the HTML table and check the current selected value. If its Type B or Type C, I want to update the selected dropdown value of the row to None. Type A should remain the same. Expected result shown after user has clicked the button.

I am confused of how to get the selected dropdown value of the row and also updating the row on HTML table.

What I have tried so far is creating a JavaScript function called "Check()" and it currently returns the full dropdown list per row.

My html and javascript code:

@model List<WebApplication5.Models.Game>

                Game_ID

                Game_Name

                Game_Type

        @for (int i = 0; i < Model.Count(); i++)
        {

                    @Html.DisplayFor(m => Model[i].Game_ID)

                    @Html.DisplayFor(m => Model[i].Game_Name)

                    @Html.DropDownListFor(m => Model[i].Game_Type_ID, Model[i].Game_Type_List, new { @class = "name" })

        }

<input type="button" value="Click me" onclick="Check()">

My controller method which returns the view:

 public ActionResult Index()
        {
            List<Game_Type> typeList = new List<Game_Type>();
            typeList.Add(new Game_Type() { Game_Type_ID = 1, Game_Type_Name = "None" });
            typeList.Add(new Game_Type() { Game_Type_ID = 2, Game_Type_Name = "Type A" });
            typeList.Add(new Game_Type() { Game_Type_ID = 3, Game_Type_Name = "Type B" });
            typeList.Add(new Game_Type() { Game_Type_ID = 4, Game_Type_Name = "Type C" });
            typeList.Add(new Game_Type() { Game_Type_ID = 5, Game_Type_Name = "Type D" });

            List<Game> gameList = new List<Game>();
            gameList.Add(new Game() { Game_ID = 1, Game_Name = "Name A", Game_Type_List = new SelectList(typeList, "Game_Type_ID", "Game_Type_Name", "1") });
            gameList.Add(new Game() { Game_ID = 2, Game_Name = "Name B", Game_Type_List = new SelectList(typeList, "Game_Type_ID", "Game_Type_Name", "2") });
            gameList.Add(new Game() { Game_ID = 3, Game_Name = "Name C", Game_Type_List = new SelectList(typeList, "Game_Type_ID", "Game_Type_Name", "3") });

            return View(gameList);
        }

My game type class:

   public class Game_Type
    {
        public int Game_Type_ID { get; set; }
        public string Game_Type_Name { get; set; }
    }

My game class:

public class Game_Type
{
    public int Game_Type_ID { get; set; }
    public string Game_Type_Name { get; set; }
}