Cleanest way to wrap a static class in a non-static object (refactoring to allow mocking) Posted: 02 Nov 2021 08:16 AM PDT I'm working with Java and Kotlin, and the codebase has some legacy static classes which really should be objects, but are too deeply tangled to make them non-static now. I want to be able to cleanly test (using mocks of these static dependencies) some (non-static) classes that depend on these static classes, so I want to wrap the static classes in non-static dummy wrappers, i.e. instantiatable objects whose instance methods just call their static counterparts. I'll then mock these wrappers in unit tests (I don't want to just use static mocking). The manual way to do this is for each static class Foo with method public static void bar() , define a new class FooWrapper with method public void bar() that just calls Foo.bar() , instantiate a FooWrapper at the top of my class, and switch all the current calls to Foo.bar() to instead call fooWrapperInstance.bar() . The above works fine but involves a lot of boring Wrapper classes that do nothing but pass calls. Is there some syntactic sugar (either Java or Kotlin is fine, but it has to work with Java) that will create, or at least shorten, these wrapper classes for me? I'm familiar with Guava's ForwardingObject but it seems to only work when the underlying logic is in an instance already, which mine is not. |
displaing one array multiple times in react Posted: 02 Nov 2021 08:16 AM PDT when i sent message i want it to display . but now its displaying same message multiple time like 4/5 times . const [messages, setMessages] = useState([]); socket.on(room, (msg) => { setMessages(message=>[...message, msg]); }); return ( <div style={{ "paddingTop": "10px", "backgroundColor": "rgb(85, 85, 85)" }} className="chat-messages"> { messages ? messages.map((message,index) => ( <div className="message " key={index}> <p className="meta"> {message.user} <span> {message.time} </span> <span></span></p> <p className="text" style={{ "maxWidth": "80ch", "overflowWrap": "break-word" }}> {message.msg} </p> </div> )) : '' } </div> ) |
RecyclerView inside a fragment in android studio crashing my app Posted: 02 Nov 2021 08:16 AM PDT My App is crashing whenever I try to put a recyclerView inside a fragment. I can't figure out what is going on. I tried using a button to replace the layout in Fragment. App was starting fine but whenever I click the button the App Crashes MainActivity: public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView=findViewById(R.id.recyclerView); FrameLayout frameLayout = new FrameLayout(this); frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)); frameLayout.setId(R.id.layout); setContentView(frameLayout); getSupportFragmentManager().beginTransaction().add(R.id.layout,new Fragment1()).commit(); } } fragment class: public class Fragment1 extends Fragment { String[] Text={"he","hdhd","hdhdhdh","dhlsd","hshdsss","he","hdhd"}; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = LayoutInflater.from(getContext()).inflate(R.layout.rows,container,false); RecyclerView recyclerView = view.findViewById(R.id.RecyclerView2); ImrulsAdapter Adapter = new ImrulsAdapter(getContext(),Text); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setAdapter(Adapter); return view; } } Custom Adapter Class: public class ImrulsAdapter extends RecyclerView.Adapter<ImrulsAdapter.ImrulsViewHolder> { String[]Text; Context context; public ImrulsAdapter(Context context, String[] text ) { Text = text; this.context = context; } @NonNull @Override public ImrulsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.rows,parent,false); return new ImrulsViewHolder(view); } @Override public void onBindViewHolder(@NonNull ImrulsViewHolder holder, int position) { holder.textView.setText(Text[position]); } @Override public int getItemCount() { return Text.length; } public class ImrulsViewHolder extends RecyclerView.ViewHolder{ TextView textView; public ImrulsViewHolder(@NonNull View itemView) { super(itemView); textView= itemView.findViewById(R.id.textView); } } } activity_main xml: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:id="@+id/Constraint_Layout"> <androidx.recyclerview.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" android:id="@+id/recyclerView"/> </androidx.constraintlayout.widget.ConstraintLayout> Fragment xml: <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:layout_width = "match_parent" android:layout_height="wrap_content" android:id="@+id/RecyclerView2"> </androidx.recyclerview.widget.RecyclerView> </FrameLayout> Adapter Rows xml: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content"> <androidx.cardview.widget.CardView android:id="@+id/cardView" android:layout_width="409dp" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" style="@style/Widget.AppCompat.TextView.SpinnerItem" android:layout_width="407dp" android:layout_height="100dp" android:text="TextView" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.cardview.widget.CardView> </androidx.constraintlayout.widget.ConstraintLayout> Android Manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.recyclerviewinsideafragment"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:largeHeap="true" android:hardwareAccelerated="false" android:theme="@style/Theme.RecyclerViewInsideAFragment"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Dependencies: plugins { id 'com.android.application' } android { compileSdk 31 defaultConfig { applicationId "com.example.recyclerviewinsideafragment" minSdk 21 targetSdk 31 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'androidx.appcompat:appcompat:1.3.1' implementation 'com.google.android.material:material:1.4.0' implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.recyclerview:recyclerview:1.3.0-alpha01' implementation 'androidx.constraintlayout:constraintlayout:2.1.1' implementation 'androidx.fragment:fragment:1.3.6' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' } |
My last array overwrites all my previous arrays, how do I fix this? Posted: 02 Nov 2021 08:16 AM PDT All my output is fine individually but the moment it gets to the last two lines inactiveResultsOnce and inactiveResultsRecurring all my previous arrays gets overwritten. How do I fix this issue so when it iterates over paymentsResultsOnce it saves the data then goes to the next... and so on. function getCatType(order) { switch (order.type) { case "Invoice": case "One-time": case "One-Time": case "Free": case "Single Sessions": case "Semester": return "Once"; case "Recurring": case order.justDeposit === true: return "Recurring"; default: return null; } } // This is for the payments section function typeOfPayment(type) { return paymentsResults.filter(order => { return getCatType(order) === type; }); } const paymentsResultsOnce = typeOfPayment("Once"); const paymentsResultsRecurring = typeOfPayment("Recurring"); // This is for the pending section function typeOfPayment(type) { return pendingResults.filter(order => { return getCatType(order) === type; }); } const pendingResultsOnce = typeOfPayment("Once"); const pendingResultsRecurring = typeOfPayment("Recurring"); // This is for the inactive section function typeOfPayment(type) { return inactive.filter(order => { return getCatType(order) === type; }); } const inactiveResultsOnce = typeOfPayment("Once"); const inactiveResultsRecurring = typeOfPayment("Recurring"); |
How to obtain "jagged" edges on silhouette images? Posted: 02 Nov 2021 08:15 AM PDT I am trying to replicate a paper in which silhouette images are transformed in order to have jagged edge: Unfortunately, the paper doesn't provide any detail about how these were generated. Do you guys have any idea how could I go around it? Doesn't need to be exactly the same, the important bit is to mess up with the local features of each object. Ideally I would like to do it in python with OpenCV/PIL/PyTorch, but anything is ok really. Thanks. |
How to rearrange pandas data frame Posted: 02 Nov 2021 08:15 AM PDT TestJob1|29.10.2021 21:25:06 program TestProgram1 job TestJob1 SUV [Toolname: Sky;, oops: 8;, ill/Cut: ill] C2 [Toolname: T04;, oops: 9;, ill/Cut: ill] TestJob2|29.10.2021 21:25:07 program TestProgram2 job TestJob2 SUV [Toolname: Sky;, oops: 8;, ill/Cut: ill] C2 [Toolname: T04_5;, oops: 9;, ill/Cut: ill] This is currently what my DF looks like Im trying to get it to look like: Job | Program | SUV/C2 | Stools | TestJob1 | TestProgram1 | SUV | Toolname: Sky | | | | oops: 8 | | | | ill/Cut: ill | | | C2 | Toolname: T04_5 | | | | oops: 9 | | | | ill/Cut: ill | TestJob2 | TestProgram2 | SUV | Toolname: Sky | | | | oops: 8 | | | | ill/Cut: ill | | | C2 | Toolname: T04_5 | | | | oops: 9 | | | | ill/Cut: ill | This is what ive got for code so far. this is usually a long txt file. ive shortend for this post. some times the "SUV" ad "C2" list are much longer. Thank you fir your help` from collections import defaultdict import pandas as pd import re job_dictionary = defaultdict(list) job_dictionary = {} with open('txt_file') as my_file: for line in my_file: line = line.strip("# \n") # clean up whitespace and # for lines if not line: # skip empty lines continue startstring = "Start Job" if startstring in line: nm = line.split('-- ')[0] result = re.search('-- (.*)_AV1_', line) job = result.group(1).split('_')[0]+'|'+nm program = result.group(1) job_dictionary[job] = {} job_dictionary[job]['program'] = program job_dictionary[job]['job'] = result.group(1).split('_')[0] continue startstring = ": " if startstring in line: job_dictionary[job][ltype].append(line) continue startstring = "C2" if startstring in line: ltype = startstring job_dictionary[job][ltype] = [] continue startstring = "SUV" if startstring in line: ltype = startstring job_dictionary[job][ltype] = [] continue # print(job_dictionary) startstring = "Z-Value =" if startstring in line: continue startstring = "SCALEX" if startstring in line: continue startstring = "End Job:" if startstring in line: continue df = pd.concat({k: pd.Series(v) for k, v in job_dictionary.items()}) print(df) |
Batch File - Colored text only works outside of if Posted: 02 Nov 2021 08:15 AM PDT i have a problem. In this code: for %%n in (%listPath%) do ( echo Starting Build echo. devenv %%n /build Debug if ERRORLEVEL 1 ( echo [101;93m ERROR: Error Build Project: %%n [0m pause > nul exit /b ) ) Why the line echo [101;93m ERROR: Error Build Project: %%n [0m works only outside the if statement? I want to display a red error inside the if. Thanks |
scene is gray color and skybox disappear on unity game engine Posted: 02 Nov 2021 08:15 AM PDT In my project scenen window look like gray or black, but game window is normal! Please help me! Thank you! ps:The same as create new project! |
Downloading s3 bucket to local directory but files not copying? Posted: 02 Nov 2021 08:15 AM PDT There are many, many examples of how to download a directory of files from an s3 bucket to a local directory. aws s3 cp s3://<bucket>/<directory> /<path>/<to>/<local>/ --recursive However, I run this command from my AWS CLI that I've connected to and see confirmation in the terminal like: download: s3://mybucket/myfolder/data1.json to /my/local/dir/data1.json download: s3://mybucket/myfolder/data2.json to /my/local/dir/data2.json download: s3://mybucket/myfolder/data3.json to /my/local/dir/data3.json ... But then I check /my/local/dir for the files, and my directory is empty. I've tried using the sync command instead, I've tried copying just a single file - nothing seems to work right now. In the past I did successfully run this command and downloaded the files as expected. Why are my files not being copied now, despite seeing no errors? |
Why is UnityWebRequest so slow in Unity 2020.3.19f1 Posted: 02 Nov 2021 08:16 AM PDT I just upgraded my project from Unity 2017 to 2020.3.19f1 version, however I found that our UnityWebRequest response time became so long. Here is my test using UnityWebRequest to Get www.yahoo.com in an empty project within Unity 2017 and 2020.3.19. Does anyone also encounter this problem ? Here is Picture of response time showing difference between the two versions. |
IF ELSE, datetime.strptime Posted: 02 Nov 2021 08:16 AM PDT I am working with the below function def convStr2Date(given): if type(given) != str: return given pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|.*)' rv = re.search(pattern, given).group(1) if rv: return datetime.strptime(rv, '%Y-%m-%d %H:%M:%S') which gives me the error ValueError: time data '2021-10-01' does not match format '%Y-%m-%d %H:%M:%S So I added an else: statement, but still getting the same error, where am I going wrong? Trying: def convStr2Date(given): if type(given) != str: return given pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|.*)' rv = re.search(pattern, given).group(1) if rv: return datetime.strptime(rv, '%Y-%m-%d %H:%M:%S') else: return datetime.strptime(rv, '%Y-%m-%d') |
in batch script compare extension with file extension and move Posted: 02 Nov 2021 08:16 AM PDT How to write a batch script according to the following instructions: - Take only folder name as input.
- List all the files in that folder.
- Loop through each file, and extract its extension.
- Check if a directory exists with that extension, if not, create it.
- Move the file to its respective extension named folder.
This is what I tried: @echo off set /p folder= please enter folder name: :: dir %folder% for %%a in (%folder%\*.*) do echo %%a set /p extension=enter extension: if exist %folder%\*.%extension% goto create :create set /p dir=enter directory: mkdir %dir% move %folder%\*.%extension% %dir% if notexist %folder%\*.%extension% echo not exist pause |
how to Search for duplicates in list (javascript)? Posted: 02 Nov 2021 08:16 AM PDT I try to look for duplicates in the array and get an error, and I glad for any solution for this problem Attached is code: let names = itemList[0].getElementsByTagName("span")[0].innerText; for (i = 1; i < itemList.length; i++) { if (!(itemList[i].getElementsByTagName("span")[0].innerText in names)) { names.push(itemList[i].getElementsByTagName("span")[0].innerText); } } |
How to split a date column into day/month/year columns using python Posted: 02 Nov 2021 08:15 AM PDT I have a csv file with just one column 'date' formatted as integer: date | 20181231 | 20190107 | 20210329 | ... | The solution would be to split the integer into different columns to represent day, month, year and quarter, like: date | day | month | year | quarter | 20181231 | 31 | 12 | 2018 | 4 | 20190107 | 07 | 01 | 2019 | 1 | 20210329 | 29 | 03 | 2021 | 2 | ... | ... | ... | ... | ... | I would appreciate every kind of solution but I should resolve it using a python program without using pandas library. So I write something like this: ''' import csv reader = csv.reader(open('date.csv', 'r')) writer = csv.writer(open('datesplit.csv', 'w')) for line in reader: year = line[0][:3] month = line[0][4:5] day = line[0][6:] ''' Thanks for helping |
How to edit each line of file and write to file after each edit Posted: 02 Nov 2021 08:16 AM PDT I have a file that is very large. I need to rearrange something in the file but the file is too large to load into memory. I was thinking of ways to achieve this goal and what I came up with was just editing the file line by line. So what I need to do is read the file, remove certain columns, and then write the file. As I mentioned before, the file is very large so I need to write the file as the script runs. I will give an example data set and the code that I am using Here is an example dataset {'CHROM': {0: 'chr1', 1: 'chr1'}, 'POS': {0: 10397, 1: 12719}, 'ID': {0: '.', 1: '.'}, 'REF': {0: 'CCCCTAA', 1: 'G'}, 'ALT': {0: 'C', 1: 'C'}, 'QUAL': {0: 943.64, 1: 255.34}, 'FILTER': {0: 'VQSRTrancheINDEL99.00to100.00', 1: 'VQSRTrancheSNP99.80to100.00'}, 'INFO': {0: 'AC=1;AF=0.5;AN=2;BaseQRankSum=1.07;ClippingRankSum=-0.322;DP=11;ExcessHet=0.2139;FS=1.056;InbreedingCoeff=0.1828;MQ=27.81;MQ0=0;MQRankSum=1.59;NEGATIVE_TRAIN_SITE;QD=25.5;ReadPosRankSum=0.572;SOR=0.922;VQSLOD=-2.735;culprit=DP', 1: 'AC=1;AF=0.5;AN=2;BaseQRankSum=-0.922;ClippingRankSum=-0.198;DP=7;ExcessHet=0.0067;FS=0;InbreedingCoeff=0.4331;MQ=24.5;MQ0=0;MQRankSum=-1.495;QD=17.02;ReadPosRankSum=1.5;SOR=3.126;VQSLOD=-28.96;culprit=MQ'}, 'FORMAT': {0: 'GT:AD:DP:GQ:PL', 1: 'GT:AB:AD:DP:GQ:PL'}, 'CGND-HDA-03201': {0: '0/1:5,6:11:99:224,0,156', 1: '0/1:0.29:2,5:7:42:126,0,42'}, 'CGND-HDA-03202': {0: '0/1:5,6:11:99:224,0,156', 1: '0/1:0.29:2,5:7:42:126,0,42'}} Here is the code that I am using n = 0 for line in open(input, "r+"): li=line.strip() if li.startswith("#"): n = n+1 if not li.startswith("#"): test = li.split("\t") test2 = (f"{test[0]}\t{test[1]}\t{test[9:]}") with open("output.txt","w") as out: out.write(test2, sep='\t') I have a few problems here the output contain on one single line, the last line that was read. For example, the file contains one line like this chr1 1021791 ['0/1:0.56:22,17:39:99:414,0,623', '0/1:0.56:22,17:39:99:414,0,623'] I don't want the output to have any bracket. I need the output to look more like this chr1 1021791 0/1:0.56:22,17:39:99:414,0,623 0/1:0.56:22,17:39:99:414,0,623 I need the ouput file to be tab delimited Is there a way I can continuously write to a file after each line is edited? The original file does contain # 's that I didn't show here, so the part of the script that ignores lines with # 's is required I know this can easily be done using bash but I am looking for a solution using python. |
Failed call to cuInit: CUDA_ERROR_NOT_INITIALIZED: initialization error Posted: 02 Nov 2021 08:16 AM PDT I am trying to run tensorflow with gpu support in a docker on a virtual machine. I have tried lots of online solutions including: none of the solutions work for me, here some steps: I verified that drivers and cuda and cudnn toolkit are installed inside the container using nvidia-smi and nvcc -V: Python version is : Python 3.8.10 and tensorflow version is: import tensorflow as tf tf.__version__ '2.6.0' The error appears with: tf.config.list_physical_devices() So the GPU is somehow not visible to the tensorflow. All tensorflow builds return the same error: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NOT_INITIALIZED: initialization error but for example for 1.14 there is an additional comment regarding the CPU type: Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 AVX512F FMA The GPU is a A100 and the CPU is Intel(R) Xeon(R) Gold 6226R. What is going on here? How do I fix this? |
Sql order by string and int Posted: 02 Nov 2021 08:15 AM PDT I have table with column days, this days value is like this: day 1 day 2 day 3 day 4 ... day n In my database these row are not ordered, so i want to retrieve it ordered by the int after the string: example i have day 2 day 4 day 1 day 3 => to got day 1 day 2 day 3 day 4 Changing column type and value is the best option but i want to work with this structure if there is an option to retrieve it. |
Shift with dynamic n (number of position lead / lag by) Posted: 02 Nov 2021 08:16 AM PDT I have the below df: df <- data.table(user = c('a', 'a', 'a', 'b', 'b') , spend = 1:5 , shift_by = c(1,1,2,1,1) ); df user spend shift_by 1: a 1 1 2: a 2 1 3: a 3 2 4: b 4 1 5: b 5 1 and am looking to create a lead lag column only this time the n parameter in data.table 's shift function is dynamic and takes df$shiftby as input. My expected result is: df[, spend_shifted := c(NA, 1, 1, NA, 4)]; df user spend shift_by spend_shifted 1: a 1 1 NA 2: a 2 1 1 3: a 3 2 1 4: b 4 1 NA 5: b 5 1 4 However, with the below attempt it gives: df[, spend_shifted := shift(x=spend, n=shift_by, type="lag"), x]; df user spend shift_by spend_shifted 1: a 1 1 NA 2: a 2 1 NA 3: a 3 2 NA 4: b 4 1 NA 5: b 5 1 NA This is the closest example I could find. However, I need a group by and am after a data.table solution because of speed. Truly look forward to finding any ideas. Thank you |
Can someone tell why this code doesn't work Posted: 02 Nov 2021 08:16 AM PDT I'm trying to open and read csv file When I try to do this the window inserted in this question displays this. How can I fix this or what am I doing wrong? I have tried muiltple things and cannot figure out what I am doing wrong. I am doing this in devc++ and am looking for answers at this point The output should be: Starting time Fri Aug 06 13:06:40 2010 Ending time Thu Apr 10 13:09:09 2014 Temperature Sensor 1 Average: -459.7ºF Temperature Sensor 2 Average: 440.3ºF Temperature Sensor 3 Average: 77.2ºF This is the file I opened: Test File #1 35 lines inc. header 1281100000,0,2047,1221 1281200000,0,2047,1221 1321300000,0,2047,1221 1331400000,0,2047,1221 1341703600,0,2047,1221 1351707899,0,2047,1221 1361703600,0,2047,1221 1371200000,0,2047,1221 1371300000,0,2047,1221 1387400000,0,2047,1221 1387703600,0,2047,1221 1388707899,0,2047,1221 1389703600,0,2047,1221 1390200000,0,2047,1221 1390300000,0,2047,1221 1390400000,0,2047,1221 1390703600,0,2047,1221 1390707899,0,2047,1221 1391703600,0,2047,1221 1392200000,0,2047,1221 1392300000,0,2047,1221 1392400000,0,2047,1221 1392703600,0,2047,1221 1392707899,0,2047,1221 1393703600,0,2047,1221 1394200000,0,2047,1221 1394300000,0,2047,1221 1394400000,0,2047,1221 1394703600,0,2047,1221 1394707899,0,2047,1221 1395703600,0,2047,1221 1395713600,0,2047,1221 1396707899,0,2047,1221 1397135349,0,2047,1221 #include <stdio.h> #include <windows.h> #include <string.h> #include <stdlib.h> #include <time.h> // For Red, Blue And Yellow Color #define RED "\x1B[31m" #define BLU "\x1B[34m" #define YEL "\x1B[33m" // Color Reset #define RESET "\033[0m" // Print Long Date In Human Readable Format void printDate(unsigned long date) { time_t seconds = date; struct tm* tm = localtime(&date); char months[][4] = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" }; // Print Fomatted Date printf("%02d-%s-%d %02d:%02d:%02d", tm->tm_mday, months[tm->tm_mon], tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec); } // Convert Reading To Fahrenheight double readingToFahrenheit(double reading) { double mv = ((reading / 2047) * 5000); double kelvin = mv / 10; return (kelvin - 273.15) * (9.0/5.0) + 32; } // Print Colored Temperature Output void printColoredOutput(double temp) { if (temp < 50.0) { printf("%s%.2f F%s", BLU, temp, RESET); } else if (temp > 90.0) { printf("%s%.2f F%s", RED, temp, RESET); } else { printf("%s%.2f F%s", YEL, temp, RESET); } } // Main int main(void) { char filePath[256]; // Read File Name From The User printf("Enter The File Path: "); fgets(filePath, sizeof(filePath) - 1, stdin); // Remove New Line From The End Of File Path filePath[strlen(filePath) - 1] = '\0'; FILE * fp; fp = fopen(filePath, "r"); if (fp == NULL) { printf("Error: %s Cannot Be Opened!\n", filePath); return -1; } else { // Process File unsigned long date; int temp1, temp2, temp3; int lineCount = 0; double sumTemp1, sumTemp2, sumTemp3; // First Line if ((fscanf(fp, "%lu,%d,%d,%d", &date, &temp1, &temp2, &temp3)) == 4) { printf("Starting Time: "); printDate(date); sumTemp1 = temp1; sumTemp2 = temp2; sumTemp3 = temp3; lineCount++; } // Rest Of The Lines while ((fscanf(fp, "%lu,%d,%d,%d", &date, &temp1, &temp2, &temp3)) == 4) { sumTemp1 += temp1; sumTemp2 += temp2; sumTemp3 += temp3; lineCount++; } // Display Result printf("\nEnding Time: "); printDate(date); // Compute Average double temp1Avg = sumTemp1 / lineCount; double temp2Avg = sumTemp2 / lineCount; double temp3Avg = sumTemp3 / lineCount; // Print Average printf("\nTemperature Sensor 1 Average: "); printColoredOutput(readingToFahrenheit(temp1Avg)); printf("\nTemperature Sensor 2 Average: "); printColoredOutput(readingToFahrenheit(temp2Avg)); printf("\nTemperature Sensor 3 Average: "); printColoredOutput(readingToFahrenheit(temp3Avg)); printf("\n"); } return 0; } the window when I try to run the program |
Helm dependency range failure Posted: 02 Nov 2021 08:16 AM PDT Take an umbrella chart, umbrella_chart, with one subchart, sub_chart: umbrella_chart has dependencies defined as follows in it's Chart.yaml: apiVersion: v2 name: umbrella_chart description: A Helm chart for Kubernetes type: application version: 0.1.0 appVersion: 0.1.0 dependencies: - name: sub_chart version: "~0.1.0" repository: "@local-development" And sub_chart has a Chart.yaml like: apiVersion: v2 name: sub_chart description: A Helm chart for Kubernetes type: application version: 0.1.0 maintainers: - name: Me appVersion: 0.1.0 As part of my CI/CD pipeline, I want to append the Jenkins build number to the sub_chart's version number, before packaging and pushing. This works fine. For build 123 I end up with a version of 0.1.0-123 pushed to local-development. helm search repo --versions --devel NAME CHART VERSION APP VERSION DESCRIPTION local-development/sub_chart 0.1.0-123 0.1.0 A Helm chart for Kubernetes However, when I run helm dep up umbrella_chart I get the following error: Hang tight while we grab the latest from your chart repositories... ...Successfully got an update from the "local-development" chart repository Update Complete. ⎈Happy Helming!⎈ Error: can't get a valid version for repositories sub_chart. Try changing the version constraint in Chart.yaml I thought the use of the tilde would allow helm take any chart version >0.1.0 and <0.2.0? Do I need to have a version 0.1.0 of sub_chart in my repo to be able to build umbrella_chart? Will it use the correct 0.1.0-123 version of sub_chart in that instance? Thanks for any help |
How to determine the port on which a Windows service is listening? Posted: 02 Nov 2021 08:15 AM PDT I have running a Windows service called my-service . The only input that I know is the service name. I can get the process identifier by using the service name: $id = Get-WmiObject -Class Win32_Service -Filter "name='my-service'" | Select-Object -ExpandProperty ProcessId To get a list of Listening ports, I can use netstat , but all my custom services have PID 4 which is not equal to the service process identifier of Get-WmiObject cmdlet. The goal is to get the port on which the service is listening by using PowerShell or CMD based on the service name or the process identifier and NOT by the image name. |
Make string operations on field in mongodb collection (Aggregation & regex) Posted: 02 Nov 2021 08:15 AM PDT I am using a collection in Mongo with a price field with multiple money type : { price: '15 gp' // 15 gold pieces } or { price: '4 sp' // 0.4 gold pieces } I'm looking for a way to modify this field before querying the collection. For example doing string modifications to remove the gp/sp and doing math operations to have a correct price in "GP" (1 GP = 10 SP) This would help ordering the collection since mongo can't understand that 10 sp < 2 gp. Is there a way to use Aggregation and regex to do it ? |
PostgreSQL SELECT based on value in JSON object Posted: 02 Nov 2021 08:15 AM PDT I would like to query a table, orders , anad select all rows based on a value in a json object in a column, updates . I want to select all rows that are within 5 days from the last time it was closed. It is a PostgreSQL 12 database. [ { "time": { "__type": "Date", "iso": "2021-09-16T09:31:57.976Z" }, "userId": "xKn5A1GuLV", "to": "created", "role": "admin" }, { "time": { "__type": "Date", "iso": "2021-09-16T09:31:57.976Z" }, "userId": "xKn5A1GuLV", "to": "opened", "role": "admin", "from": "created" }, { "time": { "__type": "Date", "iso": "2021-10-12T12:10:44.688Z" }, "userId": "Hd37AyKJsN", "to": "closed", "role": "admin", "from": "opened" }, { "time": { "__type": "Date", "iso": "2021-10-12T12:10:54.224Z" }, "userId": "Hd37AyKJsN", "to": "opened", "role": "admin", "from": "closed" }, { "time": { "__type": "Date", "iso": "2021-10-12T12:40:58.476Z" }, "userId": "Hd37AyKJsN", "to": "closed", "role": "admin", "from": "opened" } ] |
Using CSVhelper to update a single column into a previously written CSV file . I have the code in Java but can't translate it into C# Posted: 02 Nov 2021 08:15 AM PDT Essentially I have to read and update the CSVfile (only one column) with the current date after the test finishes executing(ie,there are some values written in at the start of the test execution and then I need to update the same file to input another value). I also have a DateTime error which isn't getting resolved no matter what I try. Sample of CSV start of test RunId ProductArea Product Component PageObject Control TimeTakenByLocatorJson Run_645987 R201 BN2018.5 N778 BC1 C143 CSV one column Needs to get updated after test ( TimeTakenByLocatorJson) RunId ProductArea Product Component PageObject Control TimeTakenByLocatorJson Run_645987 R201 BN2018.5 N778 BC1 C143 2021-07-19 I've been trying to update a CSV file using CSVhelper. The code I have is in Java and when I tried translating the same code in C# it doesn't work. This is the code in Java public synchronized void writeEndCSV(String runId) { CSVWriter csvWriter = null; try { String setupCSVLocation = Reporting.getSetupCSVLocation(); CSVReader csvReader = new CSVReader(new FileReader(setupCSVLocation)); List<String[]> records = csvReader.readAll(); for(int i=0;i<records.size();i++) { if(records.get(i)[SETUP_RUNID].equalsIgnoreCase(runId)); { records.get(i)[SETUP_TimeTakenByLocatorJSON] = Reporting.getExecutionEndDate(); } } csvReader.close(); csvWriter = new CSVWriter(new FileWriter(setupCSVLocation)); csvWriter.writeAll(records); csvWriter.flush(); csvWriter.close(); } catch (Exception e) { e.printStackTrace(); } } This is my code in C# (I'm new to .Net so I'm not sure about many parts) public void writeEnd(string runId) { var records = Enumerable.Empty<LocatorTime>(); try { var config = new CsvConfiguration(CultureInfo.InvariantCulture) { // Don't write the header again. HasHeaderRecord = false, }; using (var reader = new StreamReader(@"D:\Reports\" + runId + @"\LocatorTime.csv")) using (var csv = new CsvReader(reader, config)) { //csv.Context.RegisterClassMap<LocatorTime>(); records = csv.GetRecords<LocatorTime>().ToList(); foreach (var record in records) { if (record.RunID == runId) { record.TimeTakenByLocatorJSON = DateTime.Now; } // Console.WriteLine("inside loop"); } }//Endof Stream Reader using (var stream = File.Open(@"D:\Reports\" + runId + @"\LocatorTime.csv", FileMode.Append)) //not sure what the file mode should be using (var writer = new StreamWriter(stream)) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(records); } } catch (Exception e) { Console.WriteLine(e); } }//end func writeEnd This is the class used for the csv file & are also the column names in the csvfile public class LocatorTime { public string RunID { get; set; } public string ProductArea { get; set; } public string Product { get; set; } public string Component { get; set; } public string PageObject { get; set; } public string Control { get; set; } public DateTime TimeTakenByLocatorJSON //only this value needs to be written for update at end of exec { get; set; }/*error because of DateTime datatype how to resolve?*/ }//LocatorTimeClass /*public void SetExeDate() //tried this for removing DateTime error, didn't work { DateTime today = DateTime.Today; // As DateTime string s_today = today.ToString("yyyy-MM-dd"); // As String //TimeTakenByLocatorJSON = s_today.Trim(); TimeTakenByLocatorJSON = Convert.ToDateTime(s_today);} */ public sealed class LocatorTimeMap : ClassMap<LocatorTime> //is mapping helpful for updating? currently commented out { public LocatorTimeMap() { Map(m => m.RunID).Index(0); Map(m => m.ProductArea).Index(1); Map(m => m.Product).Index(2); Map(m => m.Component).Index(3); Map(m => m.PageObject).Index(4); Map(m => m.Control).Index(5); Map(m => m.TimeTakenByLocatorJSON).Index(6); //error } } I had used the below link as reference for trying to update the CSV file hence the use of "HasHeaderRecord = false" https://joshclose.github.io/CsvHelper/examples/writing/appending-to-an-existing-file/ |
Social Login doesn't work in Android browser app Posted: 02 Nov 2021 08:15 AM PDT |
Non destructive modify hash table Posted: 02 Nov 2021 08:16 AM PDT Is it possible to non-destructively add new key-value pairs to a Common Lisp (SBCL) hash table? The standard way to add new elements to a hash table is to call: (setf (gethash key *hash-table*) value) but the call to setf modifies *hash-table* corrupting the original. I have an application where I'd like to take advantage of the efficiency of hash table lookups, but I also would like to non destructively modify them. The work-around I see is to copy the original hash table before operating on it, but that is not practical in my case since the hash tables I'm dealing with contain many thousands of elements and copying large hash tables, say, in a loop would negate the computational efficiency advantage of using them in the first place. |
RecyclerView in ViewPager won't Scroll Posted: 02 Nov 2021 08:16 AM PDT In my app I have my main page, in it a ViewPager. I can navigate between fragments in the ViewPager using a drawerLayout. One of the fragments is a RecyclerView (in a FrameLayout). The problem is I cannot scroll the RecyclerView. I've asked a question of the sort before, and got the solution, only it was a ScrollView instead of RecyclerView, and the ViewPager was in a ConstraintLayout, and now it has to be in a RelativeLayout so the drawerLayout could exist. code of the layouts: activity_main.xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/mainScreenContainer" android:layout_width="match_parent" android:layout_height="match_parent" android:background="?attr/colorPrimary" tools:context=".MainActivity"> <include android:id="@+id/mainToolbar" layout="@layout/main_toolbar_layout" /> <com.google.android.material.tabs.TabLayout android:id="@+id/mainTabLayout" android:layout_width="0dp" android:layout_height="0dp" android:visibility="gone"> <com.google.android.material.tabs.TabItem android:id="@+id/main" android:layout_width="match_parent" android:layout_height="0dp" /> <com.google.android.material.tabs.TabItem android:id="@+id/activeGoals" android:layout_width="match_parent" android:layout_height="0dp" /> <com.google.android.material.tabs.TabItem android:id="@+id/achievedGoals" android:layout_width="match_parent" android:layout_height="0dp" /> <com.google.android.material.tabs.TabItem android:id="@+id/stats" android:layout_width="match_parent" android:layout_height="0dp" /> <com.google.android.material.tabs.TabItem android:id="@+id/tipsAndTricks" android:layout_width="match_parent" android:layout_height="0dp" /> <com.google.android.material.tabs.TabItem android:id="@+id/aboutUs" android:layout_width="match_parent" android:layout_height="0dp" /> </com.google.android.material.tabs.TabLayout> <androidx.viewpager.widget.ViewPager android:id="@+id/mainViewPager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_alignParentBottom="true" android:layout_below="@id/mainToolbar"/> <androidx.drawerlayout.widget.DrawerLayout android:id="@+id/drawerLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:layout_below="@id/mainToolbar"> <com.google.android.material.navigation.NavigationView android:id="@+id/list_nav_drawer" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:menu="@menu/menu_items" /> </androidx.drawerlayout.widget.DrawerLayout> </RelativeLayout> fragment_active_goals.xml: <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true" tools:context=".ActiveGoals"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/activeGoalsRecyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> I'd want the RecyclerView to be scrollable. thanks in advance (: |
manifest.json vs manifest.webmanifest Posted: 02 Nov 2021 08:16 AM PDT I'm developing an application using mongodb, Node.JS and PWA. In the first step of developing I don't know what is the difference between manifest.json and manifest.webmanifest . |
Object returning NaN when sum values Posted: 02 Nov 2021 08:17 AM PDT I'll admit I'm weak in JavaScript and JSON. I've spent a lot of time attempting to figure out why numbers from my objects returns NaN when they are added together. With that in mind, below is my JSON, stored to a variable: var data = [ { "acc_ext_id": null, "cat_code": 10002, "cat_ds": "REVENUE", "category_id": null, "chart_id": null, "created_at": null, "dept_id": null, "feb": null, "id": null, "jan": 30, "note": null, "total_cost": null, "updated_at": null, "year_id": null }, { "acc_ext_id": "41260-02600", "cat_code": 10002, "cat_ds": "REVENUE", "category_id": 2, "chart_id": 2373, "created_at": "2013-01-15 16:43:52.169213", "dept_id": 86, "feb": 45, "id": 3, "jan": 60, "note": "Two", "total_cost": 105, "updated_at": "2013-01-15 16:43:52.169213", "year_id": 1 } ] I then attempt to iterate over the objects and sum the values: var jan; for (var i=0;i<data.length;i++){ if(data[i].jan != null){ jan += parseFloat(data[i].jan); console.log(jan); } } Printed out in the console is NaN . I've attempted to parse the number as well as leave it raw, but to no avail. Is there something wrong with my objects? Here is a jsFiddle to illustrate: http://jsfiddle.net/5E2pm/3/ |
Javascript fade in fade out without Jquery and CSS3 Posted: 02 Nov 2021 08:16 AM PDT I am really squeezing my head to make the simple fade in and fade out of the background image work only with javascript without JQuery and CSS3. I know how easy is to call a fadeIn() and fadeOut() in Jquery. Unfortunately in my project I am working, they don't support Jquery. I want to support the animation from IE6 for your info. On click of the links the corresponding background of the div to be faded in and out from the previously existing background. I am trying to make it work based on setinterval but could not do it. function handleClick(evt){ var element = document.getElementsByClassName(evt.target.id); fade(element); } function fade(element) { var op = 1; // initial opacity var timer = setInterval(function () { if (op <= 0.1){ clearInterval(timer); element.style.display = 'none'; } element.style.opacity = op; element.style.filter = 'alpha(opacity=' + op * 100 + ")"; op -= op * 0.1; }, 50); } http://jsfiddle.net/meetravi/2Pd6e/4/ |
No comments:
Post a Comment