Using multiple constraints in a JSON query Posted: 29 May 2021 07:43 AM PDT using System; using System.IO; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using System.Linq; namespace ConsoleApp1 { public class Program { public static void Main() { JObject jObject = JObject.Load(new JsonTextReader(File.OpenText("categories.json"))); JArray resources = (JArray)jObject["ResourceCategories"]; foreach (var CategoryType in resources.Where(obj => obj["CategoryID"].Value<string>() == "food") && (obj["GameVersion"].Value<string>() == "1")) { Console.WriteLine(CategoryType); } Console.ReadLine(); } } } I can only match one criteria foreach (var CategoryType in resources.Where(obj => obj["CategoryID"].Value<string>() == "food")) When I try to add the second as in the code above I get an error. How can I pass multiple constraints? |
install horovod failed by anaconda3 Posted: 29 May 2021 07:42 AM PDT When I Install Horovod with the step of https://github.com/horovod/horovod/blob/master/docs/conda.rst, I meet exit code 137 This is Dockerfile's output: => => # Verifying transaction: ...working... done => => # Executing transaction: ...working... b'By downloading and using the CUDA Toolkit conda packages, you accept the terms an => => # d conditions of the CUDA End User License Agreement (EULA): https://docs.nvidia.com/cuda/eula/index.html\n' => => # b'By downloading and using the cuDNN conda packages, you accept the terms and conditions of the NVIDIA cuDNN EULA -\n h => => # ttps://docs.nvidia.com/deeplearning/cudnn/sla/index.html\n' => => # done executor failed running [/bin/sh -c conda env create --file /tmp/environment.yml --force]: exit code: 137 |
Image not loading when not found Posted: 29 May 2021 07:42 AM PDT echo "<figure><figcaption><img src='./image/".$fichier."'></img></figcaption><figcaption>Titre:".$episode ->titel[0]."</figcaption><figcaption>Date:".$episode ->date_diffusion[0]."</figcaption><figcaption>Enquêteur:".$episode ->hauptkommissar."</figcaption><figcaption>Ville:".$episode ->stadt[0]."</figcaption></figure>"; I have not download all the images yet and in the meantime I would like to add a defaulf pictures so I tried to add the option onerror in img tag but whatever the way I did it the onerror was not triggered. Probably, it is obvious for a lo of people but I found nothing on the web to make that work. thank you in advance |
Error : The non-nullable type is 'ID' in Spring Boot with the usage of Graphql Posted: 29 May 2021 07:42 AM PDT I just devised an example of Spring Boot with the usage of Graphql. I tried to update the department by id but I got an error in id part. Here is my error message which is shown below. The field at path '/updateDepartment/hospital/id' was declared as a non null type, but the code involved in retrieving data has wrongly returned a null value. The graphql specification requires that the parent field be set to null, or if that is non nullable that it bubble up null to its parent and so on. The non-nullable type is 'ID' within parent type 'Hospital' Here are my mutation and query variables snippets which is shown below. mutation updateDepartment($departmentInput: DepartmentInput!) { updateDepartment(id: 10,department: $departmentInput){ name hospital{ id } } } { "departmentInput": { "name": "Department 10 Update", "hospitalId": 3 } } Here is my project link : Project Link How can I fix that error? |
How to Convert Image to pdf using react-native-image-to-pdf in react native Posted: 29 May 2021 07:42 AM PDT I am trying to convert image to pdf using react-native-image-to-pdf. I have saved that image using react-native-view-shot. but now. I dont why in below code they are using two time imagePaths like this = "imagePaths: imagePaths: [image]". and also for name. when I copy that code in my vs code. then I am getting error because of that two imagePaths and name. but when I remove that one imagePaths and name from there. then after calling that function I am getting error like this ="[Error: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference]". please help me. here is code of image to pdf imageToPdf = async () => { try { const options = { imagePaths: imagePaths: [this.state.imagePath], name: name: "PDFName", maxSize: { // optional maximum image dimension - larger images will be resized width: 900, // height: Math.round(deviceHeight() / deviceWidth() * 900), height: 900, }, quality: 0.7, // optional compression paramter }; const pdf = await RNImageToPdf.createPDFbyImages(options); console.log(pdf.filePath); } catch (e) { console.log(e); } }; here is state this.state = { imagePath: "", }; |
Is this a curried function? Posted: 29 May 2021 07:42 AM PDT I am studying for JS coding interviews and just wanted a simple example of JS currying. Does this example pass as currying? function curry(a){ return function(b){ return function(c){ console.log(a+b+c) } } } curry(2)(2)(2) |
ASP.Net Core Razor Page - Pass Selected Name From One Index Page To Another Posted: 29 May 2021 07:41 AM PDT I have a project that I'm creating in ASP.Net Core with Razor Pages. This will track development projects that our IT department has made to our Epicor ERP system. So far, I have links at the top of the main page that opens the corresponding Index pages. These pages pull in data from our SQL Server tables. Two of these pages only have a single column with a list of element names, and I would like to be able to click on any of these names and pass the selected name to another Index page that will show only items for that name. For example, this is a list of UD Tables we've used in our ERP system (see image below)... UD Tables Index Page I would like for a user to be able to click on any name in this list, let's say the 1st name "UD02", and pass that name to the second Index page (see image below)... UD Tables Data Index Page I know you can pass asp-route-id to Details, Edit, and Delete pages, but not sure how to pass a name value to the For Each loop of an Index style page. I have tried passing the name in a similar way... @page @model EpicorDevInfo.Pages.UDTables.IndexModel @{ ViewData["Title"] = "UD Tables"; } <h1>UD Tables</h1> <p> <a asp-page="Create">Create New</a> </p> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.UDTable[0].TableName) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model.UDTable.OrderBy(r => r.TableName)) { <tr> <td> @*@Html.DisplayFor(modelItem => item.TableName)*@ <a asp-page="./Data/Data" asp-route-name="@item.TableName">@Html.DisplayFor(modelItem => item.TableName)</a> </td> <td> <a asp-page="./Edit" asp-route-id="@item.ID">Edit</a> | <a asp-page="./Details" asp-route-id="@item.ID">Details</a> | <a asp-page="./Delete" asp-route-id="@item.ID">Delete</a> </td> </tr> } </tbody> </table> And I added name to the @page of the second Index page, but that didn't do anything... @page "{name}" @model EpicorDevInfo.Pages.UDTables.Data.IndexModel @{ ViewData["Title"] = "Index"; } <h1>@Html.DisplayFor(model => model.UDTableData[0].TableName)</h1> <p> <a asp-page="Create">Create New</a> </p> <table class="table"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.UDTableData[0].TableName) </th> <th> @Html.DisplayNameFor(model => model.UDTableData[0].ColumnLabel) </th> <th> @Html.DisplayNameFor(model => model.UDTableData[0].DatabaseColumn) </th> <th></th> </tr> </thead> <tbody> @foreach (var item in Model.UDTableData) { <tr> <td> @Html.DisplayFor(modelItem => item.TableName) </td> <td> @Html.DisplayFor(modelItem => item.ColumnLabel) </td> <td> @Html.DisplayFor(modelItem => item.DatabaseColumn) </td> <td> <a asp-page="./Edit" asp-route-id="@item.ID">Edit</a> | <a asp-page="./Details" asp-route-id="@item.ID">Details</a> | <a asp-page="./Delete" asp-route-id="@item.ID">Delete</a> </td> </tr> } </tbody> </table> And here is the C# part of the second Index page... using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using EpicorDevInfo.Data; using EpicorDevInfo.Models; namespace EpicorDevInfo.Pages.UDTables.Data { public class DataModel : PageModel { private readonly EpicorDevInfo.Data.EpicorDevInfoContext _context; public DataModel(EpicorDevInfo.Data.EpicorDevInfoContext context) { _context = context; } public IList<UDTableData> UDTableData { get; set; } public async Task<IActionResult> OnGetAsync(string name) { if (String.IsNullOrEmpty(name)) { return NotFound(); } UDTableData = await _context.Epi_UDTableData_TEMP.ToListAsync(); if (UDTableData == null) { return NotFound(); } return Page(); } } } I'm sure it's something simple, but I haven't been able to find anything that works the way I'm wanting. Any help would be greatly appreciated. Thank you for your time and have a great day! |
Libraries installed through conda in a virtual environment Posted: 29 May 2021 07:41 AM PDT I am new to this but does conda, again and again, install the same libraries (let's say the versions are the same) for different virtual environments? Does it take the same amount of space each time for all the environments? If so, wouldn't it be too costly instead of installing that library globally on your system? |
Flutter Web: Unable to load asset when hosted Posted: 29 May 2021 07:41 AM PDT I'm using the package pdf in my application and need to load a font from assets: final font = await rootBundle.load("fonts/avenir-next/AvenirNext-Medium.ttf"); Locally everything works fine, but the font cannot be found when the application is deployed online (with Firebase Hosting). Uncaught Unable to load asset: fonts/avenir-next/AvenirNext-Medium.ttf I add that I use this same font all over the app and no issues to report. I guess the problem is that I am using a path to the font for generating the PDF which is no longer valid when the application is compiled with flutter build web. |
Show other columns from a SQL Server table when clicking on variable from one column in WPF Posted: 29 May 2021 07:42 AM PDT I have a WPF window with the listboxes, as the screenshot below shows. The idea is that when I click on one of the names, all the information about that name from the table shows in the EmployeeRank1 Information listbox. Below there are screenshots of the Window and the table, as well as the code that I have tried to use to solve the problem, which did not work accordingly. // a method that shows information for employees rank 1 private void ShowEmployeeRank1Information() { try { string query = "select * from EmployeeRank1 where Name = @name AND Id = @id"; SqlCommand sqlCommand = new SqlCommand(query, sqlConnection); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); using (sqlDataAdapter) { sqlCommand.Parameters.AddWithValue("@id", employeeRank1List.SelectedValue); DataTable employeeRank1InformationTable = new DataTable(); sqlDataAdapter.Fill(employeeRank1InformationTable); employeeRank1Information.DisplayMemberPath = "Salary"; employeeRank1Information.SelectedValuePath = "Id"; employeeRank1Information.ItemsSource = employeeRank1InformationTable.DefaultView; } } catch (Exception e) { // show what is the error MessageBox.Show(e.ToString()); } } |
How to wait for getValue() to complete in Firebase before return function? [duplicate] Posted: 29 May 2021 07:42 AM PDT Here my function: public Integer class_id = null; private Integer checkCode(String userCode) { DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference assignmentRef = rootRef.child("Assignment"); Query codeQuery = assignmentRef.orderByChild("Code").equalTo(userCode); codeQuery.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() { @Override public void onComplete(@NonNull Task<DataSnapshot> task) { if (task.isSuccessful()) { for (DataSnapshot ds : task.getResult().getChildren()) { Integer classID = ds.child("ClassID").getValue(Integer.class); class_id = classID; Log.d("TAGxx", "My value:" + class_id.toString()); } } else { Log.d("TAGxx", task.getException().getMessage()); } } }); Log.d("TAGxx", "Value return:" + class_id); return class_id; } In log: 2021-05-29 21:21:23.146 17680-17680/com.example.feedbackapplication D/TAGxx: Value return:null 2021-05-29 21:21:23.413 17680-17680/com.example.feedbackapplication D/TAGxx: My value:12 I always get incorrect return value. How can I fix it? |
how to convert a polygon to a multipolygon object in R? Posted: 29 May 2021 07:43 AM PDT I'm trying to cast a shapefile as a multipolygon using one or both of the following arguments from st_read() function: promote_to_multi=TRUE and type=0, but no matter what the geometry type is always set as Polygon. Is there another way to convert a sf from polygon to multypolygon in R? |
How can I make an array of words from a string in assembly language? Posted: 29 May 2021 07:42 AM PDT Im using Intel 32 masm for my project. I am trying to make an array of words of size 10 by slicing words out of a given string of length 10. If the string is "abcdefghij", the array should be [a, b, c, d, e, f, g, h, i, j]. Im learning assembly language the first time, and I can't get any sense for the solution. Please help me |
How to retrieve specific list of objects from array when changing state in react? Posted: 29 May 2021 07:42 AM PDT I have an array like this. I want to get all the actual sizes when selecting a packing name and also when selecting the one of actual size from the list it should be retrieve order size according to each actual size. How can I achieve this? const [packing, setPacking] = useState([]) const [sizes, seSizes] = useState([]) change packing name const onChangeMaterialName = async (id, setFieldValue) => { const { data } = await axios.get(`/packingDetails/${id}`) console.log('data', data.sizes) setFieldValue('actualSize', data.sizes) //here I want to fix } change actual sizes const onChangeMaterialActualSize = (e, setFieldValue, values) => { // setFieldValue('orderSize', data.sizes[0]) //I want fix } this is my components set packing name <Grid item className={classes.flex} md={3} sm={12} xs={12} > <FormControl fullWidth variant='outlined' size='small' > <Autocomplete onChange={(event, newValue) => { if (newValue) { onChangeMaterialName( newValue.id, setFieldValue ) setFieldValue( 'packingName', newValue.packingName ) } }} options={packing} size='small' getOptionLabel={(option) => option.name} renderInput={(params) => ( <TextF {...params} label='Name' variant='outlined' /> )} /> </FormControl> </Grid> set actual Size <Grid item className={classes.flex} md={3} sm={12} xs={12} > <FormControl fullWidth variant='outlined' size='small' > <InputLabel id='demo-simple-select-label'> Actual Size </InputLabel> <Select size='small' onChange={(e) => { onChangeMaterialActualSize( e, setFieldValue, values ) }} onBlur={handleBlur} value={values.actualSize} fullWidth labelId='demo-simple-select-outlined-label' id='demo-simple-select-outlined' label='Actual Size' name='actualSize' > {sizes.map((e, i) => ( <MenuItem value={e} key={e.id}> {e.actualSize} </MenuItem> ))} </Select> </FormControl> </Grid> Set order size <Grid item xs={12} sm={12} md={3}> <Field name='orderSize' size='small' label='Order Size' component={TextField} variant='outlined' disabled fullWidth ></Field> </Grid> |
How to disable button until email validated in Vuejs? Posted: 29 May 2021 07:41 AM PDT new Vue({ el: '#app', data: { email: '' }, computed: { isEmailValid() { return '/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'.test(this.email) }, isDisabled: function() { return !this.email || this.isEmailValid; } } }) <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <p> <input class="input-mobile-email" type="text" placeholder="Your email" id="email" v-model="email" name="email" /> </p> <button :disabled='isDisabled'>Send Form</button> </div> I am trying to disable the button until the email address is validated. So for that I have taken a computed property and written a function. And then I am trying to pass the function's name to isDisabled . But there is an issue with the validation and the button doesn't get enabled, even if a correct email address is entered. This is a jsfiddle where I tried the functionality https://jsfiddle.net/k69cr0sf/2/ |
Update nested object array key using spread operator Posted: 29 May 2021 07:41 AM PDT I have to update the value of a key inside the header of the following data. This is my attempt: var text = { "message": "details", "details": { "id": 343, "data": [ { "header": { "left_text": "", "left_value": "", "center_text": "", "center_value": "", "right_text": "", "right_value": "" } } ] } } text = {...text,data:{...text.data,header:{left_text:'change'}}} console.log(text) I am trying to update the left_text to change. Since I am aware that the data will have always one record so I don't want to do map I am getting this error: Uncaught SyntaxError: Unexpected token JSFiddle. Expected output: var text = { "message": "details", "details": { "id": 343, "data": [ { "header": { "left_text": "change", "left_value": "", "center_text": "", "center_value": "", "right_text": "", "right_value": "" } } ] } } How to update this with using spread operator? |
Try to Select jsonl data column in another columns with .loc but got KeyError even though the key exists Posted: 29 May 2021 07:41 AM PDT this is my data structure in jsonl "content": "Not yall gassing up a gay boy with no rhythm", "place": {"_type": "snscrape.modules.twitter.Place", "fullName": "Manhattan, NY", "name": "Manhattan", "type": "city", "country": "United States", "countryCode": "US"} i try to select countryCode from place column with this code country_df = test_df.loc[test_df['place'].notnull(), ['content', 'place']] countrycode_df = country_df["place"].loc["countryCode"] but it gave me this error KeyError: 'countryCode' how do i fix this? I had try this method but it doesnt fit my situation |
Upload file with React & NodeJs Posted: 29 May 2021 07:43 AM PDT I used NodeJs + MongoDb to upload a Word of documents to the uploads folder. Now I want to send them through the client side using ReactJs. Here's what I currently have in React function App() { const [wordFile, setWordFile] = useState(''); const onFileUpload = (event) => { const file = event.target.files[0] setWordFile(file) const reader = new FileReader() reader.readAsDataURL(file) } return ( <div className="App"> <input type="file" onChange={onFileUpload}/> </div> ); } Small code from Nodejs through which I was uploading files const storage = multer.diskStorage({ destination(req, file, cb) { cb(null, 'uploads/') }, filename(req, file, cb) { const date = moment().format('DDMMYYYY-HHmmss_SSS') cb(null, `${date}-${file.originalname}`) } }) const fileFilter = (req, file, cb) => { if (file.mimetype === 'application/msword' || file.mimetype === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') { cb(null, true) } else { cb(null, false) } } const limits = { fileSize: 1024 * 1024 * 5 } My final task is to get the text from the Word file |
Jquery append method returning html tags instead of the proper formats Posted: 29 May 2021 07:42 AM PDT The feature is for a quiz and im retrieving the data for the quiz that is the questions and answers and appending it to my div having id test_box. The data has been successfully retrieved but instead of proper formatting the data, it is returning me in form of html tags. Here is my code snippet: const url = window.location.href const testBox = document.getElementById('test_box') $.ajax({ type: 'GET', url: `${url}/data`, success: function(response){ const data = response.data data.forEach(element => { for (const [question, answers] of Object.entries(element)){ testBox.append(` <div class="question_box"> <div> <b>${question}</b> </div> `); answers.forEach(answer => { testBox.append(` <div> <input type="radio" class="ans" id=${question}-${answer}" name="${question}" value="${answer}"> <label for="${question}">${answer}</label> </div> `) }) testBox.append(`</div>`); } }); }, error: function(error){ console.log(error) } }); output of response.data Array(2)0: {1000-100 = ?: Array(4)}1: {1 + 1 = ?: Array(4)}length: 2__proto__: Array(0) |
Getting the length of an array of undetermined size at compile time Posted: 29 May 2021 07:41 AM PDT I was just messing around with Compiler Explorer a bit... I was asking myself why there is no lenth() function in C++ to determine the size of an array at compile time, because in my opinion it should be easy to write. But apparently it's not that easy. My idea was something like this: #include <iostream> using namespace std; void print_all(const int num[], const size_t n) { for (size_t i = 0; i < n; ++i) cout << num[i] << endl; } template <class T, size_t N> constexpr size_t length(T (&arr)[N]) { return N; } int main() { constexpr int a[] { 1, 2, 3, 4 }; print_all(a, length(a)); } However, according to godbolt.org with clang 11.0.1, x86-64, this will be compiled into the following: main: # @main ... call unsigned long length<int const, 4ul>(int const (&) [4ul]) mov rdi, qword ptr [rbp - 24] # 8-byte Reload mov rsi, rax call print_all(int const*, unsigned long) xor eax, eax add rsp, 32 pop rbp ret unsigned long length<int const, 4ul>(int const (&) [4ul]): # @unsigned long length<int const, 4ul>(int const (&) [4ul]) push rbp mov rbp, rsp mov qword ptr [rbp - 8], rdi mov eax, 4 pop rbp ret So it's not inlined. Is there a way to get a convenience function with zero runtime cost? PS: I am not interested in this because I actually want to use such a function. I know that std::array or std::span would be way better solutions in almost all cases and that the raw loop in print_all is fishy etc. I am asking this because I want to improve my understanding of C++ and because arrays of undetermined size occur 'in the wild.' Also I am aware that I could use sizeof(a)/sizeof(a[0]) , but I was thinking that there should be a way to get things like this done using templates and constexpr because that's somehow what they are for (creating convenience that can be paid for at compile time). |
Instabot is not working with flask web app Posted: 29 May 2021 07:41 AM PDT I am trying to use instabot for logging into my account and fetching the followers list of user. It is working fine without using flask but when I try to run the same bot with flask routes, it throws me some error import json from logging import error import os from flask import Flask, jsonify, request, abort from instabot import Bot bot = Bot() app = Flask(__name__) @app.route('/login', methods = ['POST']) def login(): try: data = request.json print(data['userName']) usernameval = data['userName'] passwordval = data['password'] bot.login(username=usernameval,password=passwordval) bot.send_message("Hi",["highoncarb"]) response = {'success': True} except Exception as error: response = {'success': False} finally: return response this is my console giving : 2021-05-29 20:03:08,275 - INFO - Not yet logged in starting: PRE-LOGIN FLOW! 2021-05-29 20:03:58,445 - INFO - Logged-in successfully as 'karter19x'! 2021-05-29 20:03:58,446 - INFO - LOGIN FLOW! Just logged-in: True 192.168.43.102 - - [29/May/2021 20:04:19] "POST /login HTTP/1.1" 200 - I am sending the request using Postman desktop agent Please help me to resolve this issue |
Distributed optimization using Analytical Target Cascading in python, convergence issue Posted: 29 May 2021 07:41 AM PDT I have a large optimization problem and I am trying to decompose it into smaller problems and solve that in a distributed form. I am using "Analytical Target Cascading" and here a simplified version of that with two problems as subproblems (mixed-integer optimization) and a coordinator as Master problem (convex quadratic) is brought. the subproblems solve their problems separately and send the variable they share p_p to the coordinator. in the coordinator, these variables are forced to satisfy p_p[problem 1][:, 1] + p_p[problem 2][:, 0] = 0 . the code is as follows: # importing libraries import numpy as np import pandas as pd import picos as pc # parameters p = 1 N = 12 # Number of time intervals J = 10 c = np.array([0.01781449, 0.05494076, 0.09294745, 0.13143326, 0.1702574 , 0.20934449, 0.24864714, 0.28813268, 0.32777717, 0.36756231]) l = np.array([[-0.178625, 0.020875], [-0.181325, -0.13055 ], [-0.200575, -0.12875 ], [-0.16895 , -0.14825 ], [-0.23155 , -0.19325 ], [-0.25675 , 0.06275 ], [-0.27425 , -0.18825 ], [-0.25575 , -0.15225 ], [-0.26 , -0.274 ], [-0.312 , -0.245 ], [-0.24 , -0.31425 ], [-0.24425 , -0.00375 ]]) landa = 1 response = dict() # ATC penalty parameters, initialize with value = 1, and target value = 0 alpha = dict() beta = dict() target = dict() for i in range(2): alpha[i] = np.ones([N, 2]) beta[i] = np.ones([N, 2]) target[i] = np.zeros([N, 2]) bid = -0.4005 * np.ones([2, 12]) # variables p_g_buy = pc.RealVariable("p_g_buy", (N, p), lower = 0) p_g_sell = pc.RealVariable("p_g_sell", (N, p), lower = 0) p_ch = pc.RealVariable("p_ch", (N, p), lower = 0) p_dc = pc.RealVariable("p_dc", (N, p), lower = 0) soc = pc.RealVariable("soc", (N+1, p), lower = 0) c_cyc = pc.RealVariable("c_cyc", (N, p), lower = 0) p_p = pc.RealVariable(f"p_p", (N, 2)) # response variable p_p_hat = dict() # target variables for i in range(2): p_p_hat[i] = pc.RealVariable(f"p_p_hat{[i]}", (N, 2))#, lower = 0) e = pc.RealVariable("e", (N, J), lower = 0) p_seg_ch = pc.RealVariable("p_seg_ch", (N, J), lower = 0) p_seg_dc = pc.RealVariable("p_seg_dc", (N, J), lower = 0) u = pc.BinaryVariable("u", (N, p)) v = pc.BinaryVariable("v", (N, p)) pt = pc.RealVariable("pt", 2, lower = 0) A = dict() for i in range(N): A[i] = pc.RealVariable(f'A{[i]}', (2, 2)) ################################################ max_iters = 10 obj = list() for k in range(max_iters): ###### follower problems ###### for p in range(2): prob = pc.Problem() prob.set_objective("min", pc.sum(0.12 * 0.45 * p_g_buy - 0.12 * 0.40 * p_g_sell ) + pc.sum(c_cyc) #cycling aging cost + 0.12 * pc.sum([(p_p[i, :]*bid[:, i].reshape(-1, 1)) for i in range(0,N)]) + pc.sum(alpha[p] ^ (p_p - target[p])) + pc.sum([x**2 for x in (beta[p] ^ (p_p - target[p]))]) ) prob.add_constraint( p_p[:, p] == 0) prob.add_constraint( p_g_buy - p_g_sell + pc.sum(p_p.T) + p_dc == l[:, p] + p_ch) prob.add_list_of_constraints( [p_p[:, i] <= 1000*u for i in range(2)]) prob.add_list_of_constraints( [p_p[:, i] >= -1000*(1 - u) for i in range(2)]) prob.add_constraint( p_g_buy <= 1000 * u) prob.add_constraint( p_g_sell <= 1000 * (1 - u)) prob.add_constraint( soc <= 9.5) prob.add_constraint( soc >= 0.5) prob.add_constraint( p_ch <= 5) prob.add_constraint( p_dc <= 5) prob.add_constraint( soc[0, :] == 5) prob.add_constraint( soc[1:, :] == soc[:N, :] + 0.12 * 0.98 * p_ch[:, :] - 0.12 * 0.98 * p_dc[:, :]) prob.add_constraint( p_ch == p_seg_ch * np.ones([J, 1])) prob.add_constraint( p_dc == p_seg_dc * np.ones([J, 1])) prob.add_constraint( c_cyc == 0.12 * p_seg_dc * c.reshape(-1, 1) ) prob.add_constraint( e[1:, :] == e[:N-1, :] + 0.12 * (0.98 * p_seg_ch[:N-1, :] - 0.98 * p_seg_dc[:N-1, :])) prob.add_constraint( e <= 1) prob.options.solver = "mosek" prob.solve() response[p] = np.array(p_p.value) #print(f'------iteration {k} problem {p+1} solved, {prob.status}------') ###### coordinator problem ###### prob_c = pc.Problem() prob_c.set_objective("min", pc.sum([pc.sum(alpha[n] ^ (p_p_hat[n] - response[n])) for n in range(2)]) + pc.sum(pt) ) prob_c.add_list_of_constraints([(abs(beta[o] ^ (p_p_hat[o] - response[o]))**2 <= pt[o]) for o in range(2)]) for m in range(N): prob_c.add_list_of_constraints([A[m][l, :] == p_p_hat[l][m, :] for l in range(2)]) prob_c.add_list_of_constraints([A[m][j, j]==0 for j in range(2)]) prob_c.add_list_of_constraints([A[n] == -A[n].T for n in range(N)]) prob_c.options.solver = "mosek" prob_c.solve() ###### store obj value of the coordinator ###### print(f'****** objective in iteration {k} is: {prob_c.value} ******') obj.append(prob_c.value) ###### update penalties and target values ###### for r in range(2): target[r] == np.array(p_p_hat[r].value) # update penalty parameters alpha[r] = alpha[r] + 2 * (beta[r]**2) * (target[r] - response[r]) beta[r] = landa * beta[r] I expect that after some iterations, the objective value of the coordinator converges to a small number but it keeps on increasing over iterations and I do not get a convergence. ****** objective in iteration 0 is: 5.359186040026116 ****** ****** objective in iteration 1 is: 10.951425464064004 ****** ****** objective in iteration 2 is: 23.906625573858193 ****** ****** objective in iteration 3 is: 32.48106633803551 ****** ****** objective in iteration 4 is: 42.39980334161794 ****** ****** objective in iteration 5 is: 56.86036315836203 ****** ****** objective in iteration 6 is: 89.4885415815636 ****** ****** objective in iteration 7 is: 194.7882740401268 ****** ****** objective in iteration 8 is: 590.779977082504 ****** ****** objective in iteration 9 is: 2149.53607142075 ****** I would highly appreciate it if someone could tell me what I am doing wrong here and where the bug is. I apologize for the code being as long as it is, I trimmed it down as much as the context is preserved. Thanks. |
Load tables from excel sheets with both multilevel column data frames and single level column data frames Posted: 29 May 2021 07:43 AM PDT I have an excel sheet with tables in multiple workbooks. I want to load all the tables from excel workbooks to pandas dataframes using pandas.read_excel() function. But the problem is few tables have single level columns and few tables have multilevel columns. I wrote the following code to handle this issue. This code is working fine, but I want to know if there is any standard pythonic way of handling this issue. xl = r"D:\\xl_tables.xlsx" f = pd.ExcelFile(xl) f.sheet_names = ["multilevel_column", "single_level_column" ] dfl = [] for i in f.sheet_names: try: df = pd.read_excel(xl, sheet_name=i, header=[0,1]) df.iloc[0,1] dfl.append(df) except: df = pd.read_excel(xl, sheet_name=i) df.iloc[0,1] dfl.append(df) |
FindOneAndDelete on MERN stack would return successful but the data is still in database? Posted: 29 May 2021 07:41 AM PDT I am trying to use findOneAndDelete method in "mongoose" on my DELETE endpoint using "Expressjs" as my server and "reactjs" handling a fetch API in a try-catch to delete the selected data. I am getting a 200 but the delete result json brings an n=0 games deleted and data is not getting deleted from my database. Here is the code: endpoint: router.delete('/trivia/:name', async (req, res) => { const gameToDelete = req.params.name; try { const deleteQuery = games.Trivia.findOneAndDelete({ name: gameToDelete }); const deleteResult = await deleteQuery.deleteOne(); console.log("Deleting a game from database", deleteResult); res.send(deleteResult); } catch (error) { console.log("Failed to delete trivia", gameToDelete); res.status(500).send({ error: error.code, message: "Something went wrong, I couldn't delete your game" }); } }); React fetch request: async function onDelete(game) { try { const res = await fetch(`/game/trivia/:${game}`, { method: "DELETE", body: null, headers: { "Content-Type": "application/json" }, }); } catch (error) { console.error("error", error); }; } |
JavaScript, Google Sheets script - problem with date comparing Posted: 29 May 2021 07:43 AM PDT I am new in Apps Script, and had never a chance previously to write in JavaScript. So, I have a dataset in one sheet in Google about personal information of clients (ID, name, mail, contact). I have another dataset in another Sheet about clients payment (date of payment of the first installment, date of payment of the second installment and amount. The last sheet that is in focus is the third one relating to unpaid bills. Now, what I want is to copy columns about personal information from the first sheet into the third one. Here condition would be to copy only information about clients where difference between date of payment of the second installment and today() is greater than 45. Here is what I have tried: function Neplacena2Novi() { var ss=SpreadsheetApp.getActiveSpreadsheet(); var sheetFrom=ss.getSheetByName("Podaci o polaznicima"); //Data entry Sheet var sheetTo=ss.getSheetByName("Neplaceni racuni"); //Data Sheet var condition=ss.getSheetByName("Uplate novoupisani"); var range1=ss.getRangeByName("Prva rata"); var range2=ss.getRangeByName("Druga rata"); var startRow=3; var endRow=ss.getLastRow(); function Neplacena2Novi(){ for var(i=startRow; i<(endRow+1)< i++) { var startDate=new Date(condition.getRange(range1+1).getValue()); var endDate= new Date(condition.getRange(range2+1).getValues()); var difference=parseInt(endDate-startDate)/1000); //Dates are in format dd.mm.yyyy. if(difference>45){ var values=sheetFrom.getRange(2, 1, sheetFrom.getLastRow(), 4).getValues(); sheetTo.getRange(3,1,1184,4).setValues(values); } } var ui = SpreadsheetApp.getUi(); var potvrda = ui.alert("Odredili ste lica koja treba da se pozovu."); } function DugmeDodajKlijenta (){ var ui = SpreadsheetApp.getUi(); } This code works but I didn't get anything in sheet! And I didn't now how to include today() function in formula for difference. But what I really want is to make a condition where difference would be today()-startDate(). Can someone please help me? |
Why is my SQL data returning undefined in my array methods? Posted: 29 May 2021 07:41 AM PDT The First array returned when I console log person The second array that returns when I console log person I am trying to create a function that pulls the data from 2 tables in my SQL database. I am using async/await, which is still new to me. The issue is somewhere in the two array methods; for some reason they are returning data as undefined. async function updateRole() { console.log('hi'); //cycle through both arrays and create new arrays with same information using maps //return object with employee and role info const allEmployees = await db.promise().query(`SELECT * FROM employees`); const allRoles = await db.promise().query(`SELECT * FROM roles`); console.log(allEmployees); const employeeChoices = allEmployees.map((person) => { return { name: `${person.first_name} ${person.last_name}`, value: person.id } }) const roleChoices = allRoles.map((role) => { return { name: role.title, value: role.id } }) const { employeeId, roleId } = await inquirer.prompt([ { type: 'list', name: 'employeeId', message: 'Which employee would you like to update?', choices: employeeChoices }, { type: 'list', name: 'roleId', message: 'What is their new role?', choices: roleChoices }]) await db.promise().query(`UPDATE employees SET role_id = ? WHERE id = ?`, [roleId, employeeId]) console.log('Successfully updated employee!'); askQuestions(); Update: I added screenshots fo the console log for person. role returns the same format, but obviously different data. I am unsure what the array of ColumnDefinition objects does, or why it's there. |
How to add custom plugin in ckeditor4-react? Posted: 29 May 2021 07:43 AM PDT I've followed the CKEditor 4 documentation on creating a basic plugin, but it doesn't seem to register in my react app. I've added the plugin file structure and added the plugin.js in node modules along with the icons. How do I pass it to config in ckeditor4-react? import logo from './logo.svg'; import './App.css'; import CKEditor from 'ckeditor4-react'; function App() { return ( <div className="App"> <header className="App-header"> <h2>Using CKEditor 4 in React</h2> <CKEditor config={{ extraPlugins: "timestamp" }} data="<p>Hello from CKEditor 4!</p>" /> in plugin.js (node_modules/ckeditor4-react/plugins/timestamp/plugin.js CKEDITOR.plugins.add( 'timestamp', { icons: 'timestamp', init: function( editor ) { editor.addCommand( 'insertTimestamp', { exec: function( editor ) { var now = new Date(); editor.insertHtml( 'The current date and time is: <em>' + now.toString() + '</em>' ); } }); editor.ui.addButton( 'Timestamp', { label: 'Insert Timestamp', command: 'insertTimestamp', toolbar: 'insert' }); } }); |
Stylesheet.create returns objects not numbers Posted: 29 May 2021 07:42 AM PDT I did a simple test on my local setup, with RN 0.62.2: const styles = Stylesheet.create({ container: { flex: 1 } }); console.log(styles); Given that in theory Stylesheet is caching the style, I expected a log like this: { container: 120 } But actually it returns the object: { container: { flex: 1 } } Then I tried the same with an expo app (https://snack.expo.io/@agustito37/4a556c) with the same version of RN, and the result was the expected: { container: 120 } So I am a little confused, some people argue that caching was removed (What is the point of StyleSheet.create); but given expo is returning the identifier I am not sure, is Stylesheet.create working properly or not? Why do I have different results with expo? Could it be that expo has an older version of Stylesheet? |
AutoHotkey - I want to set A to be Shift A Posted: 29 May 2021 07:43 AM PDT Could someone please tell me how to edit a script in AutoHotkey? I use a macro recorder, to perform several repetitive tasks, i.e. "MOVE UP n MOVE DOWN" many times, so I use to press the macro shortcut repeatedly. The issue is that in the macro recorder that I use if you assign a shortcut with a modifier to call a macro (i.e. Shift A), then you must release the modifier each time you want to perform the macro, so I usually have to (press Shift, press A, release Shift and release A), each time I want to call the macro, instead of just press Shift, hold it, and then press and release A many times. which is easier. I I am looking for an AutoHotKey script that could solve this issue, I have lots of this macros, so I can not create a bat or exe file for each one, I basically need a AutoHotkey script like: if keystate, SHIFT, P a:: send (Shift down) send (a down) send (Shift up) send (a up) or any other script that could send the Shift and A keys every time I press A but only if the Shift key is pressed. I have been trying with loops, but I just don't know how to make it stop. Consider that I need not to be obliged to release and press again "Shift + a" every time I want to call a macro, but also "Alt + a", and also "Alt + Win + a", each different combination call different macros. So it will be bad idea to set the "a" key to be always "Shift + a", because I need the "a" key to perform different macros according to which other modifier keys are pressed at same time. The list of hotkeys that I use in this application are (everyone do something different, and it can not be replaced by any other hotkey) Alt + A Shift + A Win + A Alt + Shift + A Win + Alt + A and so on with most of the letters (S, D, Q, W, E, etc. and numbers 1, 2, 3,etc.) also: Shift + Tab Win + Tab Alt + Capslock Win + Alt + Capslock (Its really annoying to got to release Shift and Tab, and press them both again, each time I want to run a macro, I run this macro many times repetitively) I think those are all the hotkeys, they all do different things that I run repetitively every time. Please, I do need a script that would launch different actions pressing the same "a" key according to which other modifier keys are pressed at same time. Hi Robert, I didn't understand quite well what you said, but I edited the script like this #MaxThreadsPerHotkey 2 #SingleInstance Force #installKeybdHook #Persistent AppName=MyKeys Menu, Tray, Tip, %AppName% Menu, Tray, Icon , Shell32.dll, 45, 1 ; 45, 28, 113, 74, 134 TrayTip, %AppName%, Started, 1 *a:: GoSub, MyGetKeyStateSub If (MyGetKeyStateValue=0) { SendInput, a } Else { if( MyGetKeyStateValue & 1 > 0) ; Compare first bit send {LAlt down} send {d down} send {LAlt up} send {d up} if( MyGetKeyStateValue & 10 > 0) ; compare second bit MsgBox, RShift if( MyGetKeyStateValue & 100 > 0) ; compare third bit send {LAlt down} send {d down} send {LAlt up} send {d up} if( MyGetKeyStateValue & 1000 > 0) MsgBox, RShift if( MyGetKeyStateValue & 10000 > 0) MsgBox, LAlt if( MyGetKeyStateValue & 100000 > 0) MsgBox, RAlt if( MyGetKeyStateValue & 1000000 > 0) MsgBox, LWin if( MyGetKeyStateValue & 10000000 > 0) MsgBox, RWin if ( MyGetKeyStateValue & 00000011 > 0) ; If LCtrl AND LShift pressed MsgBox, LCtrl AND LShift } Return MyGetKeyStateSub: MyGetKeyStateValue:=0 if getkeystate("LCtrl", P) MyGetKeyStateValue+=1 ; set least significant bit if getkeystate("RCtrl", P) MyGetKeyStateValue+=2 ; set 2nd least significant bit, etc, etc. if getkeystate("LShift", P) MyGetKeyStateValue+=4 if getkeystate("RShift", P) MyGetKeyStateValue+=8 if getkeystate("Lalt", P) MyGetKeyStateValue+=16 if getkeystate("Ralt", P) MyGetKeyStateValue+=32 if getkeystate("LWin", P) MyGetKeyStateValue+=64 if getkeystate("RWin", P) MyGetKeyStateValue+=128 Return *d:: GoSub, MyGetKeyStateSub If (MyGetKeyStateValue=0) { SendInput, d } Else { if( MyGetKeyStateValue = 1) ; LAlt { SendInput, {LAlt Down}d{LAlt Up} Return } if( MyGetKeyStateValue = 4) ; LWin { SendInput, {LAlt Down}{LWin Down}d{LAlt Up}{LWin Up} Return } } Return and open the program, and the same it didn't work, first time I press Alt D I get the macro, second time I press D holding the alt key, I get a plain D. I was thinking about what you said relative to the XY problem, perhaps I should rebuild all my macros from HK4 (Hot Keyboard Pro 4) to AutoHotkey. There are lots of macros that I created with the help of the HK4 GUI, but the macros themselves are stored inside an xml script file, I opened this file once with a text editor and its huge!, How much time could take me to script all these macros inside AHK? I have set like 25 variables that apply to every macro (like 200 macros) mostly are mouse movements, mouse clicks, copy selected text (number values) from floating windows inside an application, apply arithmetic operation to them and pasting the results inside the same boxes again (HK4 has and option that play keys, because otherwise it can't not paste inside the application), running depending on which software, which floating windows names, and which variables are enabled or disable (inverted condition), also have toggles macros that (toggle between two macros with one hotkey), I mean, how much it will take me to learn how to script all those kind of macros inside AHK?, I looked on internet, but its very hard to understand each posted case that do not apply exactly to what I intend to do, Thanks Robert, what do you suggest me? I mean, I would rebuild all my macros in AHK because inside AHK I do not have to release the modifier key to perform a macro many times simultaneously, What about Autoit its easier to learn? I read it had macrorecorder? Thanks. |
What is a daemon thread in Java? Posted: 29 May 2021 07:43 AM PDT Can anybody tell me what daemon threads are in Java? |
No comments:
Post a Comment