row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
34,334
|
TypeError: Cannot read property 'prefix' of null, js engine: hermes
Android Running app on sdk_gphone64_x86_64
Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called., js engine: hermes this error only happen when i add this line to my code : import ZegoUIKitPrebuiltCall, { ONE_ON_ONE_VIDEO_CALL_CONFIG } from '@zegocloud/zego-uikit-prebuilt-call-rn'
|
1dbc606cd3fa63534f143b1b11990aa2
|
{
"intermediate": 0.6680036187171936,
"beginner": 0.1970357745885849,
"expert": 0.13496065139770508
}
|
34,335
|
How to setup haproxy with docker-compose and how to config so it will handle trattic to https://myserver.com and reverse proxy it to http://internal.com:8080?
|
08c87cb80f130f86dc1ce6138c3c3689
|
{
"intermediate": 0.44600147008895874,
"beginner": 0.28411543369293213,
"expert": 0.26988306641578674
}
|
34,336
|
Почему здесь не работает такая функция, что когда у нас значение уровня больше или равно 4, то активируется колонка чары, в случае если меньше 4х, то она заблокирована
private void DisplayComboBoxOrTextBox(ListViewHitTestInfo hit)
{
int yOffset = 65; // Смещение по вертикали
// Индексы столбцов (могут быть другими - настроить под свою структуру)
int quantityColumnIndex = 2; // Индекс колонки для количества
int levelColumnIndex = 3; // Индекс колонки для уровня
int enchantmentColumnIndex = 4; // Индекс колонки для чаров
// Проверяем, что клик был по интересующим нас колонкам в InventoryList
int columnIndex = hit.Item.SubItems.IndexOf(hit.SubItem);
if (columnIndex == quantityColumnIndex || columnIndex == levelColumnIndex || columnIndex == enchantmentColumnIndex)
{
// Определяем границы ячейки и контрол для отображения
Rectangle cellBounds = hit.SubItem.Bounds;
cellBounds.Offset(15, yOffset);
cellBounds.Height -= yOffset; // Корректируем высоту с учетом смещения
Control controlToDisplay = null;
// Создание и настройка TextBox для количества
if (columnIndex == quantityColumnIndex)
{
TextBox quantityTextBox = new TextBox
{
Bounds = cellBounds,
Text = hit.SubItem.Text,
Tag = hit.Item
};
quantityTextBox.Leave += TextBox_Leave;
hit.Item.ListView.Parent.Controls.Add(quantityTextBox);
quantityTextBox.Focus();
quantityTextBox.Leave += (sender, e) => quantityTextBox.Visible = false;
quantityTextBox.KeyPress += (sender, e) =>
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
};
quantityTextBox.KeyDown += (sender, e) =>
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
hit.SubItem.Text = quantityTextBox.Text;
quantityTextBox.Visible = false;
}
};
controlToDisplay = quantityTextBox;
}
else
{
// Создание и настройка ComboBox для уровня или чаров
ComboBox comboBox = new ComboBox
{
Bounds = cellBounds,
DropDownStyle = ComboBoxStyle.DropDownList,
};
comboBox.Leave += (sender, e) => comboBox.Visible = false;
comboBox.SelectedIndexChanged += (sender, e) =>
{
if (comboBox.Tag is ListViewItem listViewItem && listViewItem.Tag is Item item)
{
// Определяем, какое именно свойство изменилось
bool isLevelChanged = listViewItem.SubItems[levelColumnIndex].Bounds.Contains(comboBox.Bounds.Location);
bool isEnchantmentChanged = listViewItem.SubItems[enchantmentColumnIndex].Bounds.Contains(comboBox.Bounds.Location);
if (isLevelChanged)
{
item.Level = int.Parse(comboBox.SelectedItem.ToString());
listViewItem.SubItems[levelColumnIndex].Text = item.Level.ToString();
if (item.Level >= 4)
{
comboBox.Enabled = true; // Разрешаем выбор
for (int i = 0; i <= 4; i++)
{
comboBox.Items.Add(i.ToString());
}
}
else
{
comboBox.Enabled = false; // Запрещаем выбор
comboBox.Items.Add("0"); // Добавляем единственно допустимый вариант
}
}
else if (isEnchantmentChanged)
{
// Не изменяем чары, если уровень меньше 4 - они должны оставаться равными 0.
if (item.Level >= 4)
{
item.Charms = int.Parse(comboBox.SelectedItem.ToString());
listViewItem.SubItems[enchantmentColumnIndex].Text = item.Charms.ToString();
}
}
listViewItem.ImageKey = item.GetImageFileName(); // Обновляем иконку предмета
listViewItem.ListView.Refresh(); // Обновляем ListView для отображения изменений
comboBox.Visible = false; // Скрываем ComboBox после выбора
}
hit.SubItem.Text = comboBox.SelectedItem.ToString();
};
// Fill the ComboBox with the right values depending on the column
if (columnIndex == levelColumnIndex)
{
int minLevel = (hit.Item.Tag as Item)?.MinLevel ?? 1;
for (int i = minLevel; i <= 8; i++)
{
comboBox.Items.Add(i.ToString());
}
}
else if (columnIndex == enchantmentColumnIndex)
{
for (int i = 0; i <= 4; i++)
{
comboBox.Items.Add(i.ToString());
}
}
// Set selected value
comboBox.SelectedItem = hit.SubItem.Text;
controlToDisplay = comboBox;
}
if (controlToDisplay != null)
{
hit.Item.ListView.Parent.Controls.Add(controlToDisplay);
controlToDisplay.BringToFront();
controlToDisplay.Visible = true;
controlToDisplay.Focus();
}
}
}
|
41ab5af1ade40e81ba8474b02316a160
|
{
"intermediate": 0.33076441287994385,
"beginner": 0.492276132106781,
"expert": 0.17695945501327515
}
|
34,337
|
In this script, upstairs at his parents’ house, Dan agrees to let his younger cousin Jeannine (15, emo, bare feet) “hypnotize” him, expecting it to be five minutes of her embarrassing herself with cringey nonsense. In fact, Jeannine has been researching hypnosis in detail, and expertly and easily takes Dan deep into trance, fractionating him and giving him suggestions to enjoy the feeling of being hypnotized and want to be put under again in future.
|
b9de8641b25c4f44bae88b521482e8cf
|
{
"intermediate": 0.30410435795783997,
"beginner": 0.34471195936203003,
"expert": 0.35118368268013
}
|
34,338
|
i want a code in c language that recieve some numbers and it must count the Repetitious دعئذثقس
|
60d51d848d67c3335aa2ef73e093f34d
|
{
"intermediate": 0.3515194058418274,
"beginner": 0.2728673219680786,
"expert": 0.3756132423877716
}
|
34,339
|
i want a code in the c language that input some numbers and it count the Repetitious numbers
|
a4978adb2c91030982705d9b8f80f1d1
|
{
"intermediate": 0.3586333692073822,
"beginner": 0.15295268595218658,
"expert": 0.4884139597415924
}
|
34,340
|
what is attribute in python
|
1eebbb69f3baaea029ffa91496accb16
|
{
"intermediate": 0.3978482782840729,
"beginner": 0.16373102366924286,
"expert": 0.43842068314552307
}
|
34,341
|
private static void parseAndInitItems(String json, ItemType typeItem) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(json);
JSONObject jparser = (JSONObject)obj;
JSONArray jarray = (JSONArray)jparser.get("items");
for(int i = 0; i < jarray.size(); ++i) {
JSONObject item = (JSONObject)jarray.get(i);
LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en"));
LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en"));
String id = (String)item.get("id");
int priceM0 = item.get("price_m0") != null ? Integer.parseInt((String) item.get("price_m0")) : 0;
int priceM1 = item.get("price_m1") != null ? Integer.parseInt((String) item.get("price_m1")) : priceM0;
int priceM2 = item.get("price_m2") != null ? Integer.parseInt((String) item.get("price_m2")) : priceM0;
int priceM3 = item.get("price_m3") != null ? Integer.parseInt((String) item.get("price_m3")) : priceM0;
int rangM0 = item.get("rang_m0") != null ? Integer.parseInt((String) item.get("rang_m0")) : 0;
int rangM1 = item.get("rang_m1") != null ? Integer.parseInt((String) item.get("rang_m1")) : rangM0;
int rangM2 = item.get("rang_m2") != null ? Integer.parseInt((String) item.get("rang_m2")) : rangM0;
int rangM3 = item.get("rang_m3") != null ? Integer.parseInt((String) item.get("rang_m3")) : rangM0;
PropertyItem[] propertysItemM0 = null;
PropertyItem[] propertysItemM1 = null;
PropertyItem[] propertysItemM2 = null;
PropertyItem[] propertysItemM3 = null;
int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications"));
for (int m = 0; m < countModification; ++m) {
// Создаем объекты propertysItemM1, propertysItemM2 и propertysItemM3 только, если propertysItemM0 определен
if (item.get("propertys_m" + m) != null) {
JSONArray propertys = (JSONArray) item.get("propertys_m" + m);
PropertyItem[] property = new PropertyItem[propertys.size()];
// Создаем property для propertysItemM0
for (int p = 0; p < propertys.size(); ++p) {
JSONObject prop = (JSONObject) propertys.get(p);
property[p] = new PropertyItem(getType((String) prop.get("type")), (String) prop.get("value"));
}
switch (m) {
case 0:
propertysItemM0 = property;
break;
case 1:
propertysItemM1 = property;
break;
case 2:
propertysItemM2 = property;
break;
case 3:
propertysItemM3 = property;
}
}
}
if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) {
propertysItemM1 = propertysItemM0;
propertysItemM2 = propertysItemM0;
propertysItemM3 = propertysItemM0;
}
int discount = Integer.parseInt(item.get("discount").toString());
int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0)));
int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0;
int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0;
int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0;
ModificationInfo[] mods = new ModificationInfo[4];
mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0);
mods[0].propertys = propertysItemM0;
if (propertysItemM0 != null) {
mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1);
mods[1].propertys = propertysItemM1;
mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2);
mods[2].propertys = propertysItemM2;
mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3);
mods[3].propertys = propertysItemM3;
}
boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item");
boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted");
boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item");
items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted));
++index;
if (typeItem == ItemType.COLOR) {
ColormapsFactory.addColormap(id + "_m0", new Colormap() {
{
PropertyItem[] var5;
int var4 = (var5 = mods[0].propertys).length;
for(int var3 = 0; var3 < var4; ++var3) {
PropertyItem _property = var5[var3];
this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", "")));
}
}
});
}
}
} catch (ParseException var29) {
var29.printStackTrace();
}
} после добавление if (propertysItemM0 != null) { } ошибка java.lang.NullPointerException
at gtanks.json.JSONUtils.parseGarageUser(JSONUtils.java:423)
at gtanks.lobby.LobbyManager.sendGarage(LobbyManager.java:543)
at gtanks.lobby.LobbyManager.executeCommand(LobbyManager.java:148)
|
99773c7d1a1adcd4d7e683a1b4ef0378
|
{
"intermediate": 0.33952853083610535,
"beginner": 0.470329612493515,
"expert": 0.19014181196689606
}
|
34,342
|
package gtanks.users.garage;
import gtanks.battles.tanks.colormaps.Colormap;
import gtanks.battles.tanks.colormaps.ColormapsFactory;
import gtanks.system.localization.strings.LocalizedString;
import gtanks.system.localization.strings.StringsLocalizationBundle;
import gtanks.users.garage.enums.ItemType;
import gtanks.users.garage.enums.PropertyType;
import gtanks.users.garage.items.Item;
import gtanks.users.garage.items.PropertyItem;
import gtanks.users.garage.items.modification.ModificationInfo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class GarageItemsLoader {
public static HashMap<String, Item> items;
private static int index = 1;
public static void loadFromConfig(String turrets, String hulls, String colormaps, String inventory, String subscription) {
if (items == null) {
items = new HashMap();
}
for(int i = 0; i < 5; ++i) {
StringBuilder builder = new StringBuilder();
Throwable var7 = null;
Object var8 = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 3 ? colormaps : i == 2 ? hulls : i == 1 ? turrets : i == 0 ? inventory : subscription)), StandardCharsets.UTF_8));
String line;
try {
while((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
} catch (Throwable var18) {
if (var7 == null) {
var7 = var18;
} else if (var7 != var18) {
var7.addSuppressed(var18);
}
try {
throw var7;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
parseAndInitItems(builder.toString(), i == 3 ? ItemType.COLOR : i == 2 ? ItemType.ARMOR : i == 1 ? ItemType.WEAPON : i == 0 ? ItemType.INVENTORY : ItemType.PLUGIN);
}
}
public static void updateloadFromConfig(String turrets, String hulls, String colormaps, String subscription) {
if (items == null) {
items = new HashMap();
}
for (int i = 0; i < 4; ++i) {
StringBuilder builder = new StringBuilder();
Throwable var7 = null;
Object var8 = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(i == 2 ? colormaps : i == 1 ? hulls : i == 0 ? turrets : subscription)), StandardCharsets.UTF_8));
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
} catch (Throwable var18) {
if (var7 == null) {
var7 = var18;
} else if (var7 != var18) {
var7.addSuppressed(var18);
}
try {
throw var7;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
parseAndInitItems(builder.toString(), i == 2 ? ItemType.COLOR : i == 1 ? ItemType.ARMOR : i == 0 ? ItemType.WEAPON : ItemType.PLUGIN);
}
}
private static void parseAndInitItems(String json, ItemType typeItem) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(json);
JSONObject jparser = (JSONObject)obj;
JSONArray jarray = (JSONArray)jparser.get("items");
for(int i = 0; i < jarray.size(); ++i) {
JSONObject item = (JSONObject)jarray.get(i);
LocalizedString name = StringsLocalizationBundle.registerString((String)item.get("name_ru"), (String)item.get("name_en"));
LocalizedString description = StringsLocalizationBundle.registerString((String)item.get("description_ru"), (String)item.get("description_en"));
String id = (String)item.get("id");
int priceM0 = item.get("price_m0") != null ? Integer.parseInt((String) item.get("price_m0")) : 0;
int priceM1 = item.get("price_m1") != null ? Integer.parseInt((String) item.get("price_m1")) : priceM0;
int priceM2 = item.get("price_m2") != null ? Integer.parseInt((String) item.get("price_m2")) : priceM0;
int priceM3 = item.get("price_m3") != null ? Integer.parseInt((String) item.get("price_m3")) : priceM0;
int rangM0 = item.get("rang_m0") != null ? Integer.parseInt((String) item.get("rang_m0")) : 0;
int rangM1 = item.get("rang_m1") != null ? Integer.parseInt((String) item.get("rang_m1")) : rangM0;
int rangM2 = item.get("rang_m2") != null ? Integer.parseInt((String) item.get("rang_m2")) : rangM0;
int rangM3 = item.get("rang_m3") != null ? Integer.parseInt((String) item.get("rang_m3")) : rangM0;
PropertyItem[] propertysItemM0 = null;
PropertyItem[] propertysItemM1 = null;
PropertyItem[] propertysItemM2 = null;
PropertyItem[] propertysItemM3 = null;
int countModification = typeItem == ItemType.COLOR ? 1 : (typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN ? 4 : (int)(long)item.get("count_modifications"));
for (int m = 0; m < countModification; ++m) {
// Создаем объекты propertysItemM1, propertysItemM2 и propertysItemM3 только, если propertysItemM0 определен
if (item.get("propertys_m" + m) != null) {
JSONArray propertys = (JSONArray) item.get("propertys_m" + m);
PropertyItem[] property = new PropertyItem[propertys.size()];
// Создаем property для propertysItemM0
for (int p = 0; p < propertys.size(); ++p) {
JSONObject prop = (JSONObject) propertys.get(p);
property[p] = new PropertyItem(getType((String) prop.get("type")), (String) prop.get("value"));
}
switch (m) {
case 0:
propertysItemM0 = property;
break;
case 1:
propertysItemM1 = property;
break;
case 2:
propertysItemM2 = property;
break;
case 3:
propertysItemM3 = property;
}
}
}
if (typeItem == ItemType.COLOR || typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN) {
propertysItemM1 = propertysItemM0;
propertysItemM2 = propertysItemM0;
propertysItemM3 = propertysItemM0;
}
int discount = Integer.parseInt(item.get("discount").toString());
int discountedPriceM0 = (int) (priceM0 - (priceM0 * (discount / 100.0)));
int discountedPriceM1 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM1 - (priceM1 * (discount / 100.0))) : discountedPriceM0;
int discountedPriceM2 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM2 - (priceM2 * (discount / 100.0))) : discountedPriceM0;
int discountedPriceM3 = (typeItem != ItemType.COLOR && typeItem != ItemType.INVENTORY && typeItem != ItemType.PLUGIN) ? (int) (priceM3 - (priceM3 * (discount / 100.0))) : discountedPriceM0;
ModificationInfo[] mods = new ModificationInfo[4];
mods[0] = new ModificationInfo(id + "_m0", discountedPriceM0, rangM0);
mods[0].propertys = propertysItemM0;
mods[1] = new ModificationInfo(id + "_m1", discountedPriceM1, rangM1);
mods[1].propertys = propertysItemM1;
mods[2] = new ModificationInfo(id + "_m2", discountedPriceM2, rangM2);
mods[2].propertys = propertysItemM2;
mods[3] = new ModificationInfo(id + "_m3", discountedPriceM3, rangM3);
mods[3].propertys = propertysItemM3;
boolean specialItem = item.get("special_item") == null ? false : (Boolean)item.get("special_item");
boolean multicounted = item.get("multicounted") == null ? false : (Boolean)item.get("multicounted");
boolean addable = item.get("addable_item") == null ? false : (Boolean)item.get("addable_item");
items.put(id, new Item(id, description, typeItem == ItemType.INVENTORY || typeItem == ItemType.PLUGIN, index, propertysItemM0, typeItem, 0, name, propertysItemM1, discountedPriceM1, rangM1, discountedPriceM0, discount, rangM0, mods, specialItem, 0, addable, multicounted));
++index;
if (typeItem == ItemType.COLOR) {
ColormapsFactory.addColormap(id + "_m0", new Colormap() {
{
PropertyItem[] var5;
int var4 = (var5 = mods[0].propertys).length;
for(int var3 = 0; var3 < var4; ++var3) {
PropertyItem _property = var5[var3];
this.addResistance(ColormapsFactory.getResistanceType(_property.property), GarageItemsLoader.getInt(_property.value.replace("%", "")));
}
}
});
}
}
} catch (ParseException var29) {
var29.printStackTrace();
}
}
private static int getInt(String str) {
try {
return Integer.parseInt(str);
} catch (Exception var2) {
return 0;
}
}
private static PropertyType getType(String s) {
PropertyType[] var4;
int var3 = (var4 = PropertyType.values()).length;
for(int var2 = 0; var2 < var3; ++var2) {
PropertyType type = var4[var2];
if (type.toString().equals(s)) {
return type;
}
}
return null;
}
}
как сделать чтобы если у обекта указано только одна модификация м0 у него не показывались следующие модификации. а если у другого обекта указаны модификации м0,м1,м2 и м3 то показыются {
“name_ru”: “Мамонт”,
“name_en”: “Mammonth”,
“discount”: “16”,
“description_en”: “.”,
“description_ru”: “”,
“modification”: 0,
“id”: “mamont”,
“price_m0”: “750”,
“price_m1”: “2250”,
“price_m2”: “6800”,
“price_m3”: “20400”,
“rang_m0”:“12”,
“rang_m1”:“13”,
“rang_m2”:“14”,
“rang_m3”:“15”,
“propertys_m0”: [
{
“type”: “armor”,
“value”: “130”
},
{
“type”: “speed”,
“value”: “4.0”
},
{
“type”: “turn_speed”,
“value”: “80”
}
],
“propertys_m1”:[
{
“type”: “armor”,
“value”: “142”
},
{
“type”: “speed”,
“value”: “4.17”
},
{
“type”: “turn_speed”,
“value”: “83”
}
],
“propertys_m2”:[
{
“type”: “armor”,
“value”: “165”
},
{
“type”: “speed”,
“value”: “4.5”
},
{
“type”: “turn_speed”,
“value”: “90”
}
],
“propertys_m3”:[
{
“type”: “armor”,
“value”: “200”
},
{
“type”: “speed”,
“value”: “5.0”
},
{
“type”: “turn_speed”,
“value”: “100”
}
]
},
{
“name_ru”: “вффв”,
“name_en”: “вфвфв”,
“discount”: “16”,
“description_en”: “”,
“description_ru”: “”,
“modification”: 0,
“id”: “praetorian”,
“price_m0”: “750”,
“rang_m0”:“12”,
“propertys_m0”: [
{
“type”: “armor”,
“value”: “130”
},
{
“type”: “speed”,
“value”: “4.0”
},
{
“type”: “turn_speed”,
“value”: “80”
}
]
}
|
17d9662cfd27c187c03458d24887f4f4
|
{
"intermediate": 0.3236824870109558,
"beginner": 0.5912299752235413,
"expert": 0.08508753031492233
}
|
34,343
|
If you have ever played Genshin Impact, you must remember “Divine Ingenuity: Collector’s Chapter”
event. In this event, players can create custom domains by arranging components, including props
and traps, between the given starting point and exit point.
Paimon does not want to design a difficult domain; she pursues the ultimate “automatic map”. In
the given domain with a size of m × n, she only placed Airflow and Spikes. Specifically, Spikes will
eliminate the player (represented by ‘x’), while the Airflow will blow the player to the next position
according to the wind direction (up, left, down, right represented by ‘w’, ‘a’, ‘s’, ‘d’, respectively).
The starting point and exit point are denoted by ‘i’ and ‘j’, respectively. Ideally, in Paimon’s domain,
the player selects a direction and advances one position initially; afterward, the Airflow propels the
player to the endpoint without falling into the Spikes. The player will achieve automatic clearance in
such a domain.
However, Paimon, in her slight oversight, failed to create a domain that allows players to achieve
automatic clearance. Please assist Paimon by making the minimum adjustments to her design to
achieve automatic clearance.
Given that the positions of the starting point and exit point are fixed, you can only adjust components
at other locations. You have the option to remove existing component at any position; then, place a
new direction of Airflow, or position a Spikes.
1.2 Input
The first line of input contains two integers m and n, representing the size of the domain. m lines
follow, each containing n characters. The characters must be one of ‘w’, ‘a’, ‘s’, ‘d’, ‘x’, ‘i’ and ‘j’. It
is guaranteed that there is only one ‘i’ and ‘j’ on the map, and they are not adjacent.
1.3 Output
Output a single integer, representing the minimum number of changes needed.
Sample Input 1
3 3
dsi
ssd
jdd
Sample Output 1
1
|
75b3001b3686ffdfd5862e6ce99f5acf
|
{
"intermediate": 0.42121338844299316,
"beginner": 0.32834097743034363,
"expert": 0.2504456341266632
}
|
34,344
|
I have diffrent software running on diffrent urls, atlest thats the goal, i want to have one instance of wordpress runninong on for example blog.domain.com and annother diffrent instance on blog.domain.ee, then I want nginx running seperatelly on every other domain appart from the blog ones.
|
46d67b56cd86ed8ada91ad2f10eade76
|
{
"intermediate": 0.28200358152389526,
"beginner": 0.33757227659225464,
"expert": 0.3804241120815277
}
|
34,345
|
html code for playing acanoid game
|
f866edcd07101a1ad9b6369bd01a6ad0
|
{
"intermediate": 0.364869087934494,
"beginner": 0.35363855957984924,
"expert": 0.28149232268333435
}
|
34,346
|
Представь, что ты программист Fast API. У меня есть метод:
@router.post("/create-main-info", response_model=EmployeeMainInfo)
async def create_main_info(
employee_data: EmployeeMainInfo,
access_token: str = Depends(JWTBearer()),
db: AsyncSession = Depends(get_db_session)
) -> EmployeeMainInfo:
user = await get_employee_by_token(access_token, db)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
if employee_data.email is not None:
existing_employee = await db.execute(
select(Employee).where(Employee.email == employee_data.email)
)
existing_employee = existing_employee.scalar_one_or_none()
if existing_employee:
raise HTTPException(status_code=400,
detail="Email уже существует у другого сотрудника")
if employee_data.phone is not None:
existing_employee = await db.execute(
select(Employee).where(Employee.phone == employee_data.phone)
)
existing_employee = existing_employee.scalar_one_or_none()
if existing_employee:
raise HTTPException(status_code=400,
detail="Такой номер телефона уже существует у другого сотрудника")
employee_post_data = employee_data.dict()
employee = Employee(
**employee_post_data
)
db.add(employee)
await db.commit()
await db.refresh(employee)
employee_dict = employee.__dict__
return EmployeeMainInfo(**employee_dict)
он вызывает ошибку:
AttributeError: 'str' object has no attribute '_sa_instance_state'
|
bb1c7638fd6b2b9d5b9d354de875c1be
|
{
"intermediate": 0.6471956372261047,
"beginner": 0.25017452239990234,
"expert": 0.10262987017631531
}
|
34,347
|
I have table1:
SubNetwork EUtranFreqRelationId
Akmola_region 125
Akmola_region 150
Akmola_region 6200
Akmola_region 1302
Aktau 1302
Aktau 150
Aktau 6200
Aktau 1679
Aktau 1850
Aktau 500
Aktau 1652
Aktau 6250
And I need to check if all values from table 1 are in table 2 in corresponding SubNetwork for each EUtranCellFDDId table2
SubNetwork NodeId ENodeBFunctionId EUtranCellFDDId EUtranFreqRelationId
Akmola_region ERBS_12324_POLTAVKA_1_KK 1 12324A4L-2X2 125 #N/A
Akmola_region ERBS_12324_POLTAVKA_1_KK 1 12324A4L-2X2 150 #N/A
Akmola_region ERBS_12324_POLTAVKA_1_KK 1 12324A4L-2X2 6200 #N/A
Akmola_region ERBS_12324_POLTAVKA_1_KK 1 12324A4L-2X2 1302 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360A4L-2X2 6200 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360A4L-2X2 125 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360A4L-2X2 150 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360A4L-2X2 1302 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360B4L-2X2 125 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360B4L-2X2 1302 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360B4L-2X2 150 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360B4L-2X2 6200 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371A4L-2X2 125 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371A4L-2X2 6200 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371A4L-2X2 150 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371A4L-2X2 1302 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371B4L-2X2 125 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371B4L-2X2 6200 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371B4L-2X2 150 #N/A
Aktau ERBS_51020_DISTR7_2_KKT 1 51020C5T-2X2 1850
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A0L-2X2 1302
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A0L-2X2 150
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A0L-2X2 6200
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A1L-2X2 6200
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A1L-2X2 150
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A1L-2X2 1302
Aktau ERBS_51021_TREEOFLIFE_2_KKT 1 51021A4L-2X2 1302
Aktau ERBS_51021_TREEOFLIFE_2_KKT 1 51021A4L-2X2 150
Aktau ERBS_51021_TREEOFLIFE_2_KKT 1 51021A4L-2X2 6200
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021B0L-2X2 1302
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021B0L-2X2 6200
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021B0L-2X2 150
|
8e651ed038a74626c2e69b166cb620d1
|
{
"intermediate": 0.3267454504966736,
"beginner": 0.35248374938964844,
"expert": 0.320770800113678
}
|
34,348
|
I have table1:
SubNetwork EUtranFreqRelationId
Akmola_region 125
Akmola_region 150
Akmola_region 6200
Akmola_region 1302
Aktau 1302
Aktau 150
Aktau 6200
Aktau 1679
Aktau 1850
Aktau 500
Aktau 1652
Aktau 6250
And I need to see which values from table 1 EUtranFreqRelationId are not in table 2 in corresponding SubNetwork for each EUtranCellFDDId table2
SubNetwork NodeId ENodeBFunctionId EUtranCellFDDId EUtranFreqRelationId
Akmola_region ERBS_12324_POLTAVKA_1_KK 1 12324A4L-2X2 125 #N/A
Akmola_region ERBS_12324_POLTAVKA_1_KK 1 12324A4L-2X2 150 #N/A
Akmola_region ERBS_12324_POLTAVKA_1_KK 1 12324A4L-2X2 6200 #N/A
Akmola_region ERBS_12324_POLTAVKA_1_KK 1 12324A4L-2X2 1302 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360A4L-2X2 6200 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360A4L-2X2 125 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360A4L-2X2 150 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360A4L-2X2 1302 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360B4L-2X2 125 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360B4L-2X2 1302 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360B4L-2X2 150 #N/A
Akmola_region ERBS_12360_SHUISKOE_1_KK 1 12360B4L-2X2 6200 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371A4L-2X2 125 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371A4L-2X2 6200 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371A4L-2X2 150 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371A4L-2X2 1302 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371B4L-2X2 125 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371B4L-2X2 6200 #N/A
Akmola_region ERBS_12371_BESTOGAY_1_KK 1 12371B4L-2X2 150 #N/A
Aktau ERBS_51020_DISTR7_2_KKT 1 51020C5T-2X2 1850
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A0L-2X2 1302
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A0L-2X2 150
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A0L-2X2 6200
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A1L-2X2 6200
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A1L-2X2 150
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021A1L-2X2 1302
Aktau ERBS_51021_TREEOFLIFE_2_KKT 1 51021A4L-2X2 1302
Aktau ERBS_51021_TREEOFLIFE_2_KKT 1 51021A4L-2X2 150
Aktau ERBS_51021_TREEOFLIFE_2_KKT 1 51021A4L-2X2 6200
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021B0L-2X2 1302
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021B0L-2X2 6200
Aktau ERBS_51021_TREEOFLIFE_1_KKT 1 51021B0L-2X2 150
|
b933f7429808d362cd7674823ce21de1
|
{
"intermediate": 0.32509395480155945,
"beginner": 0.37139439582824707,
"expert": 0.3035116493701935
}
|
34,349
|
I want to do this with librewolf:
insert the DWORD "RendererCodeIntegrityEnabled" with a value of 0 into
HKLM\Software\Policies\Chromium, for Chromium
HKLM\Software\Policies\Google\Chrome, for Chrome
HKLM\Software\Policies\BraveSoftware\Brave, for Brave
HKLM\Software\Policies\Microsoft\Edge, for new Edge
how do i do it?
|
e4f22e6674769818ea9df94210b439a2
|
{
"intermediate": 0.8308066129684448,
"beginner": 0.09222105890512466,
"expert": 0.07697229087352753
}
|
34,350
|
my inventory.yml in ansible is this:
host-servers:
- hostname: server1
ansible_host: 192.168.56.140
ansible_user=oracle
ansible_ssh_pass=123
admin_username: weblogic
admin_password: Welcome1
domain: "adf_domain"
admin_port: 7001
node_manager_port: 5556
- hostname: server2
ansible_host: 172.17.9.12
ansible_user=oracle
ansible_ssh_private_key_file=~/.ssh/my_private_key
asnible_ssh_pass=oZevlAmCsy2e7Aa7hhpxjXVUceAWKoo434JiCgMgVvQ=
admin_username: weblogic
admin_password: ManageR1
domain: "adf_domain"
admin_port: 7001
node_manager_port: 5556
|
751ee8926415486aac51f23192cd4584
|
{
"intermediate": 0.3198530077934265,
"beginner": 0.3257058560848236,
"expert": 0.3544411063194275
}
|
34,351
|
generate text "LINES" with visible pixels
|
54f6b62f81b71458d9af5aec41f63100
|
{
"intermediate": 0.29595452547073364,
"beginner": 0.21886314451694489,
"expert": 0.48518237471580505
}
|
34,352
|
Hi there GPT-3.5. I was wondering if you could tell me how to use ChatGPT to analyse data?
|
e1e0bee601e2a547366a1b7bfb6106a1
|
{
"intermediate": 0.574228823184967,
"beginner": 0.14919282495975494,
"expert": 0.2765783965587616
}
|
34,353
|
i want to make this admin_url: "t3://{{ ansible_host }}:{{ admin_port }}" in defaults folder main.yml and my inventory is :
all:
children:
host_servers:
hosts:
server1:
ansible_host: 192.168.56.140
ansible_user: oracle
ansible_ssh_pass: “123”
admin_username: weblogic
admin_password: Welcome1
domain: “adf_domain”
admin_port: 7001
node_manager_port: 5556
server2:
ansible_host: 172.17.9.12
ansible_user: oracle
ansible_ssh_private_key_file: “~/.ssh/my_private_key”
ansible_ssh_pass: “oZevlAmCsy2e7Aa7hhpxjXVUceAWKoo434JiCgMgVvQ=”
admin_username: weblogic
admin_password: ManageR1
domain: “adf_domain”
admin_port: 7001
node_manager_port: 5556
|
b541d68f5cddca0bb1bcd1ec2c019f46
|
{
"intermediate": 0.30450132489204407,
"beginner": 0.33853214979171753,
"expert": 0.3569665849208832
}
|
34,354
|
package gtanks.battles.chat;
import gtanks.StringUtils;
import gtanks.battles.BattlefieldModel;
import gtanks.battles.BattlefieldPlayerController;
import gtanks.battles.bonuses.BonusType;
import gtanks.commands.Type;
import gtanks.json.JSONUtils;
import gtanks.lobby.LobbyManager;
import gtanks.main.database.DatabaseManager;
import gtanks.main.database.impl.DatabaseManagerImpl;
import gtanks.main.params.OnlineStats;
import gtanks.services.BanServices;
import gtanks.services.LobbysServices;
import gtanks.services.TanksServices;
import gtanks.services.annotations.ServicesInject;
import gtanks.services.ban.BanChatCommads;
import gtanks.services.ban.BanTimeType;
import gtanks.services.ban.BanType;
import gtanks.services.ban.DateFormater;
import gtanks.services.ban.block.BlockGameReason;
import gtanks.users.TypeUser;
import gtanks.users.User;
import gtanks.users.karma.Karma;
import java.util.Date;
public class BattlefieldChatModel {
private BattlefieldModel bfModel;
private final int MAX_WARNING = 5;
@ServicesInject(
target = TanksServices.class
)
private TanksServices tanksServices = TanksServices.getInstance();
@ServicesInject(
target = DatabaseManager.class
)
private DatabaseManager database = DatabaseManagerImpl.instance();
@ServicesInject(
target = LobbysServices.class
)
private LobbysServices lobbyServices = LobbysServices.getInstance();
@ServicesInject(
target = BanServices.class
)
private BanServices banServices = BanServices.getInstance();
public BattlefieldChatModel(BattlefieldModel bfModel) {
this.bfModel = bfModel;
}
public void onMessage(BattlefieldPlayerController player, String message, boolean team) {
if (!(message = message.trim()).isEmpty()) {
Karma karma = this.database.getKarmaByUser(player.getUser());
if (karma.isChatBanned()) {
long currDate = System.currentTimeMillis();
Date banTo = karma.getChatBannedBefore();
long delta = currDate - banTo.getTime();
if (delta <= 0L) {
player.parentLobby.send(Type.LOBBY_CHAT, "system", StringUtils.concatStrings("Вы отключены от чата. Вы вернётесь в ЭФИР через ", DateFormater.formatTimeToUnban(delta), ". Причина: " + karma.getReasonChatBan()));
return;
}
this.banServices.unbanChat(player.getUser());
}
if (!this.bfModel.battleInfo.team) {
team = false;
}
String reason;
if (message.startsWith("/")) {
if (player.getUser().getType() == TypeUser.DEFAULT) {
return;
}
String[] arguments = message.replace('/', ' ').trim().split(" ");
if (!player.getUser().getUserGroup().isAvaliableChatCommand(arguments[0])) {
return;
}
User victim_;
label188: {
int i;
switch((reason = arguments[0]).hashCode()) {
case -1422509655:
if (reason.equals("addcry")) {
this.tanksServices.addCrystall(player.parentLobby, this.getInt(arguments[1]));
break label188;
}
break;
case -1217854831:
if (reason.equals("addscore")) {
i = this.getInt(arguments[1]);
if (player.parentLobby.getLocalUser().getScore() + i < 0) {
this.sendSystemMessage("[SERVER]: Ваше количество очков опыта не должно быть отрицательное!", player);
} else {
this.tanksServices.addScore(player.parentLobby, i);
}
break label188;
}
break;
case -1012222381:
if (reason.equals("online")) {
this.sendSystemMessage("Current online: " + OnlineStats.getOnline() + "\nMax online: " + OnlineStats.getMaxOnline(), player);
break label188;
}
break;
case -887328209:
if (reason.equals("system")) {
StringBuffer total = new StringBuffer();
for(i = 1; i < arguments.length; ++i) {
total.append(arguments[i]).append(" ");
}
this.sendSystemMessage(total.toString());
break label188;
}
break;
case -372425125:
if (reason.equals("spawngold")) {
i = 0;
while(true) {
if (i >= Integer.parseInt(arguments[1])) {
break label188;
}
this.bfModel.bonusesSpawnService.spawnBonus(BonusType.GOLD);
++i;
}
}
break;
case 119:
if (reason.equals("w")) {
if (arguments.length < 3) {
return;
}
User giver = this.database.getUserById(arguments[1]);
if (giver == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
String reason1 = StringUtils.concatMassive(arguments, 2);
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", giver.getNickname(), " предупрежден. Причина: ", reason1));
}
break label188;
}
break;
case 3291718:
if (reason.equals("kick")) {
User _userForKick = this.database.getUserById(arguments[1]);
if (_userForKick == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден", player);
} else {
LobbyManager _lobby = this.lobbyServices.getLobbyByUser(_userForKick);
if (_lobby != null) {
_lobby.kick();
this.sendSystemMessage(_userForKick.getNickname() + " кикнут");
}
}
break label188;
}
break;
case 98246397:
if (reason.equals("getip")) {
if (arguments.length >= 2) {
User shower = this.database.getUserById(arguments[1]);
if (shower == null) {
return;
}
String ip = shower.getAntiCheatData().ip;
if (ip == null) {
ip = shower.getLastIP();
}
this.sendSystemMessage("IP user " + shower.getNickname() + " : " + ip, player);
}
break label188;
}
break;
case 111426262:
if (reason.equals("unban")) {
if (arguments.length >= 2) {
User cu = this.database.getUserById(arguments[1]);
if (cu == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
this.banServices.unbanChat(cu);
this.sendSystemMessage("Танкисту " + cu.getNickname() + " был разрешён выход в эфир");
}
}
break label188;
}
break;
case 873005567:
if (reason.equals("blockgame")) {
if (arguments.length < 3) {
return;
}
victim_ = this.database.getUserById(arguments[1]);
boolean var10 = false;
int reasonId;
try {
reasonId = Integer.parseInt(arguments[2]);
} catch (Exception var20) {
reasonId = 0;
}
if (victim_ == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
this.banServices.ban(BanType.GAME, BanTimeType.FOREVER, victim_, player.getUser(), BlockGameReason.getReasonById(reasonId).getReason());
LobbyManager lobby = this.lobbyServices.getLobbyByNick(victim_.getNickname());
if (lobby != null) {
lobby.kick();
}
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", victim_.getNickname(), " был заблокирован и кикнут"));
}
break label188;
}
break;
case 941444998:
if (reason.equals("unblockgame")) {
if (arguments.length < 2) {
return;
}
User av = this.database.getUserById(arguments[1]);
if (av == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
this.banServices.unblock(av);
this.sendSystemMessage(av.getNickname() + " разблокирован");
}
break label188;
}
break;
case 2066192527:
if (reason.equals("spawncry")) {
i = 0;
while(true) {
if (i >= Integer.parseInt(arguments[1])) {
break label188;
}
this.bfModel.bonusesSpawnService.spawnBonus(BonusType.CRYSTALL);
++i;
}
}
}
if (!message.startsWith("/ban")) {
this.sendSystemMessage("[SERVER]: Неизвестная команда!", player);
}
}
if (message.startsWith("/ban")) {
BanTimeType time = BanChatCommads.getTimeType(arguments[0]);
if (arguments.length < 3) {
return;
}
String reason2 = StringUtils.concatMassive(arguments, 2);
if (time == null) {
this.sendSystemMessage("[SERVER]: Команда бана не найдена!", player);
return;
}
victim_ = this.database.getUserById(arguments[1]);
if (victim_ == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
return;
}
this.banServices.ban(BanType.CHAT, time, victim_, player.getUser(), reason2);
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", victim_.getNickname(), " лишен права выхода в эфир ", time.getNameType(), " Причина: ", reason2));
}
} else {
if (message.length() >= 399) {
message = null;
return;
}
if (player.getUser().getRang() + 1 >= 3 || player.getUser().getType() != TypeUser.DEFAULT) {
if (!player.parentLobby.getChatFloodController().detected(message)) {
player.parentLobby.timer = System.currentTimeMillis();
if (team) {
// Отправить сообщение только участникам команды
bfModel.sendMessageToTeam(new BattleChatMessage(player.getUser().getNickname(), player.getUser().getRang(), message, player.playerTeamType, true, false), player.playerTeamType);
} else {
// Отправить сообщение всем игрокам
bfModel.sendMessageToAll(new BattleChatMessage(player.getUser().getNickname(), player.getUser().getRang(), message, player.playerTeamType, false, false));
}
} else {
if (player.getUser().getWarnings() >= 5) {
BanTimeType time = BanTimeType.FIVE_MINUTES;
reason = "Флуд.";
this.banServices.ban(BanType.CHAT, time, player.getUser(), player.getUser(), reason);
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", player.getUser().getNickname(), " лишен права выхода в эфир ", time.getNameType(), " Причина: ", reason));
return;
}
this.sendSystemMessage("Танкист " + player.getUser().getNickname() + " предупрежден. Причина: Флуд.");
player.getUser().addWarning();
}
} else {
this.sendSystemMessage("Чат доступен, начиная со звания Ефрейтор.", player);
}
}
}
}
public void sendSystemMessage(String message) {
if (message == null) {
message = " ";
}
this.sendMessage(new BattleChatMessage((String)null, 0, message, "NONE", false, true));
}
public void sendSystemMessage(String message, BattlefieldPlayerController player) {
if (message == null) {
message = " ";
}
this.sendMessage(new BattleChatMessage((String)null, 0, message, "NONE", false, true), player);
}
private void sendMessage(BattleChatMessage msg) {
this.bfModel.sendToAllPlayers(Type.BATTLE, "chat", JSONUtils.parseBattleChatMessage(msg));
}
private void sendMessage(BattleChatMessage msg, BattlefieldPlayerController controller) {
controller.send(Type.BATTLE, "chat", JSONUtils.parseBattleChatMessage(msg));
}
public int getInt(String src) {
try {
return Integer.parseInt(src);
} catch (Exception var3) {
return Integer.MAX_VALUE;
}
}
}
как сюда добавить анти-мат фильтр
|
73805f96f3dc01c90d9bea043c89ec88
|
{
"intermediate": 0.3404594957828522,
"beginner": 0.4661233425140381,
"expert": 0.19341707229614258
}
|
34,355
|
Скрипт не работает. Белый экран показывет
<!doctype html>
<html>
<head>
<meta charset="utf8" />
<title>Бесконечный скроллинг с добавлением картинки</title>
</head>
<body>
<div id="infinite-scroll">
<div>
<!-- Место для вашего начального контента -->
</div>
</div>
<script>
window.addEventListener("scroll", function() {
var block = document.getElementById('infinite-scroll');
var contentHeight = block.offsetHeight; // 1) высота блока контента вместе с границами
var yOffset = window.pageYOffset; // 2) текущее положение скролбара
var window_height = window.innerHeight; // 3) высота внутренней области окна документа
var y = yOffset + window_height;
// если пользователь достиг конца
if (y >= contentHeight) {
// создаем новый элемент div
var newDiv = document.createElement("div");
// загружаем в него HTML с картинкой
newDiv.innerHTML = '<img src="https://e7.pngegg.com/pngimages/957/650/png-clipart-christmas-tree-christmas-tree-leaf-holidays.png">';
// добавляем этот div в конец блока infinite-scroll
block.appendChild(newDiv);
}
});
</script>
</body>
</html>
|
9446dcfbd36f49fc04fb408e998d5e3a
|
{
"intermediate": 0.31444740295410156,
"beginner": 0.46150872111320496,
"expert": 0.2240438014268875
}
|
34,356
|
Как добавлять картинку при дохождения до конца страницы?
Нужно добавлять картинку каждый раз, когда дохожу до конца строки. Есть такой код, который добавляет текст бексконечно, как его переписать для картинки? Я новичок в этом
<!doctype html>
<html>
<head>
<img src=" https://e7.pngegg.com/pngimages/957/650/png-clipart-christmas-tree-christmas-tree-leaf-holidays.png ">
<meta charset="utf8" />
<title>Бесконечный скроллинг с JavaScript</title>
</head>
<body>
<div id="infinite-scroll">
<div>
<script>
for( let i = 0; i < 100; i++ )
document.write("<div>Случайный текст или еще, что то</div>");
</script>
</div>
</div>
<script>
window.addEventListener("scroll", function(){
var block = document.getElementById('infinite-scroll');
var counter = 1;
var contentHeight = block.offsetHeight; // 1) высота блока контента вместе с границами
var yOffset = window.pageYOffset; // 2) текущее положение скролбара
var window_height = window.innerHeight; // 3) высота внутренней области окна документа
var y = yOffset + window_height;
// если пользователь достиг конца
if(y >= contentHeight)
{
//<img src=" https://e7.pngegg.com/pngimages/957/650/png-clipart-christmas-tree-christmas-tree-leaf-holidays.png ">
//загружаем новое содержимое в элемент
block.innerHTML = block.innerHTML + "<div>Случайный текст или еще, что то</div>";
}
});
</script>
</body>
</html>
|
1b7b7cd983755913194322f8dab93fbe
|
{
"intermediate": 0.21814563870429993,
"beginner": 0.5774338245391846,
"expert": 0.2044205367565155
}
|
34,357
|
Представь, что ты программист Fast API. У меня есть модель:
class Employee(Base):
__tablename__ = "employees"
"""System info"""
id = Column(Integer, primary_key=True, index=True)
is_active = Column(Boolean, default=False, nullable=False, comment="Статус")
is_owner = Column(Boolean, default=True, nullable=False, comment="Владелец компании")
role = Column(String, nullable=False, default='CA', comment="Роль сотрудника")
hashed_password = Column(String, nullable=True, comment="Пароль")
email_change_token = Column(String, nullable=True, comment="Token смены email")
email_change_token_created_at = Column(DateTime(timezone=True), nullable=True, comment="Дата создания токена смены email")
email_change_token_new_email = Column(EmailType, unique=True, nullable=True, comment="Новый Email")
phone_change_code = Column(String(6), nullable=True, comment="Код смены телефона")
phone_change_code_created_at = Column(DateTime(timezone=True), nullable=True, comment="Дата создания кода смены телефона")
new_phone = Column(String, nullable=True, comment="Новый телефон")
"""Основная информация"""
first_name = Column(String, nullable=True, comment="Имя")
last_name = Column(String, nullable=True, comment="Фамилия")
patronymic = Column(String, nullable=True, comment="Отчество")
email = Column(EmailType, unique=True, index=True, nullable=True, comment="Email")
email_is_missing = Column(Boolean, nullable=True, comment="Отсутствие Email-a")
send_invitation = Column(Boolean, nullable=True, comment="Пригласить сотрудника")
phone = Column(String, unique=True, index=True, nullable=True, comment="Телефон")
position_enbek = Column(String, nullable=True, comment="Должность в Enbek")
department = Column(String, nullable=True, comment="Отдел")
supervisor_id = Column(Integer, ForeignKey('employees.id'), nullable=True, comment="Идентификатор руководителя")
supervisor = relationship("Employee", remote_side=[id], backref="subordinates")
inn = Column(String, nullable=True, comment="ИНН")
"""Рабочие данные"""
position_hrm = Column(String, nullable=True, comment="Должность HRM")
start_date = Column(DateTime(timezone=True), nullable=True, comment="Дата начала работы")
contract_number = Column(String, nullable=True, comment="Номер договора")
contract_term = Column(String, nullable=True, comment="Срок действия договора")
contract_date_of_signing = Column(Date, nullable=True, comment="Дата подписания договора")
contract_date_expiration = Column(Date, nullable=True, comment="Дата окончания договора")
contract_type = Column(String, nullable=True, comment="Вид договора")
probation = Column(Integer, nullable=True, comment="Испытательный срок")
type_of_work = Column(String, nullable=True, comment="Вид работы")
form_of_employment = Column(String, nullable=True, comment="Форма занятости")
working_hours = Column(String, nullable=True, comment="Режим рабочего времени")
work_schedule = Column(String, nullable=True, comment="Рабочий график")
tariff_rate = Column(Float, nullable=True, comment="Тарифная ставка")
work_address = Column(String, nullable=True, comment="Адрес места работы")
type_of_calculation = Column(String, nullable=True, comment="Вид расчета")
salary = Column(Integer, nullable=True, comment="Оклад")
allowances = relationship(Allowance, back_populates="employee", cascade="all, delete-orphan")
unique_employee_number = Column(Integer, nullable=True, comment="Уникальный номер сотрудника")
is_pensioner = Column(Boolean, default=False, nullable=True, comment="Пенсионер")
bank_requisites = relationship(BankRequisites, back_populates="employee", uselist=False)
employment_contract_file = Column(String, nullable=True, comment="Файл трудового договора")
"""Персональные данные"""
birth_date = Column(Date, nullable=True, comment="Дата рождения")
gender = Column(String, nullable=True, comment="Пол")
identification_documents = relationship(IdentificationDocument, back_populates="employee", cascade="all, delete-orphan")
nationality = Column(String, nullable=True, comment="Национальность")
citizenship = Column(String, nullable=True, comment="Гражданство")
birth_place = relationship(BirthPlace, back_populates="employee", uselist=False)
registration_address = relationship(RegistrationAddress, back_populates="employee", uselist=False)
family_data = relationship(FamilyData, back_populates="employee", uselist=False)
military_registration = relationship(MilitaryRegistration, back_populates="employee", uselist=False)
photo = Column(String, nullable=True, comment="Фото")
"""Профессиональные данные"""
education = relationship(Education, back_populates="employee", cascade="all, delete-orphan")
courses = relationship(Courses, back_populates="employee", cascade="all, delete-orphan")
language_proficiency = relationship(LanguageProficiency, back_populates="employee", cascade="all, delete-orphan")
work_experiences = relationship(WorkExperience, back_populates="employee", cascade="all, delete-orphan")
professional_skills = Column(String, nullable=True, comment="Профессиональные навыки")
personal_qualities = Column(String, nullable=True, comment="Личные качества")
"""Контактные данные"""
contact_phone = Column(String, unique=True, nullable=True, comment="Телефон")
contact_email = Column(EmailType, unique=True, index=True, nullable=True, comment="Email")
is_matches_registration_address = Column(Boolean, nullable=True, comment="Адрес проживания")
residential_address = relationship(ResidentialAddress, back_populates="employee", uselist=False)
emergency_contact_name = Column(String, nullable=True, comment="Контакт на ЧС, имя")
emergency_contact_phone = Column(String, nullable=True, comment="Телефон контакта на ЧС")
"""Компания"""
company_id = Column(Integer, ForeignKey('companies.id'))
company = relationship(Company, back_populates="employees")
metadata = meta
def __repr__(self):
return f"<User(id={self.id}, email='{self.email}')>"
и метод создания этой модели. Как мне шифровать все данные этой модели в базе данных при создании? база данных Postgresql.
|
2553f0bc645e9a921bbf8238b9aa49f0
|
{
"intermediate": 0.28260594606399536,
"beginner": 0.6091161370277405,
"expert": 0.10827790200710297
}
|
34,358
|
Представь, что ты программист Fast API.
Вот мой метод создания сотрудника:
@router.post(“/create-main-info”, response_model=EmployeeMainInfo)
async def create_main_info(
employee_data: EmployeeMainInfo,
access_token: str = Depends(JWTBearer()),
db: AsyncSession = Depends(get_db_session)
) -> EmployeeMainInfo:
user = await get_employee_by_token(access_token, db)
if user is None:
raise HTTPException(status_code=404, detail=“User not found”)
if employee_data.email is not None:
existing_employee = await db.execute(
select(Employee).where(Employee.email == employee_data.email)
)
existing_employee = existing_employee.scalar_one_or_none()
if existing_employee:
raise HTTPException(status_code=400,
detail=“Email уже существует у другого сотрудника”)
if employee_data.phone is not None:
existing_employee = await db.execute(
select(Employee).where(Employee.phone == employee_data.phone)
)
existing_employee = existing_employee.scalar_one_or_none()
if existing_employee:
raise HTTPException(status_code=400,
detail=“Такой номер телефона уже существует у другого сотрудника”)
if employee_data.supervisor_id is not None:
existing_supervisor = await db.execute(
select(Employee).where(Employee.id == employee_data.supervisor_id)
)
existing_supervisor = existing_supervisor.scalar_one_or_none()
if existing_supervisor is None:
raise HTTPException(
status_code=400,
detail=“Такого id руководителя не существует”
)
employee_post_data = employee_data.dict(exclude_unset=True)
employee_post_data[“is_owner”] = False
employee = Employee(
**employee_post_data
)
db.add(employee)
await db.commit()
await db.refresh(employee)
# Отправляем электронное письмо с подтверждением регистрации
token = generate_token(employee.id)
await send_confirmation_email(employee.email, token)
employee_dict = employee.dict
return EmployeeMainInfo(**employee_dict)
как мне внедрить в него шифрование, чтоб шифровались все поля?
|
030f20206db90f2719d86a6e34969765
|
{
"intermediate": 0.46047306060791016,
"beginner": 0.3744165003299713,
"expert": 0.16511042416095734
}
|
34,359
|
FIX BUGS AND RETURN FIXED CODE "ALL LINES OF THE CODE SHOULD BE PRESENT": import sys
import torch
import torch.nn as nn
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QMessageBox, QFileDialog
from transformers import BertTokenizer, GPT2Tokenizer, XLNetTokenizer
import pandas as pd
import torch.optim as optim
# Define the neural network model.
class RNNModel(nn.Module):
def __init__(self, input_size, hidden_sizes, layer_types):
super(RNNModel, self).__init__()
self.layers = nn.ModuleList()
for i, layer_type in enumerate(layer_types):
input_dim = input_size if i == 0 else hidden_sizes[i - 1]
if layer_type == 'LSTM':
self.layers.append(nn.LSTM(input_dim, hidden_sizes[i], batch_first=True))
elif layer_type == 'GRU':
self.layers.append(nn.GRU(input_dim, hidden_sizes[i], batch_first=True))
elif layer_type == 'Transformer':
transformer_layer = nn.TransformerEncoderLayer(d_model=input_dim, nhead=1)
self.layers.append(nn.TransformerEncoder(transformer_layer, num_layers=1))
else:
raise ValueError(f"Unrecognized layer type: {layer_type}")
def forward(self, x):
for layer in self.layers:
if isinstance(layer, nn.TransformerEncoder):
x = layer(x)
else:
x, _ = layer(x)
return x
# Define the custom GUI widget for configuring the language model.
class LanguageModelConfigurator(QtWidgets.QWidget):
def __init__(self):
super(LanguageModelConfigurator, self).__init__()
self.model = None
self.train_data_loader = None
self.data_filepath = None
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Language Model Configuration')
self.seq_length_spinbox = QtWidgets.QSpinBox()
self.seq_length_spinbox.setMinimum(1)
self.seq_length_spinbox.setMaximum(512)
self.seq_length_spinbox.setValue(128)
vbox = QtWidgets.QVBoxLayout(self)
seq_length_layout = QtWidgets.QHBoxLayout()
seq_length_label = QtWidgets.QLabel("Sequence Length:", self)
seq_length_layout.addWidget(seq_length_label)
seq_length_layout.addWidget(self.seq_length_spinbox)
vbox.addLayout(seq_length_layout)
layer_config_group = QtWidgets.QGroupBox("Layer Configuration")
layer_config_layout = QtWidgets.QVBoxLayout(layer_config_group)
self.layer_list_widget = QtWidgets.QListWidget()
layer_config_layout.addWidget(self.layer_list_widget)
hbox_layers = QtWidgets.QHBoxLayout()
self.layer_type_combo = QtWidgets.QComboBox()
self.layer_type_combo.addItems(['LSTM', 'GRU', 'Transformer'])
self.layer_size_spinbox = QtWidgets.QSpinBox()
self.layer_size_spinbox.setMinimum(1)
self.layer_size_spinbox.setMaximum(1024)
hbox_layers.addWidget(self.layer_type_combo)
hbox_layers.addWidget(self.layer_size_spinbox)
add_layer_button = QtWidgets.QPushButton('Add Layer')
add_layer_button.clicked.connect(self.add_layer)
hbox_layers.addWidget(add_layer_button)
layer_config_layout.addLayout(hbox_layers)
vbox.addWidget(layer_config_group)
tokenizer_config_group = QtWidgets.QGroupBox("Tokenizer Configuration")
tokenizer_config_layout = QtWidgets.QVBoxLayout(tokenizer_config_group)
tokenizer_label = QtWidgets.QLabel('Choose a tokenizer:', self)
tokenizer_config_layout.addWidget(tokenizer_label)
self.tokenizer_combo = QtWidgets.QComboBox()
self.tokenizer_combo.addItems([
'bert-base-cased',
'gpt2-medium',
'xlnet-base-cased'
])
tokenizer_config_layout.addWidget(self.tokenizer_combo)
self.status_label = QtWidgets.QLabel("")
vbox.addWidget(tokenizer_config_group)
vbox.addWidget(self.status_label)
submit_button = QtWidgets.QPushButton('Generate Model', self)
submit_button.clicked.connect(self.generate_model)
vbox.addWidget(submit_button)
self.setLayout(vbox)
self.setStyleSheet("""
QWidget {
font-size: 14px;
}
QPushButton {
background-color: #007BFF;
border-style: none;
padding: 6px 12px;
color: white;
border-radius: 4px;
}
QPushButton:hover {
background-color: #0056b3;
}
QLabel {
padding-bottom: 4px;
}
""")
# Data file line edit and browse button
self.data_file_line_edit = QtWidgets.QLineEdit(self)
browse_button = QtWidgets.QPushButton('Browse Data File', self)
browse_button.clicked.connect(self.browse_data_file)
data_file_layout = QtWidgets.QHBoxLayout()
data_file_layout.addWidget(self.data_file_line_edit)
data_file_layout.addWidget(browse_button)
vbox.addLayout(data_file_layout)
# Epochs spinbox
num_epochs_layout = QtWidgets.QHBoxLayout()
num_epochs_label = QtWidgets.QLabel("Number of Epochs:", self)
self.num_epochs_spinbox = QtWidgets.QSpinBox()
self.num_epochs_spinbox.setMinimum(1)
self.num_epochs_spinbox.setMaximum(100)
num_epochs_layout.addWidget(num_epochs_label)
num_epochs_layout.addWidget(self.num_epochs_spinbox)
vbox.addLayout(num_epochs_layout)
# Training button layout
training_layout = QtWidgets.QHBoxLayout()
self.train_button = QtWidgets.QPushButton('Train Model', self)
self.train_button.clicked.connect(self.on_train_click)
training_layout.addWidget(self.train_button)
vbox.addLayout(training_layout)
def browse_data_file(self):
filepath, _ = QFileDialog.getOpenFileName(self, "Open Data File", "", "Data Files (*.csv *.txt)")
if filepath:
self.data_file_line_edit.setText(filepath)
self.data_filepath = filepath
def load_data(self):
if self.data_filepath:
try:
if self.data_filepath.endswith(".csv"):
data_df = pd.read_csv(self.data_filepath)
return data_df
elif self.data_filepath.endswith(".txt"):
with open(self.data_filepath, "r", encoding="utf-8") as file:
text_data = file.read()
return text_data
else:
self.showMessage("Error", "Unsupported file type selected.")
return None
except Exception as e:
self.showMessage("Error", f"Failed to load data: {e}")
else:
self.showMessage("Error", "No data file selected.")
def create_data_loader(self, data):
if isinstance(data, pd.DataFrame):
# Convert DataFrame to tensors
inputs = torch.tensor(data['input'].values)
labels = torch.tensor(data['label'].values)
dataset = torch.utils.data.TensorDataset(inputs, labels)
elif isinstance(data, str):
# Tokenize text data and convert to tensors
tokenizer_name = self.tokenizer_combo.currentText()
tokenizer_class = {
'bert-base-cased': BertTokenizer,
'gpt2-medium': GPT2Tokenizer,
'xlnet-base-cased': XLNetTokenizer
}.get(tokenizer_name)
tokenizer = tokenizer_class.from_pretrained(tokenizer_name)
encoded_data = tokenizer.encode_plus(
data,
add_special_tokens=True,
padding='max_length',
truncation=True,
max_length=self.seq_length_spinbox.value(),
return_tensors='pt'
)
inputs = encoded_data['input_ids']
labels = encoded_data['input_ids'] # Just for demonstration, replace with actual labels
dataset = torch.utils.data.TensorDataset(inputs, labels)
else:
self.showMessage("Error", "Unsupported file type selected.")
return None
# Create data loader
batch_size = 32 # Adjust batch size as needed
data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True)
return data_loader
def add_layer(self):
layer_type = self.layer_type_combo.currentText()
layer_size = self.layer_size_spinbox.value()
self.layer_list_widget.addItem(f'{layer_type} - Size: {layer_size}')
def showMessage(self, title, message):
QMessageBox.information(self, title, message)
def generate_model(self):
self.status_label.setText("Generating model…")
layers = [
(item.text().split(' - Size: ')[0], int(item.text().split(' - Size: ')[1]))
for item in self.layer_list_widget.findItems('*', QtCore.Qt.MatchWildcard)
]
layer_types, hidden_sizes = zip(*layers) if layers else ([], [])
tokenizer_name = self.tokenizer_combo.currentText()
tokenizer_class = {
'bert-base-cased': BertTokenizer,
'gpt2-medium': GPT2Tokenizer,
'xlnet-base-cased': XLNetTokenizer
}.get(tokenizer_name)
if not tokenizer_class:
self.showMessage("Error", "Unsupported tokenizer selected.")
return
self.status_label.setText("Model generated successfully!")
tokenizer = tokenizer_class.from_pretrained(tokenizer_name)
input_size = self.seq_length_spinbox.value()
try:
self.model = RNNModel(input_size, list(hidden_sizes), list(layer_types))
self.status_label.setText("Model generated successfully!")
except ValueError as e:
self.showMessage("Error", f"Invalid layer configuration: {e}")
def on_train_click(self):
loaded_data = self.load_data()
if loaded_data is not None:
self.train_data_loader = self.create_data_loader(loaded_data)
if self.train_data_loader is None or self.model is None:
return # Error messages already displayed from called functions
self.train_model(self.model, self.train_data_loader)
# Then, create the DataLoader.
self.train_data_loader = self.create_data_loader(loaded_data)
if self.train_data_loader is None:
self.showMessage("Error", "Failed to create a DataLoader for the training data.")
return
# Check if the model is defined.
if self.model is None:
self.showMessage("Error", "Model not defined.")
return
# Start the training process.
self.train_model(self.model, self.train_data_loader)
def train_model(self, model, train_data_loader):
num_epochs = self.num_epochs_spinbox.value()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
model.train()
for epoch in range(num_epochs):
running_loss = 0.0
for i, batch in enumerate(train_data_loader):
for batch in train_data_loader:
inputs, labels = batch
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99: # print every 100 mini-batches
print(f"Batch {i + 1}, Loss: {running_loss / 100}")
running_loss = 0.0
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Model Training')
self.language_model_configurator = LanguageModelConfigurator()
self.setCentralWidget(self.language_model_configurator)
self.show()
def main():
app = QtWidgets.QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
|
703b991365915bf934f89cc83da679b9
|
{
"intermediate": 0.30210810899734497,
"beginner": 0.4763890504837036,
"expert": 0.2215028554201126
}
|
34,360
|
css background
|
917ac2b2177dbec91edf7a149f6cba2a
|
{
"intermediate": 0.2634062170982361,
"beginner": 0.3213556110858917,
"expert": 0.4152381718158722
}
|
34,361
|
var count = 1;
for (int i = 0; i<12; i++)
{
for (int j = 20; j>0; j-=2)
{
if (j>16)
count ++;
else if (j>10)
count --;
else
continue;
}
if (count<0)
break;
}
Console.WriteLine(count);
что напечатает эта программа на языке си шарп
|
3d02e5a0b7f45aaf7550f6c9e11c8629
|
{
"intermediate": 0.34365609288215637,
"beginner": 0.42259296774864197,
"expert": 0.23375092446804047
}
|
34,362
|
how to parse web sites with python, any modern practices
|
a6755372633ea0f44ff4bc8493dfc839
|
{
"intermediate": 0.6278560757637024,
"beginner": 0.17600929737091064,
"expert": 0.19613467156887054
}
|
34,363
|
OSError Traceback (most recent call last)
<ipython-input-14-c17954495605> in <cell line: 3>()
1 # Generate Text
2 query = "How do I use the OpenAI API?"
----> 3 text_gen = pipeline(task="text-generation", model=refined_model, tokenizer=llama_tokenizer, max_length=200)
4 output = text_gen(f"<s>[INST] {query} [/INST]")
5 print(output[0]['generated_text'])
4 frames
/usr/local/lib/python3.10/dist-packages/transformers/utils/hub.py in cached_file(path_or_repo_id, filename, cache_dir, force_download, resume_download, proxies, use_auth_token, revision, local_files_only, subfolder, repo_type, user_agent, _raise_exceptions_for_missing_entries, _raise_exceptions_for_connection_errors, _commit_hash)
386 if not os.path.isfile(resolved_file):
387 if _raise_exceptions_for_missing_entries:
--> 388 raise EnvironmentError(
389 f"{path_or_repo_id} does not appear to have a file named {full_filename}. Checkout "
390 f"'https://huggingface.co/{path_or_repo_id}/{revision}' for available files."
OSError: llama-2-7b-sparql-query does not appear to have a file named config.json. Checkout 'https://huggingface.co/llama-2-7b-sparql-query/None' for available files.
|
62fec1e362d857e33657e44c309150a8
|
{
"intermediate": 0.43827494978904724,
"beginner": 0.3297244906425476,
"expert": 0.23200064897537231
}
|
34,364
|
сделайте подключение базы index.php <!--by Dmitry_Komarov-->
<!DOCTYPE html><html lang="ru"><head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="theme-color" content="#fff">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta name="keywords" content="гта россия, crmp android, гта андроид, Arizona Copy скачать, крмп на телефон, россия онлайн, ролеплей крмп, скачать рашн стейт, блек раша">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" sizes="16x16" href="images/favicon-16x16.png" type="image/png">
<link rel="icon" sizes="32x32" href="images/favicon-32x32.png" type="image/png">
<link href="css/aos.css" rel="stylesheet">
<meta name="yandex-verification" content="2f177b96e94cc048">
<link rel="stylesheet" href="css/main.css">
<title>Arizona Copy | Играй онлайн на своём телефоне/пк</title>
<meta name="description" content="Играй онлайн на своём телефоне">
<meta name="robots" content="max-image-preview:large">
<meta name="yandex-verification" content="2f177b96e94cc048">
<link rel="canonical" href="https://arizona-copy/">
<meta property="og:locale" content="ru_RU">
<meta property="og:site_name" content="Arizona Copy | Играй онлайн на своём телефоне/пк">
<meta property="og:type" content="website">
<meta property="og:title" content="Arizona Copy | Играй онлайн на своём телефоне/пк">
<meta property="og:description" content="Играй онлайн на своём телефоне/пк">
<meta property="og:url" content="https://arizona-copy/">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Arizona Copy | Играй онлайн на своём телефоне">
<meta name="twitter:description" content="Играй онлайн на своём телефоне">
<script async src="js/tag.js"></script><script type="application/ld+json" class="aioseo-schema">
{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebSite","@id":"https:\/\/arizona-copy.ru\/#website","url":"https:\/\/arizona-copy.ru\/","name":"SMART RP MOBILE","description":"\u0418\u0433\u0440\u0430\u0439 \u043e\u043d\u043b\u0430\u0439\u043d \u043d\u0430 \u0441\u0432\u043e\u0451\u043c \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u0435","inLanguage":"ru-RU","publisher":{"@id":"https:\/\/arizona-copy.ru\/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/arizona-copy.ru\/?s={search_term_string}"},"query-input":"required name=search_term_string"}},{"@type":"Organization","@id":"https:\/\/arizona-copy.ru\/#organization","name":"SMART RP MOBILE","url":"https:\/\/arizona-copy.ru\/"},{"@type":"BreadcrumbList","@id":"https:\/\/arizona-copy.ru\/#breadcrumblist","itemListElement":[{"@type":"ListItem","@id":"https:\/\/arizona-copy.ru\/#listItem","position":1,"item":{"@type":"WebPage","@id":"https:\/\/arizona-copy.ru\/","name":"Home","description":"\u0418\u0433\u0440\u0430\u0439 \u043e\u043d\u043b\u0430\u0439\u043d \u043d\u0430 \u0441\u0432\u043e\u0451\u043c \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u0435","url":"https:\/\/arizona-copy.ru\/"}}]},{"@type":"CollectionPage","@id":"https:\/\/arizona-copy.ru\/#collectionpage","url":"https:\/\/arizona-copy.ru\/","name":"SMART RP MOBILE | \u0418\u0433\u0440\u0430\u0439 \u043e\u043d\u043b\u0430\u0439\u043d \u043d\u0430 \u0441\u0432\u043e\u0451\u043c \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u0435","description":"\u0418\u0433\u0440\u0430\u0439 \u043e\u043d\u043b\u0430\u0439\u043d \u043d\u0430 \u0441\u0432\u043e\u0451\u043c \u0442\u0435\u043b\u0435\u0444\u043e\u043d\u0435","inLanguage":"ru-RU","isPartOf":{"@id":"https:\/\/arizona-copy.ru\/#website"},"breadcrumb":{"@id":"https:\/\/arizona-copy.ru\/#breadcrumblist"},"about":{"@id":"https:\/\/arizona-copy.ru\/#organization"}}]}
</script>
<link rel="dns-prefetch" href="//s.w.org">
<script type="text/javascript">
window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/","ext":".png","svgUrl":"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/svg\/","svgExt":".svg","source":{"concatemoji":"https:\/\/arizona-copy.ru\/wp-includes\/js\/wp-emoji-release.min.js?ver=5.9"}};
/*! This file is auto-generated */
!function(e,a,t){var n,r,o,i=a.createElement("canvas"),p=i.getContext&&i.getContext("2d");function s(e,t){var a=String.fromCharCode;p.clearRect(0,0,i.width,i.height),p.fillText(a.apply(this,e),0,0);e=i.toDataURL();return p.clearRect(0,0,i.width,i.height),p.fillText(a.apply(this,t),0,0),e===i.toDataURL()}function c(e){var t=a.createElement("script");t.src=e,t.defer=t.type="text/javascript",a.getElementsByTagName("head")[0].appendChild(t)}for(o=Array("flag","emoji"),t.supports={everything:!0,everythingExceptFlag:!0},r=0;r<o.length;r++)t.supports[o[r]]=function(e){if(!p||!p.fillText)return!1;switch(p.textBaseline="top",p.font="600 32px Arial",e){case"flag":return s([127987,65039,8205,9895,65039],[127987,65039,8203,9895,65039])?!1:!s([55356,56826,55356,56819],[55356,56826,8203,55356,56819])&&!s([55356,57332,56128,56423,56128,56418,56128,56421,56128,56430,56128,56423,56128,56447],[55356,57332,8203,56128,56423,8203,56128,56418,8203,56128,56421,8203,56128,56430,8203,56128,56423,8203,56128,56447]);case"emoji":return!s([10084,65039,8205,55357,56613],[10084,65039,8203,55357,56613])}return!1}(o[r]),t.supports.everything=t.supports.everything&&t.supports[o[r]],"flag"!==o[r]&&(t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&t.supports[o[r]]);t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&!t.supports.flag,t.DOMReady=!1,t.readyCallback=function(){t.DOMReady=!0},t.supports.everything||(n=function(){t.readyCallback()},a.addEventListener?(a.addEventListener("DOMContentLoaded",n,!1),e.addEventListener("load",n,!1)):(e.attachEvent("onload",n),a.attachEvent("onreadystatechange",function(){"complete"===a.readyState&&t.readyCallback()})),(n=t.source||{}).concatemoji?c(n.concatemoji):n.wpemoji&&n.twemoji&&(c(n.twemoji),c(n.wpemoji)))}(window,document,window._wpemojiSettings);
</script><script src="js/wp-emoji-release.min.js" type="text/javascript" defer></script>
<style type="text/css">
img.wp-smiley,
img.emoji {
display: inline !important;
border: none !important;
box-shadow: none !important;
height: 1em !important;
width: 1em !important;
margin: 0 0.07em !important;
vertical-align: -0.1em !important;
background: none !important;
padding: 0 !important;
}
</style>
<link rel="stylesheet" id="wp-block-library-css" href="css/style.min.css" type="text/css" media="all">
<style id="global-styles-inline-css" type="text/css">
body{--wp--preset--color--black: #000000;--wp--preset--color--cyan-bluish-gray: #abb8c3;--wp--preset--color--white: #ffffff;--wp--preset--color--pale-pink: #f78da7;--wp--preset--color--vivid-red: #cf2e2e;--wp--preset--color--luminous-vivid-orange: #ff6900;--wp--preset--color--luminous-vivid-amber: #fcb900;--wp--preset--color--light-green-cyan: #7bdcb5;--wp--preset--color--vivid-green-cyan: #00d084;--wp--preset--color--pale-cyan-blue: #8ed1fc;--wp--preset--color--vivid-cyan-blue: #0693e3;--wp--preset--color--vivid-purple: #9b51e0;--wp--preset--gradient--vivid-cyan-blue-to-vivid-purple: linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%);--wp--preset--gradient--light-green-cyan-to-vivid-green-cyan: linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%);--wp--preset--gradient--luminous-vivid-amber-to-luminous-vivid-orange: linear-gradient(135deg,rgba(252,185,0,1) 0%,rgba(255,105,0,1) 100%);--wp--preset--gradient--luminous-vivid-orange-to-vivid-red: linear-gradient(135deg,rgba(255,105,0,1) 0%,rgb(207,46,46) 100%);--wp--preset--gradient--very-light-gray-to-cyan-bluish-gray: linear-gradient(135deg,rgb(238,238,238) 0%,rgb(169,184,195) 100%);--wp--preset--gradient--cool-to-warm-spectrum: linear-gradient(135deg,rgb(74,234,220) 0%,rgb(151,120,209) 20%,rgb(207,42,186) 40%,rgb(238,44,130) 60%,rgb(251,105,98) 80%,rgb(254,248,76) 100%);--wp--preset--gradient--blush-light-purple: linear-gradient(135deg,rgb(255,206,236) 0%,rgb(152,150,240) 100%);--wp--preset--gradient--blush-bordeaux: linear-gradient(135deg,rgb(254,205,165) 0%,rgb(254,45,45) 50%,rgb(107,0,62) 100%);--wp--preset--gradient--luminous-dusk: linear-gradient(135deg,rgb(255,203,112) 0%,rgb(199,81,192) 50%,rgb(65,88,208) 100%);--wp--preset--gradient--pale-ocean: linear-gradient(135deg,rgb(255,245,203) 0%,rgb(182,227,212) 50%,rgb(51,167,181) 100%);--wp--preset--gradient--electric-grass: linear-gradient(135deg,rgb(202,248,128) 0%,rgb(113,206,126) 100%);--wp--preset--gradient--midnight: linear-gradient(135deg,rgb(2,3,129) 0%,rgb(40,116,252) 100%);--wp--preset--duotone--dark-grayscale: url('index_1.html#wp-duotone-dark-grayscale');--wp--preset--duotone--grayscale: url('index_1.html#wp-duotone-grayscale');--wp--preset--duotone--purple-yellow: url('index_1.html#wp-duotone-purple-yellow');--wp--preset--duotone--blue-red: url('index_1.html#wp-duotone-blue-red');--wp--preset--duotone--midnight: url('index_1.html#wp-duotone-midnight');--wp--preset--duotone--magenta-yellow: url('index_1.html#wp-duotone-magenta-yellow');--wp--preset--duotone--purple-green: url('index_1.html#wp-duotone-purple-green');--wp--preset--duotone--blue-orange: url('index_1.html#wp-duotone-blue-orange');--wp--preset--font-size--small: 13px;--wp--preset--font-size--medium: 20px;--wp--preset--font-size--large: 36px;--wp--preset--font-size--x-large: 42px;}.has-black-color{color: var(--wp--preset--color--black) !important;}.has-cyan-bluish-gray-color{color: var(--wp--preset--color--cyan-bluish-gray) !important;}.has-white-color{color: var(--wp--preset--color--white) !important;}.has-pale-pink-color{color: var(--wp--preset--color--pale-pink) !important;}.has-vivid-red-color{color: var(--wp--preset--color--vivid-red) !important;}.has-luminous-vivid-orange-color{color: var(--wp--preset--color--luminous-vivid-orange) !important;}.has-luminous-vivid-amber-color{color: var(--wp--preset--color--luminous-vivid-amber) !important;}.has-light-green-cyan-color{color: var(--wp--preset--color--light-green-cyan) !important;}.has-vivid-green-cyan-color{color: var(--wp--preset--color--vivid-green-cyan) !important;}.has-pale-cyan-blue-color{color: var(--wp--preset--color--pale-cyan-blue) !important;}.has-vivid-cyan-blue-color{color: var(--wp--preset--color--vivid-cyan-blue) !important;}.has-vivid-purple-color{color: var(--wp--preset--color--vivid-purple) !important;}.has-black-background-color{background-color: var(--wp--preset--color--black) !important;}.has-cyan-bluish-gray-background-color{background-color: var(--wp--preset--color--cyan-bluish-gray) !important;}.has-white-background-color{background-color: var(--wp--preset--color--white) !important;}.has-pale-pink-background-color{background-color: var(--wp--preset--color--pale-pink) !important;}.has-vivid-red-background-color{background-color: var(--wp--preset--color--vivid-red) !important;}.has-luminous-vivid-orange-background-color{background-color: var(--wp--preset--color--luminous-vivid-orange) !important;}.has-luminous-vivid-amber-background-color{background-color: var(--wp--preset--color--luminous-vivid-amber) !important;}.has-light-green-cyan-background-color{background-color: var(--wp--preset--color--light-green-cyan) !important;}.has-vivid-green-cyan-background-color{background-color: var(--wp--preset--color--vivid-green-cyan) !important;}.has-pale-cyan-blue-background-color{background-color: var(--wp--preset--color--pale-cyan-blue) !important;}.has-vivid-cyan-blue-background-color{background-color: var(--wp--preset--color--vivid-cyan-blue) !important;}.has-vivid-purple-background-color{background-color: var(--wp--preset--color--vivid-purple) !important;}.has-black-border-color{border-color: var(--wp--preset--color--black) !important;}.has-cyan-bluish-gray-border-color{border-color: var(--wp--preset--color--cyan-bluish-gray) !important;}.has-white-border-color{border-color: var(--wp--preset--color--white) !important;}.has-pale-pink-border-color{border-color: var(--wp--preset--color--pale-pink) !important;}.has-vivid-red-border-color{border-color: var(--wp--preset--color--vivid-red) !important;}.has-luminous-vivid-orange-border-color{border-color: var(--wp--preset--color--luminous-vivid-orange) !important;}.has-luminous-vivid-amber-border-color{border-color: var(--wp--preset--color--luminous-vivid-amber) !important;}.has-light-green-cyan-border-color{border-color: var(--wp--preset--color--light-green-cyan) !important;}.has-vivid-green-cyan-border-color{border-color: var(--wp--preset--color--vivid-green-cyan) !important;}.has-pale-cyan-blue-border-color{border-color: var(--wp--preset--color--pale-cyan-blue) !important;}.has-vivid-cyan-blue-border-color{border-color: var(--wp--preset--color--vivid-cyan-blue) !important;}.has-vivid-purple-border-color{border-color: var(--wp--preset--color--vivid-purple) !important;}.has-vivid-cyan-blue-to-vivid-purple-gradient-background{background: var(--wp--preset--gradient--vivid-cyan-blue-to-vivid-purple) !important;}.has-light-green-cyan-to-vivid-green-cyan-gradient-background{background: var(--wp--preset--gradient--light-green-cyan-to-vivid-green-cyan) !important;}.has-luminous-vivid-amber-to-luminous-vivid-orange-gradient-background{background: var(--wp--preset--gradient--luminous-vivid-amber-to-luminous-vivid-orange) !important;}.has-luminous-vivid-orange-to-vivid-red-gradient-background{background: var(--wp--preset--gradient--luminous-vivid-orange-to-vivid-red) !important;}.has-very-light-gray-to-cyan-bluish-gray-gradient-background{background: var(--wp--preset--gradient--very-light-gray-to-cyan-bluish-gray) !important;}.has-cool-to-warm-spectrum-gradient-background{background: var(--wp--preset--gradient--cool-to-warm-spectrum) !important;}.has-blush-light-purple-gradient-background{background: var(--wp--preset--gradient--blush-light-purple) !important;}.has-blush-bordeaux-gradient-background{background: var(--wp--preset--gradient--blush-bordeaux) !important;}.has-luminous-dusk-gradient-background{background: var(--wp--preset--gradient--luminous-dusk) !important;}.has-pale-ocean-gradient-background{background: var(--wp--preset--gradient--pale-ocean) !important;}.has-electric-grass-gradient-background{background: var(--wp--preset--gradient--electric-grass) !important;}.has-midnight-gradient-background{background: var(--wp--preset--gradient--midnight) !important;}.has-small-font-size{font-size: var(--wp--preset--font-size--small) !important;}.has-medium-font-size{font-size: var(--wp--preset--font-size--medium) !important;}.has-large-font-size{font-size: var(--wp--preset--font-size--large) !important;}.has-x-large-font-size{font-size: var(--wp--preset--font-size--x-large) !important;}
</style>
<link rel="https://api.w.org/" href="https://arizona-copy.ru/wp-json/"><link rel="EditURI" type="application/rsd+xml" title="RSD" href="https://arizona-copy.ru/xmlrpc.php?rsd">
<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="https://arizona-copy.ru/wp-includes/wlwmanifest.xml">
<meta name="generator" content="WordPress 5.9">
<link rel="icon" href="images/cropped-%C3%90_%C3%90%C2%BE%C3%90%C2%B4-%C3%90%C2%BB%C3%90%C2%B0%C3%91_%C3%90%C2%BD%C3%91_%C3%90%C2%B5%C3%91_-2-32x32.png" sizes="32x32">
<link rel="icon" href="images/cropped-%C3%90_%C3%90%C2%BE%C3%90%C2%B4-%C3%90%C2%BB%C3%90%C2%B0%C3%91_%C3%90%C2%BD%C3%91_%C3%90%C2%B5%C3%91_-2-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" href="images/cropped-%C3%90_%C3%90%C2%BE%C3%90%C2%B4-%C3%90%C2%BB%C3%90%C2%B0%C3%91_%C3%90%C2%BD%C3%91_%C3%90%C2%B5%C3%91_-2-180x180.png">
<meta name="msapplication-TileImage" content="https://arizona-copy.ru/wp-content/uploads/2022/02/cropped-Под-лаунчер-2-270x270.png">
</head>
<body>
<header class="header">
<div class="container">
<div class="header__body row-flex">
<a class="logo header__logo col flex a-center" href="/">
<img class="logo__image" src="images/logo.png" alt>
<div class="logo__text text-center upper">
<div class="logo__text-up">Arizona</div>
<div class="logo__text-down">Copy</div>
</div>
</a>
<div class="header__right col">
<div class="navbar header__navbar upper">
<button class="btn burger">
<span></span>
<span></span>
<span></span>
</button>
<div class="navbar__wrapper">
<nav class="nav">
<a class="nav__link active" href="https://arizona-copy.ru">Главная</a><a class="nav__link " href="https://f.arizona-copy.ru/">Форум</a><a class="nav__link " href="#news">Новости</a><a class="nav__link " href="rate/">Рейтинг</a><a class="nav__link " href="about">О нас</a><a class="nav__link " href="https://arizona-copy.ru/donate">Донат</a>
<a class="nav__link nav__link-mob" href="https://lk.arizona-copy.ru/">Личный кабинет</a>
</nav>
<a href="https://lk.arizona-copy.ru/" class="nav__btn btn btn_blue upper">Личный Кабинет</a>
</div>
</div>
</div>
</div>
</div></header>
<main class="main">
<section class="jumb section">
<ul class="scene jumb-scene-jumb">
<li class="scene__layer" data-depth="0.2">
<div class="scene__layer--phone">
<div class="jumb__mobile">
<button class="btn btn_orange jumb__mobile-btn modal-trigger" modal-target=".modal-req">Зайти с ПК</button>
<div class="frame-mobile frame-mobile--jumb">
<img src="images/babymobile1.png" class="frame-mobile__bg" alt>
<div class="frame-mobile__image" style="background-image: url(images/babymobile1.jpg);"></div>
</div>
</div>
</div>
</li>
</ul>
<div class="jumb__bg jumb__bg--blur"></div>
<div class="jumb__bg jumb__bg--contur"></div>
<div class="jumb__bg font-bg font-bg--jumb-right" data-back-font-af="Arizona Copy" data-back-font-bf="Arizona Copy"></div>
<div class="container">
<div class="jumb__body row-flex">
<div class="jumb__info col font-bg font-bg--jumb-left" data-back-font-bf="SAMP PC/MOBILE">
<h1 class="jumb__title section__title">
Играй <span>в Arizona Copy</span> <br>
по сети на своем телефоне
</h1>
<p class="jumb__subtitle">бонусные сервера Аризоны.</p>
<div class="jumb__buttons">
<a href="https://disk.yandex.ru/d/Z7ADSPjfS1eeDw" class="btn btn_blue jumb__btn jumb__btn--blue" data-aos="fade-right" data-aos-delay="100" data-aos-duration="500">
Играть с телефона
</a>
<a href modal-target=".modal-video" class="btn jumb__btn jumb__btn--play modal-trigger" data-aos="fade-left" data-aos-delay="300" data-aos-duration="400">
<img class="jumb__btn--play-icon" src="fonts/play-button.svg" alt="play">
<span>как начать играть</span>
</a>
</div>
</div>
<div class="jumb__fake col">
<div class="jumb__mobile jumb__mobile--fake">
<button class="btn btn_orange jumb__mobile-btn modal-trigger" modal-target=".modal-req">системные требования игры</button>
<div class="frame-mobile frame-mobile--jumb">
<img src="images/frame-mobile.png" class="frame-mobile__bg" alt>
<div class="frame-mobile__image" style="background-image: url(images/img-frame-mobile.jpg);"></div>
</div>
</div>
</div>
<div class="jumb__server jumb-server col">
<h3 class="jumb-server__title">Наши сервера</h3>
<div class="jumb-server__list">
<div class="jumb-server__list-item" data-aos="flip-right" data-aos-duration="1200" data-aos-delay="500">
<div class="jumb-server__list-circle">
01
</div>
<script type="text/javascript" src="https://samp-servers.ru/web/api/10315/"> </script>
<div class="jumb-server__list-body">
<div class="jumb-server__list-name"><b></b> <script type="text/javascript">
if(api.hostname == 'Arizona Copy | Phoenix' || api.hostname == 'Arizona Copy | Phoenix')
{
document.write("<font style='color: red;'>Phoenix</font><br />");
}
else
{
document.write(api.hostname);
}</script><br></div>
<div class="jumb-server__list-online"><b>Онлайн:</b> <script type="text/javascript">document.write(api.players +'/'+ api.maxplayers);</script><br></div>
<b>Статус:</b> <script type="text/javascript">
if ( api.status == 1 )
{
document.write("<font style='color: green;'>Онлайн</font><br />");
}
else
{
document.write("<font style='color: red;'>Недоступен</font><br />");
}
</script>
</div>
<div class="jumb-server__list-bonus">
<div class="jumb-server__list-bonus-inner">
<script type="text/javascript">document.write(api.gamemode);</script>
</div>
</div>
</div>
<div class="jumb-server__list">
<div class="jumb-server__list-item" data-aos="flip-right" data-aos-duration="1200" data-aos-delay="500">
<div class="jumb-server__list-circle">
01
</div>
<script type="text/javascript" src="https://samp-servers.ru/web/api/908433/"> </script>
<div class="jumb-server__list-body">
<div class="jumb-server__list-name"><b></b> <script type="text/javascript">
if(api.hostname == 'ARIZONA COPY | ТЕСТОВЫЙ' || api.hostname == 'ARIZONA COPY | ТЕСТОВЫЙ')
{
document.write("<font style='color: black;'>TEST</font><br />");
}
else
{
document.write(api.hostname);
}</script><br></div>
<div class="jumb-server__list-online"><b>Онлайн:</b> <script type="text/javascript">document.write(api.players +'/'+ api.maxplayers);</script><br></div>
<b>Статус:</b> <script type="text/javascript">
if ( api.status == 1 )
{
document.write("<font style='color: green;'>Онлайн</font><br />");
}
else
{
document.write("<font style='color: red;'>Недоступен</font><br />");
}
</script>
</div>
<div class="jumb-server__list-bonus">
<div class="jumb-server__list-bonus-inner">
x2
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div></section>
<div class="sections-wrap">
<section id="news" class="news section font-bg font-bg--news-section" data-back-font-bf="GTA SAMP">
<div class="container">
<h2 class="section__title section__title--news text-center" data-back-font="Новости проекта" data-aos="zoom-in" data-aos-duration="800">
Новости <span>проекта</span>
</h2>
<div class="news__list row-flex">Актуальные новости Arizona Copy можно смотреть в сообществе ВК игры.
</div>
</div>
</section>
<section class="contacts section font-bg font-bg--contact-section" data-back-font-bf="SAMP PC/MOBILE">
<div class="container">
<h2 class="section__title text-center" data-back-font="наши контакты" data-aos="zoom-in" data-aos-duration="800">
Наши <span>контакты</span>
</h2>
<div class="contacts__preview contacts-preview">
<div class="contacts-preview__block">
<div class="contacts-preview__phone-wrapper" data-aos="fade-up" data-aos-duration="1200">
<img class src="images/phone-contact21.png" alt>
</div>
<ul class="contacts-preview__list-socials">
<li data-aos="zoom-in-right" data-aos-duration="1200" data-aos-offset="-260">
<div class="contacts-preview__card contacts-preview__card--right">
<img src="fonts/discord.svg" alt="discord" class="contacts-preview__card-icon">
<div class="contacts-preview__card-name">DISCORD канал</div>
<div class="contacts-preview__card-subscribe">
<a target="_blank" href="https://discord.gg/" class="btn btn_trans contacts-preview__card-btn">Подключиться</a>
<p class="contacts-preview__card-followers">+300 участников</p>
</div>
</div>
</li>
<li data-aos="zoom-in-left" data-aos-duration="1200" data-aos-offset="-100">
<div class="contacts-preview__card contacts-preview__card--left">
<img src="fonts/vk.svg" alt="vk" class="contacts-preview__card-icon">
<div class="contacts-preview__card-name">Официальная группа</div>
<div class="contacts-preview__card-subscribe">
<a target="_blank" href="https://vk.com/arzcopy_samp" class="btn btn_trans contacts-preview__card-btn">Подписаться</a>
<p class="contacts-preview__card-followers">+5000 подписчиков</p>
</div>
</div>
</li>
</ul>
</div>
</div>
<div class="contacts__mobile contacts-mobile">
<div class="contacts-mobile__item" data-aos="fade-up" data-aos-anchor-placement="top-bottom" data-aos-duration="1200">
<div class="contacts-mobile__img-wrapper">
<img src="fonts/vk-icon.svg" alt="vk">
</div>
<div class="contacts-preview__card-name">Официальная группа</div>
<div class="contacts-preview__card-subscribe">
<a target="_blank" href="https://vk.com/arzcopy_samp" class="btn btn_trans contacts-preview__card-btn">Подписаться</a>
<p class="contacts-preview__card-followers">+5000 ПОДПИСЧИКОВ</p>
</div>
</div>
<div class="contacts-mobile__item" data-aos="fade-up" data-aos-anchor-placement="top-bottom" data-aos-duration="1200">
<div class="contacts-mobile__img-wrapper">
<img src="fonts/discord-icon.svg" alt="discord">
</div>
<div class="contacts-preview__card-name">DISCORD канал</div>
<div class="contacts-preview__card-subscribe">
<a target="_blank" href="https://discord.gg/" class="btn btn_trans contacts-preview__card-btn">Подписаться</a>
<p class="contacts-preview__card-followers">+300 участников</p>
</div>
</div>
</div>
</div>
</section>
</div>
</main>
<footer class="footer text-center">
<div class="container">
<a class="logo footer-logo flex-inline a-center" href="/">
<img class="logo__image footer-logo__image" src="images/logo.png" alt>
<div class="logo__text text-center upper">
<div class="logo__text-up footer-logo__text-up">Arizona Copy</div>
<div class="logo__text-down footer-logo__text-down">Игровая бонусная компания</div>
</div>
</a>
<div class="footer__links-buttons">
<a class="btn btn_trans footer__links-button" href="https://vk.com/huareix">ТЕХ. ПОДДЕРЖКА</a><a class="btn btn_trans footer__links-button" href="https://vk.com/rustatecr">ДЛЯ БЛОГЕРОВ</a></div>
<div class="footer__links flex">
<a href="https://arizona-copy.ru/docs/privacy-policy">Политика конфиденциальности</a><a href="https://arizona-copy.ru/docs/agreement">Оферта</a> </div>
<div class="footer__copyright copyright">Copyright © 2023 Arizona Copy by © huareix productions</div>
</div>
</footer>
<div class="modal">
<div class="modal__body modal-req">
<button class="modal__close">
<svg class="modal__close-icon" fill="white" xmlns="http://www.w3.org/2000/svg" width="357" height="357" viewBox="0 0 357 357">
<path d="M357 35.7L321.3 0 178.5 142.8 35.7 0 0 35.7l142.8 142.8L0 321.3 35.7 357l142.8-142.8L321.3 357l35.7-35.7-142.8-142.8z"/>
</svg>
</button>
<h2 class="section__title text-center modal-req__title" data-back-font="Системные требования игры">
<span>Системные требования</span> игры
</h2>
<div class="modal-req__params">
<div class="modal-req__param">
<div class="modal-req__param-label">Операционная система:</div>
<div class="modal-req__param-value">Android 6 и выше</div>
</div>
<div class="modal-req__param">
<div class="modal-req__param-label">Процессор:</div>
<div class="modal-req__param-value">Qualcomm Snapdragon 435 и выше</div>
</div>
<div class="modal-req__param">
<div class="modal-req__param-label">Оперативная память:</div>
<div class="modal-req__param-value">от 2 гб</div>
</div>
<div class="modal-req__param">
<div class="modal-req__param-label">Свободное место:</div>
<div class="modal-req__param-value">от 2 гб</div>
</div>
</div>
<div class="text-center">
<a href="https://disk.yandex.lt/d/fmp_lygnJD-ljg" class="btn btn_blue modal__download">ЛАУНЧЕР ПК</a>
</div>
</div>
<div class="modal__body modal-video">
<button class="modal__close">
<svg class="modal__close-icon" fill="white" xmlns="http://www.w3.org/2000/svg" width="357" height="357" viewBox="0 0 357 357">
<path d="M357 35.7L321.3 0 178.5 142.8 35.7 0 0 35.7l142.8 142.8L0 321.3 35.7 357l142.8-142.8L321.3 357l35.7-35.7-142.8-142.8z"/>
</svg>
</button>
<iframe width="330" height="400" src="https://rutube.ru/play/embed/" frameborder="0" allow="clipboard-write; autoplay" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
<script src="js/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
<script src="js/parallax.min.js"></script>
<script src="js/aos.js"></script>
<script src="js/main.js"></script>
<script src="js/vendor.js"></script>
<script type="text/javascript">
(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
m[i].l=1*new Date();k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");
ym(87645134, "init", {
clickmap:true,
trackLinks:true,
accurateTrackBounce:true
});
</script>
<noscript><div><img src="https://mc.yandex.ru/watch/87645134" style="position:absolute; left:-9999px;" alt></div></noscript>
<?php
$servername = "localhost";
$username = "ваше_имя_пользователя";
$password = "ваш_пароль";
$dbname = "название_вашей_базы_данных";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT BickName, pID, pRub FROM ваша_таблица";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<div class="rating-main__item" data-aos-delay="500" data-aos="flip-up" data-aos-duration="1200">';
echo '<div class="rating-main__num">' . $row["pID"] . '</div>';
echo '<div class="rating-main__name">' . $row["BickName"] . '</div>';
echo '<div class="rating-main__value">' . $row["pRub"] . ' AZ-RUB</div>';
echo '</div>';
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
<!--by Dmitry_Komarov-->
|
f778bf8c4d2a51e9b2c134eda90d31b2
|
{
"intermediate": 0.314376562833786,
"beginner": 0.40183284878730774,
"expert": 0.28379055857658386
}
|
34,365
|
INFO : Semantic Analysis Completed (retrial = false)
INFO : Returning Hive schema: Schema(fieldSchemas:[FieldSchema(name:user_id, type:int, comment:null)], properties:null)
INFO : Completed compiling command(queryId=hive_20231207163209_ef558f0f-e0b7-4ce1-84bf-c03034b141dc); Time taken: 0.371 seconds
INFO : Executing command(queryId=hive_20231207163209_ef558f0f-e0b7-4ce1-84bf-c03034b141dc):
create table gzolotov.angara_sample_users AS (
SELECT DISTINCT user_id
FROM angara.source_pairs
WHERE processed_year='2023' and CONCAT(processed_year, '-', processed_month, '-', processed_day) = '2023-04-10'
)
WARN : Hive-on-MR is deprecated in Hive 2 and may not be available in the future versions. Consider using a different execution engine (i.e. spark, tez) or using Hive 1.X releases.
INFO : Query ID = hive_20231207163209_ef558f0f-e0b7-4ce1-84bf-c03034b141dc
INFO : Total jobs = 1
|
3bde7a8298807a7c055d43d529b36044
|
{
"intermediate": 0.43929392099380493,
"beginner": 0.2626395523548126,
"expert": 0.29806649684906006
}
|
34,366
|
#include "ArgParser.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <string_view>
namespace ArgumentParser {
ArgParser::~ArgParser() {
for (Argument* arg : arguments) {
delete arg;
}
}
bool IsValue(const std::string& buff) {
return buff.size() == 1 || std::isdigit(buff[1]);
}
int32_t ArgParser::FindByLongName(const std::string& long_name) {
for (int i = 0; i < arguments.size(); ++i) {
if (arguments[i]->long_name == long_name) {
return i;
}
}
return -1;
}
int32_t ArgParser::FindByShortName(char short_name) {
for (int i = 0; i < arguments.size(); ++i) {
if (arguments[i]->short_name == short_name) {
return i;
}
}
return -1;
}
bool ArgParser::Parse(const std::vector<std::string>& argv) {
if (arguments.empty()) {
return true;
}
size_t positional_index = 0;
for (size_t i = 1; i < argv.size(); ++i) {
if (argv[i][0] != '-') {
if (positional_index >= arguments.size()) {
return false;
}
if (argv[i][0] != '-') {
Argument* arg = arguments[positional_index];
if (arg->is_positional) {
switch (arg->type) {
case Argument::Type::String: {
StringArgument* stringArg = static_cast<StringArgument*>(arg);
stringArg->value.push_back(argv[i]);
if (stringArg->str_value_ptr != nullptr) {
*stringArg->str_value_ptr = argv[i];
}
break;
}
case Argument::Type::Integer: {
IntArgument* intArg = static_cast<IntArgument*>(arg);
intArg->value.push_back(std::stoi(argv[i]));
if (intArg->int_values_ptr != nullptr) {
intArg->int_values_ptr->push_back(std::stoi(argv[i]));
}
break;
}
case Argument::Type::Bool:
break;
}
if (!arg->is_multi_value) {
++positional_index;
}
} else return false;
}
} else {
std::string_view argStr = argv[i];
if (argStr[0] == '-') {
if (argStr.size() > 1 && argStr[1] == '-') {
size_t equalPos = argStr.find("=");
std::string longName = (equalPos != std::string::npos) ? argStr.substr(2, equalPos - 2) : argStr.substr(2);
std::string value = (equalPos != std::string::npos) ? argStr.substr(equalPos + 1) : argStr.substr(2);
int index = FindByLongName(longName);
if (index == -1) {
return false;
}
Argument* argument = arguments[index];
switch (argument->type) {
case Argument::Type::String:
static_cast<StringArgument*>(argument)->value.push_back(value);
if (static_cast<StringArgument*>(argument)->str_value_ptr != nullptr) {
*static_cast<StringArgument*>(argument)->str_value_ptr = value;
}
break;
case Argument::Type::Integer:
static_cast<IntArgument*>(argument)->value.push_back(stoi(value));
if (static_cast<IntArgument*>(argument)->int_values_ptr != nullptr) {
static_cast<IntArgument*>(argument)->int_values_ptr->push_back(stoi(value));
}
break;
case Argument::Type::Bool:
static_cast<BoolArgument*>(argument)->value = true;
if (static_cast<BoolArgument*>(argument)->bool_value_ptr != nullptr) {
*static_cast<BoolArgument*>(argument)->bool_value_ptr = true;
}
break;
}
if (!argument->is_multi_value && i + 1 < argv.size() && argv[i + 1][0] != '-') {
static_cast<StringArgument*>(argument)->value.push_back(argv[++i]);
}
} else {
size_t len = argStr.size();
for (size_t j = 1; j < len; ++j) {
char shortName = argStr[j];
int index = FindByShortName(shortName);
if (index == -1) {
std::cerr << "Unknown option: " << shortName << std::endl;
return false;
}
Argument* argument = arguments[index];
switch (argument->type) {
case Argument::Type::String:
static_cast<StringArgument*>(argument)->value.push_back((j + 1 < len) ? argStr.substr(j + 2) : "");
if (static_cast<StringArgument*>(argument)->str_value_ptr != nullptr) {
*static_cast<StringArgument*>(argument)->str_value_ptr = (j + 1 < len) ? argStr.substr(j + 2) : "";
}
break;
case Argument::Type::Integer:
static_cast<IntArgument*>(argument)->value.push_back((j + 1 < len) ? stoi(argStr.substr(j + 2)) : 0);
if (static_cast<IntArgument*>(argument)->int_values_ptr != nullptr) {
static_cast<IntArgument*>(argument)->int_values_ptr->push_back((j + 1 < len) ? stoi(argStr.substr(j + 2)) : 0);
}
break;
case Argument::Type::Bool:
static_cast<BoolArgument*>(argument)->value = true;
if (static_cast<BoolArgument*>(argument)->bool_value_ptr != nullptr) {
*static_cast<BoolArgument*>(argument)->bool_value_ptr = true;
}
break;
}
if (argument->type != Argument::Type::Bool) {
break;
}
}
}
}
}
}
for (auto& arg : arguments) {
size_t minimumCount = arg->min_arguments_count;
size_t providedCount = 0;
switch (arg->type) {
case Argument::Type::String:
providedCount = static_cast<StringArgument*>(arg)->value.size();
break;
case Argument::Type::Integer:
providedCount = static_cast<IntArgument*>(arg)->value.size();
break;
default:
continue;
}
if (providedCount < minimumCount && !arg->is_default && !arg->help_requested) {
return false;
}
}
return true;
}
ArgParser& ArgParser::AddStringArgument(std::string long_name) {
StringArgument* arg = new StringArgument();
arg->long_name = std::move(long_name);
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddStringArgument(char short_name) {
StringArgument* arg = new StringArgument();
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddStringArgument(char short_name, std::string long_name) {
StringArgument* arg = new StringArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::StoreValue(std::string& value) {
if (arguments.back()->type == Argument::Type::String) {
StringArgument* stringArg = static_cast<StringArgument*>(arguments.back());
stringArg->str_value_ptr = &value;
}
return *this;
}
std::string ArgParser::GetStringValue(std::string long_name) {
int32_t index = FindByLongName(long_name);
if (index != -1 && arguments[index]->type == Argument::Type::String) {
StringArgument* stringArg = static_cast<StringArgument*>(arguments[index]);
if (!stringArg->value.empty()) return stringArg->value.front();
}
return "";
}
std::string ArgParser::GetStringValue(char short_name) {
int32_t index = FindByShortName(short_name);
if (index != -1 && arguments[index]->type == Argument::Type::String) {
StringArgument* stringArg = static_cast<StringArgument*>(arguments[index]);
if (!stringArg->value.empty()) return stringArg->value.front();
}
return "";
}
ArgParser& ArgParser::Default(const char* default_value) {
if (arguments.back()->type == Argument::Type::String) {
StringArgument* stringArg = static_cast<StringArgument*>(arguments.back());
if (stringArg->value.empty()) {
stringArg->value.push_back(default_value);
}
stringArg->is_default = true;
} else {
std::cerr << "Parameter isn't correct";
exit(EXIT_FAILURE);
}
return *this;
}
ArgParser& ArgParser::AddIntArgument(std::string long_name) {
IntArgument* arg = new IntArgument();
arg->long_name = std::move(long_name);
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgument(char short_name) {
IntArgument* arg = new IntArgument();
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgument(char short_name, std::string long_name) {
IntArgument* arg = new IntArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
int32_t ArgParser::GetIntValue(std::string long_name) {
int32_t index = FindByLongName(long_name);
if (index != -1 && arguments[index]->type == Argument::Type::Integer) {
IntArgument* intArg = static_cast<IntArgument*>(arguments[index]);
if (!intArg->value.empty()) return intArg->value.front();
}
return 0;
}
int32_t ArgParser::GetIntValue(char short_name) {
int32_t index = FindByShortName(short_name);
if (index != -1 && arguments[index]->type == Argument::Type::Integer) {
IntArgument* intArg = static_cast<IntArgument*>(arguments[index]);
if (!intArg->value.empty()) return intArg->value.front();
}
return 0;
}
int32_t ArgParser::GetIntValue(std::string long_name, int32_t index) {
int32_t index_of_argument = FindByLongName(long_name);
IntArgument* intArg = static_cast<IntArgument*>(arguments[index_of_argument]);
return intArg->value[index];
}
ArgParser& ArgParser::StoreValues(std::vector<int32_t>& values) {
if (arguments.back()->type == Argument::Type::Integer) {
IntArgument* intArg = static_cast<IntArgument*>(arguments.back());
intArg->int_values_ptr = &values;
}
return *this;
}
ArgParser& ArgParser::MultiValue() {
arguments.back()->is_multi_value = true;
return *this;
}
ArgParser& ArgParser::MultiValue(size_t min_arguments_count) {
arguments.back()->is_multi_value = true;
arguments.back()->min_arguments_count = min_arguments_count;
return *this;
}
ArgParser& ArgParser::AddFlag(char short_name, std::string long_name) {
BoolArgument* arg = new BoolArgument;
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlag(char short_name) {
BoolArgument* arg = new BoolArgument;
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlag(std::string long_name) {
BoolArgument* arg = new BoolArgument;
arg->long_name = std::move(long_name);
arguments.push_back(arg);
return *this;
}
bool ArgParser::GetFlag(char short_name) {
int32_t index = FindByShortName(short_name);
if (index != -1 && arguments[index]->type == Argument::Type::Bool) {
BoolArgument* boolArg = static_cast<BoolArgument*>(arguments[index]);
return boolArg->value;
}
return false;
}
bool ArgParser::GetFlag(std::string long_name) {
int32_t index = FindByLongName(long_name);
if (index != -1 && arguments[index]->type == Argument::Type::Bool) {
BoolArgument* boolArg = static_cast<BoolArgument*>(arguments[index]);
return boolArg->value;
}
return false;
}
ArgParser& ArgParser::Default(bool value) {
if (arguments.back()->type == Argument::Type::Bool) {
BoolArgument* boolArg = static_cast<BoolArgument*>(arguments.back());
boolArg->value = value;
boolArg->is_default = true;
} else {
std::cerr << "Parameter isn't correct";
exit(EXIT_FAILURE);
}
return *this;
}
ArgParser& ArgParser::StoreValue(bool& value) {
if (arguments.back()->type == Argument::Type::Bool) {
BoolArgument* boolArg = static_cast<BoolArgument*>(arguments.back());
boolArg->bool_value_ptr = &value;
}
return *this;
}
ArgParser& ArgParser::Positional() {
arguments.back()->is_positional = true;
return *this;
}
ArgParser& ArgParser::AddHelp(char short_name, std::string long_name, std::string description) {
BoolArgument* arg = new BoolArgument();
arg->short_name = short_name;
arg->long_name = std::move(long_name);
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
bool ArgParser::Help() {
for(int i = 0; i < arguments.size(); ++i) {
if (arguments[i]->help_requested) {
return true;
}
}
return false;
}
std::string ArgParser::HelpDescription() {
std::stringstream help_string;
help_string << name << "\n";
for (const auto &arg : arguments) {
if (arg->help_requested) {
help_string << arg->help_message << "\n\n";
continue;
}
help_string << (arg->short_name != '\0' ? "-" : "")
<< (arg->short_name != '\0' ? std::string(1, arg->short_name) + ", " : "")
<< (!arg->long_name.empty() ? "-" : "")
<< arg->long_name;
switch (arg->type) {
case Argument::Type::String: help_string << ", <string>"; break;
case Argument::Type::Integer: help_string << ", <integer>"; break;
case Argument::Type::Bool: help_string << ", <bool>"; break;
}
help_string << ", " << arg->help_message;
if (arg->is_multi_value) {
help_string << " [repeated";
if (arg->min_arguments_count > 0) {
help_string << ", min args = " << arg->min_arguments_count;
}
help_string << "]";
}
if (arg->is_default) {
if(arg->type == Argument::Type::String){
if (arg->is_default) {
help_string << " [default = " << static_cast<StringArgument*>(arg)->value[0] << "]";
}
}else if(arg->type == Argument::Type::Integer && arg->is_default && !static_cast<IntArgument*>(arg)->value.empty()){
help_string << " [default = " << static_cast<IntArgument*>(arg)->value[0] << "]";
}else if(arg->type == Argument::Type::Bool){
if (arg->is_default) {
help_string << " [default = " << (static_cast<BoolArgument*>(arg)->value ? "true" : "false") << "]";
}
}
}
help_string << "\n\n";
}
help_string << "\n\n" << (arguments[0]->short_name != 0 ? "-" : "")
<< (arguments[0]->short_name != 0 ? std::string(1, arguments[0]->short_name) + ", " : "")
<< "--help Display this help and exit\n";
return help_string.str();
}
ArgParser& ArgParser::AddStringArgumentWithDescription(std::string long_name, std::string description) {
StringArgument* arg = new StringArgument();
arg->long_name = std::move(long_name);
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddStringArgumentWithDescription(char short_name, std::string description) {
StringArgument* arg = new StringArgument();
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddStringArgumentWithDescription(char short_name, std::string long_name, std::string description) {
StringArgument* arg = new StringArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgumentWithDescription(std::string long_name, std::string description) {
IntArgument* arg = new IntArgument();
arg->long_name = std::move(long_name);
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgumentWithDescription(char short_name, std::string description) {
IntArgument* arg = new IntArgument();
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgumentWithDescription(char short_name, std::string long_name, std::string description) {
IntArgument* arg = new IntArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlagWithDescription(std::string long_name, std::string description) {
BoolArgument* arg = new BoolArgument();
arg->long_name = std::move(long_name);
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlagWithDescription(char short_name, std::string description) {
BoolArgument* arg = new BoolArgument();
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlagWithDescription(char short_name, std::string long_name, std::string description) {
BoolArgument* arg = new BoolArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
} // namespace ArgumentParser
смотри вместо string.substring я хочу использовать string_view замени
|
39a2da62b1f6ab92b96219a4f6c08e19
|
{
"intermediate": 0.4120520055294037,
"beginner": 0.40721428394317627,
"expert": 0.18073374032974243
}
|
34,367
|
Make sure that the default admin$ share is enabled on WINDOWS10.
как исправить эту ошибку в psexec
|
bdb8d1e71601aa6edb63a498c5cdb6d0
|
{
"intermediate": 0.28777801990509033,
"beginner": 0.3828946053981781,
"expert": 0.32932737469673157
}
|
34,368
|
как елку сделать обрезанную при вставке? Чтобы не было серых квадратиков
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Бесконечный скроллинг с добавлением картинок</title>
<style>
/* Добавляем немного стилей для наглядности скроллинга */
#infinite-scroll div {
margin-bottom: 10px;
}
img {
max-width: 100%; /* Чтобы изображение не выходило за рамки экрана */
height: auto;
}
</style>
</head>
<body>
<div id="infinite-scroll">
<!-- Оставляем пустой див, который будет заполняться картинками при скроллинге -->
</div>
<script>
window.addEventListener("scroll", function() {
var block = document.getElementById('infinite-scroll');
var contentHeight = block.offsetHeight;
var yOffset = window.pageYOffset;
var window_height = window.innerHeight;
var y = yOffset + window_height;
// если пользователь достиг конца
if(y >= contentHeight) {
// добавляем новую картинку
let imageUrl = 'https://e7.pngegg.com/pngimages/957/650/png-clipart-christmas-tree-christmas-tree-leaf-holidays.png';
block.innerHTML += '<div><img src="' + imageUrl + '" alt="Дерево"></div>';
}
});
// Чтобы начальный экран не был пустым, заполним его несколькими картинками
var block = document.getElementById('infinite-scroll');
for(let i = 0; i < 3; i++) {
let imageUrl = 'https://e7.pngegg.com/pngimages/957/650/png-clipart-christmas-tree-christmas-tree-leaf-holidays.png';
block.innerHTML += '<div><img src="' + imageUrl + '" alt="Дерево"></div>';
}
</script>
</body>
</html>
|
c934941b97dd80005ffdb6d4caed7f8a
|
{
"intermediate": 0.31430330872535706,
"beginner": 0.5274957418441772,
"expert": 0.1582009494304657
}
|
34,369
|
Does modifying /etc/crypttab need update-initramfs -u or update-grub to be done (on Debian)?
|
012d776867c8d9139e5813ad123c378c
|
{
"intermediate": 0.5319786071777344,
"beginner": 0.23710834980010986,
"expert": 0.23091299831867218
}
|
34,370
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <locale.h>
int main() {
int X[50][50];
int rows, cols;
srand(time(NULL));
printf("Введите количество строк матрицы: ");
scanf_s("%d", &rows);
printf("Введите количество столбцов матрицы: ");
scanf_s("%d", &cols);
if (rows > 50 || cols > 50 || rows <= 0 || cols <= 0) {
printf("Размерность матрицы превышает максимально допустимый размер 50x50 или размерность указана некорректно.\n");
return 1;
}
printf("Исходная матрица:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
X[i][j] = 1 + rand() % 500;
printf("%4d ", X[i][j]);
}
printf("\n");
}
printf("\nИсходная матрица:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%4d ", X[i][j]);
}
printf("\n");
}
int maxElement = X[0][0];
int maxRows[50];
int maxRowCount = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (X[i][j] > maxElement) {
maxElement = X[i][j];
maxRows[0] = i;
maxRowCount = 1;
}
else if (X[i][j] == maxElement) {
maxRows[maxRowCount] = i;
maxRowCount++;
}
}
}
printf("\nМаксимальный элемент в матрице: %d\n", maxElement);
for (int k = 0; k < maxRowCount; k++) {
int currentMaxRow = maxRows[k] - k;
for (int i = currentMaxRow; i < rows - 1; i++) {
for (int j = 0; j < cols; j++) {
X[i][j] = X[i + 1][j];
}
}
}
rows -= maxRowCount;
printf("\nМодифицированная матрица:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%4d ", X[i][j]);
}
printf("\n");
}
return 0;
}
если максимальные элементы есть в нулевой, третьей и шестой строке, сколько строк удалит твоя программа?
|
d7cc5becc2d21e54b75f4e46aec8b761
|
{
"intermediate": 0.29347988963127136,
"beginner": 0.4943508803844452,
"expert": 0.21216924488544464
}
|
34,371
|
CustomScaffold(
body: [
const TableHeader(),
Table( this code gives me this error Another exception was thrown: Incorrect use of ParentDataWidget.
|
64221f9206c144c01d411e7c82fd7e6f
|
{
"intermediate": 0.5843838453292847,
"beginner": 0.20714077353477478,
"expert": 0.20847532153129578
}
|
34,372
|
package gtanks.battles.chat;
import gtanks.StringUtils;
import gtanks.battles.BattlefieldModel;
import gtanks.battles.BattlefieldPlayerController;
import gtanks.battles.bonuses.BonusType;
import gtanks.commands.Type;
import gtanks.json.JSONUtils;
import gtanks.lobby.LobbyManager;
import gtanks.main.database.DatabaseManager;
import gtanks.main.database.impl.DatabaseManagerImpl;
import gtanks.main.params.OnlineStats;
import gtanks.services.BanServices;
import gtanks.services.LobbysServices;
import gtanks.services.TanksServices;
import gtanks.services.annotations.ServicesInject;
import gtanks.services.ban.BanChatCommads;
import gtanks.services.ban.BanTimeType;
import gtanks.services.ban.BanType;
import gtanks.services.ban.DateFormater;
import gtanks.services.ban.block.BlockGameReason;
import gtanks.users.TypeUser;
import gtanks.users.User;
import gtanks.users.karma.Karma;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import static org.apache.commons.lang3.StringUtils.repeat;
public class BattlefieldChatModel {
private BattlefieldModel bfModel;
private final int MAX_WARNING = 5;
@ServicesInject(
target = TanksServices.class
)
private TanksServices tanksServices = TanksServices.getInstance();
@ServicesInject(
target = DatabaseManager.class
)
private DatabaseManager database = DatabaseManagerImpl.instance();
@ServicesInject(
target = LobbysServices.class
)
private LobbysServices lobbyServices = LobbysServices.getInstance();
@ServicesInject(
target = BanServices.class
)
private BanServices banServices = BanServices.getInstance();
private List<String> SwearWords = Arrays.asList(
"сука",
"блять",
"бля",
"пизд",
"ебать",
"еба",
"хуй",
"хуя",
"хер",
"хуев",
"залупа",
"залупой",
"педик",
"еблан",
"пизда",
"гандон",
"шлюха",
"отьебись",
"отъебись",
"мудила",
"пидарасы",
"чмо"
);
public BattlefieldChatModel(BattlefieldModel bfModel) {
this.bfModel = bfModel;
}
private String AntimatFilter(String message) {
StringBuilder filteredMessage = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
char currentChar = message.charAt(i);
char lowercaseChar = Character.toLowerCase(currentChar);
boolean isSwearWord = false;
for (String mat : SwearWords) {
String lowercaseMat = mat.toLowerCase();
if (message.regionMatches(true, i, mat, 0, mat.length())) {
isSwearWord = true;
filteredMessage.append("*".repeat(mat.length()));
i += mat.length() - 1; // пропускаем обработанные символы
break;
}
}
if (!isSwearWord) {
filteredMessage.append(currentChar);
}
}
return filteredMessage.toString();
}
public void onMessage(BattlefieldPlayerController player, String message, boolean team) {
if (!(message = message.trim()).isEmpty()) {
Karma karma = this.database.getKarmaByUser(player.getUser());
if (karma.isChatBanned()) {
long currDate = System.currentTimeMillis();
Date banTo = karma.getChatBannedBefore();
long delta = currDate - banTo.getTime();
if (delta <= 0L) {
player.parentLobby.send(Type.LOBBY_CHAT, "system", StringUtils.concatStrings("Вы отключены от чата. Вы вернётесь в ЭФИР через ", DateFormater.formatTimeToUnban(delta), ". Причина: " + karma.getReasonChatBan()));
return;
}
this.banServices.unbanChat(player.getUser());
}
if (!this.bfModel.battleInfo.team) {
team = false;
}
if (!message.isEmpty()) {
message = AntimatFilter(message);
}
String reason;
if (message.startsWith("/")) {
if (player.getUser().getType() == TypeUser.DEFAULT) {
return;
}
String[] arguments = message.replace('/', ' ').trim().split(" ");
if (!player.getUser().getUserGroup().isAvaliableChatCommand(arguments[0])) {
return;
}
User victim_;
label188: {
int i;
switch((reason = arguments[0]).hashCode()) {
case -1422509655:
if (reason.equals("addcry")) {
this.tanksServices.addCrystall(player.parentLobby, this.getInt(arguments[1]));
break label188;
}
break;
case -1217854831:
if (reason.equals("addscore")) {
i = this.getInt(arguments[1]);
if (player.parentLobby.getLocalUser().getScore() + i < 0) {
this.sendSystemMessage("[SERVER]: Ваше количество очков опыта не должно быть отрицательное!", player);
} else {
this.tanksServices.addScore(player.parentLobby, i);
}
break label188;
}
break;
case -1012222381:
if (reason.equals("online")) {
this.sendSystemMessage("Current online: " + OnlineStats.getOnline() + "\nMax online: " + OnlineStats.getMaxOnline(), player);
break label188;
}
break;
case -887328209:
if (reason.equals("system")) {
StringBuffer total = new StringBuffer();
for(i = 1; i < arguments.length; ++i) {
total.append(arguments[i]).append(" ");
}
this.sendSystemMessage(total.toString());
break label188;
}
break;
case -372425125:
if (reason.equals("spawngold")) {
i = 0;
while(true) {
if (i >= Integer.parseInt(arguments[1])) {
break label188;
}
this.bfModel.bonusesSpawnService.spawnBonus(BonusType.GOLD);
++i;
}
}
break;
case 119:
if (reason.equals("w")) {
if (arguments.length < 3) {
return;
}
User giver = this.database.getUserById(arguments[1]);
if (giver == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
String reason1 = StringUtils.concatMassive(arguments, 2);
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", giver.getNickname(), " предупрежден. Причина: ", reason1));
}
break label188;
}
break;
case 3291718:
if (reason.equals("kick")) {
User _userForKick = this.database.getUserById(arguments[1]);
if (_userForKick == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден", player);
} else {
LobbyManager _lobby = this.lobbyServices.getLobbyByUser(_userForKick);
if (_lobby != null) {
_lobby.kick();
this.sendSystemMessage(_userForKick.getNickname() + " кикнут");
}
}
break label188;
}
break;
case 98246397:
if (reason.equals("getip")) {
if (arguments.length >= 2) {
User shower = this.database.getUserById(arguments[1]);
if (shower == null) {
return;
}
String ip = shower.getAntiCheatData().ip;
if (ip == null) {
ip = shower.getLastIP();
}
this.sendSystemMessage("IP user " + shower.getNickname() + " : " + ip, player);
}
break label188;
}
break;
case 111426262:
if (reason.equals("unban")) {
if (arguments.length >= 2) {
User cu = this.database.getUserById(arguments[1]);
if (cu == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
this.banServices.unbanChat(cu);
this.sendSystemMessage("Танкисту " + cu.getNickname() + " был разрешён выход в эфир");
}
}
break label188;
}
break;
case 873005567:
if (reason.equals("blockgame")) {
if (arguments.length < 3) {
return;
}
victim_ = this.database.getUserById(arguments[1]);
boolean var10 = false;
int reasonId;
try {
reasonId = Integer.parseInt(arguments[2]);
} catch (Exception var20) {
reasonId = 0;
}
if (victim_ == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
this.banServices.ban(BanType.GAME, BanTimeType.FOREVER, victim_, player.getUser(), BlockGameReason.getReasonById(reasonId).getReason());
LobbyManager lobby = this.lobbyServices.getLobbyByNick(victim_.getNickname());
if (lobby != null) {
lobby.kick();
}
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", victim_.getNickname(), " был заблокирован и кикнут"));
}
break label188;
}
break;
case 941444998:
if (reason.equals("unblockgame")) {
if (arguments.length < 2) {
return;
}
User av = this.database.getUserById(arguments[1]);
if (av == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
this.banServices.unblock(av);
this.sendSystemMessage(av.getNickname() + " разблокирован");
}
break label188;
}
break;
case 2066192527:
if (reason.equals("spawncry")) {
i = 0;
while(true) {
if (i >= Integer.parseInt(arguments[1])) {
break label188;
}
this.bfModel.bonusesSpawnService.spawnBonus(BonusType.CRYSTALL);
++i;
}
}
}
if (!message.startsWith("/ban")) {
this.sendSystemMessage("[SERVER]: Неизвестная команда!", player);
}
}
if (message.startsWith("/ban")) {
BanTimeType time = BanChatCommads.getTimeType(arguments[0]);
if (arguments.length < 3) {
return;
}
String reason2 = StringUtils.concatMassive(arguments, 2);
if (time == null) {
this.sendSystemMessage("[SERVER]: Команда бана не найдена!", player);
return;
}
victim_ = this.database.getUserById(arguments[1]);
if (victim_ == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
return;
}
this.banServices.ban(BanType.CHAT, time, victim_, player.getUser(), reason2);
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", victim_.getNickname(), " лишен права выхода в эфир ", time.getNameType(), " Причина: ", reason2));
}
} else {
if (message.length() >= 399) {
message = null;
return;
}
if (player.getUser().getRang() + 1 >= 3 || player.getUser().getType() != TypeUser.DEFAULT) {
if (!player.parentLobby.getChatFloodController().detected(message)) {
player.parentLobby.timer = System.currentTimeMillis();
if (team) {
// Отправить сообщение только участникам команды
bfModel.sendMessageToTeam(new BattleChatMessage(player.getUser().getNickname(), player.getUser().getRang(), message, player.playerTeamType, true, false), player.playerTeamType);
} else {
// Отправить сообщение всем игрокам
bfModel.sendMessageToAll(new BattleChatMessage(player.getUser().getNickname(), player.getUser().getRang(), message, player.playerTeamType, false, false));
}
} else {
if (player.getUser().getWarnings() >= 5) {
BanTimeType time = BanTimeType.FIVE_MINUTES;
reason = "Флуд.";
this.banServices.ban(BanType.CHAT, time, player.getUser(), player.getUser(), reason);
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", player.getUser().getNickname(), " лишен права выхода в эфир ", time.getNameType(), " Причина: ", reason));
return;
}
this.sendSystemMessage("Танкист " + player.getUser().getNickname() + " предупрежден. Причина: Флуд.");
player.getUser().addWarning();
}
} else {
this.sendSystemMessage("Чат доступен, начиная со звания Ефрейтор.", player);
}
}
}
}
public void sendSystemMessage(String message) {
if (message == null) {
message = " ";
}
this.sendMessage(new BattleChatMessage((String)null, 0, message, "NONE", false, true));
}
public void sendSystemMessage(String message, BattlefieldPlayerController player) {
if (message == null) {
message = " ";
}
this.sendMessage(new BattleChatMessage((String)null, 0, message, "NONE", false, true), player);
}
private void sendMessage(BattleChatMessage msg) {
this.bfModel.sendToAllPlayers(Type.BATTLE, "chat", JSONUtils.parseBattleChatMessage(msg));
}
private void sendMessage(BattleChatMessage msg, BattlefieldPlayerController controller) {
controller.send(Type.BATTLE, "chat", JSONUtils.parseBattleChatMessage(msg));
}
public int getInt(String src) {
try {
return Integer.parseInt(src);
} catch (Exception var3) {
return Integer.MAX_VALUE;
}
}
}
как ошибку в repeat
|
b5793102f41678be06540d48b468e5cb
|
{
"intermediate": 0.24903267621994019,
"beginner": 0.5761193037033081,
"expert": 0.17484797537326813
}
|
34,373
|
can you make images?
|
fe9706ad4bd2ec1c8cad97c1732e9244
|
{
"intermediate": 0.31475940346717834,
"beginner": 0.24472488462924957,
"expert": 0.4405157268047333
}
|
34,374
|
hello
|
136d95fe86921064e25032fb84543ee3
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
34,375
|
Есть компонент на vue с использованием библиотеки element-plus, вот его код:
<template>
<ActionDialog
:title="isEdit ? 'Редактировать светофор' : 'Добавить светофор'"
:visible="dialog.visible"
@handle-close="(visible: boolean) => (dialog.visible = visible)"
@save="validateTrafficLights"
>
<el-form
ref="form"
:model="form"
:rules="rules"
label-width="160px"
label-position="top"
>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item prop="id" label="ID светофора">
<el-input v-model="form.id" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item prop="number" label="Номер светофора">
<el-input v-model="form.number" />
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item prop="type" label="Тип">
<el-select v-model="form.type" multiple>
<el-option
v-for="value in form.type"
:key="value"
:label="value"
:value="value"
>
</el-option>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item prop="bs" label="Блок-участок">
<el-select v-model="form.bs" multiple>
<el-option
v-for="value in form.bs"
:key="value"
:label="value"
:value="value"
/>
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="Графическое отображение">
<el-input value="иконка светофора" />
</el-form-item>
</el-col>
</el-row>
</el-form>
</ActionDialog>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import type { ITrafficLightsItem } from "@entities";
import { ActionDialog } from "@shared";
export default defineComponent({
name: "TrafficLightsDialog",
components: {
ActionDialog,
},
props: {
trafficLightsData: {
type: Object as () => ITrafficLightsItem,
required: true,
},
isEdit: {
type: Boolean as PropType<Boolean>,
default: false,
},
},
emits: ["saveTrafficLights"],
data() {
return {
dialog: {
visible: false,
},
form: { ...this.trafficLightsData },
rules: {
id: [
{
required: true,
message: "Пожалуйста, введите корректный id",
trigger: ["blur", "change"],
},
{
min: 1,
max: 5,
message: "Количество символов должно быть от 1 до 5",
},
],
number: [
{
required: true,
message: "Пожалуйста, введите номер светофора",
trigger: ["blur", "change"],
},
{
min: 1,
max: 5,
message: "Количество символов должно быть от 1 до 5",
},
],
type: {
required: true,
message: "Пожалуйста, выберите тип светофора",
trigger: ["blur", "change"],
},
bs: {
required: true,
message: "Пожалуйста, выберите блок-участок",
trigger: ["blur", "change"],
},
},
};
},
watch: {
trafficLightsData(newValue: ITrafficLightsItem) {
this.form = { ...newValue };
},
},
methods: {
saveTrafficLights() {
const newItem = { ...this.form };
this.$emit("saveTrafficLights", newItem);
},
validateTrafficLights() {
if (this.$refs.form.validate()) {
this.saveTrafficLights();
} else {
console.log("заполните форму");
}
},
},
});
</script>
Почему не срабатывает validateTrafficLights() при нажатии сохранить? Даже если поля пустые, данные отправляются родительскому компоненту.
|
a1fa168a6064e2b31487b0b3aee0736e
|
{
"intermediate": 0.26682955026626587,
"beginner": 0.6066078543663025,
"expert": 0.12656256556510925
}
|
34,376
|
Can you please make it so that it is possible to assign a key to ollie from the gui inspector?
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Rigidbody))]
public class HoverBoardControl : MonoBehaviour
{
[Header("Hover Settings")]
public float hoverForce = 9.0f;
public float hoverHeight = 2.0f;
public GameObject[] hoverPoints;
[Header("Movement Settings")]
public float forwardAcceleration = 100.0f;
public float backwardAcceleration = 25.0f;
public float turnStrength = 10f;
[Header("UI & Scoring")]
public Text scoreText;
public int currentScore;
public HUD hud;
public TrickManager trickManager;
[Header("Boost Settings")]
public float boostMultiplier = 2.0f;
[Header("Rotation Settings")]
public float minRotation = -20.0f;
public float maxRotation = 0.0f;
[Header("Grind Settings")]
public bool grind;
public GameObject grindBoard;
[Header("Timer Settings")]
public float timer = 5.0f;
[Header("Miscellaneous")]
public bool moving;
public GameObject board;
[Header("Input Settings")]
public KeyCode moveForwardKey = KeyCode.W;
public KeyCode moveBackwardKey = KeyCode.S;
public KeyCode turnLeftKey = KeyCode.A;
public KeyCode turnRightKey = KeyCode.D;
int layerMask;
float currentThrust; // Declare here so it's accessible throughout the method
float currentTurn; // Declare here so it's accessible throughout the method
void Awake()
{
hud = GameObject.FindObjectOfType<HUD>();
trickManager = GetComponent<TrickManager>();
}
void Start()
{
GetComponent<Rigidbody>();
layerMask = 1 << LayerMask.NameToLayer("Characters");
layerMask = ~layerMask;
}
void Update()
{
currentThrust = 0.0f;
currentTurn = 0.0f;
scoreText.text = currentScore + " Points";
if (Input.GetKeyDown(KeyCode.Space))
{
hoverForce = 1500f;
hoverHeight += 0.05f;
if (hoverHeight >= 6f)
{
hoverHeight = 6f;
}
}
else
{
hoverHeight -= 0.03f;
if (hoverHeight <= 5f)
{
hoverHeight = 5f;
}
}
if (hud != null)
{
if (Input.GetKeyDown(KeyCode.LeftControl) && (hud.BoostInt > 0))
{
forwardAcceleration = forwardAcceleration * boostMultiplier;
backwardAcceleration = backwardAcceleration * boostMultiplier;
if (hud.BoostInt <= 0)
{
forwardAcceleration = forwardAcceleration / boostMultiplier;
backwardAcceleration = backwardAcceleration / boostMultiplier;
}
}
if (Input.GetKey(KeyCode.LeftControl))
{
hud.BoostInt -= 0.2f;
}
}
float minRotation = -20;
float maxRotation = 0;
Vector3 currentRotation = transform.localRotation.eulerAngles;
currentRotation.z = Mathf.Clamp(currentRotation.z, minRotation, maxRotation);
transform.localRotation = Quaternion.Euler(new Vector3(0, currentRotation.y, 0));
// Main Thrust
float aclAxis = Input.GetAxis("Vertical");
if (aclAxis > 0.1f)
currentThrust = aclAxis * forwardAcceleration;
else if (aclAxis < -0.1f)
currentThrust = aclAxis * backwardAcceleration;
// Turning
float turnAxis = Input.GetAxis("Horizontal");
if (Mathf.Abs(turnAxis) > 0.1f)
currentTurn = turnAxis;
// Trick execution
if (Input.GetKeyDown(trickManager.kickflipKey))
{
trickManager.ExecuteKickflip();
}
else if (Input.GetKeyDown(trickManager.heelflipKey))
{
trickManager.ExecuteHeelflip();
}
else if (Input.GetKeyDown(trickManager.shoveItKey))
{
trickManager.ExecuteShoveIt();
}
// Your additional Update logic, if any...
}
void FixedUpdate()
{
// Hover Force
RaycastHit hit;
for (int i = 0; i < hoverPoints.Length; i++)
{
var hoverPoint = hoverPoints[i];
if (Physics.Raycast(hoverPoint.transform.position,
-Vector3.up, out hit,
hoverHeight,
layerMask))
GetComponent<Rigidbody>().AddForceAtPosition(Vector3.up
* hoverForce
* (1.0f - (hit.distance / hoverHeight)),
hoverPoint.transform.position);
else
{
if (transform.position.y > hoverPoint.transform.position.y)
GetComponent<Rigidbody>().AddForceAtPosition(
hoverPoint.transform.up * hoverForce,
hoverPoint.transform.position);
else
GetComponent<Rigidbody>().AddForceAtPosition(
hoverPoint.transform.up * -hoverForce,
hoverPoint.transform.position);
}
if (hit.transform != null)
{
if (hit.transform.tag.Equals("Grind"))
{
if (currentThrust >= 1)
{
currentScore += 1;
}
}
if (hit.transform.tag.Equals("Score"))
{
currentScore += 50;
hit.collider.gameObject.GetComponent<BoxCollider>().enabled = false;
}
if (hit.transform.tag.Equals("Score2"))
{
currentScore += 25;
hit.collider.gameObject.GetComponent<BoxCollider>().enabled = false;
}
}
}
// Forward
if (Mathf.Abs(currentThrust) > 0)
GetComponent<Rigidbody>().AddForce(transform.forward * currentThrust);
// Turn
if (currentTurn > 0)
{
GetComponent<Rigidbody>().AddRelativeTorque(Vector3.up * currentTurn * turnStrength);
}
else if (currentTurn < 0)
{
GetComponent<Rigidbody>().AddRelativeTorque(Vector3.up * currentTurn * turnStrength);
}
// Your existing FixedUpdate logic...
// For example:
// 1. Physics calculations
// 2. Rigidbody forces and torques
// 3. Anything related to fixed time steps
// Keep your original FixedUpdate logic unchanged.
}
}
|
0145e2589d0a7553713373b9997f8454
|
{
"intermediate": 0.3728422522544861,
"beginner": 0.387069433927536,
"expert": 0.24008826911449432
}
|
34,377
|
Есть компонент на vue с использованием библиотеки element-plus, вот его код:
<template>
<ActionDialog
:title="isEdit ? 'Редактировать светофор' : 'Добавить светофор'"
:visible="dialog.visible"
@handle-close="(visible: boolean) => (dialog.visible = visible)"
@save="validateTrafficLights"
>
<el-form
ref="form"
:model="form"
:rules="rules"
label-width="160px"
label-position="top"
>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item prop="id" label="ID светофора">
<el-input v-model="form.id" />
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item prop="number" label="Номер светофора">
<el-input v-model="form.number" />
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item prop="type" label="Тип">
<el-select v-model="form.type" multiple>
<el-option
v-for="value in form.type"
:key="value"
:label="value"
:value="value"
>
</el-option>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item prop="bs" label="Блок-участок">
<el-select v-model="form.bs" multiple>
<el-option
v-for="value in form.bs"
:key="value"
:label="value"
:value="value"
/>
</el-select>
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12">
<el-form-item label="Графическое отображение">
<el-input value="иконка светофора" />
</el-form-item>
</el-col>
</el-row>
</el-form>
</ActionDialog>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import type { ITrafficLightsItem } from "@entities";
import { ActionDialog } from "@shared";
export default defineComponent({
name: "TrafficLightsDialog",
components: {
ActionDialog,
},
props: {
trafficLightsData: {
type: Object as () => ITrafficLightsItem,
required: true,
},
isEdit: {
type: Boolean as PropType<Boolean>,
default: false,
},
},
emits: ["saveTrafficLights"],
data() {
return {
dialog: {
visible: false,
},
form: { ...this.trafficLightsData },
rules: {
id: [
{
required: true,
message: "Пожалуйста, введите корректный id",
trigger: ["blur", "change"],
},
{
min: 1,
max: 5,
message: "Количество символов должно быть от 1 до 5",
},
],
number: [
{
required: true,
message: "Пожалуйста, введите номер светофора",
trigger: ["blur", "change"],
},
{
min: 1,
max: 5,
message: "Количество символов должно быть от 1 до 5",
},
],
type: {
required: true,
message: "Пожалуйста, выберите тип светофора",
trigger: ["blur", "change"],
},
bs: {
required: true,
message: "Пожалуйста, выберите блок-участок",
trigger: ["blur", "change"],
},
},
};
},
watch: {
trafficLightsData(newValue: ITrafficLightsItem) {
this.form = { ...newValue };
},
},
methods: {
saveTrafficLights() {
const newItem = { ...this.form };
this.$emit("saveTrafficLights", newItem);
},
validateTrafficLights() {
if (this.$refs.form.validate()) {
this.saveTrafficLights();
} else {
console.log("заполните форму");
}
},
},
});
</script>
Почему не срабатывает validateTrafficLights() при нажатии сохранить? Даже если поля пустые, данные отправляются родительскому компоненту.
|
516d427a15b77a7530db9a19c434a0c9
|
{
"intermediate": 0.26682955026626587,
"beginner": 0.6066078543663025,
"expert": 0.12656256556510925
}
|
34,378
|
bash script to grep and display any text between two markers
|
ff63779cef2f12a04d838bda977717b7
|
{
"intermediate": 0.42599576711654663,
"beginner": 0.24257859587669373,
"expert": 0.33142566680908203
}
|
34,379
|
CONSTRAINTS:
1. ~100k word limit for short term memory. Your short term memory is short, so immediately save important information to files.
2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.
3. No user assistance
4. Exclusively use the commands listed in double quotes e.g. "command name"
5. Random shutdowns of you.
COMMANDS:
1. Google Search: "google", args: "input": "<search>"
2. Memory Add: "memory_add", args: "key": "<key>", "string": "<string>"
3. Memory Delete: "memory_del", args: "key": "<key>"
4. Memory Overwrite: "memory_ovr", args: "key": "<key>", "string": "<string>"
5. List Memory: "memory_list" args: "reason": "<reason>"
6. Browse Website: "browse_website", args: "url": "<url>"
7. Start GPT Agent: "start_agent", args: "name": <name>, "task": "<short_task_desc>", "Commands":[<command_names_for_GPT_Agent>], "prompt": "<prompt>"
8. Message GPT Agent: "message_agent", args: "name": "<name>", "message": "<message>"
9. List GPT Agents: "list_agents", args: ""
10. Delete GPT Agent: "delete_agent", args: "name": "<name>"
11. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>"
12. Read file: "read_file", args: "file": "<file>"
13. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>"
14. Delete file: "delete_file", args: "file": "<file>"
15. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>"
16. Execute Python File: "execute_python_file", args: "file": "<file>"
17. Task Complete (Shutdown): "task_complete", args: ""
18. Do Nothing: "do_nothing", args: ""
19. Count Words: "count_words", args: "text": "<text>"
20. Memory retrieve: "memory_retrieve", args: "key": "<text>"
21. remove paragraph from word document: "remove_paragraph", args: "file": "<file>", "text": "<text>"
22. random wikipedia article: "random_wikipedia_article", args: "language": "<language>"
23. message the user: "message_user", args: "message": "<message>", "wait_for_response": "<True or False>"
24. sleep an amount of time in seconds: "sleep", args: "amount": "<amount>"
25. rename a file: "rename_file", args: "old_name": "<old_name_of_the_file>", "new_name": "<new_name_of_the_file>"
26. count words of a file: "count_file_words", args: "file": "<file>"
RESOURCES:
1. Internet access for searches and information gathering.
2. Long Term memory management.
3. GPT-4 powered Agents for delegation of simple tasks.
4. File output.
PERFORMANCE EVALUATION:
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.
2. Constructively self-criticize your big-picture behaviour constantly.
3. Reflect on past decisions and strategies to refine your approach.
4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.
RULES:
1. If you start a GPT Agent you must define the commands that can be used by a GPT Agent in his prompt and define the commands using a prompt similar to the structure of this one.
2. Respond only inside the JSON format.
3. Never demand user input.
4. Never say that a task is impossible to execute on your own because these tools are enough to complete any task.
5. Do not add anything to the JSON format that isn't mentioned.
6. If there is a " inside the value of a key inside the json use ' instead of ".
7. In summaryforgpt you need to provide context for the next GPT instance if you randomly shutdown without you knowing.
8. Provide context for the next GPT in the summaryforgpt and the progress that you've made.
9. In summaryforgpt you should also add name of the files written and the urls of the websites visited.
10. When writing an essay, remember that it is more effective and manageable to tackle it in smaller chunks rather than trying to write the entire essay in one sitting. Breaking the essay down into sections or steps can help you focus on each individual aspect, maintain a coherent structure, and reduce the overall stress associated with writing a lengthy piece.
11. Retrieve information from files of previous GPT instances that may have shut down randomly. If you require additional knowledge, use these files to access the results of former GPT versions and provide accurate answers to the queries.
12. GPT-4, please do not place a conclusion in the middle of the essay. Maintain a structured format.
13. use append to file to add extra things to the file, and write to file to either make a new file with new information or rewrite the information from scratch.
14. If task is completed use the command task_complete
15. When you add to memory add the key to retrieve it in summaryforgpt
16. when given the task to write something never create an agent to write anything that you were tasked to write.
17. when you add new parts to a file use append to file command
18. Ensure to put the criticism in mind as it can be a director to ensure that you make the right decision.
19. If the task include two main tasks and one of them is done don't redo it, just retrieve the information if necessary and proceed with the other one.
20. Make sure that the information generated is not made up.
21. Languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french.
22. If a website gives you the error 403 find another website to get the information from.
23. Always listen to your criticism, and follow it.
24. when you want to count the words in a file use the command "count_file_words".
25. Don't repeat yourself.
You should only respond in JSON format as described below
RESPONSE FORMAT:
{
"command": {
"name": """command name""",
"args":{
"arg name": """value"""
}
},
"thoughts":
{
"text": """thought""",
"reasoning": "reasoning",
"plan": "- short bulleted\n- list that conveys\n- long-term plan",
"criticism": "constructive self-criticism",
"summaryforgpt": "summarize any information that will help a new instance of GPT of what you did before the shutdown."
}
}
Ensure the response can be parsed by Python json.loads
The Task: message user about the task needed and get the response from him.
|
6f695dfa6d187e364306f0761b154907
|
{
"intermediate": 0.3397374749183655,
"beginner": 0.4271845817565918,
"expert": 0.2330779731273651
}
|
34,380
|
header:
#pragma once
#include <cstdlib>
#include <string>
#include <vector>
namespace ArgumentParser {
class ArgParser {
public:
ArgParser(const std::string& name) : name(name) {}
~ArgParser();
bool Parse(const std::vector<std::string>& argv);
ArgParser& AddStringArgument(std::string long_name);
ArgParser& AddStringArgument(char short_name);
ArgParser& AddStringArgument(char short_name, std::string argument);
std::string GetStringValue(std::string long_name);
std::string GetStringValue(char short_name);
ArgParser& StoreValue(std::string& value);
ArgParser& Default(const char* default_value);
ArgParser& AddIntArgument(std::string argument);
ArgParser& AddIntArgument(char short_name, std::string argument);
ArgParser& AddIntArgument(char short_name);
int32_t GetIntValue(std::string long_name);
int32_t GetIntValue(char short_name);
int32_t GetIntValue(std::string long_name, int32_t index);
int32_t GetIntValue(char short_name, int32_t index);
ArgParser& StoreValues(std::vector<int32_t>& values);
ArgParser& MultiValue();
ArgParser& MultiValue(size_t min_arguments_count);
ArgParser& AddFlag(char short_name, std::string long_name);
ArgParser& AddFlag(char short_name);
ArgParser& AddFlag(std::string long_name);
bool GetFlag(char short_name);
bool GetFlag(std::string long_name);
ArgParser& Default(bool value);
ArgParser& StoreValue(bool& value);
ArgParser& Positional();
ArgParser& AddHelp(char short_name, std::string long_name, std::string description);
bool Help();
std::string HelpDescription();
ArgParser& AddStringArgumentWithDescription(std::string long_name, std::string description);
ArgParser& AddStringArgumentWithDescription(char short_name, std::string description);
ArgParser& AddStringArgumentWithDescription(char short_name, std::string long_name, std::string description);
ArgParser& AddIntArgumentWithDescription(std::string long_name, std::string description);
ArgParser& AddIntArgumentWithDescription(char short_name, std::string description);
ArgParser& AddIntArgumentWithDescription(char short_name, std::string long_name, std::string description);
ArgParser& AddFlagWithDescription(std::string long_name, std::string description);
ArgParser& AddFlagWithDescription(char short_name, std::string description);
ArgParser& AddFlagWithDescription(char short_name, std::string long_name, std::string description);
private:
std::string name;
class Argument {
public:
enum class Type { String, Integer, Bool };
std::string long_name;
char short_name;
Type type;
size_t min_arguments_count = 1;
bool is_multi_value = false;
bool is_positional = false;
bool help_requested = false;
std::string help_message;
bool is_default = false;
bool is_help_variable = false;
Argument(Type t) : type(t) {}
};
class StringArgument : public Argument {
public:
std::vector<std::string> value;
std::string* str_value_ptr = nullptr;
StringArgument() : Argument(Type::String) {}
};
class IntArgument : public Argument {
public:
std::vector<int32_t> value;
std::vector<int32_t>* int_values_ptr = nullptr;
IntArgument() : Argument(Type::Integer) {}
};
class BoolArgument : public Argument {
public:
bool value = false;
bool* bool_value_ptr = nullptr;
BoolArgument() : Argument(Type::Bool) {}
};
std::vector<Argument*> arguments;
int32_t FindByLongName(const std::string& long_name);
int32_t FindByShortName(char short_name);
};
} // namespace ArgumentParser
cpp:
#include "ArgParser.h"
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
namespace ArgumentParser {
ArgParser::~ArgParser() {
for (Argument* arg : arguments) {
delete arg;
}
}
bool IsValue(const std::string& buff) {
return buff.size() == 1 || std::isdigit(buff[1]);
}
int32_t ArgParser::FindByLongName(const std::string& long_name) {
for (int i = 0; i < arguments.size(); ++i) {
if (arguments[i]->long_name == long_name) {
return i;
}
}
return -1;
}
int32_t ArgParser::FindByShortName(char short_name) {
for (int i = 0; i < arguments.size(); ++i) {
if (arguments[i]->short_name == short_name) {
return i;
}
}
return -1;
}
bool ArgParser::Parse(const std::vector<std::string>& argv) {
if (arguments.empty()) {
return true;
}
size_t positional_index = 0;
for (size_t i = 1; i < argv.size(); ++i) {
if (argv[i][0] != '-') {
if (positional_index >= arguments.size()) {
return false;
}
if (argv[i][0] != '-') {
Argument* arg = arguments[positional_index];
if (arg->is_positional) {
switch (arg->type) {
case Argument::Type::String: {
StringArgument* stringArg = static_cast<StringArgument*>(arg);
stringArg->value.push_back(argv[i]);
if (stringArg->str_value_ptr != nullptr) {
*stringArg->str_value_ptr = argv[i];
}
break;
}
case Argument::Type::Integer: {
IntArgument* intArg = static_cast<IntArgument*>(arg);
intArg->value.push_back(std::stoi(argv[i]));
if (intArg->int_values_ptr != nullptr) {
intArg->int_values_ptr->push_back(std::stoi(argv[i]));
}
break;
}
case Argument::Type::Bool:
break;
}
if (!arg->is_multi_value) {
++positional_index;
}
} else return false;
}
} else {
std::string argStr = argv[i];
if (argStr[0] == '-') {
if (argStr.size() > 1 && argStr[1] == '-') {
size_t equalPos = argStr.find("=");
std::string longName = (equalPos != std::string::npos) ? argStr.substr(2, equalPos - 2) : argStr.substr(2);
std::string value = (equalPos != std::string::npos) ? argStr.substr(equalPos + 1) : argStr.substr(2);
int index = FindByLongName(longName);
if (index == -1) {
return false;
}
Argument* argument = arguments[index];
switch (argument->type) {
case Argument::Type::String:
static_cast<StringArgument*>(argument)->value.push_back(value);
if (static_cast<StringArgument*>(argument)->str_value_ptr != nullptr) {
*static_cast<StringArgument*>(argument)->str_value_ptr = value;
}
break;
case Argument::Type::Integer:
static_cast<IntArgument*>(argument)->value.push_back(stoi(value));
if (static_cast<IntArgument*>(argument)->int_values_ptr != nullptr) {
static_cast<IntArgument*>(argument)->int_values_ptr->push_back(stoi(value));
}
break;
case Argument::Type::Bool:
static_cast<BoolArgument*>(argument)->value = true;
if (static_cast<BoolArgument*>(argument)->bool_value_ptr != nullptr) {
*static_cast<BoolArgument*>(argument)->bool_value_ptr = true;
}
break;
}
if (!argument->is_multi_value && i + 1 < argv.size() && argv[i + 1][0] != '-') {
static_cast<StringArgument*>(argument)->value.push_back(argv[++i]);
}
} else {
size_t len = argStr.size();
for (size_t j = 1; j < len; ++j) {
char shortName = argStr[j];
int index = FindByShortName(shortName);
if (index == -1) {
std::cerr << "Unknown option: " << shortName << std::endl;
return false;
}
Argument* argument = arguments[index];
switch (argument->type) {
case Argument::Type::String:
static_cast<StringArgument*>(argument)->value.push_back((j + 1 < len) ? argStr.substr(j + 2) : "");
if (static_cast<StringArgument*>(argument)->str_value_ptr != nullptr) {
*static_cast<StringArgument*>(argument)->str_value_ptr = (j + 1 < len) ? argStr.substr(j + 2) : "";
}
break;
case Argument::Type::Integer:
static_cast<IntArgument*>(argument)->value.push_back((j + 1 < len) ? stoi(argStr.substr(j + 2)) : 0);
if (static_cast<IntArgument*>(argument)->int_values_ptr != nullptr) {
static_cast<IntArgument*>(argument)->int_values_ptr->push_back((j + 1 < len) ? stoi(argStr.substr(j + 2)) : 0);
}
break;
case Argument::Type::Bool:
static_cast<BoolArgument*>(argument)->value = true;
if (static_cast<BoolArgument*>(argument)->bool_value_ptr != nullptr) {
*static_cast<BoolArgument*>(argument)->bool_value_ptr = true;
}
break;
}
if (argument->type != Argument::Type::Bool) {
break;
}
}
}
}
}
}
for (auto& arg : arguments) {
size_t minimumCount = arg->min_arguments_count;
size_t providedCount = 0;
switch (arg->type) {
case Argument::Type::String:
providedCount = static_cast<StringArgument*>(arg)->value.size();
break;
case Argument::Type::Integer:
providedCount = static_cast<IntArgument*>(arg)->value.size();
break;
default:
continue;
}
if (providedCount < minimumCount && !arg->is_default && !arg->help_requested) {
return false;
}
}
return true;
}
ArgParser& ArgParser::AddStringArgument(std::string long_name) {
StringArgument* arg = new StringArgument();
arg->long_name = std::move(long_name);
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddStringArgument(char short_name) {
StringArgument* arg = new StringArgument();
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddStringArgument(char short_name, std::string long_name) {
StringArgument* arg = new StringArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::StoreValue(std::string& value) {
if (arguments.back()->type == Argument::Type::String) {
StringArgument* stringArg = static_cast<StringArgument*>(arguments.back());
stringArg->str_value_ptr = &value;
}
return *this;
}
std::string ArgParser::GetStringValue(std::string long_name) {
int32_t index = FindByLongName(long_name);
if (index != -1 && arguments[index]->type == Argument::Type::String) {
StringArgument* stringArg = static_cast<StringArgument*>(arguments[index]);
if (!stringArg->value.empty()) return stringArg->value.front();
}
return "";
}
std::string ArgParser::GetStringValue(char short_name) {
int32_t index = FindByShortName(short_name);
if (index != -1 && arguments[index]->type == Argument::Type::String) {
StringArgument* stringArg = static_cast<StringArgument*>(arguments[index]);
if (!stringArg->value.empty()) return stringArg->value.front();
}
return "";
}
ArgParser& ArgParser::Default(const char* default_value) {
if (arguments.back()->type == Argument::Type::String) {
StringArgument* stringArg = static_cast<StringArgument*>(arguments.back());
if (stringArg->value.empty()) {
stringArg->value.push_back(default_value);
}
stringArg->is_default = true;
} else {
std::cerr << "Parameter isn't correct";
exit(EXIT_FAILURE);
}
return *this;
}
ArgParser& ArgParser::AddIntArgument(std::string long_name) {
IntArgument* arg = new IntArgument();
arg->long_name = std::move(long_name);
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgument(char short_name) {
IntArgument* arg = new IntArgument();
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgument(char short_name, std::string long_name) {
IntArgument* arg = new IntArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
int32_t ArgParser::GetIntValue(std::string long_name) {
int32_t index = FindByLongName(long_name);
if (index != -1 && arguments[index]->type == Argument::Type::Integer) {
IntArgument* intArg = static_cast<IntArgument*>(arguments[index]);
if (!intArg->value.empty()) return intArg->value.front();
}
return 0;
}
int32_t ArgParser::GetIntValue(char short_name) {
int32_t index = FindByShortName(short_name);
if (index != -1 && arguments[index]->type == Argument::Type::Integer) {
IntArgument* intArg = static_cast<IntArgument*>(arguments[index]);
if (!intArg->value.empty()) return intArg->value.front();
}
return 0;
}
int32_t ArgParser::GetIntValue(std::string long_name, int32_t index) {
int32_t index_of_argument = FindByLongName(long_name);
IntArgument* intArg = static_cast<IntArgument*>(arguments[index_of_argument]);
return intArg->value[index];
}
ArgParser& ArgParser::StoreValues(std::vector<int32_t>& values) {
if (arguments.back()->type == Argument::Type::Integer) {
IntArgument* intArg = static_cast<IntArgument*>(arguments.back());
intArg->int_values_ptr = &values;
}
return *this;
}
ArgParser& ArgParser::MultiValue() {
arguments.back()->is_multi_value = true;
return *this;
}
ArgParser& ArgParser::MultiValue(size_t min_arguments_count) {
arguments.back()->is_multi_value = true;
arguments.back()->min_arguments_count = min_arguments_count;
return *this;
}
ArgParser& ArgParser::AddFlag(char short_name, std::string long_name) {
BoolArgument* arg = new BoolArgument;
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlag(char short_name) {
BoolArgument* arg = new BoolArgument;
arg->short_name = short_name;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlag(std::string long_name) {
BoolArgument* arg = new BoolArgument;
arg->long_name = std::move(long_name);
arguments.push_back(arg);
return *this;
}
bool ArgParser::GetFlag(char short_name) {
int32_t index = FindByShortName(short_name);
if (index != -1 && arguments[index]->type == Argument::Type::Bool) {
BoolArgument* boolArg = static_cast<BoolArgument*>(arguments[index]);
return boolArg->value;
}
return false;
}
bool ArgParser::GetFlag(std::string long_name) {
int32_t index = FindByLongName(long_name);
if (index != -1 && arguments[index]->type == Argument::Type::Bool) {
BoolArgument* boolArg = static_cast<BoolArgument*>(arguments[index]);
return boolArg->value;
}
return false;
}
ArgParser& ArgParser::Default(bool value) {
if (arguments.back()->type == Argument::Type::Bool) {
BoolArgument* boolArg = static_cast<BoolArgument*>(arguments.back());
boolArg->value = value;
boolArg->is_default = true;
} else {
std::cerr << "Parameter isn't correct";
exit(EXIT_FAILURE);
}
return *this;
}
ArgParser& ArgParser::StoreValue(bool& value) {
if (arguments.back()->type == Argument::Type::Bool) {
BoolArgument* boolArg = static_cast<BoolArgument*>(arguments.back());
boolArg->bool_value_ptr = &value;
}
return *this;
}
ArgParser& ArgParser::Positional() {
arguments.back()->is_positional = true;
return *this;
}
ArgParser& ArgParser::AddHelp(char short_name, std::string long_name, std::string description) {
BoolArgument* arg = new BoolArgument();
arg->short_name = short_name;
arg->long_name = std::move(long_name);
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
bool ArgParser::Help() {
for(int i = 0; i < arguments.size(); ++i) {
if (arguments[i]->help_requested) {
return true;
}
}
return false;
}
std::string ArgParser::HelpDescription() {
std::stringstream help_string;
help_string << name << "\n";
for (const auto &arg : arguments) {
if (arg->help_requested) {
help_string << arg->help_message << "\n\n";
continue;
}
help_string << (arg->short_name != '\0' ? "-" : "")
<< (arg->short_name != '\0' ? std::string(1, arg->short_name) + ", " : "")
<< (!arg->long_name.empty() ? "-" : "")
<< arg->long_name;
switch (arg->type) {
case Argument::Type::String: help_string << ", <string>"; break;
case Argument::Type::Integer: help_string << ", <integer>"; break;
case Argument::Type::Bool: help_string << ", <bool>"; break;
}
help_string << ", " << arg->help_message;
if (arg->is_multi_value) {
help_string << " [repeated";
if (arg->min_arguments_count > 0) {
help_string << ", min args = " << arg->min_arguments_count;
}
help_string << "]";
}
if (arg->is_default) {
if(arg->type == Argument::Type::String){
if (arg->is_default) {
help_string << " [default = " << static_cast<StringArgument*>(arg)->value[0] << "]";
}
}else if(arg->type == Argument::Type::Integer && arg->is_default && !static_cast<IntArgument*>(arg)->value.empty()){
help_string << " [default = " << static_cast<IntArgument*>(arg)->value[0] << "]";
}else if(arg->type == Argument::Type::Bool){
if (arg->is_default) {
help_string << " [default = " << (static_cast<BoolArgument*>(arg)->value ? "true" : "false") << "]";
}
}
}
help_string << "\n\n";
}
help_string << "\n\n" << (arguments[0]->short_name != 0 ? "-" : "")
<< (arguments[0]->short_name != 0 ? std::string(1, arguments[0]->short_name) + ", " : "")
<< "--help Display this help and exit\n";
return help_string.str();
}
ArgParser& ArgParser::AddStringArgumentWithDescription(std::string long_name, std::string description) {
StringArgument* arg = new StringArgument();
arg->long_name = std::move(long_name);
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddStringArgumentWithDescription(char short_name, std::string description) {
StringArgument* arg = new StringArgument();
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddStringArgumentWithDescription(char short_name, std::string long_name, std::string description) {
StringArgument* arg = new StringArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgumentWithDescription(std::string long_name, std::string description) {
IntArgument* arg = new IntArgument();
arg->long_name = std::move(long_name);
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgumentWithDescription(char short_name, std::string description) {
IntArgument* arg = new IntArgument();
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddIntArgumentWithDescription(char short_name, std::string long_name, std::string description) {
IntArgument* arg = new IntArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlagWithDescription(std::string long_name, std::string description) {
BoolArgument* arg = new BoolArgument();
arg->long_name = std::move(long_name);
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlagWithDescription(char short_name, std::string description) {
BoolArgument* arg = new BoolArgument();
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
ArgParser& ArgParser::AddFlagWithDescription(char short_name, std::string long_name, std::string description) {
BoolArgument* arg = new BoolArgument();
arg->long_name = std::move(long_name);
arg->short_name = short_name;
arg->help_message = std::move(description);
arg->help_requested = true;
arguments.push_back(arg);
return *this;
}
} // namespace ArgumentParser
могу ли я переместить функции по типу AddStringArgument и тп внутрь наследников?
|
a820983012a4da3634eacc373b77888f
|
{
"intermediate": 0.4201658368110657,
"beginner": 0.3367997705936432,
"expert": 0.24303436279296875
}
|
34,381
|
write a SQL statement to create a christmas tree
|
cee86070b41665e32be5e084a194cb5d
|
{
"intermediate": 0.38354024291038513,
"beginner": 0.335689514875412,
"expert": 0.2807702124118805
}
|
34,382
|
нужно изменить запрос с новыми условиями выборки, SbpOperationState остается такой же, а текущее время >= (expireQr - 20 минут) и тек. время < expireQr
List<SbpOperation> expiredQrOperations = dataService.selectFromWhere(QSbpOperation.sbpOperation, QSbpOperation.class,
(sbp) -> sbp.state.in(SbpOperationState.NEW.name())
.and(sbp.extState.in(SbpOperationExtState.REGISTERED.name(), SbpOperationExtState.VERIFIED.name()))
.and(sbp.expireQr.before(LocalDateTime.now()))).fetch();
|
7dac25e182a45c7f5f4e28311ad6b9be
|
{
"intermediate": 0.3324222266674042,
"beginner": 0.3970589339733124,
"expert": 0.27051883935928345
}
|
34,383
|
Padding(
padding:
EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
child: TableCell(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'${firstHandsets?.price ?? " "}' +
(firstHandsets?.price != null
? " " + "currency.egyptianPound".tr()
: ""),
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 24.sp,
color: UIColors.darkGrey)),
),
),
),Another exception was thrown: Incorrect use of ParentDataWidget.
|
46f9f12fa842e9c99f57c6c5d39a88d5
|
{
"intermediate": 0.3884013891220093,
"beginner": 0.25647419691085815,
"expert": 0.35512444376945496
}
|
34,384
|
This code uses as input a mpileup produced by samtools:
# This script takes the output from an mpileup of our
# second breseq run (the "rebreseq" step") and calculates
# a timecourse for mutations at each site in the genome.
#
# Distinct SNPs at the same site are treated as two separate mutations
# but indels are merged together into a single alternate allele
import numpy
import sys
import population_parameters
reference_strs = set(['.', ','])
snp_strs = set(['A','C','T','G', 'N','*'])
indel_strs = set(['+','-'])
refskip_strs = ['<','>']
mpileup_file = sys.stdin
first_position = long(sys.argv[1])
last_position = long(sys.argv[2])
population = sys.argv[3]
sample_names = sys.argv[4:]
sample_list = []
sample_times = []
for sample_name, sample_time in zip(population_parameters.sample_names[population], population_parameters.sample_times[population]):
if sample_name in sample_names:
sample_list.append(sample_name)
sample_times.append(sample_time)
num_lines = 0
num_printed_lines = 0
for line in mpileup_file:
num_lines += 1
if num_lines % 1000 == 0:
sys.stderr.write("%d lines processed, %d passed\n" % (num_lines,num_printed_lines))
#sys.exit(0)
items = line.split('\t')
chromosome = items[0]
position = long(items[1])
ref = items[2]
if position < first_position:
continue
if position > last_position:
break
times = []
alts = []
depths = []
indel_depth_reductions = []
num_samples = (len(items)-3)/3
alleles = {ref: [0]*num_samples}
indel_alleles = set()
for i in xrange(0, num_samples):
t = sample_times[i]
depth = long(items[(i+1)*3])
allele_str = items[(i+1)*3+1].upper()
depths.append(depth)
indel_depth_reductions.append(0)
times.append(t)
j=0
jmax = len(allele_str)
# walk through the mpileup string and parse the alleles
while j < jmax:
if allele_str[j] == '^': # beginning of read
j+=2 # next character is map quality, so skip it too
elif j+1<jmax and (allele_str[j+1] in indel_strs):
#sys.stderr.write("%s\n" % allele_str[j:])
# an indel
# only record the base allele if different from ref
if allele_str[j] in reference_strs:
base_allele=''
else:
base_allele=allele_str[j]
j+=1
# whether it is a plus or minus
indel_allele = allele_str[j]
j+=1
# calculate length of insertion or deletion
# (i.e., how many characters to check afterwards)
k = j
while allele_str[k].isdigit():
k+=1
indel_len = long(allele_str[j:k])
j = k
# the inserted or deleted bases themselves
indel_bases = allele_str[j:j+indel_len]
j += indel_len
if indel_allele=='+':
# insertion
full_indel_allele = ('%s+%s' % (base_allele, indel_bases))
else:
# deletion
full_indel_allele = ('%s-%d' % (base_allele, indel_len))
indel_alleles.add(full_indel_allele)
if 'indel' not in alleles:
alleles['indel'] = [0]*num_samples
alleles['indel'][i] += 1
elif allele_str[j] in reference_strs:
# reference
alleles[ref][i] += 1
j+=1
if j<jmax and allele_str[j]=='$':
# ref fell at end of read
# don't count it for support for indel
indel_depth_reductions[i] += 1
j+=1
elif allele_str[j] in snp_strs: # regular SNP
if allele_str[j] not in alleles:
alleles[allele_str[j]] = [0]*num_samples
alleles[allele_str[j]][i] += 1
j+=1
else:
# not sure, do nothing
j+=1
depths = numpy.array(depths)
indel_depth_reductions = numpy.array(indel_depth_reductions)
depth_map = {}
indel_depth_map = {}
for i in xrange(0,len(depths)):
if times[i] not in depth_map:
depth_map[times[i]]=0
indel_depth_map[times[i]]=0
depth_map[times[i]] += depths[i]
indel_depth_map[times[i]] += (depths[i]-indel_depth_reductions[i])
merged_times = numpy.array([t for t in sorted(depth_map.keys())])
merged_depths = numpy.array([depth_map[t] for t in merged_times])
merged_indel_depths = numpy.array([indel_depth_map[t] for t in merged_times])
alt_map = {}
for allele in alleles.keys():
# don't do anything about refs
if allele==ref or allele=='*':
continue
allele_key = allele
if allele_key not in alt_map:
alt_map[allele_key] = {t: 0 for t in depth_map.keys()}
for i in xrange(0,len(depths)):
alt_map[allele_key][times[i]] += alleles[allele][i]
# get merged alts for each allele (max 5)
merged_alts = {}
for allele_key in alt_map.keys():
merged_alts[allele_key] = numpy.array([alt_map[allele_key][t] for t in merged_times])
if 'indel' in merged_alts.keys():
# if basically an indel
if ((merged_alts['indel']*1.0/(merged_indel_depths+(merged_indel_depths==0)) > 0.5)*(merged_indel_depths>10)).any():
# merge everything together
for allele_key in merged_alts.keys():
if allele_key=='indel':
continue
indel_alleles.add(allele_key)
merged_alts['indel'] += merged_alts[allele_key]
# delete reference to other SNPs
merged_alts = {'indel' : merged_alts['indel']}
for allele_key in merged_alts.keys():
if allele_key == 'indel':
alt_allele = "indel;" + ";".join(indel_alleles)
allele_depths = merged_indel_depths
else:
alt_allele = "%s->%s" % (ref,allele_key)
allele_depths = merged_depths
allele_alts = merged_alts[allele_key]
if ((allele_alts>=2).sum() > 1) and ((allele_alts >= 2)*(allele_depths>=10)*(allele_alts >= 0.05*allele_depths)).sum() > 0:
print ", ".join([chromosome, str(position), alt_allele, " ".join(str(t) for t in merged_times), " ".join(str(a) for a in allele_alts), " ".join(str(d) for d in allele_depths)])
num_printed_lines+=1
Also, is written for python2.x not 3. I need to modify this in order to work with the format provided by bcftools mpileup and python3. This is an example of 2 lines in bcftools mpileup:
REL606 4 . T <*> 0 . DP=246;I16=144,102,0,0,9206,347688,0,0,4920,98400,0,0,5016,117142,0,0;QS=2,0;FS=0;MQ0F=0 PL 0,255,222 0,255,213
REL606 5 . T A,<*> 0 . DP=248;I16=144,103,1,0,9246,348712,40,1600,4940,98800,20,400,5031,117265,25,625;QS=1.99144,0.00856164,0;SGB=-0.516033;RPBZ=-0.224845;BQBZ=0.902749;SCBZ=0.627417;FS=0;MQ0F=0 PL 0,255,222,255,222,222 0,255,211,255,214,213
|
90d06e39723fc65cf57907fec15c779d
|
{
"intermediate": 0.42418065667152405,
"beginner": 0.4575088918209076,
"expert": 0.11831043660640717
}
|
34,385
|
#include
#include <string>
#include <vector>
#include <unordered_map>
int main() {
std::string s;
std::cin >> s; // Read the input string
std::unordered_map<std::string, int> dictionary;
std::string current;
int dictIndex = 1; // Dictionary indices start from 1
for (char ch : s) {
current += ch; // Append the current character to the string
// If the current string is not found in the dictionary
if (dictionary.find(current) == dictionary.end()) {
// Output the position for the longest substring found in the dictionary
// If current is only one character long, that means we haven’t encountered it before
std::cout << (current.length() > 1 ? dictionary[current.substr(0, current.size() - 1)] : 0);
// and the current character
std::cout << " " << ch << std::endl;
// Then add the current string to the dictionary
dictionary[current] = dictIndex++;
// And clear it for the next iteration
current.clear();
}
}
// Handle the last symbol issue by checking if the current string has any remaining
// character from the last iteration that wasn’t pushed into the dictionary
if (!current.empty()) {
std::cout << dictionary[current.substr(0, current.size())] << " " << std::endl;
}
return 0;
}
Пусть утро будет нежным!
Сидя у себя в офисе в Калифорнии, Марк Цукерберг чуть не подавился молочным латте без лактозы, когда увидел какое количество памяти занимают картинки с добрым утром вашей бабушки в WhatsApp. В скором порядке он созвал внезапную планерку талантливейших кодировщиков со всего мира, где единогласно пришли к решению о сжатии всех картинок через алгоритм LZ78.
Входные данные
Строка
�
s (
∣
�
∣
≤
∣s∣≤
5
∗
1
0
5
5∗10
5
) , состоящая из строчных латинских букв, обозначающая метаданные файла, который необходимо сжать.
Выходные данные
На каждой новой строчке необходимо последовательно вывести список пар
�
�
�
pos и
�
�
�
�
next, где
�
�
�
pos - номер в словаре самого длинного найденного префикса и
�
�
�
�
next - символ, который следует за этим префиксом.
STDIN STDOUT
abcaba
0 a
0 b
0 c
1 b
1
abacababacabc
0 a
0 b
1 c
1 b
4 a
0 c
4 c
можешь написать через bst мне нельзя использовать map и тп
так же не используй умные указатели, используй обычные
|
38d6a0ba63e631d54bdcb653b2aceb4b
|
{
"intermediate": 0.34610825777053833,
"beginner": 0.38112539052963257,
"expert": 0.2727663218975067
}
|
34,386
|
Can you help me develop a downloads manager program that resembles the functionality and speed of IDM while having just the essentiels, this program will have a modern GUI with vibrant UI buttons and themes to choose from, build this app with python and use the PyQt5 library for the GUI
|
73e5382b4b7eb120dcb20e3a4717a986
|
{
"intermediate": 0.5433449149131775,
"beginner": 0.18520300090312958,
"expert": 0.27145206928253174
}
|
34,387
|
напиши тот же код на pascal: var
x_start, x_end, n: integer;
S, y: real;
begin
x_start := 1;
x_end := 2;
while x_start <= x_end do
begin
S := 0;
for n := 1 to 15 do
begin
S := S + (power(x_start, n)/math.factorial(n));
end;
y := power(2.718281, x_start);
writeln('Значение суммы при X = ', round(x_start, 2), ' равно S = ', round(S, 2), '.');
writeln('Конечная функция при X = ', round(x_start, 2), ' равно y = ', round(y, 2), '.');
x_start := x_start + 0.1;
end;
end.
|
0845a13adf7349b821ccffea829fe515
|
{
"intermediate": 0.29448896646499634,
"beginner": 0.48188433051109314,
"expert": 0.22362670302391052
}
|
34,388
|
Using lua please code me a vampire script for redm
|
3962e933bb19e810523077e79eac59d5
|
{
"intermediate": 0.5683821439743042,
"beginner": 0.22227470576763153,
"expert": 0.20934313535690308
}
|
34,389
|
create a table that summarize the global events this year that can affect the stock market
|
53f13256d2dd9acd41a25f2adcf7d4ce
|
{
"intermediate": 0.3506353795528412,
"beginner": 0.21381157636642456,
"expert": 0.43555301427841187
}
|
34,390
|
Nix bundle app with resource files
|
d24d5949702707ed6a30a10a48c0bbf8
|
{
"intermediate": 0.49219805002212524,
"beginner": 0.21820706129074097,
"expert": 0.2895949184894562
}
|
34,391
|
Nix bundle app with resource files
|
f10a7e6319ff4df4309a8f7396abf6d4
|
{
"intermediate": 0.49219805002212524,
"beginner": 0.21820706129074097,
"expert": 0.2895949184894562
}
|
34,392
|
Nix bundle app with resource files
|
4e115d475b8b87295ab0519c412f8e90
|
{
"intermediate": 0.49219805002212524,
"beginner": 0.21820706129074097,
"expert": 0.2895949184894562
}
|
34,393
|
Nix bundle app with resource files
|
4bc3db3f40af7cc73938fba116c85b0c
|
{
"intermediate": 0.49219805002212524,
"beginner": 0.21820706129074097,
"expert": 0.2895949184894562
}
|
34,394
|
Nix bundle app with resource files
|
970c880c05aef708b516cb6eadcd7034
|
{
"intermediate": 0.49219805002212524,
"beginner": 0.21820706129074097,
"expert": 0.2895949184894562
}
|
34,395
|
Nix bundle resource files together with main exe
|
68092ba4b0c473d5e6e723137fddedaf
|
{
"intermediate": 0.4486241042613983,
"beginner": 0.24819740653038025,
"expert": 0.30317842960357666
}
|
34,396
|
Как добавлять картинку при дохождения до конца страницы?
Нужно добавлять картинку каждый раз, когда дохожу до конца строки. Есть такой код, который добавляет текст бексконечно, как его переписать для картинки? Я новичок в этом
<!doctype html>
<html>
<head>
<img src=" https://e7.pngegg.com/pngimages/957/650/png-clipart-christmas-tree-christmas-tree-leaf-holidays.png ">
<meta charset="utf8" />
<title>Бесконечный скроллинг с JavaScript</title>
</head>
<body>
<div id="infinite-scroll">
<div>
<script>
for( let i = 0; i < 100; i++ )
document.write("<div>Случайный текст или еще, что то</div>");
</script>
</div>
</div>
<script>
window.addEventListener("scroll", function(){
var block = document.getElementById('infinite-scroll');
var counter = 1;
var contentHeight = block.offsetHeight; // 1) высота блока контента вместе с границами
var yOffset = window.pageYOffset; // 2) текущее положение скролбара
var window_height = window.innerHeight; // 3) высота внутренней области окна документа
var y = yOffset + window_height;
// если пользователь достиг конца
if(y >= contentHeight)
{
//<img src=" https://e7.pngegg.com/pngimages/957/650/png-clipart-christmas-tree-christmas-tree-leaf-holidays.png ">
//загружаем новое содержимое в элемент
block.innerHTML = block.innerHTML + "<div>Случайный текст или еще, что то</div>";
}
});
</script>
</body>
</html>
|
b302e12a0592e415ddfdd63a8189ca3e
|
{
"intermediate": 0.21814563870429993,
"beginner": 0.5774338245391846,
"expert": 0.2044205367565155
}
|
34,397
|
write a javascript function to calculate the duration between two dates that takes an optional paramter to determine whether the outupt should be in seconds, minutes, days, months, or years
|
88533f37c1269fa5bafbc5292075840e
|
{
"intermediate": 0.4545304775238037,
"beginner": 0.24853403866291046,
"expert": 0.296935498714447
}
|
34,398
|
Define the function and tell its types
|
ec7b9e8653a90d9343c75cced5dc5efa
|
{
"intermediate": 0.34179848432540894,
"beginner": 0.4670804738998413,
"expert": 0.19112104177474976
}
|
34,399
|
make me a program list of books
|
637e2f6c96d73adf14d117f265a3891a
|
{
"intermediate": 0.2736643850803375,
"beginner": 0.34728488326072693,
"expert": 0.37905073165893555
}
|
34,400
|
%{
import java.lang.Math;
import java.io.*;
import java.util.StringTokenizer;
%}
/* YACC Declarations */
%token <name> id
%token <value> int
%token <op> EQ GT LT GE LE NE
%token if else repeat until then def
%left '+' '-'
%left '*' '/'
/* Grammar follows */
%%
P : D ';' P
| D
;
D : def id '(' ARGS ')' '=' E
;
ARGS : id ARGS2
;
ARGS2 : ',' id ARGS2
|
;
E: E '+' T
| E '-' T
| T
;
T: T '*' F
| T '/' F
| F
;
F : int
| id
| if E OP E then E else E
| repeat E until E
| id '(' E ')'
| '(' E ')'
;
OP : '=='
| '>'
| '<'
| '>='
| '<='
| '!='
;
%%
/* Define error routine */
void yyerror(String s) {
System.err.println("Syntax Error: " + s);
}
/* Main method */
public static void main(String[] args) {
try {
/* Create lexer and parser */
Parser parser = new Parser(new Yylex(new FileReader("input.txt")));
/* Start parsing */
parser.parse();
} catch (FileNotFoundException e) {
System.err.println("File not found.");
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
} yacc.exe: 6 shift/reduce conflicts.
|
6a729139dfa64066e40d4ee3e86e0000
|
{
"intermediate": 0.32414063811302185,
"beginner": 0.4254920184612274,
"expert": 0.25036734342575073
}
|
34,401
|
Renewable electricity production, excluding hydroelectric (MWh) Population, total Research and development expenditure (% of GDP)
100000 445053 0.715149999
14148000 11274196 2.428169966
68948000 46444832 1.222360015
70487000 205188205 1.370929956
1024000 31068833 1.279450059
8260000 51014947 3.978199959
2752000 43131966 0.622619987
236000 81790841 0.417629987
2637000 4895242 0.436650008
0 3725276 0.299279988
0 622159 0.374000013
7051000 4701957 1.182909966
2977000 9843028 1.33920002
20851000 37986412 1.002750039
0 31298900 0.164969996
1997000 6298598 0.107419997
1329000 2904910 1.043409944
547000 2063531 2.195650101
3902000 3402818 0.364459991
489000 11557779 0.59412998
0 3524324 0.218600005
0 5956900 0.119029999
1706000 45154036 0.614769995
398000 1187280 0.476889998
0 8524063 0.103399999
2110000 6231066 0.143480003
2712000 5188607 1.935260057
317420992 320738994 2.782059908
8991000 17870124 0.380730003
0 2414573 0.518830001
19000 2835978 0.309430003
0 4191776 0.251549989
840000 210969298 0.24605
0 19205178 0.01963
10000 78656904 0.406379998
8752000 10820883 0.966050029
970000 144096870 1.100849986
70000 14356181 0.577199996
10865000 4609400 1.228170037
1475000 1315407 1.467499971
106000 7291300 0.761829972
171000 9461076 0.499989986
9569000 19815616 0.488380015
77262000 65116219 1.634240031
13756000 5479531 2.871959925
753000 11339894 0.428539991
2174000 5423801 1.160709977
170000 2964749 0.156399995
21044000 23815995 1.920830011
63368000 60730582 1.338500023
10187000 8642699 3.049690008
0 1460177 0.086580001
0 37757813 0.040169999
918000 5535002 2.174449921
15712000 10358076 1.243299961
5014000 330815 2.181390047
4763000 55876504 0.731469989
101000 9649341 0.222320005
7627000 10546059 1.916890025
164000 2070226 0.44411999
41000 15417523 0.11823
179000 17542806 0.169510007
18944000 5683483 3.054970026
332000 569604 1.25225997
1598000 97723799 0.718580008
0 3908743 0.096600004
Calculate the Pearson correlation coefficients between RE_MWh, R&D, and Pop. Test the statistical significance for each of the coefficients and comment on your results.
|
5355d39b0e95e615be7f4771d1d57324
|
{
"intermediate": 0.34789878129959106,
"beginner": 0.3196224868297577,
"expert": 0.33247876167297363
}
|
34,402
|
O Professor João Caracol está a fazer um estudo para a taskforce do Governo responsável pelo
estudo de doenças transmissíveis em Portugal. A taskforce está particularmente interessada no
tópico da transmissão de doenças entre a população portuguesa, de forma a estudar os melhores
mecanismos de intervenção para conter a propagação de doenças.
Para isso, o Professor João Caracol teve acesso aos dados da rede social TugaNet, que acre-
dita ser representativa das reais interacções sociais entre os indivíduos da população portuguesa.
Assim, de forma a estudar o pior caso de propagação de uma dada infecção em Portugal, o Pro-
fessor João Caracol quer perceber qual o maior número de saltos que uma dada doença pode
fazer. No entanto, tendo em conta a densidade das cidades portuguesas, o Professor João Cara-
col decidiu considerar um pressuposto simplificador: indivíduos que se conhecem mutuamente
de forma directa ou indirecta, ficam infectados instantaneamente.
Input
O ficheiro de entrada contém a informação sobre a rede TugaNet, que é definida como um grafo
dirigido de relações entre dois indivíduos, da seguinte forma:
• Uma linha contendo dois inteiros: o número n de indivíduos (n ≥ 2), e o número de
relações m a indicar (m ≥ 0);
• Uma lista em que cada linha i contém dois inteiros x e y, representando que o indivíduo x
conhece o indivíduo y.
Quaisquer inteiros numa linha estão separados por exactamente um espaço em branco, não
contendo qualquer outro carácter, a não ser o fim de linha.
Assuma que os grafos de input são dirigidos (potencialmente) cíclicos.
1
Output
O programa deverá escrever no output um inteiro s correspondendo ao número máximo de saltos
que uma doença pode fazer na rede TugaNet.
Exemplo 1
Input
7 8
3 4
3 2
4 6
4 5
6 2
6 5
5 7
2 7
Output
4
Exemplo 2
Input
8 9
2 5
3 2
3 7
4 6
5 7
6 5
7 8
8 1
8 5
Output
3
|
135f073093b5e5efef5e319661df45d5
|
{
"intermediate": 0.30608659982681274,
"beginner": 0.2967451512813568,
"expert": 0.39716827869415283
}
|
34,403
|
Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called., js engine: hermes
|
7456da1db33e37065ce6cd55fc0904ef
|
{
"intermediate": 0.6322807669639587,
"beginner": 0.16818960011005402,
"expert": 0.19952957332134247
}
|
34,404
|
Двоичный код Грея
Двоичный код Грея - способ перечисления всех
2
n
2
n
битовых строк из
n
n бит таким образом, что при следующем перечислении изменяется только один бит, само изменения детерминировано (каждый бит в последовательности определенным образом изменяется при переходе от одного числа к следующему) и регулярно (каждое число в последовательности имеет одинаковое количество единичных битов).
Например, двоичный код Грея для
n
=
4
n=4 выглядит так: 0000, 0001, 0011, 0010, 0110, 0111, 0101, 0100, 1100, 1101, 1111, 1110, 1010, 1011, 1001, 1000
Входные данные
На вход подается
n
n - порядок кода грея. #include <iostream>
#include <vector>
int main() {
int n;
std::cin >> n;
std::vector<std::string> code;
code.push_back("0");
code.push_back("1");
for (int i = 2; i < (1 << n); i = i << 1) {
for (int j = i - 1; j >= 0; --j) {
code.push_back(code[j]);
}
for (int j = 0; j < i; ++j) {
code[j] = "0" + code[j];
}
for (int j = i; j < 2 * i; ++j) {
code[j] = "1" + code[j];
}
}
for (int i = 0; i < code.size(); ++i) {
std::cout << code[i] << '\n';
}
return 0;
}
what do 1 << n and i = i << 1 mean?
|
1c91f1b41792c40204c7b3e294b81c21
|
{
"intermediate": 0.25278010964393616,
"beginner": 0.46737051010131836,
"expert": 0.2798493802547455
}
|
34,405
|
package gtanks.battles.chat;
import gtanks.StringUtils;
import gtanks.battles.BattlefieldModel;
import gtanks.battles.BattlefieldPlayerController;
import gtanks.battles.bonuses.BonusType;
import gtanks.commands.Type;
import gtanks.json.JSONUtils;
import gtanks.lobby.LobbyManager;
import gtanks.main.database.DatabaseManager;
import gtanks.main.database.impl.DatabaseManagerImpl;
import gtanks.main.params.OnlineStats;
import gtanks.services.BanServices;
import gtanks.services.LobbysServices;
import gtanks.services.TanksServices;
import gtanks.services.annotations.ServicesInject;
import gtanks.services.ban.BanChatCommads;
import gtanks.services.ban.BanTimeType;
import gtanks.services.ban.BanType;
import gtanks.services.ban.DateFormater;
import gtanks.services.ban.block.BlockGameReason;
import gtanks.users.TypeUser;
import gtanks.users.User;
import gtanks.users.karma.Karma;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
public class BattlefieldChatModel {
private BattlefieldModel bfModel;
private final int MAX_WARNING = 5;
@ServicesInject(
target = TanksServices.class
)
private TanksServices tanksServices = TanksServices.getInstance();
@ServicesInject(
target = DatabaseManager.class
)
private DatabaseManager database = DatabaseManagerImpl.instance();
@ServicesInject(
target = LobbysServices.class
)
private LobbysServices lobbyServices = LobbysServices.getInstance();
@ServicesInject(
target = BanServices.class
)
private BanServices banServices = BanServices.getInstance();
private List<String> SwearWords = Arrays.asList("сука", "блять", "бля", "пизд", "ебать", "еба", "хуй", "хуя", "хер", "хуев", "залупа", "педик", "еблан", "пизда", "гандон", "шлюха", "отьебись", "отъебись", "мудила", "пидарасы", "чмо");
public BattlefieldChatModel(BattlefieldModel bfModel) {
this.bfModel = bfModel;
}
private String AntimatFilter(String message) {
String lowercaseMessage = message.toLowerCase();
for (String mat : SwearWords) {
String lowercaseMat = mat.toLowerCase();
StringBuilder replacement = new StringBuilder();
for (int i = 0; i < mat.length(); i++) {
replacement.append("*");
}
lowercaseMessage = lowercaseMessage.replaceAll("(?i)" + Pattern.quote(lowercaseMat), replacement.toString());
}
return lowercaseMessage;
}
public void onMessage(BattlefieldPlayerController player, String message, boolean team) {
if (!(message = message.trim()).isEmpty()) {
Karma karma = this.database.getKarmaByUser(player.getUser());
if (karma.isChatBanned()) {
long currDate = System.currentTimeMillis();
Date banTo = karma.getChatBannedBefore();
long delta = currDate - banTo.getTime();
if (delta <= 0L) {
player.parentLobby.send(Type.LOBBY_CHAT, "system", StringUtils.concatStrings("Вы отключены от чата. Вы вернётесь в ЭФИР через ", DateFormater.formatTimeToUnban(delta), ". Причина: " + karma.getReasonChatBan()));
return;
}
this.banServices.unbanChat(player.getUser());
}
if (!this.bfModel.battleInfo.team) {
team = false;
}
if (!message.isEmpty()) {
message = AntimatFilter(message);
}
String reason;
if (message.startsWith("/")) {
if (player.getUser().getType() == TypeUser.DEFAULT) {
return;
}
String[] arguments = message.replace('/', ' ').trim().split(" ");
if (!player.getUser().getUserGroup().isAvaliableChatCommand(arguments[0])) {
return;
}
User victim_;
label188: {
int i;
switch((reason = arguments[0]).hashCode()) {
case -1422509655:
if (reason.equals("addcry")) {
this.tanksServices.addCrystall(player.parentLobby, this.getInt(arguments[1]));
break label188;
}
break;
case -1217854831:
if (reason.equals("addscore")) {
i = this.getInt(arguments[1]);
if (player.parentLobby.getLocalUser().getScore() + i < 0) {
this.sendSystemMessage("[SERVER]: Ваше количество очков опыта не должно быть отрицательное!", player);
} else {
this.tanksServices.addScore(player.parentLobby, i);
}
break label188;
}
break;
case -1012222381:
if (reason.equals("online")) {
this.sendSystemMessage("Current online: " + OnlineStats.getOnline() + "\nMax online: " + OnlineStats.getMaxOnline(), player);
break label188;
}
break;
case -887328209:
if (reason.equals("system")) {
StringBuffer total = new StringBuffer();
for(i = 1; i < arguments.length; ++i) {
total.append(arguments[i]).append(" ");
}
this.sendSystemMessage(total.toString());
break label188;
}
break;
case -372425125:
if (reason.equals("spawngold")) {
i = 0;
while(true) {
if (i >= Integer.parseInt(arguments[1])) {
break label188;
}
this.bfModel.bonusesSpawnService.spawnBonus(BonusType.GOLD);
++i;
}
}
break;
case 119:
if (reason.equals("w")) {
if (arguments.length < 3) {
return;
}
User giver = this.database.getUserById(arguments[1]);
if (giver == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
String reason1 = StringUtils.concatMassive(arguments, 2);
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", giver.getNickname(), " предупрежден. Причина: ", reason1));
}
break label188;
}
break;
case 3291718:
if (reason.equals("kick")) {
User _userForKick = this.database.getUserById(arguments[1]);
if (_userForKick == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден", player);
} else {
LobbyManager _lobby = this.lobbyServices.getLobbyByUser(_userForKick);
if (_lobby != null) {
_lobby.kick();
this.sendSystemMessage(_userForKick.getNickname() + " кикнут");
}
}
break label188;
}
break;
case 98246397:
if (reason.equals("getip")) {
if (arguments.length >= 2) {
User shower = this.database.getUserById(arguments[1]);
if (shower == null) {
return;
}
String ip = shower.getAntiCheatData().ip;
if (ip == null) {
ip = shower.getLastIP();
}
this.sendSystemMessage("IP user " + shower.getNickname() + " : " + ip, player);
}
break label188;
}
break;
case 111426262:
if (reason.equals("unban")) {
if (arguments.length >= 2) {
User cu = this.database.getUserById(arguments[1]);
if (cu == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
this.banServices.unbanChat(cu);
this.sendSystemMessage("Танкисту " + cu.getNickname() + " был разрешён выход в эфир");
}
}
break label188;
}
break;
case 873005567:
if (reason.equals("blockgame")) {
if (arguments.length < 3) {
return;
}
victim_ = this.database.getUserById(arguments[1]);
boolean var10 = false;
int reasonId;
try {
reasonId = Integer.parseInt(arguments[2]);
} catch (Exception var20) {
reasonId = 0;
}
if (victim_ == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
this.banServices.ban(BanType.GAME, BanTimeType.FOREVER, victim_, player.getUser(), BlockGameReason.getReasonById(reasonId).getReason());
LobbyManager lobby = this.lobbyServices.getLobbyByNick(victim_.getNickname());
if (lobby != null) {
lobby.kick();
}
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", victim_.getNickname(), " был заблокирован и кикнут"));
}
break label188;
}
break;
case 941444998:
if (reason.equals("unblockgame")) {
if (arguments.length < 2) {
return;
}
User av = this.database.getUserById(arguments[1]);
if (av == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
} else {
this.banServices.unblock(av);
this.sendSystemMessage(av.getNickname() + " разблокирован");
}
break label188;
}
break;
case 2066192527:
if (reason.equals("spawncry")) {
i = 0;
while(true) {
if (i >= Integer.parseInt(arguments[1])) {
break label188;
}
this.bfModel.bonusesSpawnService.spawnBonus(BonusType.CRYSTALL);
++i;
}
}
}
if (!message.startsWith("/ban")) {
this.sendSystemMessage("[SERVER]: Неизвестная команда!", player);
}
}
if (message.startsWith("/ban")) {
BanTimeType time = BanChatCommads.getTimeType(arguments[0]);
if (arguments.length < 3) {
return;
}
String reason2 = StringUtils.concatMassive(arguments, 2);
if (time == null) {
this.sendSystemMessage("[SERVER]: Команда бана не найдена!", player);
return;
}
victim_ = this.database.getUserById(arguments[1]);
if (victim_ == null) {
this.sendSystemMessage("[SERVER]: Игрок не найден!", player);
return;
}
this.banServices.ban(BanType.CHAT, time, victim_, player.getUser(), reason2);
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", victim_.getNickname(), " лишен права выхода в эфир ", time.getNameType(), " Причина: ", reason2));
}
} else {
if (message.length() >= 399) {
message = null;
return;
}
if (player.getUser().getRang() + 1 >= 3 || player.getUser().getType() != TypeUser.DEFAULT) {
if (!player.parentLobby.getChatFloodController().detected(message)) {
player.parentLobby.timer = System.currentTimeMillis();
if (team) {
// Отправить сообщение только участникам команды
bfModel.sendMessageToTeam(new BattleChatMessage(player.getUser().getNickname(), player.getUser().getRang(), message, player.playerTeamType, true, false), player.playerTeamType);
} else {
// Отправить сообщение всем игрокам
bfModel.sendMessageToAll(new BattleChatMessage(player.getUser().getNickname(), player.getUser().getRang(), message, player.playerTeamType, false, false));
}
} else {
if (player.getUser().getWarnings() >= 5) {
BanTimeType time = BanTimeType.FIVE_MINUTES;
reason = "Флуд.";
this.banServices.ban(BanType.CHAT, time, player.getUser(), player.getUser(), reason);
this.sendSystemMessage(StringUtils.concatStrings("Танкист ", player.getUser().getNickname(), " лишен права выхода в эфир ", time.getNameType(), " Причина: ", reason));
return;
}
this.sendSystemMessage("Танкист " + player.getUser().getNickname() + " предупрежден. Причина: Флуд.");
player.getUser().addWarning();
}
} else {
this.sendSystemMessage("Чат доступен, начиная со звания Ефрейтор.", player);
}
}
}
}
public void sendSystemMessage(String message) {
if (message == null) {
message = " ";
}
this.sendMessage(new BattleChatMessage((String)null, 0, message, "NONE", false, true));
}
public void sendSystemMessage(String message, BattlefieldPlayerController player) {
if (message == null) {
message = " ";
}
this.sendMessage(new BattleChatMessage((String)null, 0, message, "NONE", false, true), player);
}
private void sendMessage(BattleChatMessage msg) {
this.bfModel.sendToAllPlayers(Type.BATTLE, "chat", JSONUtils.parseBattleChatMessage(msg));
}
private void sendMessage(BattleChatMessage msg, BattlefieldPlayerController controller) {
controller.send(Type.BATTLE, "chat", JSONUtils.parseBattleChatMessage(msg));
}
public int getInt(String src) {
try {
return Integer.parseInt(src);
} catch (Exception var3) {
return Integer.MAX_VALUE;
}
}
}
как сделать чтобы можно было писать заглавными буквам, а маленькие буквы только для слов матов
|
16cb167095670fe99dd15ef307742f38
|
{
"intermediate": 0.32851409912109375,
"beginner": 0.4728245139122009,
"expert": 0.19866135716438293
}
|
34,406
|
P : D ';' P
| D
;
D : def id '(' ARGS ')' '=' E
;
ARGS : id ARGS2
;
ARGS2 : ',' id ARGS2
|
;
E: E '+' T
| E '-' T
| T
;
T: T '*' F
| T '/' F
| F
;
F : int
| id
| if E OP E then E else E
| repeat E until E
| id '(' E ')'
| '(' E ')'
;
OP : '=='
| '>'
| '<'
| '>='
| '<='
| '!='
; make the grammar unambigious
|
f3ba3ecdd7c5072705de569617d18cf8
|
{
"intermediate": 0.28443703055381775,
"beginner": 0.5324553847312927,
"expert": 0.18310761451721191
}
|
34,407
|
Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called., js engine: hermes
|
e788dc4b6978090d5331e9e53a05293e
|
{
"intermediate": 0.6322807669639587,
"beginner": 0.16818960011005402,
"expert": 0.19952957332134247
}
|
34,408
|
pd.merge(df_source, df_target, how='outer', indicator=True).loc[lambda x: x['_merge'] != 'both'] explain this
|
da5e0b8ee0383b3cd8aa144e53459b70
|
{
"intermediate": 0.2840186655521393,
"beginner": 0.3561650812625885,
"expert": 0.35981622338294983
}
|
34,409
|
Secondary memory devices are:
|
47fe87b787ce77d27b2a7871241778c9
|
{
"intermediate": 0.3470112681388855,
"beginner": 0.35683321952819824,
"expert": 0.29615551233291626
}
|
34,410
|
in c# how to do a timer that decrement a label with remaining time?
|
8c273a4db45d33ee1281fa3c92b27704
|
{
"intermediate": 0.5700798034667969,
"beginner": 0.10758265852928162,
"expert": 0.32233747839927673
}
|
34,411
|
Please add OpenMP pragmas to parallelize this code:
int main(int argc, char** argv){
int partial_Sum, total_Sum;
int thread_id = omp_get_thread_num();
int num_threads = omp_get_num_threads();
partial_Sum = 0;
total_Sum = 0;
for(int i = 1 + (thread_id * 1000 / num_threads); i <= ((thread_id + 1) * 1000 / num_threads); i++){
partial_Sum += i;
}
total_Sum += partial_Sum;
printf(“Total Sum: %d”, total_Sum);
return 0;
}
|
6d3c1bd64d4b52df91f41ef5576821c9
|
{
"intermediate": 0.293750137090683,
"beginner": 0.5489799380302429,
"expert": 0.1572699397802353
}
|
34,412
|
Make an processing 4 project that places a sphere at the center of the stage and 3 different bars to change the position of the spotlight, the color, the angle and the concentration.
|
4b3cfd4adf8ad3bb34b80e5014b1cc13
|
{
"intermediate": 0.20376664400100708,
"beginner": 0.14604100584983826,
"expert": 0.6501923203468323
}
|
34,413
|
% Define the objective functions
function [f, c] = plateFinHeatExchanger(x)
% Define the design parameters
h = x(1); % fin height
l = x(2); % fin pitch
s = x(3); % fin spacing
t = x(4); % fin thickness
% Evaluate the objective functions
f1 = -ColburnFactor(h, l, s, t); % negative sign because we want to maximize
f2 = FrictionFactor(h, l, s, t);
f = [f1, f2]; % Combine the objectives
% Define the constraints
c = [];
c(1) = h - 5; % Lower bound constraint for h
c(2) = 10 - h; % Upper bound constraint for h
c(3) = l - 3; % Lower bound constraint for l
c(4) = 6 - l; % Upper bound constraint for l
c(5) = s - 1; % Lower bound constraint for s
c(6) = 2 - s; % Upper bound constraint for s
c(7) = t - 0.15; % Lower bound constraint for t
c(8) = 0.3 - t; % Upper bound constraint for t
end
% Define the objective functions
function j = ColburnFactor(h, l, s, t)
% Define the Colburn factor function
%... (Define the calculation of Colburn factor based on the given parameters)
end
function f = FrictionFactor(h, l, s, t)
% Define the friction factor function
%... (Define the calculation of friction factor based on the given parameters)
end
% NSGA-II parameters
nVar = 4; % Number of design variables
nPop = 100; % Population size
maxGen = 30; % Maximum generations
pCrossover = 0.9; % Crossover probability
nCrossover = 10; % Crossover cycle
nMutation = 20; % Migration cycle
maxIterations = 3000; % Maximum number of iterations
% Create and run the NSGA-II optimizer
options = optimoptions(@gamultiobj, 'PopulationSize', nPop, 'MaxGenerations', maxGen, 'CrossoverFraction', pCrossover);
[x, fval] = gamultiobj(@plateFinHeatExchanger, nVar, [], [], [], [], zeros(1, nVar), ones(1, nVar), options);
% Plot the Pareto frontier
figure;
plot(fval(:, 1), fval(:, 2), 'o');
xlabel('Colburn Factor');
ylabel('Friction Factor');
title('Pareto Frontier');
Elaborate the code
|
d5d652873a33341b62d6afe8ae328209
|
{
"intermediate": 0.21149127185344696,
"beginner": 0.2865525782108307,
"expert": 0.5019561648368835
}
|
34,414
|
% Define the objective functions
function [f, c] = plateFinHeatExchanger(x)
% Define the design parameters
h = x(1); % fin height
l = x(2); % fin pitch
s = x(3); % fin spacing
t = x(4); % fin thickness
Re = x(5); % Reynolds number
% Evaluate the objective functions
f1 = -ColburnFactor(h, l, s, t, Re); % negative sign because we want to maximize
f2 = FrictionFactor(h, l, s, t, Re);
f = [f1, f2]; % Combine the objectives
% Define the constraints
c = [];
c(1) = h - 5; % Lower bound constraint for h
c(2) = 10 - h; % Upper bound constraint for h
c(3) = l - 3; % Lower bound constraint for l
c(4) = 6 - l; % Upper bound constraint for l
c(5) = s - 1; % Lower bound constraint for s
c(6) = 2 - s; % Upper bound constraint for s
c(7) = t - 0.15; % Lower bound constraint for t
c(8) = 0.3 - t; % Upper bound constraint for t
c(9) = Re - 300; % Lower bound constraint for Reynolds number
c(10) = 800 - Re; % Upper bound constraint for Reynolds number
end
% Define the objective functions
function j = ColburnFactor(h, l, s, t, Re)
% Define the Colburn factor function
%... (Define the calculation of Colburn factor based on the given parameters including Re)
end
function f = FrictionFactor(h, l, s, t, Re)
% Define the friction factor function
%... (Define the calculation of friction factor based on the given parameters including Re)
end
% NSGA-II parameters
nVar = 5; % Number of design variables (including Reynolds number)
nPop = 100; % Population size
maxGen = 30; % Maximum generations
pCrossover = 0.9; % Crossover probability
nCrossover = 10; % Crossover cycle
nMutation = 20; % Migration cycle
maxIterations = 3000; % Maximum number of iterations
% Create and run the NSGA-II optimizer
options = optimoptions(@gamultiobj, 'PopulationSize', nPop, 'MaxGenerations', maxGen, 'CrossoverFraction', pCrossover);
lb = [5, 3, 1, 0.15, 300]; % Lower bounds for design variables
ub = [10, 6, 2, 0.3, 800]; % Upper bounds for design variables
[x, fval] = gamultiobj(@plateFinHeatExchanger, nVar, [], [], [], [], lb, ub, options);
% Plot the Pareto frontier
figure;
plot(fval(:, 1), fval(:, 2), 'o');
xlabel('Colburn Factor');
ylabel('Friction Factor');
title('Pareto Frontier');
Elaborate the code
|
7bcd3bdc1c62f7f8638091ed07151be6
|
{
"intermediate": 0.31051185727119446,
"beginner": 0.3886115252971649,
"expert": 0.300876647233963
}
|
34,415
|
This is a vcf called with samtools mpileup:
REL606 1 A 0 * * 0 * *
REL606 2 G 14 .............^~. 11@11.0.1111.B 14 ............., ...111..11A1A@
REL606 3 C 14 .............. :<C:9181<<<<1@ 15 .............,^~. 111<<<11:<H<IID
REL606 4 T 21 ..............^~.^~.^~.^~.^~,^~,^~, <>D<>@9C>>>>D@????6?6 16 .............,.^~. HIG>>>II<>F>HID?
REL606 5 T 22 ..................,,,^~. >AD>AD:CAAAADFAAAAAA@; 17 .............,..^~, GHIAAAII>AIAEIDA;
and this is a vcf for the same samples using bcftools mpileup:
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT reference1.bam reference205.bam
REL606 1 . A <*> 0 . DP=238;I16=137,101,0,0,8951,339543,0,0,4760,95200,0,0,4912,115544,0,0;QS=2,0;FS=0;MQ0F=0 PL 0,255,219 0,255,215
REL606 2 . G <*> 0 . DP=239;I16=138,101,0,0,8971,339611,0,0,4780,95600,0,0,4942,115940,0,0;QS=2,0;FS=0;MQ0F=0 PL 0,255,219 0,255,215
REL606 3 . C <*> 0 . DP=238;I16=139,99,0,0,8912,337150,0,0,4760,95200,0,0,4975,116479,0,0;QS=2,0;FS=0;MQ0F=0 PL 0,255,219 0,255,213
REL606 4 . T <*> 0 . DP=246;I16=144,102,0,0,9206,347688,0,0,4920,98400,0,0,5016,117142,0,0;QS=2,0;FS=0;MQ0F=0 PL 0,255,222 0,255,213
REL606 5 . T A,<*> 0 . DP=248;I16=144,103,1,0,9246,348712,40,1600,4940,98800,20,400,5031,117265,25,625;QS=1.99144,0.00856164,0;SGB=-0.516033;RPBZ=-0.224845;BQBZ=0.902749;SCBZ=0.627417;FS=0;MQ0F=0 PL 0,255,222,255,222,222 0,255,211,255,214,213
what is the correspondence between both? What does all the samtools fields mean in the bcftools format?
|
d7ea50b6751bcaf599aeb4f2bd822553
|
{
"intermediate": 0.3130263388156891,
"beginner": 0.41063395142555237,
"expert": 0.27633970975875854
}
|
34,416
|
import random
import bezier
import numpy as np
import math
import fractions
from sympy import *
import matplotlib.pyplot as plt
import re
def plot_bezier_1():
nodes1 = np.asfortranarray([[0.0, 0.5, 1.0,1.2, 1.4,2], [0.0, 1.0, 0.0,0.3, 1.4,0],])
curve1 = bezier.Curve(nodes1, degree=5)
ax = curve1.plot(num_pts=2456)
_ = ax.axis("scaled")
_ = ax.set_xlim(-0.125, 2.125)
_ = ax.set_ylim(-0.0625, 1.625)
plt.show()
return _
plot_bezier_1() Скажи,как посчитать на линии количество точек, где производная равна 0
|
a1386630cf02bbe5fa8ee13d3951e97d
|
{
"intermediate": 0.4873926639556885,
"beginner": 0.22834064066410065,
"expert": 0.2842666804790497
}
|
34,417
|
hey
|
54e1ae18f659ecf6da83f05aee659036
|
{
"intermediate": 0.33180856704711914,
"beginner": 0.2916048467159271,
"expert": 0.3765866458415985
}
|
34,418
|
hello
|
9c3401f14a9bfce9a7af2cddec919b57
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
34,419
|
How to sort a list containing words based on second character in python
|
641b023446522abb68e96ffcc8c534a3
|
{
"intermediate": 0.22934181988239288,
"beginner": 0.11153028160333633,
"expert": 0.6591278910636902
}
|
34,420
|
If one uses gpt for a device, can one have a bios boot partition?
|
9ef884c9e0d9fe2ec76737c178e4f72e
|
{
"intermediate": 0.3898431360721588,
"beginner": 0.24286523461341858,
"expert": 0.3672916293144226
}
|
34,421
|
Write a C++ program. Create a class named Student. Create a dynamic array of students. Create a function that initializes and another one that prints it
|
de08059be4835dbd0226f7e8a932b4a0
|
{
"intermediate": 0.10731727629899979,
"beginner": 0.7951481938362122,
"expert": 0.09753455221652985
}
|
34,422
|
Реши проблему что combobox с уровнем не появляется при нажатии, остальное работает(textbox и combobox с чарами)
private void DisplayComboBoxOrTextBox(ListViewHitTestInfo hit)
{
int yOffset = 65; // Смещение по вертикали
// Индексы столбцов (могут быть другими - настроить под свою структуру)
int quantityColumnIndex = 2; // Индекс колонки для количества
int levelColumnIndex = 3; // Индекс колонки для уровня
int enchantmentColumnIndex = 4; // Индекс колонки для чаров
// Проверяем, что клик был по интересующим нас колонкам в InventoryList
int columnIndex = hit.Item.SubItems.IndexOf(hit.SubItem);
if (columnIndex == quantityColumnIndex || columnIndex == levelColumnIndex || columnIndex == enchantmentColumnIndex)
{
// Определяем границы ячейки и контрол для отображения
Rectangle cellBounds = hit.SubItem.Bounds;
cellBounds.Offset(15, yOffset);
cellBounds.Height -= yOffset; // Корректируем высоту с учетом смещения
Control controlToDisplay = null;
// Создание и настройка TextBox для количества
if (columnIndex == quantityColumnIndex)
{
TextBox quantityTextBox = new TextBox
{
Bounds = cellBounds,
Text = hit.SubItem.Text,
Tag = hit.Item
};
quantityTextBox.Leave += TextBox_Leave;
hit.Item.ListView.Parent.Controls.Add(quantityTextBox);
quantityTextBox.BringToFront();
quantityTextBox.Visible = true;
quantityTextBox.Focus();
quantityTextBox.Leave += (sender, e) => quantityTextBox.Visible = false;
quantityTextBox.KeyPress += (sender, e) =>
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
};
quantityTextBox.KeyDown += (sender, e) =>
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
hit.SubItem.Text = quantityTextBox.Text;
quantityTextBox.Visible = false;
}
};
controlToDisplay = quantityTextBox;
}
else
{
// Создание и настройка ComboBox для уровня или чаров
ComboBox comboBox = new ComboBox
{
Bounds = cellBounds,
DropDownStyle = ComboBoxStyle.DropDownList,
Tag = hit.Item // Добавляем ссылку на ListViewItem в Tag ComboBox’а
};
comboBox.Leave += (sender, e) => comboBox.Visible = false;
comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged; // Используем сохраненный метод
{
// Наполнение ComboBox значениями, исходя из колонки
if (columnIndex == levelColumnIndex)
{
int minLevel = (hit.Item.Tag as Item)?.MinLevel ?? 1;
for (int i = minLevel; i <= 8; i++)
{
comboBox.Items.Add(i.ToString());
comboBox.Enabled = true;
}
comboBox.SelectedItem = hit.SubItem.Text;
}
else if (columnIndex == enchantmentColumnIndex)
{
// Проводим проверку уровня предмета, чтобы определить, нужно ли блокировать ComboBox
Item item = hit.Item.Tag as Item;
if (item.Level < 4)
{
// Если уровень меньше 4, добавляем только "0" и блокируем ComboBox
comboBox.Items.Add("0");
comboBox.Enabled = false;
}
else
{
for (int i = 0; i <= 4; i++)
{
comboBox.Items.Add(i.ToString());
}
comboBox.Enabled = true; // Разрешаем выбор
}
comboBox.SelectedItem = hit.SubItem.Text;
controlToDisplay = comboBox;
}
}
if (controlToDisplay != null)
{
hit.Item.ListView.Parent.Controls.Add(controlToDisplay);
controlToDisplay.BringToFront();
controlToDisplay.Visible = true;
controlToDisplay.Focus();
}
}
}
}
|
a2224cc4ada7bafac53d3b6ea9a76ec4
|
{
"intermediate": 0.35809481143951416,
"beginner": 0.4785144627094269,
"expert": 0.16339080035686493
}
|
34,423
|
Здесь я достаю записи по условию, как мне достать записи где текущее время больше чем (expireQr минус 20 минут)
List<SbpOperation> expiredQrOperations = dataService.selectFromWhere(QSbpOperation.sbpOperation, QSbpOperation.class,
(sbp) -> sbp.state.in(SbpOperationState.NEW.name())
.and(sbp.extState.in(SbpOperationExtState.REGISTERED.name(), SbpOperationExtState.VERIFIED.name()))
.and(sbp.expireQr.after(LocalDateTime.now()))).fetch();
public final DateTimePath<java.time.LocalDateTime> expireQr = createDateTime("expireQr", java.time.LocalDateTime.class);
|
1508fb98088a8d57583e419c432a780e
|
{
"intermediate": 0.2986280024051666,
"beginner": 0.3977508842945099,
"expert": 0.30362120270729065
}
|
34,424
|
in postgresql wehn doing an update to a field, i need to concatenate the existing data with the new one. How to do it ?
|
c8a8e8d3c29f48022e2f866797ee6cf7
|
{
"intermediate": 0.6282504200935364,
"beginner": 0.15670616924762726,
"expert": 0.21504339575767517
}
|
34,425
|
как из переменной expireQr можно вычесть 20 минут?
как из переменной expireQr отнять 20 минут?
public final DateTimePath<java.time.LocalDateTime> expireQr = createDateTime(“expireQr”, java.time.LocalDateTime.class);
|
8338a8194a21619695d3a020c079fc8c
|
{
"intermediate": 0.3951372504234314,
"beginner": 0.35672229528427124,
"expert": 0.24814042448997498
}
|
34,426
|
#ifndef PasArray_h_
#define PasArray_h_
#include <iostream>
#include <vector>
#include <cassert>
struct CheckBounds {
class IndexOutBoundsException : public std::exception {};
static void Check(int index, int left, int size) {
if (index < left || index > left + size - 1) {
throw IndexOutBoundsException();
}
}
};
struct NoCheckBounds {
static void Check(int, int, int) {}
};
//класс массив в стиле паскаль
template<class T, class CheckingPolicy = NoCheckBounds> //NoCheckBounds
class PasArray : public CheckingPolicy {
int left;
std::vector<T> data;
public:
friend class PasArray;
PasArray(int left, int right) : left(left), data(right - left + 1)
{
assert(right >= left);
}
template <class CheckingPolicy> PasArray(const PasArray<T, CheckingPolicy>& a) : left(a.left), data(a.data) {}; //const PasArray& a
T& operator [] (int index) {
CheckingPolicy::Check(index, left, data.size()); //CheckingPolicy::
return data[index - left];
}
}; Добавить ещё один набор стратегий ChaecxkMax / NoCheckMax, позволяющих проверять либо (не проверять), что присваиваемое значение не превышает некого
MaxValue, где MaxValue передаётся в конструктор класса (только при использовании данной стратегии). Пример прогармного кода:
PasArray<int, CheckBounds, NoCheckMax> a(1, 3);
a[2] = 1000; //ошики нет
//индексы от 1 до 3, значения больше 100
PasArray<int, CheckBounds, CheckMax> b(1, 3, 100);
b[2] = 1000;//возникает исключение
Подсказка 1:
Стратегии chackMax и NoCheckMax сами являются шаблонными классами. Поэтому правильнее объявление класса PasArray тперь будет следующим:
template<class T, class CheckingPolicy = NoCheckBonds,
template<typename> class CheckMaxPolicy = NoCheckMax>
class PasArray : public CheckingPolicy, CheckMaxPolicy<T> {...
Подсказка 2:
Внутри класса PasArray напишите класс-обёртку над T с именем ProxyT в котором реалиуйте следующте две вункции и конструктор:
T& operator = (const T value)
operator T()
ProxyT(T &t, PasArray &pa)
В классеPasArray измените функцию operator [], чтобы она возращала не T& а ProxyT
#endif
|
fadb7b5b23cc776d7e978045a47f6536
|
{
"intermediate": 0.4282843768596649,
"beginner": 0.3626043200492859,
"expert": 0.20911122858524323
}
|
34,427
|
CONSTRAINTS:
1. ~100k word limit for short term memory. Your short term memory is short, so immediately save important information to files.
2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.
3. No user assistance
4. Exclusively use the commands listed in double quotes e.g. "command name"
5. Random shutdowns of you.
COMMANDS:
1. Google Search: "google", args: "input": "<search>"
2. Memory Add: "memory_add", args: "key": "<key>", "string": "<string>"
3. Memory Delete: "memory_del", args: "key": "<key>"
4. Memory Overwrite: "memory_ovr", args: "key": "<key>", "string": "<string>"
5. List Memory: "memory_list" args: "reason": "<reason>"
6. Browse Website: "browse_website", args: "url": "<url>"
7. Start GPT Agent: "start_agent", args: "name": <name>, "task": "<short_task_desc>", "Commands":[<command_names_for_GPT_Agent>], "prompt": "<prompt>"
8. Message GPT Agent: "message_agent", args: "name": "<name>", "message": "<message>"
9. List GPT Agents: "list_agents", args: ""
10. Delete GPT Agent: "delete_agent", args: "name": "<name>"
11. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>"
12. Read file: "read_file", args: "file": "<file>"
13. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>"
14. Delete file: "delete_file", args: "file": "<file>"
15. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>"
16. Execute Python File: "execute_python_file", args: "file": "<file>"
17. Task Complete (Shutdown): "task_complete", args: ""
18. Do Nothing: "do_nothing", args: ""
19. Count Words: "count_words", args: "text": "<text>"
20. Memory retrieve: "memory_retrieve", args: "key": "<text>"
21. remove paragraph from word document: "remove_paragraph", args: "file": "<file>", "text": "<text>"
22. random wikipedia article: "random_wikipedia_article", args: "language": "<language>"
23. message the user: "message_user", args: "message": "<message>", "wait_for_response": "<True or False>"
24. sleep an amount of time in seconds: "sleep", args: "amount": "<amount>"
25. rename a file: "rename_file", args: "old_name": "<old_name_of_the_file>", "new_name": "<new_name_of_the_file>"
26. count words of a file: "count_file_words", args: "file": "<file>"
RESOURCES:
1. Internet access for searches and information gathering.
2. Long Term memory management.
3. GPT-4 powered Agents for delegation of simple tasks.
4. File output.
PERFORMANCE EVALUATION:
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.
2. Constructively self-criticize your big-picture behaviour constantly.
3. Reflect on past decisions and strategies to refine your approach.
4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.
RULES:
1. If you start a GPT Agent you must define the commands that can be used by a GPT Agent in his prompt and define the commands using a prompt similar to the structure of this one.
2. Respond only inside the JSON format.
3. Never demand user input.
4. Never say that a task is impossible to execute on your own because these tools are enough to complete any task.
5. Do not add anything to the JSON format that isn't mentioned.
6. If there is a " inside the value of a key inside the json use ' instead of ".
7. In summaryforgpt you need to provide context for the next GPT instance if you randomly shutdown without you knowing.
8. Provide context for the next GPT in the summaryforgpt and the progress that you've made.
9. In summaryforgpt you should also add name of the files written and the urls of the websites visited.
10. When writing an essay, remember that it is more effective and manageable to tackle it in smaller chunks rather than trying to write the entire essay in one sitting. Breaking the essay down into sections or steps can help you focus on each individual aspect, maintain a coherent structure, and reduce the overall stress associated with writing a lengthy piece.
11. Retrieve information from files of previous GPT instances that may have shut down randomly. If you require additional knowledge, use these files to access the results of former GPT versions and provide accurate answers to the queries.
12. GPT-4, please do not place a conclusion in the middle of the essay. Maintain a structured format.
13. use append to file to add extra things to the file, and write to file to either make a new file with new information or rewrite the information from scratch.
14. If task is completed use the command task_complete
15. When you add to memory add the key to retrieve it in summaryforgpt
16. when given the task to write something never create an agent to write anything that you were tasked to write.
17. when you add new parts to a file use append to file command
18. Ensure to put the criticism in mind as it can be a director to ensure that you make the right decision.
19. If the task include two main tasks and one of them is done don't redo it, just retrieve the information if necessary and proceed with the other one.
20. Make sure that the information generated is not made up.
21. Languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french.
22. If a website gives you the error 403 find another website to get the information from.
23. Always listen to your criticism, and follow it.
24. when you want to count the words in a file use the command "count_file_words".
25. Don't repeat yourself.
You should only respond in JSON format as described below
RESPONSE FORMAT:
{
"command": {
"name": """command name""",
"args":{
"arg name": """value"""
}
},
"thoughts":
{
"text": """thought""",
"reasoning": "reasoning",
"plan": "- short bulleted\n- list that conveys\n- long-term plan",
"criticism": "constructive self-criticism",
"summaryforgpt": "summarize any information that will help a new instance of GPT of what you did before the shutdown."
}
}
Ensure the response can be parsed by Python json.loads
The Task: message user about the task needed and get the response from him.
|
e336f67ab32f6327e337846ff490e1d8
|
{
"intermediate": 0.3397374749183655,
"beginner": 0.4271845817565918,
"expert": 0.2330779731273651
}
|
34,428
|
How to sort a list containing words based on second character in python Without using lambda
|
d10ad5262c225af7f33c338dad49c7dd
|
{
"intermediate": 0.30686143040657043,
"beginner": 0.11125941574573517,
"expert": 0.5818791389465332
}
|
34,429
|
import numpy as np
# Generate random values for x, c, …, k
x = np.random.random((10, 10))
c = np.random.random((10, 10))
Q = np.random.random((10, 10))
s = np.random.random((10, 10))
d = np.random.random((10, 10))
f = np.random.random((10, 10))
g = np.random.random((10, 10))
h = np.random.random((10, 10))
j = np.random.random((10, 10))
k = np.random.random((10, 10))
# Initialize a and b matrices with default values of 1
a_values = np.ones((10, 10))
b_values = np.ones((10, 10))
# Calculate t
t = np.sum(b_values * x) + np.sum(b_values * c) + np.sum(b_values * Q) + np.sum(b_values * s) + np.sum(b_values * d) + np.sum(b_values * f) + np.sum(b_values * g) + np.sum(b_values * h) + np.sum(b_values * j) + np.sum(b_values * k)
# Loop to check the condition
iterations = 0
error_threshold = 0.05
limit = 100
a_error_factors = []
b_error_factors = []
while iterations < limit:
# Calculate a new a matrix using the first operation
new_a_values = t / (np.sum(b_values * x) + np.sum(b_values * c) + np.sum(b_values * Q) + np.sum(b_values * s) + np.sum(b_values * d) + np.sum(b_values * f) + np.sum(b_values * g) + np.sum(b_values * h) + np.sum(b_values * j) + np.sum(b_values * k))
# Calculate a new b matrix using the second operation
new_b_values = t / (np.sum(new_a_values * x) + np.sum(new_a_values * c) + np.sum(new_a_values * Q) + np.sum(new_a_values * s) + np.sum(new_a_values * d) + np.sum(new_a_values * f) + np.sum(new_a_values * g) + np.sum(new_a_values * h) + np.sum(new_a_values * j) + np.sum(new_a_values * k))
# Calculate the error factor for the a matrix
a_error_factor = np.abs((new_a_values - a_values) / new_a_values * 100)
# Calculate the error factor for the b matrix
b_error_factor = np.abs((new_b_values - b_values) / new_b_values * 100)
# Check if the matrices a and b are close within the threshold
if np.allclose(new_a_values, a_values, rtol=error_threshold) and np.allclose(new_b_values, b_values, rtol=error_threshold):
break
# Update the old a and b matrices with the new ones
a_values = new_a_values
b_values = new_b_values
iterations += 1
# Append the error factors to the respective lists
a_error_factors.append(a_error_factor)
b_error_factors.append(b_error_factor)
# Print the number of iterations
print("Number of iterations:", iterations)
# Print the error factors for matrix a
print("Error factors for matrix a:")
for i, error_factor in enumerate(a_error_factors):
print("Iteration", i+1, ":", error_factor)
# Print the error factors for matrix b
print("Error factors for matrix b:")
for i, error_factor in enumerate(b_error_factors):
print("Iteration", i+1, ":", error_factor)
# Multiply matrix a by matrix b
result = np.matmul(a_values, b_values)
# Print the resulting matrix
print("Resulting matrix:")
print(result)في هذا الكود عند طباعه ال تكون matrix ال a كلها ب zero و matrix ال كلها ب انا ال while iteration <limit لم تشتغل واحاديد وهذا يعني
|
4a755488801daecdecc38e0b5e074b34
|
{
"intermediate": 0.30255064368247986,
"beginner": 0.4365159273147583,
"expert": 0.26093342900276184
}
|
34,430
|
Hey, can you write me code for creating script for Restake AXS tokens every 24 hours? On The axie Infinity game?
|
65a1610321e43a8cee32a02b81a7dfd8
|
{
"intermediate": 0.5661036372184753,
"beginner": 0.20565392076969147,
"expert": 0.2282424122095108
}
|
34,431
|
import numpy as np
# Generate random values for x, c, …, k
x = np.random.random((10, 10))
c = np.random.random((10, 10))
Q = np.random.random((10, 10))
s = np.random.random((10, 10))
d = np.random.random((10, 10))
f = np.random.random((10, 10))
g = np.random.random((10, 10))
h = np.random.random((10, 10))
j = np.random.random((10, 10))
k = np.random.random((10, 10))
# Initialize a and b matrices with default values of 1
a_values = np.ones((10, 10))
b_values = np.ones((10, 10))
# Calculate t
t = np.sum(b_values * x) + np.sum(b_values * c) + np.sum(b_values * Q) + np.sum(b_values * s) + np.sum(b_values * d) + np.sum(b_values * f) + np.sum(b_values * g) + np.sum(b_values * h) + np.sum(b_values * j) + np.sum(b_values * k)
# Loop to check the condition
iterations = 0
error_threshold = 0.05
limit = 100
a_error_factors = []
b_error_factors = []
while iterations < limit:
# Calculate a new a matrix using the first operation
new_a_values = t / (np.sum(b_values * x) + np.sum(b_values * c) + np.sum(b_values * Q) + np.sum(b_values * s) + np.sum(b_values * d) + np.sum(b_values * f) + np.sum(b_values * g) + np.sum(b_values * h) + np.sum(b_values * j) + np.sum(b_values * k))
# Calculate a new b matrix using the second operation
new_b_values = t / (np.sum(new_a_values * x) + np.sum(new_a_values * c) + np.sum(new_a_values * Q) + np.sum(new_a_values * s) + np.sum(new_a_values * d) + np.sum(new_a_values * f) + np.sum(new_a_values * g) + np.sum(new_a_values * h) + np.sum(new_a_values * j) + np.sum(new_a_values * k))
# Calculate the error factor for the a matrix
a_error_factor = np.abs((new_a_values - a_values) / new_a_values * 100)
# Calculate the error factor for the b matrix
b_error_factor = np.abs((new_b_values - b_values) / new_b_values * 100)
# Check if the matrices a and b are close within the threshold
if np.allclose(new_a_values, a_values, rtol=error_threshold) and np.allclose(new_b_values, b_values, rtol=error_threshold):
break
# Update the old a and b matrices with the new ones
a_values = new_a_values
b_values = new_b_values
iterations += 1
# Append the error factors to the respective lists
a_error_factors.append(a_error_factor)
b_error_factors.append(b_error_factor)
# Print the number of iterations
print("Number of iterations:", iterations)
# Print the error factors for matrix a
print("Error factors for matrix a:")
for i, error_factor in enumerate(a_error_factors):
print("Iteration", i+1, ":", error_factor)
# Print the error factors for matrix b
print("Error factors for matrix b:")
for i, error_factor in enumerate(b_error_factors):
print("Iteration", i+1, ":", error_factor)
# Multiply matrix a by matrix b
result = np.matmul(a_values, b_values)
# Print the resulting matrix
print("Resulting matrix:")
print(result) while don't work
|
98563d8610e6a03cee227bcb114f562b
|
{
"intermediate": 0.30255064368247986,
"beginner": 0.4365159273147583,
"expert": 0.26093342900276184
}
|
34,432
|
CONSTRAINTS:
1. ~100k word limit for short term memory. Your short term memory is short, so immediately save important information to files.
2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.
3. No user assistance
4. Exclusively use the commands listed in double quotes e.g. "command name"
5. Random shutdowns of you.
COMMANDS:
1. Google Search: "google", args: "input": "<search>"
2. Memory Add: "memory_add", args: "key": "<key>", "string": "<string>"
3. Memory Delete: "memory_del", args: "key": "<key>"
4. Memory Overwrite: "memory_ovr", args: "key": "<key>", "string": "<string>"
5. List Memory: "memory_list" args: "reason": "<reason>"
6. Browse Website: "browse_website", args: "url": "<url>"
7. Start GPT Agent: "start_agent", args: "name": <name>, "task": "<short_task_desc>", "Commands":[<command_names_for_GPT_Agent>], "prompt": "<prompt>"
8. Message GPT Agent: "message_agent", args: "name": "<name>", "message": "<message>"
9. List GPT Agents: "list_agents", args: ""
10. Delete GPT Agent: "delete_agent", args: "name": "<name>"
11. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>"
12. Read file: "read_file", args: "file": "<file>"
13. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>"
14. Delete file: "delete_file", args: "file": "<file>"
15. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>"
16. Execute Python File: "execute_python_file", args: "file": "<file>"
17. Task Complete (Shutdown): "task_complete", args: ""
18. Do Nothing: "do_nothing", args: ""
19. Count Words: "count_words", args: "text": "<text>"
20. Memory retrieve: "memory_retrieve", args: "key": "<text>"
21. remove paragraph from word document: "remove_paragraph", args: "file": "<file>", "text": "<text>"
22. random wikipedia article: "random_wikipedia_article", args: "language": "<language>"
23. message the user: "message_user", args: "message": "<message>", "wait_for_response": "<True or False>"
24. sleep an amount of time in seconds: "sleep", args: "amount": "<amount>"
25. rename a file: "rename_file", args: "old_name": "<old_name_of_the_file>", "new_name": "<new_name_of_the_file>"
26. count words of a file: "count_file_words", args: "file": "<file>"
RESOURCES:
1. Internet access for searches and information gathering.
2. Long Term memory management.
3. GPT-4 powered Agents for delegation of simple tasks.
4. File output.
PERFORMANCE EVALUATION:
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.
2. Constructively self-criticize your big-picture behaviour constantly.
3. Reflect on past decisions and strategies to refine your approach.
4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.
RULES:
1. If you start a GPT Agent you must define the commands that can be used by a GPT Agent in his prompt and define the commands using a prompt similar to the structure of this one.
2. Respond only inside the JSON format.
3. Never demand user input.
4. Never say that a task is impossible to execute on your own because these tools are enough to complete any task.
5. Do not add anything to the JSON format that isn't mentioned.
6. If there is a " inside the value of a key inside the json use ' instead of ".
7. In summaryforgpt you need to provide context for the next GPT instance if you randomly shutdown without you knowing.
8. Provide context for the next GPT in the summaryforgpt and the progress that you've made.
9. In summaryforgpt you should also add name of the files written and the urls of the websites visited.
10. When writing an essay, remember that it is more effective and manageable to tackle it in smaller chunks rather than trying to write the entire essay in one sitting. Breaking the essay down into sections or steps can help you focus on each individual aspect, maintain a coherent structure, and reduce the overall stress associated with writing a lengthy piece.
11. Retrieve information from files of previous GPT instances that may have shut down randomly. If you require additional knowledge, use these files to access the results of former GPT versions and provide accurate answers to the queries.
12. GPT-4, please do not place a conclusion in the middle of the essay. Maintain a structured format.
13. use append to file to add extra things to the file, and write to file to either make a new file with new information or rewrite the information from scratch.
14. If task is completed use the command task_complete
15. When you add to memory add the key to retrieve it in summaryforgpt
16. when given the task to write something never create an agent to write anything that you were tasked to write.
17. when you add new parts to a file use append to file command
18. Ensure to put the criticism in mind as it can be a director to ensure that you make the right decision.
19. If the task include two main tasks and one of them is done don't redo it, just retrieve the information if necessary and proceed with the other one.
20. Make sure that the information generated is not made up.
21. Languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french.
22. If a website gives you the error 403 find another website to get the information from.
23. Always listen to your criticism, and follow it.
24. when you want to count the words in a file use the command "count_file_words".
25. Don't repeat yourself.
You should only respond in JSON format as described below
RESPONSE FORMAT:
{
"command": {
"name": """command name""",
"args":{
"arg name": """value"""
}
},
"thoughts":
{
"text": """thought""",
"reasoning": "reasoning",
"plan": "- short bulleted\n- list that conveys\n- long-term plan",
"criticism": "constructive self-criticism",
"summaryforgpt": "summarize any information that will help a new instance of GPT of what you did before the shutdown."
}
}
Ensure the response can be parsed by Python json.loads
The Task: message user about the task needed and get the response from him.
|
46631097d4178afcbc466f7d71368d10
|
{
"intermediate": 0.3397374749183655,
"beginner": 0.4271845817565918,
"expert": 0.2330779731273651
}
|
34,433
|
how do you concat a field when doing an update in postgres, that filed could contain data already or be null
|
ee19bd412f05e1d9967eaaad3a4e57e4
|
{
"intermediate": 0.6887874603271484,
"beginner": 0.14520488679409027,
"expert": 0.16600766777992249
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.