Creat a list with repeated terms by adding a multiplier index in Pandas Dataframe Posted: 31 Jan 2022 08:00 AM PST Given a dataframe like this: row1 = ['AAA', 'BBB', 'BBB', 'CCC', 'AAA', 'AAA'] row2 = ['CCC', 'CCC', 'BBB', 'AAA', 'AAA', 'AAA'] col = {'Lists': [row1, row2]} df = pd.DataFrame(col) which leads to: Index | List | 0 | ['AAA', 'BBB', 'BBB', 'CCC', 'AAA', 'AAA'] | 1 | ['CCC', 'CCC', 'BBB', 'AAA', 'AAA', 'AAA'] | I would like to generate the following dataframe: | List | 0 | ['AAA', 'BBB x 2', 'CCC', 'AAA x 2'] | 1 | ['CCC x 2', 'BBB', 'AAA x 3'] | where the final column List contain a multiplier index that indicates how many times the term appears consecutively in the list. Could you suggest a pandas instruction that solves this task? |
Integrating DynamoDB Table with Lambda to fetch data for Lex Chatbot - No response Posted: 31 Jan 2022 07:59 AM PST I am building a AWS Lex bot integrated with Lambda which can fetch data from table in DynamoDB. I have granted Full Access to DynamoDB for Lambda by adding new role. But every time it is showing- "Invalid Lambda responses". Below I am sharing the Lambda code in python. import json import boto3 client = boto3.client('dynamodb') result = {} intent="" Accountnumber="" def lambda_handler(event, context): intent=(event['currentIntent']['name']) #print('the intent is : ',intent) Accountnumber=(event['currentIntent']['slots']['AccountNumber']) #print('accountnumber is : ',Accountnumber) if intent=='AccountBalanceEnquiry': balanceenquiry(Accountnumber) return result # Method to Fetch the account balance from database by giving the Accountnumber as paramater def balanceenquiry(Accountnumber): response = client.get_item( TableName='customerdetails', Key={ 'accountnumber': { 'S': Accountnumber, } } ) #print('responce is: ',response) # Declaring a key to verify the response key='Item' # Storing the boolean value wether key present or not value = key in response.keys() if value: accountnumber=response['Item']['accountnumber']['S'] name=response['Item']['name']['S'] balance=response['Item']['balance']['N'] message='Hello ', name, ' You have $',balance, ' in your account' msg=''.join(message) #print(msg) global result # Result to lex bot result = { "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": msg }, } } return result else: #print("didnt find the account") message="Sorry I can't find your details in our records please contact our support center on 8083829227" result = { "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": message }, } } return result |
How to request refresh token from Etsy using OAuth-2.0 from C# Posted: 31 Jan 2022 07:59 AM PST Having failed miserably using C# code to get an Etsy OAuth 2 token, I resorted to using Postman for the initial request figuring that it would then be a simple matter of requesting a refresh token as and when needed. So, from Postman, all good, I can sign in and grant access, which then causes Etsy to respond with a shortlived access token (and a refresh token to use to request another access token without having to go through the whole grant process again). However, I cannot figure out how to get another access token using this refresh token as Etsy keeps on responding with grant_type is required. OK, the initial response from Postman following the success grant access is: { "access_token": "<initial-access-token-from_Etsy>", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "<my-refresh-token>" } And following their docs to request a refresh OAuth token, it implies that all I need to do is to make a POST request to https://openapi.etsy.com/v3/public/oauth/token, adding the following parameters to the JSON body with content type: application/x-www-form-urlencoded: { "grant_type": "refresh_token", "client_id": "<my-client-API-string>", "refresh_token": "<my-refresh-token>" } Thus, setting all this up in Postman and looking at the generated code for the request gives: var client = new RestClient("https://openapi.etsy.com/v3/public/oauth/token"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddHeader("x-api-key", "<my-client-API-string>");* request.AddParameter("grant_type", "refresh_token"); request.AddParameter("client_id", "<my-client-API-string>"); request.AddParameter("refresh_token", "<my-refresh-token>"); IRestResponse response = client.Execute(request); Console.WriteLine(response.Content); *NOTE - I had to add in the header the parameter x-api-key otherwise it would fail with "error": "Missing x-api-key header or client_id" Alas, the response from Etsy is always { "error": "invalid_request", "error_description": "grant_type is required" } This post guided me in making the initial request. Why is it moaning about grant_type when it's in the body as requested!?!?!? |
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task UnknownReason Posted: 31 Jan 2022 07:59 AM PST With this code I'd got data from oracle, postgres or sql server many times, how ever this time receiving error message in the subject Comlete log message is below: py4j.protocol.Py4JJavaError: An error occurred while calling o33.showString. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task 0.3 in stage 0.0 (TID 3) (10.42.8.125 executor 1): UnknownReason Will be appreciated with any help. Regards, Mert. |
SFTP How to List Large # of Files Posted: 31 Jan 2022 07:59 AM PST I am currently working on SFTP load to GCS bucket. However, I am able to do it for a limited number of files in any given SFTP directory. However, if the directory has too many files (or files within another folder), I am not able to do a simple ls & get the list of files to download from SFTP. Following is the working code to get the list of files in any given directory recursively from sftp: import sys from stat import S_ISDIR, S_ISREG import paramiko sftp_url = '<URL>' sftp_user = '<USER>' sftp_pwd = '<PWD>' def get_sftp_obj(sftp_cred_dict): server = sftp_cred_dict['server'] username = sftp_cred_dict['username'] password = sftp_cred_dict['password'] timeout_min = sftp_cred_dict['timeout_min'] paramiko.sftp_file.SFTPFile.MAX_REQUEST_SIZE = pow(2, 22) #4MB Chunk Default transport = paramiko.Transport((server, 22)) transport.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.get_channel().settimeout(timeout_min*60) return sftp def sftp_get_recursive_files(path, skip_dir_list, sftp, sftp_files=[]): item_list = sftp.listdir_attr(path) for item in item_list: mode = item.st_mode item = item.filename if S_ISDIR(mode): path_build = path + '/' + item if not(item in skip_dir_list): sftp_get_recursive_files(path_build, skip_dir_list, sftp, sftp_files) else: print('skip directory files: ' + path_build) elif S_ISREG(mode): sftp_file_path = path + '/' + item sftp_files.append(sftp_file_path) return sftp_files def main(): sftp_cred_dict = { "server": sftp_url, "username": sftp_user, "password": sftp_pwd, "timeout_min": 60 } skip_dir_list = ["archive"] arguments = sys.argv ls_dir = arguments[1] print(ls_dir) sftp = get_sftp_obj(sftp_cred_dict) files = sftp_get_recursive_files(ls_dir, skip_dir_list, sftp, []) print(len(files)) if __name__ == "__main__": main() I get the following exception after some time of execution: (venv-sftp) user@poc-sftp:~/experiments/sftp-v1$ python ls-sftp.py /BU/SYSTEM/outbound/SYSTEM_Txn_Payment Traceback (most recent call last): File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp_client.py", line 852, in _read_response t, data = self._read_packet() File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp.py", line 201, in _read_packet x = self._read_all(4) File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp.py", line 188, in _read_all raise EOFError() EOFError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "ls-sftp.py", line 62, in <module> main() File "ls-sftp.py", line 57, in main files = sftp_get_recursive_files(ls_dir, skip_dir_list, sftp, []) File "ls-sftp.py", line 27, in sftp_get_recursive_files item_list = sftp.listdir_attr(path) File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp_client.py", line 246, in listdir_attr t, msg = self._request(CMD_READDIR, handle) File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp_client.py", line 822, in _request return self._read_response(num) File "/home/user/experiments/sftp-v1/venv-sftp/lib/python3.7/site-packages/paramiko/sftp_client.py", line 854, in _read_response raise SSHException("Server connection dropped: {}".format(e)) paramiko.ssh_exception.SSHException: Server connection dropped: |
Gstreamer how to get element information from STATE_CHANGED message from the bus Posted: 31 Jan 2022 07:59 AM PST I am working with Gstreamer and its Python bindings. Consider the following bus_call function: import sys from gi.repository import Gst def bus_call(bus, message, loop): t = message.type if t == Gst.MessageType.EOS: print("Bus call: End-of-stream\n") # loop.quit() elif t == Gst.MessageType.WARNING: err, debug = message.parse_warning() sys.stderr.write("Bus call: Warning: %s: %s\n" % (err, debug)) elif t == Gst.MessageType.ERROR: err, debug = message.parse_error() sys.stderr.write("Bus call: Error: %s: %s\n" % (err, debug)) # loop.quit() elif t == Gst.MessageType.BUFFERING: print("Bus call: Buffering\n") elif t == Gst.MessageType.STATE_CHANGED: old_state, new_state, pending_state = message.parse_state_changed() print(( f"Bus call: Pipeline state changed from {old_state.value_nick} to {new_state.value_nick} " f"(pending {pending_state.value_nick})" )) else: print(f"Bus call: {message}\n") return True When the message type is Gst.MessageType.STATE_CHANGED , how can I retrieve the element that has changed the state? |
app update in google developer console for payment subcribtion Posted: 31 Jan 2022 07:59 AM PST I had completed my first app using android studio and firebase and I am now trying to upload to google play store through google play console. I have two sets of users in my app , 1. Buyers and 2. Sellers. Currently my app is free for both buyers and sellers, so in data safety section in developer account, in Financial info section I didn't select any thing like credit card or debit card , but in next update I am planning to make seller subscription charges or 1 year or 2 year like that , so I will be collecting their credit or debit card information... I like to know whether financial information can be changed in every update or I need to plan prior and select payment information in first upload itself. |
spark trying to convert .Mf4 to save as .txt files, getting issue Posted: 31 Jan 2022 07:59 AM PST I have a spark code which reads .mf4 files and write as a .txt file. Also running this code in databricks. Could you please suggest? Even after increasing the executor memory in data bricks in cluster, still having the issue. pip install asammdf from pyspark import SparkContext from pyspark.sql import SparkSession from asammdf import MDF import io import os import sys from pyspark.sql.functions import col os.environ['PYSPARK_PYTHON'] = sys.executable os.environ['PYSPARK_DRIVER_PYTHON'] = sys.executable spark = SparkSession \ .builder \ .appName("mdf4") \ .getOrCreate() sc = spark.sparkContext def decodeBinary(val): file_stream = io.BytesIO(val) mdf = MDF(file_stream) location = mdf.whereis(test_1) return location print("1") input_hdfs_path_to_mdf4 = "dbfs:/FileStore/inputmfd4/" channel_name = "test_1" local_or_hdfs_output_path = "dbfs:/FileStore/outputmfd4/opp4.txt" print("2") raw_binary = sc.binaryFiles(input_hdfs_path_to_mdf4) print("3") decoded_binary = raw_binary.map(lambda r: r[1]).map(decodeBinary) print("4") decoded_binary.saveAsTextFile(local_or_hdfs_output_path) print("5") print(decoded_binary) I am running this code in databricks , I have 5Gb mf4 file as a input. When I try to run small file there is no issue. But when I use this 5GB mf4 file getting Caused by org.apache.spark.api.python.PythonException: asammdf.blocks.utils.MdfException: <_io.BytesIO object at 0x7efed84482c0> is not a valid ASAM MDF file: magic header is b\xff\xd8\xff\xe1H\xe6Ex from command-2705692180399242 line 24 Full traceback below Traceback (most recent call last) |
unit testing in springboot - best approach Posted: 31 Jan 2022 07:59 AM PST I'm trying to figure out what is the best approch to unittesting in SpringBoot app. Before last friday i thought that best approach is to test: - controllers with mockmvc and mocked services
- services with mocked repositories
- repositories with mocked db
- using
SpringBootTest mainly for integration tests. But then i watched this -Ian Cooper - TDD, Where Did It All Go Wrong and I've realized that my testswas implementation tests, and I should only mock db, filesystem, other systems, not my application. And I'am wondering how should I be doing this? Because when I will be creating all objects myself it will still be "testing implementation", so I can use SpringBootTest with MockBean but this would be extremly slow. Can someone clever than me could share his experience or thougths on this? |
node-polyfill-webpack-plugin not recognizing in webpack.config.js Posted: 31 Jan 2022 07:59 AM PST I am trying to use knex for sqlite local storage in an electron application and have gotten the "Breaking Change" message due to knex uses some of the polyfll components that seize to exist on webpack v5. I heard that I can use node-polyfill-webpack-plugin to put the polyfills back in. For this project, I created a "webpack.config.js" at root and put the following contents inside: const NodePolyfillPlugin = require("node-polyfill-webpack-plugin") module.exports = { // Other rules... plugins: [ new NodePolyfillPlugin() ] } Here is my package.json: { "name": "react_test", "homepage": "./", "version": "0.1.0", "private": true, "main": "public/electron.js", "dependencies": { "@testing-library/jest-dom": "^5.16.1", "@testing-library/react": "^12.1.2", "@testing-library/user-event": "^13.5.0", "assert": "^2.0.0", "axios": "^0.21.1", "babel-loader": "^8.2.2", "buffer": "^6.0.3", "constants-browserify": "^1.0.0", "copy-webpack-plugin": "^7.0.0", "crypto-browserify": "^3.12.0", "css-loader": "^5.0.1", "concurrently": "^6.0.0", "cross-env": "^7.0.3", "file-loader": "^6.2.0", "html-loader": "^1.3.2", "html-webpack-plugin": "^5.0.0", "https-browserify": "^1.0.0", "electron": "^12.0.0", "electron-is-dev": "^2.0.0", "knex": "^1.0.1", "node-polyfill-webpack-plugin": "^1.1.4", "os-browserify": "^0.3.0", "path-browserify": "^1.0.1", "prettier": "^2.2.1", "process": "^0.11.10", "react": "^17.0.2", "react-dom": "^17.0.2", "react-router": "^5.2.1", "react-router-dom": "^5.2.1", "react-scripts": "5.0.0", "regenerator-runtime": "^0.13.7", "stream-browserify": "^3.0.0", "stream-http": "^3.2.0", "style-loader": "^2.0.0", "svg-url-loader": "^7.1.1", "webpack": "^5.21.1", "webpack-cli": "^3.3.12", "wait-on": "^5.2.1", "web-vitals": "^2.1.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "electron": "wait-on tcp:3000 && electron .", "electron:build": "npm build && electron-builder -c.extraMetadata.main=build/main.js", "package-mac": "electron-packager . --overwrite --platform=darwin --arch=x64 --icon=assets/icons/mac/icon.icns --prune=true --out=release-builds", "package-win": "electron-packager . electron-tutorial-app --overwrite --asar=true --platform=win32 --arch=ia32 --icon=assets/icons/win/icon.ico --prune=true --out=release-builds --version-string.CompanyName=CE --version-string.FileDescription=CE --version-string.ProductName=\"Electron Tutorial App\"", "package-all": "electron-packager . electron-app --all --asar", "package-linux": "electron-packager . electron-tutorial-app --overwrite --asar=true --platform=linux --arch=x64 --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } However, when I run "npm start", I am still getting all of the webpack breaking change messages. Any help would be much appreciated. I have never seen this problem until I am trying to use any type of local storage (such as sqlite or NEDB) and have done an extensive search on Stack Overflow and tried several of those suggested methods (in fact the node-polyfill-webpack-plugin was from reading this site) but I still cannot get it to work. |
Xamarin: Modal from not popping Posted: 31 Jan 2022 07:59 AM PST since a couple of weeks I have the problem that a modal form which provides a spinner and a label is not popping anymore. It was running in older versions but not with all NuGet Packages updated. Any idea what this can be? Funnywise it is working on some forms and not on others. protected async override void OnAppearing() { try { await Navigation.PushModalAsync(new BusyPopUpPage("loading products")); //ActivityTracker.StartSpinner(true); base.OnAppearing(); IsFiltered = false; LblAttributesVisible = false; AllProducts = await App.AllProductsController.GetAllProducts(); grouped = new ObservableCollection<AssortmentGroups>(); GroupProducts(); AllProductsListView.IsGroupingEnabled = true; AllProductsListView.ItemsSource = grouped; await Navigation.PopModalAsync(); } catch (Exception ex) { await CreateNewBug.CreateANewBug(ex.Message,"Error in Module " + ex.Source,"\nMessage---\n{ 0}" + ex.Message + "\nInnerException---\n{ 0}" + ex.InnerException + "\nStackTrace---\n{ 0}" + ex.StackTrace + "\nTargetSite---\n{ 0}" + ex.TargetSite); ToastOptions toastOptions = Message.ShowMessage("An error was raised and a new bug created in our system.", "error"); await this.DisplayToastAsync(toastOptions); } } |
array of string to string Posted: 31 Jan 2022 07:59 AM PST Can I use JSONPath expressions to get a string out of an array of string? Example, here is an array of strings: { "objects": [ "a" "b" "c" ] } and the expresion $.objects[:] will result into [ "a" "b" "c" ] however I want to have something like { "a b c" } or better { "a, b, c" } is this possible? |
How to achieve auto scaling with AWS sage maker with single docker image and multiple model artifact? Posted: 31 Jan 2022 07:58 AM PST I am exploring AWS sage maker for deploying the machine learning models with single container/docker image and wants to achieve scalability too. For your info, we have written the training and prediction code in such a way that so, same code is being used for different customers. Only the ENV variables,VERSION_NUMBER are different according to customer. VERSION_NUMBER : Refers to S3 folder name as current timestamp which contains latest model artifact. for e.g. Customer name : XYZ docker image(training and prediction) : **intent-mapping:latest** s3 model atrifact path : s3_bucket/XYZ/VERSION_NUMBER/XYZ.tar.gz ENV variable : CUSTOMER_SUFFIX,IS_INCREMENTAL Customer name : PQR docker image(training and prediction) : **intent-mapping:latest** s3 model atrifact path : s3_bucket/PQR/VERSION_NUMBER/PQR.tar.gz ENV variable : CUSTOMER_SUFFIX,IS_INCREMENTAL If you read it carefully, you will see same docker image is being refereed everywhere So,my doubts are as follow. - Which approach should i follow to deploy the model with such a scenario?
- Let's say, if we use multiple model/multi container option of sage maker then how auto scaling will be managed for each customer independently?
Please let me know your inputs on the same. |
Replace strings inside of a file with the same name file for multiple files Posted: 31 Jan 2022 07:59 AM PST Im working with coco datasets, so I have jpg files and json files with same name for each image(for example: image1.jpg and image1.json). I needed rename the files, but inside the json files has an "adress" path with the name of the jpg image, this way ("imagePath": "image1.jpg" ). But I renamed all my files and the "imagePath" is the former name of jpg file. For example, new names(1.jpg and 1.json ), but the ("imagePath": "image1.jpg" ) and I need ("imagePath": "1.jpg" ), but this for around 1500 images and the json files. I tried some codes, but they are unseful and didn't make sense. There is a way to do this with UNIX code? thank you. |
best approche to asynchronous programming Posted: 31 Jan 2022 07:59 AM PST I'm building an app with NodeJs that get data from a websocket server and then store or update these data on an array of objects, after that the data on the array is analysed (heavy calculations) none stop. I need help to choose the best way to execute these two tasks independently from each other. I tried parallel tasking but it's didn't work, the calculation part takes 250 ms and the websocket takes only 1ms, the app waits untill calculation is done and miss all data from websocket server.. What's the best approach to achieve this? PS: i'm a self taught please don't down vote :) |
How do you POST html form data with javascript Posted: 31 Jan 2022 08:00 AM PST Im trying to POST data from a html form using javascript however on submission I believe no data is actually being sent because my alert is showing no data. when i added an alert box var jsonStr = JSON.stringify(FD); alert(jsonStr); the output came up as "{}" here is my full code below if anyone can spot my errora <form class="emailentry" " method="post" name="myForm" id="myForm"> <label for ="name">Name: </label><br> <input type ="text"id="name" name="name: " ><br> <label for ="emailad">Email: </label><br> <input type ="email"id="emailad" name="emailad" ><br> <input type= "submit" id="btn" name="submit" class="submitstyle"> </form> <script> window.addEventListener( "load", function () { function sendData() { const XHR = new XMLHttpRequest(); // Bind the FormData object and the form element const FD = new FormData( form ); // Define what happens on successful data submission XHR.addEventListener( "load", function(event) { var jsonStr = JSON.stringify(FD); alert(jsonStr); // should present me the data i entered but it isnt alert("hi"); } ); // Define what happens in case of error XHR.addEventListener( "error", function( event ) { alert( 'Oops! Something went wrong.' ); } ); // Set up our request XHR.open( "POST", "ExampleUrl.ForStackOveerflow/post" ); // The data sent is what the user provided in the form XHR.send( FD ); } // Access the form element... const form = document.getElementById( "myForm" ); // ...and take over its submit event. form.addEventListener( "submit", function ( event ) { event.preventDefault(); sendData(); } ); } ); </script> |
how to return the pointer of a specific value in a tree in C? Posted: 31 Jan 2022 07:59 AM PST using this struct : typedef struct node { int content; struct node* right; struct node* left; }Node; I'm trying to write a code that return the pointer of the the node if node ->content== x I have tried this so far but I don't think its right : Node* find (Node* p,int x) { Node* L,*R; if(p==NULL) retutn NULL; L=find(p->left,x); if(L->content == x) return L; R=find(p->right,x); if(R->content == x) return R; } can u help me correct my code? |
Common Lisp Package Definition with Dependencies for Exploloration at the REPL? Posted: 31 Jan 2022 07:59 AM PST This is another take at the question of packages and systems especially for usage locally in personal projects (maybe similiar to HOWTO definition and usage of Common Lisp packages (libraries)? from 2014). What are recommendations for how to approach this and can links be provided for sources that describe the recommended approach in 2022? CL's long half-life means lots of old blogs and books are still useful, but unfortunately not all of them, and it is hard for the novice to know which are the still viable guides. Here is the start of a file that I might write for a simple personal exploration project. My basic working mode would be to start slime, load and compile this in emacs, and then change to the slime repl and use in-package to move into my package and start playing with my functions. (ql:quickload "alexandria") (ql:quickload "trivia") (defpackage computing-with-cognitive-states (:use cl) (:nicknames :cwcs) (:local-nicknames (:alex :alexandria))) (in-package :cwcs) (defun sum-denom (dimension dist) ... ; and more defun's The leading ql:quickload 's strike me as ugly, but without them I can't load and compile. Is it recommended that I do this manually in slime repl first? Or is this considered an acceptable practice for small use cases like this? Or is there another recommended way? If I am thinking of using my package elsewhere someday is it recommended that I make it a system, perhaps with quickproject? Or is it the more traditional approach to just load a fasl file from one directory on my system when another session (or another package definition) needs it? In summary, the questions are about the writing of code that is for personal use, might be a small file, or might be a few files that depend on each other and a few external systems. What are some of the reasonable approaches and resources that describe those approaches? And which are the ones that would be easiest to scale up if the project grew into something that one wanted to share? |
GravityForms Dynamic Confirmation Redirects Posted: 31 Jan 2022 08:00 AM PST I have set up a gravity form with a single line text field. I am using it to check for zip codes and cities. If someone types in the correct zip code it will redirect to a specific page. Also if someone types in a zip code or city and there is no matching value it will also redirect to a certain page. I have tried this code. But I can not seem to get it to work correctly. It works if I have one number but if I add multiple numbers separated by a comma it does not work. Please help if possible. <?php function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) { if ( $form['id'] == '38' ) { if ( $entry['1'] == '89103,80205,91030' ) { $confirmation = array( 'redirect' => 'https://google.com' ); } else if ( $entry['1'] == '90210,89554,90454' ) { $confirmation = array( 'redirect' => 'https://yahoo.com' ); } else if ( $entry['1'] == '56678,89004,78896' ) { $confirmation = array( 'redirect' => 'https://test.com' ); } } return $confirmation; } add_filter( 'gform_confirmation', 'de_gforms_confirmation_dynamic_redirect', 10, 4 ); ?> |
Firebird reading database issue on iis asp.net core 5 Posted: 31 Jan 2022 07:58 AM PST I want to develop a demo project in ASP.NET Core MVC with embedded Firebird v2.5. I read Firebird connection string information from a text file. Because I will change database in project presentation thus I must read from a text file. Or what is the your idea? In this project I create a DbContext file and I fill in the database information using this class: public class DbContext { string startupdirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)+"\\settings.txt"; string dblocation = string.Empty; string userName = string.Empty; string pass = string.Empty; int port = 0; string dataSource = string.Empty; public DbContext() { if (File.Exists(startupdirectory)) { string[] allData = File.ReadAllLines(startupdirectory); dblocation = allData[0].ToString(); userName = allData[1].ToString(); pass = allData[2].ToString(); port = Convert.ToInt32(allData[3].ToString()); dataSource = allData[4].ToString(); } } public string GetConnectionString() { FbConnectionStringBuilder csb = new(); csb.Database = dblocation; csb.DataSource = dataSource; csb.UserID = userName; csb.Password = pass; csb.ServerType = FbServerType.Default; csb.Port = port; //i added below code for embedded db csb.Dialect = 3; csb.Role = ""; csb.ConnectionLifeTime = 15; csb.Pooling = true; csb.MinPoolSize = 0; csb.MaxPoolSize = 50; csb.PacketSize = 8192; return csb.ToString(); } public FbConnection GetConnection() { string connectionString = GetConnectionString(); FbConnection connection = new(); connection.ConnectionString = connectionString; connection.Open(); return connection; } public void KillConnection(FbConnection connection) { connection.Close(); connection.Dispose(); } } When I work locally, everything is fine. I can do all CRUD operations. But when I upload my project, I see this screen: An unhandled exception occurred while processing the request. IscException: I/O error during "CreateFile (open)" operation for file "C:\Firma\BlinePalmeWEB\Mandanten\11PalmeIT\GDI21.FDB" Error while trying to open file FirebirdSql.Data.Client.Managed.GdsConnection.HandleResponseException(IResponse response) FbException: I/O error during "CreateFile (open)" operation for file "C:\Firma\BlinePalmeWEB\Mandanten\11PalmeIT\GDI21.FDB" Error while trying to open file FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect() Stack Query Cookies Headers Routing IscException: I/O error during "CreateFile (open)" operation for file "C:\Firma\BlinePalmeWEB\Mandanten\11PalmeIT\GDI21.FDB" Error while trying to open file FirebirdSql.Data.Client.Managed.GdsConnection.HandleResponseException(IResponse response) FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.ReadResponse() FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.Attach(DatabaseParameterBufferBase dpb, string database, byte[] cryptKey) FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect() Show raw exception details FbException: I/O error during "CreateFile (open)" operation for file "C:\\Firma\\BlinePalmeWEB\\Mandanten\\11PalmeIT\\GDI21.FDB" Error while trying to open file FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect() FirebirdSql.Data.FirebirdClient.FbConnection.Open() GDIWebApplication.Controllers.DbContext.GetConnection() in DbContext.cs GDIWebApplication.Models.Deneme.ProductRepository.GetArtikelList() in ProductRepository.cs GDIWebApplication.Controllers.ProductController.Index(string search) in ProductController.cs lambda_method1(Closure , object , object[] ) Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) Show raw exception details FirebirdSql.Data.FirebirdClient.FbException (0x80004005): I/O error during "CreateFile (open)" operation for file "C:\\Firma\\BlinePalmeWEB\\Mandanten\\11PalmeIT\\GDI21.FDB" Error while trying to open file ---> FirebirdSql.Data.Common.IscException: I/O error during "CreateFile (open)" operation for file "C:\\Firma\\BlinePalmeWEB\\Mandanten\\11PalmeIT\\GDI21.FDB" Error while trying to open file at FirebirdSql.Data.Client.Managed.GdsConnection.HandleResponseException(IResponse response) at FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.ReadResponse() at FirebirdSql.Data.Client.Managed.Version10.GdsDatabase.Attach(DatabaseParameterBufferBase dpb, String database, Byte[] cryptKey) at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect() at FirebirdSql.Data.FirebirdClient.FbConnectionInternal.Connect() at FirebirdSql.Data.FirebirdClient.FbConnection.Open() at GDIWebApplication.Controllers.DbContext.GetConnection() in C:\Users\MD\source\repos\GDIWebApplication\Models\Context\DbContext.cs:line 60 at GDIWebApplication.Models.Deneme.ProductRepository.GetArtikelList() in C:\Users\MD\source\repos\GDIWebApplication\Models\Repositories\ProductRepository.cs:line 20 at GDIWebApplication.Controllers.ProductController.Index(String search) in C:\Users\MD\source\repos\GDIWebApplication\Controllers\ProductController.cs:line 16 at lambda_method1(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) I added all privileges is IIS but I can't make this work - how can I solve this? |
Wrong number of item passed 13, placement implies 1 while pivot using pandas Posted: 31 Jan 2022 07:59 AM PST I am getting the above error if I add 'column' in the pivot table function of pandas. Without 'Column' it works fine. df1 = {'Material Code':['A','B','C','D','E','F','G'], 'Material Desc':['ABC','XYZ','QWE','ERT','MNH','LKJ','HGF'], 'Vendor':['Vendor_1','Vendor_2','Vendor_3','Vendor_4','Vendor_5','Vendor_6','Vendor_7'],'Currency':['INR','INR','INR','INR','USD','USD','USD'],'Months':['JAN','FEB','MAR','JAN','FEB','JAN','APR'], 'GRN Quantity':[100, 200, 500, 400, 100, 100, 500], 'Purchase Price':[10, 15, 20, 45, 45, 12, 15]} index_data = ['Material Code', 'Material Desc', 'Vendor', 'Currency'] column_data = 'Months' pf = pd.pivot_table(data=df1,index=index_data, columns=column_data,values=values_data,aggfunc={"GRN Quantity":np.sum, "Purchase Price":np.sum}, fill_value=0).reset_index() It would be great help, I am struck mid of a project. Thanks You |
How This React Hook i.e useEffect is re-rendering even if the second argument being passed is an empty array Posted: 31 Jan 2022 07:59 AM PST function WindowSizeList() { const [windowWidth, setWindowWidth] = useState(window.innerWidth) const updateWindowWidth = () => { setWindowWidth(window.innerWidth) } useEffect(() => { window.addEventListener('resize', updateWindowWidth) }, []) return ( <> <div>Window Width: {windowWidth}</div> </> ) } This component renders window width when mounted for first time for which useEffect() runs, Ok... then when the browser window is resized the window.addEventListener('resize', updateWindowWidth) runs inside the useEffect() useEffect(() => { window.addEventListener('resize', updateWindowWidth) }, []) and then it triggers const updateWindowWidth = () => { setWindowWidth(window.innerWidth) } for which the component re-renders with the state change of windowWidth and also renders that value in the component, Ok...But when I again resize the browser window, how come the process is repeated i.e useEffect is re-running and then updating the value in DOM even thought it should run once as I have used empty second argument [] in useEffect(() => { window.addEventListener('resize', updateWindowWidth) }, []) |
how to add and remove specific attribute values Posted: 31 Jan 2022 08:00 AM PST In angular it is possible to add and remove class attribute values from an element by specifying a boolean that is bound to a specific variable in the controller: @HostBinding('class.value-1') value1 = true; Is it possible to do the same for other attributes? Similar to below (which does not work) @HostBinding('attr.data-custom.value-1') value1 = true; |
nested for loop issue for subfolders and files makefile Posted: 31 Jan 2022 07:59 AM PST I have a logical issue, trying to do a nested for loop for a fpöder which holds two subfolders with code files in it. for folder in $(twofolders); do \ for file in $$folder; do \ zip -j $$file"_lambda.zip" $(PYTHONPATH)/$$file/*.py; \ aws s3 cp ./$$file"_lambda.zip" s3://$(S3_BUCKET)/$(SOURCE_CODE_VERSION)/lambda/; \ done done But I receive the following error /bin/bash: -c: line 5: syntax error: unexpected end of file make: *** [Makefile:62: build] Error 1 Anyone knows what Iam doing wrong? |
How to make Wordpress plugin Posted: 31 Jan 2022 07:59 AM PST I want to make my first Wordpress plugin. I made perfect work js, css, html and php widget. Now I want to insert it into plugin. I watched some Udemy.com curses but still do not know exactly how to make. Please give me support. First, I want to add scripts function es_scripts() { if (!is_admin()) { wp_register_script('jquery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js'); wp_enqueue_script('jquery'); wp_register_script('jquery.cycle.all', 'https://cdn.datatables.net/1.11.3/js/jquery.dataTables.js'); wp_enqueue_script('jquery.cycle.all'); wp_register_script('jquery.cycssle.all', 'https://cdn.jsdelivr.net/npm/apexcharts'); wp_enqueue_script('jquery.cycssle.all'); wp_register_script('jquery.cycssle.all', 'https://cdnjs.cloudflare.com/ajax/libs/mathjs/10.0.0/math.min.js'); wp_enqueue_script('jquery.cycssle.all'); wp_register_script('jquery.all', 'https://code.jquery.com/jquery-migrate-3.3.2.min.js'); wp_enqueue_script('jquery.all'); } } and here style function es_styles() { if (!is_admin()) { wp_register_style('font_old_standard_tt', 'https://cdn.datatables.net/1.11.3/css/jquery.dataTables.css'); wp_enqueue_style('font_old_standard_tt'); wp_register_style('font_lobster', plugins_url('kalk.css', __FILE__)); wp_enqueue_style('font_lobster'); } } add_action('wp_head', 'es_styles'); and html function html_section(){ echo: '<div>...</div>' } add_shortcode('html_content', 'html_section'); i have a second script function wp_super_first_plugin() { ?> <script> }</script><?php } add_action('wp_footer', 'wp_super_first_plugin'); ?> there is no error, what's making me proud, but first it look ugly because look different then in localhost. Second, javascript do not work at all. Update: Finally I know what is require to change the look. My plugin is container into div which have width: 600px, I tried change its possition to another one using script <script> $(document).ready(){ $('container').appendTo('wp-container-61f7e07100333 entry-content wp-block-post-content'); } </script> which had 1000px but not work; also change params of the first one. Another problem is words are callopse one by one like a s d f I tried it remove by <pre>....</pre> but then the <div> does not appear at all. Update2: Yuap, it was a jQuery conflict. I change all $ to jQuery and start running. But still have issue with appearance of plugin. The main <section> should have at least 1000px but have just 600px because of the parent one. What's more the text is writing collapse like <pre> a b c d </pre> |
Emscripten: How to catch JS exception? Posted: 31 Jan 2022 08:00 AM PST Emscripten 'val.h' API allows calling methods of JS objects, however, C++ try-catch won't catch JS exception. Consider this example: #include <emscripten.h> #include <emscripten/val.h> void test(){ string t = "some invalid json"; val v = val::object(); // This C++ try-catch doesn't catch JS exception try { v = val::global("JSON").call<val>("parse", t); cout <<"ok" <<endl; } catch(...){ cout <<"failed" <<endl; } cout <<"ret" <<endl; } The JS exception makes the 'test' function stop and no ok , no failed , no ret printed out. How to catch that JS exception thrown by JSON.parse ? There's 1 issue here but it's still open: https://github.com/emscripten-core/emscripten/issues/11496 |
TVCardView rounded corners strange behaviour Posted: 31 Jan 2022 07:59 AM PST I'm setting up a new tvOS app with a UISplitViewController and a UICollectionView as a detail view. To achieve some nice out-of-the-box focus behaviour, I'm trying to use TVCardView inside the UICollectionViewCell and adding an image view and a label to the card views content view (in interface builder). That works, but the problem is that the card views always applies rounded corners to the content once they have been selected. Initially all views have sharp corners, but as soon as a cell has been selected, it switches to rounded corners. First of all, I don't even want rounded corners and in Apples examples, I never see those rounded corners anyway: https://developer.apple.com/documentation/tvuikit/tvcardview But even then, it's kind of useless to have rounded corners only partially after selection. Has anyone experience with TVCardView and knows about this strange behaviour? I cannot find any example code or more detailed documentation. I also tried to use TVLockupView instead, but that doesn't seem to be supported by interface builder. |
SQL Cannot get WHERE EXISTS Clause to work properly and only return rows that have a type for a client within a certain date Posted: 31 Jan 2022 07:58 AM PST OK, this is driving me crazy and the solution I am sure will be pretty simple and I will probably bang my head into a wall. I have a query where I have client data. On some queries I ONLY want clients between a certain date that have had a client visit at some point within that date range, which correspond to Call_Report_ID's 3, 8 or 12. For these clients, I want it to bring back ALL data within the date range, not just the rows with this client visit code. For the other clients who DON'T have a client visit, I want to exclude them from the data. Here is what I have been playing around with and cannot get it working at all. SELECT * FROM CV.Data AS CV WHERE EXISTS (SELECT * FROM CV.Data AS CVD WHERE CVD.Call_Report_ID IN(3,8,12) AND CVD.User_ID = 33) AND CV.User_ID = 33 AND CV.Activity_Date BETWEEN '10/1/2018' AND '3/31/2019' So here is an example of What I want: Cust_ID Call_Report_ID Activity_Date 5 3 10/15/2018 5 7 10/28/2018 6 9 10/21/2018 6 11 10/25/2018 In the above when I run this query, I want it to return both rows from Customer 5 since they have a call report ID of 3,8, or 12 in ANY row within the date range, and exclude both rows from Customer 6 since they do not have a call_report_Id with those types in a date range However, every time I run it, it returns all rows for this user, not just the ones specified in the WHERE EXISTS SubQuery. What am I dong wrong here? |
How do I notify VueJS/Vuex of an value change in an array? Posted: 31 Jan 2022 07:59 AM PST when I update a value in an array of the store, the interface doesn't reflect the change. Goal: I'm trying to display a simple minesweeper grid. Once I click on a cell, the object attach to that cell should update isRevealed to true to say is was revealed and Vuejs should add the class dug to that cell. What's working: isRevealed is switched to true. What was working: using only props everything was working, but trying to learn VueJS and including Vuex store the UI doesn't update anymore with the array. Structure: App shows a grid and grid shows multiple cell. store.js for Vuex import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export const store = new Vuex.Store({ state: { GameGrid: [], }, mutations: { revealCell(state, cell) { state.GameGrid[cell.y][cell.x].isRevealed = true; console.log("revealCell ", cell); }, }); GameGrid contain the following: 10 arrays of 10 objects: { isRevealed: false, x: 0, y: 0 ... } grid.vue, nothing special, display every cell <template> <div class="grid"> <div v-for="row in $store.state.GameGrid" class="row"> <app-cell v-for="col in row" :cell="col"></app-cell> </div> </div> </template> cell.vue: <template> <div @click="dig" :class="{dug: cell.isRevealed, dd: cell.debug}"> <span class="text" v-html="cell.display"></span> <span class="small">{{ cell.code }}</span> </div> </template> <script> export default { props: { cell: { type: Object }, }, data: function() { return { display: null, } }, methods: { dig() { this.$store.commit('revealCell', this.cell); }, } </script> Edit accoridng to pirs answer: Grid.vue file <template> <div class="grid"> <div v-for="row in gameGridAlias" class="row"> <app-cell v-for="col in row" :cell="col"></app-cell> </div> </div> </template> <script> import { mapState } from 'vuex'; import Cell from './Cell.vue'; export default { components: { 'app-cell': Cell, }, data: { gameGridAlias: [] }, methods: { }, computed: mapState({ gameGridAlias: state => state.GameGrid }) } </script> Note that I get The "data" option should be a function that returns a per-instance value in component definitions. error since data doesn't return a function. My functions to set isRevealed are on the cell.vue though. I'm still seeing no UI updates (except when I'm saving?). Cells with this.cell.isRevealed = true confirmed with console.log but no change in classes. Here is how I'm populating GameGrid This function is calling when the user press a button on the hmm, home page? App.vue file. generateGrid() { console.log("generateGrid"); //Generate empty play grid for(let y = 0; y < this.$store.state.GameGridHeight; y++) { this.$store.state.GameGrid[y] = new Array(); for(let x = 0; x < this.$store.state.GameGridWidth; x++) { this.$store.state.GameGrid[y][x] = { content: 'Empty', code: 0, isRevealed: false, x: x, y: y, debug: false, }; } } }, //End generateGrid |
Simpler way of sorting three numbers Posted: 31 Jan 2022 07:58 AM PST Is there a simpler and better way to solve this problem because - I used too many variables.
- I used so many
if else statements - I did this using the brute force method
Write a program that receives three integers as input and outputs the numbers in increasing order. Do not use loop / array. #include <stdio.h> main(){ int no1; int no2; int no3; int sto; int hi; int lo; printf("Enter No. 1: "); scanf("%d", &no1); printf("Enter No. 2: "); scanf("%d", &no2); printf("Enter No. 3: "); scanf("%d", &no3); if (no1>no2) { sto=no1; lo=no2; } else { sto=no2; lo=no1; } if (sto>no3) { hi=sto; if(lo>no3){ sto=lo; lo=no3; }else { sto=no3; } }else hi=no3; printf("LOWEST %d\n", lo); printf("MIDDLE %d\n", sto); printf("HIGHEST %d\n", hi); getch(); } |