Using filter driver for demonstrating smartcard PIN-caching Posted: 22 Jan 2022 05:18 AM PST |
What are the ways to change sub categories when category in clicked? Posted: 22 Jan 2022 05:18 AM PST please help me out with an idea. My category structure is like category>sub-category>sub-sub-categories. Now, When I hover on category sub-categories will display with sub-sub-categories. Now, If I click on another sub-categories the sub-sub-categories have to change without reloading the webpage. Please have a look at the pictures I will be easier to understand my problem. Tell me how can I code this. website link: https://www.cat.com/en_IN.html |
How to attach a link only for calculation with a button for my tkinter program Posted: 22 Jan 2022 05:17 AM PST I am making a currency converter. I want to attach the live link of currency converter calculation with a button. In this program we takes input from an Entry widget and also give output to an Entry Widget. I want to attach the link only for the calculation of currency conversion with the button. So that the currency values will auto update in that program and I don't have to add mannual calculation to program for conversion. Please help me with this problem as I have to submit this program in my college. |
Why doesn't sizeof() doesn't include the NUL byte in this example? Posted: 22 Jan 2022 05:17 AM PST Let's consider the following example: int main() { char some_string[] = "12345678"; printf("%zu", sizeof(some_string)); return 0; } Output 9 ...Program finished with exit code 0 Press ENTER to exit console.` The above is correct. The size of the some_string var is 8 characters + the NUL byte = 9 Now if we change it a little bit to: int main() { char some_string[8] = "12345678"; printf("%zu", sizeof(some_string)); return 0; } it prints: 8 ...Program finished with exit code 0 Press ENTER to exit console.` Why is the latter case ignoring the NUL byte? |
'addDoc' is not exported from 'firebase/firestore' Posted: 22 Jan 2022 05:17 AM PST My project is working perfectly from past month but when i reinstall windows and try to run my project again it show error 'addDoc' is not exported from 'firebase/firestore' and now for some region if that error fixed it show collection not exported. i already install Firebase inside my project and firebase cli too. import "./PlanScreen.css"; import React, { useState, useEffect } from "react"; import { collection, getDocs, where, query, onSnapshot, deleteDoc, doc, addDoc, } from "firebase/firestore"; import { db } from "../../../utils/config"; import { useSelector } from "react-redux"; import { selectUser } from "../../../features/userSlice"; import { loadStripe } from "@stripe/stripe-js"; const stripe_public_key = "key stripe"; function PlanScreen({ Subscription }) { const [products, setProducts] = useState([]); const user = useSelector(selectUser); useEffect(() => { const products = []; async function fetchData() { const conditional_fetch = query( collection(db, "products"), where("active", "==", true) ); const querySnapshot = await getDocs(conditional_fetch); querySnapshot.forEach(async (doc) => { products[doc.id] = doc.data(); const ref = collection(db, `products/${doc.id}/prices`); const snap = await getDocs(ref); snap.forEach((price) => { products[doc.id].prices = { priceId: price.id, priceData: price.data(), }; }); }); setProducts(products); return products; } fetchData(); }, []); const loadCheckout = async (priceId) => { const reference = collection(db, `customers/${user.uid}/checkout_sessions`); const get = await getDocs(reference); get.forEach(async (document) => { const ref = doc( db, `customers/${user.uid}/checkout_sessions/${document.id}` ); await deleteDoc(ref); }); const docRef = await addDoc( collection(db, `customers/${user.uid}/checkout_sessions`), { price: priceId, success_url: window.location.origin, cancel_url: window.location.origin, } ); const ref = collection(db, `customers/${user.uid}/checkout_sessions`); const snap = onSnapshot( ref, { includeMetadataChanges: true }, async (doc) => { var error = null, sessionId = null; var first = true; doc.forEach((ele) => { if (first) { error = ele.data().error; sessionId = ele.data().sessionId; console.log("first"); first = false; } }); if (error) { alert(error); } if (sessionId) { const stripe = await loadStripe(stripe_public_key); stripe.redirectToCheckout({ sessionId }); } } ); }; return ( <div className="planScreen"> {Subscription && ( <p> Renew Date:{new Date(Subscription?.endAt * 1000).toLocaleDateString()} </p> )} {Object.entries(products).map(([productId, productData]) => { const is_selected_Plan = productData.name ?.toLowerCase() .includes(Subscription?.role.toLowerCase()); return ( <div className="planScreen_plan" key={productId}> <div className="planScreen_info"> <h5>{productData?.name}</h5> <h6>{productData?.description}</h6> </div> {!is_selected_Plan ? ( <button className="unselected_btn" onClick={() => !is_selected_Plan && loadCheckout(productData?.prices?.priceId) } > Subscribe </button> ) : ( <h4 id="current_plan_mark">Current Plan</h4> )} </div> ); })} </div> ); } export default PlanScreen; |
Reset a bot command cooldown every night at midnight discord.py Posted: 22 Jan 2022 05:17 AM PST I was trying to update a "daily" command for my economy discord.py bot. I've been trying to make the command reusable every time the day starts. For now the code works like this: if I do the /daily command at 3:50pm, I'll need to wait till 3:50pm the next day before I can do this again. But I want to be able to reuse it after midnight, without waiting 24 hours from the last time I did the command. Here's the code I'm currently using. import discord, time from discord.ext import commands import save class EcoCog(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def daily(self, ctx): if save.checkExist(ctx.author.id): pass else: user = save.createUser(ctx.author.id) print("Working") user = save.restore(ctx.author.id) currentTime = time.time() lastTime = int(user['bonusTime']) if lastTime+86400 <= currentTime: user['smackers'] += 500 user['bonusTime'] = time.time() save.save(user) # save the changes await ctx.send("You earned 500 siuuuuuum") else: await ctx.send(f"{ctx.author.mention}, you need to wait {str(round(((86400-(currentTime-lastTime)) / 60)/60, 2))} hours") |
I can't run my Live Broadcast in my Agora Application in Android Studio Posted: 22 Jan 2022 05:17 AM PST My problem here is that I can't seem to stream from my mobile application using Agora in android studios. I have the right tokens and app id in my strings.xml. I also add maven { url 'https://www.jitpack.io' } in the build.gradle(Project:Projectname) and put implementation 'io.agora.rtc:full-sdk:3.2.1' in the build.grade(Module:Projectname:app) strings.xml <resources> <string name="app_name">VeriClean</string> <string name="private_app_id">781938c7945a413ba398215dcd94472e</string> <string name="agora_access_token" translatable="false">006d44b624a0d28492e828415846f996938IAD4L7AfPvzO2ZdzbBVPpZmOlpelC</string> <resources> but it does not seem to work. I just started coding and copied the code from github "https://github.com/Meherdeep/agora-android-live-streaming" and want to create my own project as well. the camera does not preview it only displays a white screen and ask for request access. I need help in looking for what is the problem. This is the manifest code <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.BLUETOOTH" /> MainActivity code package com.example.vericlean; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.RadioButton; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import io.agora.rtc.Constants; public class MainActivity extends AppCompatActivity { int channelProfile; public static final String channelMessage = "com.example.vericlean.CHANNEL"; public static final String profileMessage = "com.example.vericlean.PROFILE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); int MY_PERMISSIONS_REQUEST_CAMERA = 0; // Here, this is the current activity if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_REQUEST_CAMERA); } } public void onRadioButtonClicked(View view) { boolean checked = ((RadioButton) view).isChecked(); switch (view.getId()) { case R.id.host: if (checked) { channelProfile = Constants.CLIENT_ROLE_BROADCASTER; } break; case R.id.audience: if (checked) { channelProfile = Constants.CLIENT_ROLE_AUDIENCE; } break; } } public void onSubmit(View view) { EditText channel = (EditText) findViewById(R.id.channel); String channelName = channel.getText().toString(); Intent intent = new Intent(this, VideoActivity.class); intent.putExtra(channelMessage, channelName); intent.putExtra(profileMessage, channelProfile); startActivity(intent); } } VideoActivity code import android.content.Intent; import android.graphics.PorterDuff; import android.os.Bundle; import android.util.Log; import android.view.SurfaceView; import android.view.View; ;//;.; import android.widget.FrameLayout; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import io.agora.rtc.Constants; import io.agora.rtc.IRtcEngineEventHandler; import io.agora.rtc.RtcEngine; import io.agora.rtc.video.VideoCanvas; import io.agora.rtc.video.VideoEncoderConfiguration; public class VideoActivity extends AppCompatActivity { private RtcEngine mRtcEngine; private String channelName; private int channelProfile; public static final String LOGIN_MESSAGE = "com.example.vericlean.CHANNEL_LOGIN"; private IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() { @Override public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) { runOnUiThread(new Runnable() { @Override public void run() { setupRemoteVideo(uid); } }); } @Override public void onUserOffline(int uid, int reason) { runOnUiThread(new Runnable() { @Override public void run() { onRemoteUserLeft(); } }); } @Override public void onUserMuteVideo(final int uid, final boolean muted) { runOnUiThread(new Runnable() { @Override public void run() { onRemoteUserVideoMuted(uid, muted); } }); } }; public void onLocalAudioMuteClicked(View view) { ImageView iv = (ImageView) view; if (iv.isSelected()) { iv.setSelected(false); iv.clearColorFilter(); } else { iv.setSelected(true); iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY); } mRtcEngine.muteLocalAudioStream(iv.isSelected()); } private void onRemoteUserVideoMuted(int uid, boolean muted) { FrameLayout container = (FrameLayout) findViewById(R.id.remote_video_view_container); SurfaceView surfaceView = (SurfaceView) container.getChildAt(0); Object tag = surfaceView.getTag(); if (tag != null && (Integer) tag == uid) { surfaceView.setVisibility(muted ? View.GONE : View.VISIBLE); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video); Intent intent = getIntent(); channelName = intent.getStringExtra(MainActivity.channelMessage); channelProfile = intent.getIntExtra(MainActivity.profileMessage, -1); if (channelProfile == -1) { Log.e("TAG: ", "No profile"); } initAgoraEngineAndJoinChannel(); } public void onLocalVideoMuteClicked(View view) { ImageView iv = (ImageView) view; if (iv.isSelected()) { iv.setSelected(false); iv.clearColorFilter(); } else { iv.setSelected(true); iv.setColorFilter(getResources().getColor(R.color.colorPrimary), PorterDuff.Mode.MULTIPLY); } mRtcEngine.muteLocalVideoStream(iv.isSelected()); FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container); SurfaceView surfaceView = (SurfaceView) container.getChildAt(0); surfaceView.setZOrderMediaOverlay(!iv.isSelected()); surfaceView.setVisibility(iv.isSelected() ? View.GONE : View.VISIBLE); } private void setupRemoteVideo(int uid) { FrameLayout container = (FrameLayout) findViewById(R.id.remote_video_view_container); // if (container.getChildCount() > 1) { // return; // } SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext()); container.addView(surfaceView); mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, uid)); } private void onRemoteUserLeft() { FrameLayout container = (FrameLayout) findViewById(R.id.remote_video_view_container); container.removeAllViews(); } private void initAgoraEngineAndJoinChannel() { initalizeAgoraEngine(); mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING); mRtcEngine.setClientRole(channelProfile); setupVideoProfile(); setupLocalVideo(); joinChannel(); } private void initalizeAgoraEngine() { try { mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.private_app_id), mRtcEventHandler); } catch (Exception e) { e.printStackTrace(); } } private void setupVideoProfile() { mRtcEngine.enableVideo(); mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(VideoEncoderConfiguration.VD_640x480, VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15, VideoEncoderConfiguration.STANDARD_BITRATE, VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT)); } private void setupLocalVideo() { FrameLayout container = (FrameLayout) findViewById(R.id.local_video_view_container); SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext()); surfaceView.setZOrderMediaOverlay(true); container.addView(surfaceView); mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0)); } private void joinChannel() { mRtcEngine.joinChannel(getString(R.string.agora_access_token), getString(R.string.private_app_id), "Optional Data", 0); } private void leaveChannel() { mRtcEngine.leaveChannel(); } @Override protected void onDestroy() { super.onDestroy(); leaveChannel(); RtcEngine.destroy(); mRtcEngine = null; } public void onSwitchCameraClicked(View view) { mRtcEngine.switchCamera(); } public void onEndCallClicked(View view) { finish(); } } ``` [1]: https://github.com/Meherdeep/agora-android-live-streaming |
PL/SQL Function returning multiple values Posted: 22 Jan 2022 05:17 AM PST Suppose I have a table XX_TEST which has two columns ID(number) and NAME(varchar2(20)) It has following values:- ID NAME 1 RJ 1 NJ 2 AJ 2 PJ Now I want to create a PL/SQL FUNCTION which has 1 parameter say P_ID. where if I pass P_ID value as 1 then it should return values as RJ and NJ. and if I pass P_ID value as 2 it should return AJ and PJ. I tried below code but not working. It is giving me error "ORA-01422: exact fetch returns more than requested number of rows" create or replace type emp_obj_type as object (name varchar2(20)); create or replace type emp_tbl_type is table of emp_obj_type; create or replace function F_RET_VAL(P_ID number) return emp_tbl_type IS P_NAME varchar2(20); emp_details emp_tbl_type:=emp_tbl_type(); BEGIN emp_details.extend(); select name into P_NAME from xx_test where ID=P_ID; emp_details(1):=emp_obj_type(p_name); return emp_details; end; Kindly suggest. |
re-render as soon as the state is changed Posted: 22 Jan 2022 05:17 AM PST I have app.js file like so export const App = () => { const [selectedMeals, setSelectedMeals] = useState<string[]>(["allItems"]); const onCheckHandler = (e: any) => { const checkedValue = e.target.value; if (e.target.checked && checkedValue !== "allItems") { setSelectedMeals( [...new Set([...selectedMeals, checkedValue])].filter( (item) => item !== "allItems" ) ); } else if (e.target.checked && checkedValue === "allItems") { setSelectedMeals(["allItems"]); } else { setSelectedMeals(selectedMeals.filter((item) => item !== checkedValue)); } }; return ( <MenuFilter onClick={hideMenuModalHandler} onCheck={onCheckHandler} checkedItems={selectedMeals} /> ); } The menu filter in turn uses a checkbox component to render several check boxes & the checked status of these checkboxes depends on the selectedMeals prop that i pass to the menufilter component export const MenuFilter = ({ onClick, onCheck, checkedItems, }: MenuFilterProps) => { const excelDataContextObject = useContext(excelDataContext); const excelData = excelDataContextObject.excelData; const colorModeState = useContext(colorModeContext); const toggled = colorModeState.toggled; let meals = [...new Set(excelData.map((item: menuItem) => item.Meal))]; return ( <Modal filterItems={meals} toggled={toggled} onClick={onClick}> <div className={`${styles["modal-header"]} grid ${ toggled ? "theme-dark" : "theme-light" }`} > Filter Menu </div> <div className={`${styles["menu-filter"]} grid ${ toggled ? "theme-dark" : "theme-light" }`} > <CheckBox key={"allItems"} standAlone={false} text={"All Items"} onCheck={onCheck} isChecked={checkedItems.includes("allItems")} value={"allItems"} /> {meals.map((meal: string) => ( <CheckBox key={meal} standAlone={false} text={meal} onCheck={onCheck} isChecked={checkedItems.includes(meal)} value={meal} /> ))} </div> <div className={`${styles["modal-footer"]}`}> <button className={`${styles.ok} ${toggled ? "theme-dark" : "theme-light"}`} > OK </button> <button className={`${styles.cancel} ${ toggled ? "theme-dark" : "theme-light" }`} onClick={onClick} > Cancel </button> </div> </Modal> ); }; I read that when the state is passed as a prop, the re-rendering happens as soon as the state changes but this is not happening. The selectedMeals state is initialized with allItems and then managed such that when any other items is click, that items is set & allItems and these individual items can be several at once. The state management works fine but the checkbox is not getting updated based on the state! See the video here (https://youtu.be/Zmfc0MQGaIU) where the state change (allItems gets removed & when allItems is checked other items get removed) works perfectly but the check boxes are not re-rendering appropriately What am I doing wrong & more importantly how do I get the result I want? |
Return a manipulated mutable Python object passed by reference Posted: 22 Jan 2022 05:17 AM PST Is it good practice to return an object that is passed by reference and manipulated in a function? Which of these two approaches is more pythonic? Not returning a manipulated object in place or to return it: def append42(mylist: list) -> None: mylist.append(42) def append42(mylist: list) -> list: mylist.append(42) return mylist The latter looks nicer to me, but it is ambiguous as the function can be used in two different ways to get the same result, e.g.: mylist = [1, 2, 3] append42(mylist) print(mylist) >>> [1, 2, 3, 42] or mylist = [1, 2, 3] stillmylist = append42(mylist) assert stillmylist == mylist print(stillmylist) >>> [1, 2, 3, 42] |
Flutter upload List of Images on FTP Server Posted: 22 Jan 2022 05:17 AM PST Hello I use ftpConnect package "https://github.com/salim-lachdhaf/ftpConnect" to save a List of Images on my Server. Now, the connection on the Server work and also the folder or directory creation. The problem is just "upload a list of images on the FTP Server". This is my upload function: Future<void> _uploadFiles( String folder, name, List<ImageObject> images) async { FTPConnect ftpConnect = FTPConnect(host, user: user, pass: password); try { await ftpConnect.connect(); await ftpConnect.makeDirectory(folder); await ftpConnect.changeDirectory(folder); await ftpConnect.createFolderIfNotExist(name); await ftpConnect.uploadFile(File(images.first.modifiedPath)); debugPrint('FILE UPLOADED SUCCESSFULLY'); await ftpConnect.disconnect(); } on SocketException catch (e) { debugPrint('ERRORE_SocketException: ${e.message}'); } catch (e) { debugPrint('ERRORE_e: ${e.toString()}'); } } Thanks. |
Take out js code from .html file cause error 400 Posted: 22 Jan 2022 05:17 AM PST Here is the part of the code that I try to take out to .js file function checkEmailUnique(form) { url = "[[@{/users/check_email}]]"; userId = $("#id").val(); userEmail = $("#email").val(); csrfValue = $("input[name='_csrf']").val(); params = {id: userId, email: userEmail, _csrf: csrfValue}; $.post(url, params, function (response) { console.log(response); if (response == "OK") { form.submit(); } else if (response == "Duplicated") { showModalDialog("Warning", "There is another user having the email: " + userEmail); } else { showModalDialog("Error", "Unknown response from server"); } }).fail(function () { showModalDialog("Error", "Could not connect to the server"); }); return false; } function showModalDialog(title, message) { $("#modalTitle").text(title); $("#modalBody").text(message); $("#modalDialog").modal(); } and link to this file from .html right before close body tag: <script type="text/javascript" th:src="@{/js/userForm.js?v=1}"></script> </body> I am sure path to .js file is correct. I tried to use versions (/js/userForm.js?v=1) but id didn't solve the problem. I have an error 400 and modal dialog with an expected message "Could not connect to the server". In console I have this message: Failed to load resource: the server responded with a status of 400 () Do I miss any import/export state? |
Sorting character from string Posted: 22 Jan 2022 05:17 AM PST I need help solving this problem, if anyone had a similar problem it would help me a lot. The task is: Enter string, print and sort only letter from string. I don't know why program breaks when I want to sort charcter in string, also if I try anything with the variable r in the main, for example to print its length the program will break. Note, the program needs to be done with the functions listed. Code is: #include <stdio.h> #include <stdlib.h> #include <math.h> #define MAX 200 #define KV(x) (x)*(x) char* letter(const char *); void sort(char *s); int lenght(char *); int main() { char s[100]; char *r; printf("Enter string:"); gets(s); r=letter(s); sort(r); printf("%c",r); free(r); return 0; } char* letter(const char *s) { int i; int j=0; char *r; r=(char*)calloc(lenght(s)+1,sizeof(char)); for(i=0;s[i]!=0;i++) { if(s[i]>='a' && s[i]<='z' || s[i]>='A' && s[i]<='Z') { r[j]=s[i]; printf("%c",r[j]); j++; } } } void sort(char *s) { for(int i=0;i<lenght(s)-1;i++) { for(int j=i+1;j<lenght(s);j++) { if(s[i]<s[j]) { char pom=s[i]; s[i]=s[j]; s[j]=pom; } } } } int lenght(char *s) { int d; for(d=0;s[d]!=0;d++); return d; } Thanks in advance ! |
Adding product to Cart Not Working Express,Node and Ejs Posted: 22 Jan 2022 05:16 AM PST I am working on an e commerce project in express with ejs as template engine. I am trying to add products to the cart,however it somehow doesn't work without throwing any error. My aim is that cart be updated as i add product to the cart. I have tried to log the result on console which works fine but the cart isn't updated. header.ejs: <li> <a href="/cart/checkout"> My Cart ( <% if (typeof cart !== "undefined") { %> <%= cart.length %> <% } else {%> 0 <% } %> )</a> </li> the cart controller in cart.js: router.get('/add/:product', function (req, res) { var slug = req.params.product; Product.findOne({slug: slug}, function (err, p) { if (err) console.log(err); if (typeof req.session.cart == "undefined") { req.session.cart = []; req.session.cart.push({ title: slug, qty: 1, price: parseFloat(p.price).toFixed(2), image: '/product_images/' + p._id + '/' + p.image }); } else { var cart = req.session.cart; var newItem = true; for (var i = 0; i < cart.length; i++) { if (cart[i].title == slug) { cart[i].qty++; newItem = false; break; } } if (newItem) { cart.push({ title: slug, qty: 1, price: parseFloat(p.price).toFixed(2), image: '/product_images/' + p._id + '/' + p.image }); } } req.flash('success', 'Product added!'); res.redirect('back'); }); }); and app.js: var cart = require('./routes/cart.js'); app.use('/cart', cart); app.get('*', function(req,res,next) { res.locals.cart = req.session.cart; next(); }); |
How can I get characters of a String without using any library except IO [duplicate] Posted: 22 Jan 2022 05:16 AM PST I have to get characters of a String for my homework but the only library I can use is Java.IO for this. I need to have characters of a String which is given as a parameter and I can't use different libraries then IO library. Any suggestion about it? |
pandas Dataframe from itertools.product output not able to be created Posted: 22 Jan 2022 05:17 AM PST I want to create a Dataframe of all possible combinations: Primary_function=['Office','Hotel','Hospital(General Medical & Surgical)','Other - Education'] City=['Miami','Houston','Phoenix','Atlanta','Las Vegas','San Francisco','Baltimore','Chicago','Boulder','Minneapolis'] Gross_Floor_Area=[50,100,200] Years_Built=[1950,1985,2021] Floors_above_grade=[2,6,15] Heat=['Electricity - Grid Purchase','Natural Gas','District Steam'] WWR=[30,50,70] Buildings=[Primary_function,City,Gross_Floor_Area,Years_Built,Floors_above_grade,Heat,WWR] a=list((itertools.product(*Buildings))) df=pd.DataFrame(a,columns=Buildings) The error that I am getting is : ValueError: Length of columns passed for MultiIndex columns is different |
When user doesnt enter any choice Posted: 22 Jan 2022 05:19 AM PST I need to ask user in unix shell script to enter input to proceed further in a code block. Need to display 'Hi' only when user enters Y (case sensitive) otherwise just display 'Bye'. 'Bye' should be displayed when user hits enter key on keyboard or when he wont enter any input. Also, please note that, I need to show either of echo messages based on user input and finally reach 'Proceeding to next line of code' code as well. I am getting below error for else condition when user hits enter key [: ==: unary operator expected echo 'Do you want to proceed?' read i if [ $i == 'Y' ] then echo 'Hi' else echo 'Bye' fi echo 'Proceeding to next line of code' |
python check if user input has the correct int value in a string Posted: 22 Jan 2022 05:17 AM PST I try to fix a problem where the user can input for example "blub1234" or "blub4567" or "blub912" and the code can check if the user typed in the right word "blub" and the possible value as an int from 1 up to 100k. user_input = str("Type your blub User) if user_input == ("user_input" + ???): print("Okay") else: print("Not Okay") The user shouldn't type for example "blob2312" or "blib1212" only the word "blub" with the number value to 100k. I tried it with ranges and for loops, but it ends every time with: TypeError: can only concatenate str (not "int") to str |
In Google Sheets, how can I copy a row based on a specific column value into a new tab, and then append checkboxes to the row? Posted: 22 Jan 2022 05:17 AM PST I'm trying to write a script which would allow me to copy a row into a new tab based on a specific cell value. In this case, it is a checkbox of being set to TRUE. I have no issue with copying the row to a new sheet based on the cell value, but now I'm unsure as to how I can use insertCheckboxes to append 5 checkboxes to the copied row in the new sheet. This is the code I have at the moment: function onEdit(event) { var ss = SpreadsheetApp.getActiveSpreadsheet(); var s = event.source.getActiveSheet(); var r = event.source.getActiveRange(); if(s.getName() == "Client Database" && r.getColumn() == 9 && r.getValue() == true) { var row = r.getRow(); var numColumns = s.getLastColumn(); var targetSheet = ss.getSheetByName("Referrals"); var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1); s.getRange(row, 1, 1, numColumns).copyTo(target); } } Column 9 contains checkboxes which when set to true, copies the row from "Client Database" into my new tab ("Referrals"). I'm scratching my head over two things: - What do I need to change in the code to only copy columns 1 and 4 from the original sheet? (as it is currently copying all columns from the row).
- Unless there is an easier workaround, how can I append checkboxes into the adjacent columns within the new sheet using
insertCheckboxes ? (Illustration below). This is simply to avoid having to manually insert the boxes each time (as I will not be the one using the sheet) Any advice is greatly appreciated. |
Pandas: MultiIndex from Nested Dictionary Posted: 22 Jan 2022 05:16 AM PST Suppose I have a nested dictionary of the format: dictionary={ "A":[1, 2], "B":[2, 3], "Coords":[{ "X":[1,2,3], "Y":[1,2,3], "Z":[1,2,3], },{ "X":[2,3], "Y":[2,3], "Z":[2,3], }] } How can I turn this into a Pandas MultiIndex Dataframe? Equivalently, how can I produce a Dataframe where the information in the row is not duplicated for every co-ordinate? In what I imagine, the two rows of output DataFrame should appear as follows: Index A B Coords --------------------- 0 1 2 X Y Z 1 1 1 2 2 2 3 3 3 -------------------- --------------------- 1 2 3 X Y Z 2 2 2 3 3 3 -------------------- |
How to get EditText (vertical line) animation without keyboard Posted: 22 Jan 2022 05:17 AM PST How to get EditText (vertical line) animation without keyboard? The edittext keyboard should not appear when the activity starts, but the write animation should start. Please help me! |
Flutter null safety http, shared_preferences requiring plugin_platform_interface without null safety. How to fix it? Posted: 22 Jan 2022 05:16 AM PST So, I added two devDependencies in flutter pubspec.yml : dev_dependencies: flutter_test: sdk: flutter shared_preferences: ^2.0.0-nullsafety http: ^0.13.0-nullsafety.0 Both shared_preferences and http versions are based upon null safety. The flutter application is working perfectly before including these. But after I try running the app I get the following error: Error: Cannot run with sound null safety, because the following dependencies don't support null safety: - package:plugin_platform_interface For solutions, see https://dart.dev/go/unsound-null-safety I am not sure which package has a dependency to plugin_platform_interface , but how can I solve this without overriding the null-safety rule for code execution? I don't want to run the code without null-safety. I didn't include plugin_platform_interface anywhere in the dependencies but still getting an error with respect to the same package. Edit: Moving the dependencies to dependencies from dev_dependencies doesn't solve the problem. Nor does replacing the versions by any |
What is the return type of subspan() [closed] Posted: 22 Jan 2022 05:18 AM PST I have been trying to write a function that returns a subset of a vector of type T. I am able to use auto sspan = std::span(vectorname).subspan(start,length) to get this, but what should the return type of the function be? (aka what could "auto" be replaced with) I've tried vector and vector<T*>, but thats not right, as people say, subspan doesn't return a vector it just provides a view into that data. |
How to overcome variable length limitation of 32767 characters, when handling output from a function in a SAS data step? Posted: 22 Jan 2022 05:17 AM PST I want to put a html-generating macro function inside a html document and write the html document to _webout via a data step that uses resolve, see below pseudocode for details. However when the output of the html_generating_macro function exceeds 32767 characters, it gets truncated. As I understand it, the limitation is within the datastep variable text. How can I overcome this limitation and get the output of resolve (and the html_generating_macro) to _webout? data _null_; file _webout; length text $32767; retain text; infile index.html flowover end=last; input; text = resolve(_infile_); put text; run; %macro html_generating_macro(); %do i=1 %to 10000; some html code %end; %mend; <html> <body> %html_generating_macro </body> </html> |
Adding the values of a field using FOR loop Posted: 22 Jan 2022 05:17 AM PST How do I add the values in a field based on the same values in another field using FOR loop? Types: Begin of ty_final, doctype type char5, posnr type char5, total type quan5, End of ty_final. DATA(lt_final) = VALUE ty_final( FOR line IN lt_history WHERE ( hist_type = 'U' ) ( doctype = line-hist_type total = line-quantity posnr = line-po_item ) ). What I have in LT_HISTORY: HIST_TYPE POSNR QUANTITY U 10 5 U 10 2 U 20 3 U 20 -3 What I need in LT_FINAL: DOCTYPE POSNR QUANTITY U 10 7 U 20 0 I am trying to use GROUP BY to get the sum of the values in TOTAL field based on POSNR and DOCTYPE fields. It's just that I am not sure where exactly I need to add GROUP BY in my FOR loop. REDUCE makes my head spin. So I was trying out as simple as possible. |
OperationalError at /admin/sybase_app/packageweight/ (b"Table 'sybase_app_packageweight' not found", -141) Posted: 22 Jan 2022 05:17 AM PST When I edit my admin.py file from django.contrib import admin from .models import Packageweight admin.site.register(Packageweight) and the run python manage.py runserver and click in the admin page on Packageweight it throws this error Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/sybase_app/packageweight/ Django Version: 1.8 Python Version: 3.6.9 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'sybase_app') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/home/pd/.local/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 616. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 233. return view(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 34. return bound_func(*args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 110. response = view_func(request, *args, **kwargs) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 30. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/options.py" in changelist_view 1548. self.list_max_show_all, self.list_editable, self) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/views/main.py" in __init__ 82. self.get_results(request) File "/home/pd/.local/lib/python3.6/site-packages/django/contrib/admin/views/main.py" in get_results 177. result_count = paginator.count File "/home/pd/.local/lib/python3.6/site-packages/django/core/paginator.py" in _get_count 72. self._count = self.object_list.count() File "/home/pd/.local/lib/python3.6/site-packages/django/db/models/query.py" in count 318. return self.query.get_count(using=self.db) File "/home/pd/.local/lib/python3.6/site-packages/django/db/models/sql/query.py" in get_count 464. number = obj.get_aggregation(using, ['__count'])['__count'] File "/home/pd/.local/lib/python3.6/site-packages/django/db/models/sql/query.py" in get_aggregation 445. result = compiler.execute_sql(SINGLE) File "/home/pd/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql 829. cursor.execute(sql, params) File "/home/pd/.local/lib/python3.6/site-packages/django/db/backends/utils.py" in execute 79. return super(CursorDebugWrapper, self).execute(sql, params) File "/home/pd/.local/lib/python3.6/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/home/pd/.local/lib/python3.6/site-packages/django/db/utils.py" in __exit__ 97. six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/pd/.local/lib/python3.6/site-packages/django/utils/six.py" in reraise 658. raise value.with_traceback(tb) File "/home/pd/.local/lib/python3.6/site-packages/django/db/backends/utils.py" in execute 64. return self.cursor.execute(sql, params) File "/home/pd/.local/lib/python3.6/site-packages/sqlany_django/base.py" in execute 98. ret = self.cursor.execute(trace(query), trace(args)) File "/home/pd/.local/lib/python3.6/site-packages/sqlanydb.py" in execute 796. self.executemany(operation, [parameters]) File "/home/pd/.local/lib/python3.6/site-packages/sqlanydb.py" in executemany 767. bind_count = self.api.sqlany_num_params(self.stmt) File "/home/pd/.local/lib/python3.6/site-packages/sqlanydb.py" in __stmt_get 701. self.handleerror(*self.parent.error()) File "/home/pd/.local/lib/python3.6/site-packages/sqlanydb.py" in handleerror 695. eh(self.parent, self, errorclass, errorvalue, sqlcode) File "/home/pd/.local/lib/python3.6/site-packages/sqlanydb.py" in standardErrorHandler 379. raise errorclass(errorvalue,sqlcode) Exception Type: OperationalError at /admin/sybase_app/packageweight/ Exception Value: (b"Table 'sybase_app_packageweight' not found", -141) How could I fix it? Ubuntu 18.04 |
Why isn't Form.Select recognized in my simple react-bootstrap app, following the react-bootstrap documentation? Posted: 22 Jan 2022 05:17 AM PST I am a "react-bootstrap with hooks" first-timer and I am creating a simple form. I am following the react-bootstrap documentation's example and I am running into a problem with select/option form elements. Regular text input fields render normally without an error. Select statements seem to blow things up. Here is my code: import { Form, Button } from "react-bootstrap"; export default function FormComponentName(props) { return ( <> <h1>Search Form</h1> <Form> <Form.Group className="mb-3" controlId="searchState"> <Form.Label>State</Form.Label> <Form.Select defaultValue="State..."> <option>State...</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </Form.Select> </Form.Group> <Button variant="primary" type="submit"> Search Data </Button> </Form> </> ) } Here is the yarn error message: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check the render method of `FormComponentName`. And from the console: index.js:1 Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports. Check your code at FormComponentName.js:14. at FormComponentName Do I need to install an additional module, or is it something more obvious? |
EXNetwork error 403 when publishing app to ios with Expo? Posted: 22 Jan 2022 05:16 AM PST I am currently publishing my app for user testing using Expo, and it works fine when Android users scan the QR code. However when my friend on iOS tries to use the QR code on their Expo Go app(they are logged in), they get the following error: "The Operation couldn't be completed. EXNetwork Error 403". This also happens when I email my friend the link to the project. |
Shutdown Windows machine from linux terminal Posted: 22 Jan 2022 05:16 AM PST I am running an application on linux machine. By giving the ip address of a windows machine as input, the application must shutdown the windows machine. If the machines run the same OS it is very easy but I'm confused how to do it in cross OS. |
Ruler in Visual Studio Posted: 22 Jan 2022 05:17 AM PST We are developing a windows forms application in Visual Studio 2010. I know there's no ruler in VS, is there any addin that does the job? Thanks. |
No comments:
Post a Comment