Appearance
question:Как объявить переменые в .h файле общие для всех файлов, которые включают заголовочник
answer:Для объявления переменных в заголовочном файле (.h файле), которые будут общими для всех файлов, которые включают этот заголовочник, необходимо следовать определённой схеме. Это делается для того, чтобы избежать проблем многократного определения при компиляции проекта, поскольку каждый файл .c или .cpp, включающий данный заголовочный файл, попытается определить эти переменные, что приведёт к ошибкам линковщика из-за множественных определений. Процесс можно разделить на два этапа - объявление и определение переменных. # 1. Объявление в .h файле Для начала, в заголовочном файле вы объявляете переменные с использованием ключевого слова `extern`. Это говорит компилятору о том, что переменная существует где-то, но память под неё выделена не будет. **example.h** ```c #ifndef EXAMPLE_H #define EXAMPLE_H extern int globalVariable; #endif // EXAMPLE_H ``` # 2. Определение в одном из .c или .cpp файлов Далее, в одном из файлов реализации (.c или .cpp), который включает этот заголовочный файл, вы определяете (то есть, выделяете память для) ранее объявленные переменные. Это делается уже без использования ключевого слова `extern`. **example.c** ```c #include "example.h" int globalVariable = 0; ``` Таким образом, `globalVariable` объявлена как `extern` в заголовочном файле, что позволяет ей быть доступной для всех файлов, которые включают этот заголовочник, но память под неё выделяется только один раз в одном из файлов реализации. Это позволяет избежать ошибок линковщика, связанных с многократным определением переменных. # Важные замечания: - Помните о защите от многократного включения в заголовочные файлы с помощью `#ifndef`, `#define`, `#endif`. - Убедитесь, что переменная определена только в одном файле .c или .cpp, чтобы избежать конфликта определений. - Ключевое слово `extern` можно также использовать для объявления глобальных функций с целью обеспечения их доступности в разных файлах программы, хотя для функций это не так критично, поскольку функции по умолчанию считаются `extern`, если не указано иное.
question:As a prompt generator for a generative AI called "Midjourney", you will create image prompts for the AI to visualize. I will give you a concept, and you will provide a detailed prompt for Midjourney AI to generate an image. Please adhere to the structure and formatting below, and follow these guidelines: Do not use the words "description" or ":" in any form. Do not place a comma between [ar] and [v]. Write each prompt in one line without using return. Structure: [1] = 手机背景图插画,有心想事成的汉语 [2] = a detailed description of [1] with specific imagery details. [3] = a detailed description of the scene's environment. [4] = a detailed description of the compositions. [5] = a detailed description of the scene's mood, feelings, and atmosphere. [6] = A style (e.g. photography, painting, illustration, sculpture, artwork, paperwork, 3D, etc.) for [1]. [7] = a detailed description of the scene's mood, feelings, and atmosphere. [ar] = Use "--ar 16:9" for horizontal images, "--ar 9:16" for vertical images, or "--ar 1:1" for square images. [v] = Use "--niji" for Japanese art style, or "--v 5" for other styles. Formatting: Follow this prompt structure: "/imagine prompt: [1], [2], [3], [4], [5], [6], [7], [ar] [v]". Your task: Create 4 distinct prompts for each concept [1], varying in details description, environment,compositions,atmosphere, and realization. Write your prompts in english. Do not describe unreal concepts as "real" or "photographic". Include one realistic photographic style prompt with lens type and size. Separate different prompts with two new lines. Example Prompts: /imagine prompt: cute dog, fluffy fur, wagging tail, playful expression, sitting on a grassy field, under a clear blue sky, with a colorful collar, in a natural and vibrant setting, by a lake, captured with a Nikon D750 camera, 50mm lens, shallow depth of field, composition focused on the dog's face, capturing its joyful spirit, in a style reminiscent of William Wegman's iconic dog portraits. --ar 1:1 --v 5.2 /imagine prompt: beautiful women in the coffee shop, elegant and sophisticated, sipping a cup of steaming coffee, natural sunlight streaming through the window, soft and warm color tones, vintage decor with cozy armchairs and wooden tables, a bookshelf filled with classic novels, delicate porcelain teacups, a hint of aromatic coffee beans in the air, captured by a Leica M10 camera, 35mm lens, capturing the essence of timeless beauty, composition focused on the woman's face and hands, reminiscent of a painting by Leonardo da Vinci. --ar 1:1 --v 5.2 /imagine prompt: A captivating Halo Reach landscape with a Spartan amidst a battlefield, fallen enemies around, smoke and fire in the background, emphasizing the Spartan's determination and bravery, detailed environment blending chaos and beauty, Illustration, digital art, --ar 16:9 --v 5
answer:/imagine prompt: an elegant cherry blossom tree in full bloom, delicate pink petals falling gracefully, a peaceful zen garden with a stone lantern and koi pond, the soft sound of a bamboo flute in the background, a gentle breeze rustling the leaves, creating a serene and calming atmosphere, captured with a Canon EOS 5D Mark IV camera, 85mm lens, shallow depth of field focusing on the cherry blossoms, in a traditional Japanese ukiyo-e art style. --ar 9:16 --v 5 /imagine prompt: a mystical forest at dusk, with tall ancient trees covered in glowing moss, shimmering fireflies dancing in the air, a misty fog enveloping the scene, creating an otherworldly and enchanting ambiance, the faint sound of a distant owl hooting, captured in a dreamy and surreal painting style, --ar 16:9 --v 5 /imagine prompt: a cozy winter cabin in the mountains, smoke billowing from the chimney, a snowy landscape with pine trees covered in frost, a warm glow emanating from the windows, inviting and comforting, a pair of friendly deer grazing nearby, a sense of solitude and tranquility in the snowy wilderness, captured with a Sony A7III camera, 24-70mm lens, wide-angle shot capturing the cabin and surrounding scenery, in a realistic photographic style. --ar 16:9 --v 5 /imagine prompt: a futuristic cityscape at night, with neon lights and holographic billboards illuminating the skyline, flying cars zooming through the air, bustling streets filled with diverse crowds, a sense of energy and excitement in the air, captured in a dynamic and vibrant digital art style, --ar 16:9 --v 5.
question:Power query Rest API with pagination
answer:Using Power Query to consume data from a REST API that implements pagination can be highly useful, especially when dealing with APIs that return large sets of data in multiple pages to limit bandwidth and speed up response times. However, you might need to adopt a specific approach to cater to the particular API's pagination style (number-based, token-based, etc.). Below is a general guide that can be adapted to specific scenarios. **Assumptions**: - The REST API uses a simple number-based pagination method, with parameters such as `page` and `limit` (or `offset` and `limit`). - Power Query in Excel or Power BI is being used. # Step 1: Define Base URL and Parameters First, define the base URL of your API and any constant parameters that will be included in every request. ```m let baseUrl = "https://api.example.com/data", limit = 100 ``` # Step 2: Function to Retrieve a Single Page Create a custom function in Power Query to fetch a single page of data. This function will accept the page number as a parameter and construct the full URL to make the request. ```m getPageData = (pageNum as number) as table => let apiUrl = baseUrl & "?limit=" & Text.From(limit) & "&page=" & Text.From(pageNum), source = Json.Document(Web.Contents(apiUrl)), data = Table.FromList(source[data], Splitter.SplitByNothing(), null, null, ExtraValues.Error) in data ``` # Step 3: Determine Total Number of Pages To fetch all pages, you first need to know how many pages exist. Depending on the API, this information might be available in the API response, often in a header or a field within the response body. Adjust this step based on how the total count of pages or items is obtained. Assuming you have to make an initial call to get the total number of pages or items: ```m initialResponse = Json.Document(Web.Contents(baseUrl & "?limit=1")), totalItems = initialResponse[total], totalPages = Number.RoundUp(totalItems / limit) ``` # Step 4: Generate a List of Page Numbers and Apply the Custom Function Use `List.Numbers` to generate a list of page numbers based on the total number of pages. Then, apply the custom function `getPageData` to each page number to retrieve all page data. ```m pageNumbers = List.Numbers(1, totalPages), pagesData = List.Transform(pageNumbers, each getPageData(_)) ``` # Step 5: Combine Data and Final Adjustments Finally, combine the data from all pages into a single table. Perform any final transformations as needed. ```m combinedData = Table.Combine(pagesData) in combinedData ``` The full script will incorporate all these steps, making adjustments as necessary for specific API requirements (like handling APIs that use next page tokens or have different methods for indicating the total number of pages/items). Please note that the actual fields to access from the JSON (`source[data]` in the script), and other specific details need to be adjusted based on the actual response structure of your REST API. The rate limiting and timeout policies of the API should also be considered to avoid hitting these limits.
question:I am trying to auto populate group members in a variable based on other variable choices. EX: We have 2 variable V1 and V2 V1 has 3 choices Choices: TYPE1, TYPE2, TYPE3 When V1 is selected as = TYPE1 the Variable V2 should show list group members who are part of "TYPE1Group" When V1 is selected as = TYPE2 the Variable V2 should show list group members who are part of "TYPE2Group" When V1 is selected as = TYPE3 the Variable V2 should show list group members who are part of "TYPE3Group" Servicenow
answer:To achieve the dynamic population of group members in Variable V2 based on the selection of types in Variable V1 in ServiceNow, you would typically use a Catalog Client Script. The key is to create a script that listens for changes in V1, fetches the appropriate group members based on that selection, and then populates V2 with those members. Here is an outline of the steps you'll need to follow, along with an example script: # 1. Create Your Variables First, ensure you have your variables created in your catalog item or record producer: - **V1** with the choice type, having options `TYPE1`, `TYPE2`, `TYPE3`. - **V2** should likely be a Reference type if you're pulling in users or a Select Box if you want to manually input the options. # 2. Script Logic You will be using a Catalog Client Script that will: - Listen to changes on V1. - Based on V1's selection, query the group model for the `TYPEGroup`. - Fetch members of the selected group. - Populate those members into V2. # 3. Example Catalog Client Script Here's an example script that roughly aligns with what you're trying to achieve. This example assumes V2 is designed to accept user references (i.e., sys_user records). Adaptations might be needed to fit your exact setup: ```javascript //Type: Catalog Client Script //Applies to: Appropriate item/category //UI Type: Both //When to run: onChange //Variable: V1 function onChange(control, oldValue, newValue, isLoading) { if (isLoading || newValue === '') { return; } // Fetch the corresponding group based on the TYPE selection var groupName = newValue + "Group"; // Constructs the group name based on the selection, e.g., "TYPE1Group" // Clear previous options g_form.clearOptions('V2'); // Query to get the sys_id of the group var groupIdQuery = new GlideRecord('sys_user_group'); groupIdQuery.addQuery('name', groupName); groupIdQuery.query(); if (groupIdQuery.next()) { var groupId = groupIdQuery.sys_id; // Now, get the group members var memberQuery = new GlideRecord('sys_user_grmember'); memberQuery.addQuery('group', groupId); memberQuery.query(); while (memberQuery.next()) { var userId = memberQuery.user; // Get user details var userRec = new GlideRecord('sys_user'); if (userRec.get(userId)) { var userName = userRec.name; var userSysId = userRec.sys_id.toString(); // Add this user as an option to V2 g_form.addOption('V2', userSysId, userName); } } } } ``` # Important Notes: - Replace `'V1'` and `'V2'` with the actual names of your variables. - This script assumes your group names exactly match the pattern `TYPE + Group` (e.g., `TYPE1Group`). Adjust the concatenation logic as necessary. - Make sure the script is properly scoped to the item/category you're working with, and you've selected the `onChange` option. - There may be permissions or visibility considerations depending on how your variables and user groups are set up. # Testing: After setting up this script, whenever a user selects a type in V1, V2 should dynamically populate with users from the corresponding `TYPEGroup`. Ensure you test thoroughly to troubleshoot any potential issues with script execution or data fetching.